System.Linq.Expressions.Expression.Compile()

Here are the examples of the csharp api System.Linq.Expressions.Expression.Compile() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1962 Examples 7

19 Source : MethodInvoker.cs
with MIT License
from 1100100

private Func<object, object[], dynamic> BuildInvoker(MethodInfo methodInfo)
        {
            if (methodInfo == null)
                throw new ArgumentNullException(nameof(methodInfo), "MethodInfo cannot be null.");
            var instanceParameter = Expression.Parameter(typeof(object));
            var argsParameter = Expression.Parameter(typeof(object[]));

            var argsExpressions = methodInfo.GetParameters().Select((item, index) => Expression.Convert(Expression.ArrayIndex(argsParameter, Expression.Constant(index)), item.ParameterType));

            var instanceObj = methodInfo.IsStatic ? null : Expression.Convert(instanceParameter, methodInfo.DeclaringType ?? throw new InvalidOperationException());
            var methodCaller = Expression.Call(instanceObj, methodInfo, argsExpressions);
            if (methodCaller.Type == typeof(Task))
            {
                var action = Expression.Lambda<Action<object, object[]>>(methodCaller, instanceParameter, argsParameter).Compile();
                return (instance, args) => { action(instance, args); return Task.CompletedTask; };
            }

            var instanceMethodCaller = Expression.Convert(methodCaller, methodInfo.ReturnType);
            return Expression.Lambda<Func<object, object[], object>>(instanceMethodCaller, instanceParameter, argsParameter).Compile();
        }

19 Source : ObjectFormatter.cs
with MIT License
from 1996v

public void Serialize(ref BssomWriter writer, ref BssomSerializeContext context, object value)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            Type realType = value.GetType();
            if (realType == typeof(object))
            {
                writer.WriteArray1BuildInType(BssomType.Map2);
                BssMapObjMarshal.WriteEmptyMapObject(ref writer);
                return;
            }

            object formatter = context.Option.FormatterResolver.GetFormatterWithVerify(realType);

            if (!SerializerDelegates.TryGetValue(realType, out SerializeMethod serializerDelegate))
            {
                Type formatterType = typeof(IBssomFormatter<>).MakeGenericType(realType);
                ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter");
                ParameterExpression param1 = Expression.Parameter(typeof(BssomWriter).MakeByRefType(), "writer");
                ParameterExpression param2 = Expression.Parameter(typeof(BssomSerializeContext).MakeByRefType(), "context");
                ParameterExpression param3 = Expression.Parameter(typeof(object), "value");

                MethodInfo serializeMethod = formatterType.GetRuntimeMethod(nameof(Serialize), new[] { typeof(BssomWriter).MakeByRefType(), typeof(BssomSerializeContext).MakeByRefType(), realType });

                MethodCallExpression body = Expression.Call(
                    Expression.Convert(param0, formatterType),
                    serializeMethod,
                    param1, param2,
                    realType.IsValueType ? Expression.Unbox(param3, realType) : Expression.Convert(param3, realType)
                    );

                serializerDelegate = Expression.Lambda<SerializeMethod>(body, param0, param1, param2, param3).Compile();
                SerializerDelegates.TryAdd(realType, serializerDelegate);
            }

            serializerDelegate(formatter, ref writer, ref context, value);

        }

19 Source : ObjectFormatter.cs
with MIT License
from 1996v

public int Size(ref BssomSizeContext context, object value)
        {
            if (value == null)
            {
                return BssomBinaryPrimitives.NullSize;
            }

            Type realType = value.GetType();
            if (realType == typeof(object))
            {
                return BssMapObjMarshal.Empty.Length + BssomBinaryPrimitives.BuildInTypeCodeSize;
            }

            object formatter = context.Option.FormatterResolver.GetFormatterWithVerify(realType);

            if (!SizeDelegates.TryGetValue(realType, out SizeMethod sizeDelegate))
            {
                Type formatterType = typeof(IBssomFormatter<>).MakeGenericType(realType);
                ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter");
                ParameterExpression param1 = Expression.Parameter(typeof(BssomSizeContext).MakeByRefType(), "context");
                ParameterExpression param2 = Expression.Parameter(typeof(object), "value");

                MethodInfo sizeMethod = formatterType.GetRuntimeMethod(nameof(Size), new[] { typeof(BssomSizeContext).MakeByRefType(), realType });

                MethodCallExpression body = Expression.Call(
                    Expression.Convert(param0, formatterType),
                    sizeMethod, param1,
                    realType.IsValueType ? Expression.Unbox(param2, realType) : Expression.Convert(param2, realType)
                    );

                sizeDelegate = Expression.Lambda<SizeMethod>(body, param0, param1, param2).Compile();
                SizeDelegates.TryAdd(realType, sizeDelegate);
            }

            return sizeDelegate(formatter, ref context, value);
        }

19 Source : ObjectFormatter.cs
with MIT License
from 1996v

public static object Deserialize(Type type, ref BssomReader reader, ref BssomDeserializeContext context)
        {
            object formatter = context.Option.FormatterResolver.GetFormatterWithVerify(type);

            if (!DeserializerDelegates.TryGetValue(type, out DeserializeMethod deserializerDelegate))
            {
                Type formatterType = typeof(IBssomFormatter<>).MakeGenericType(type);
                ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter");
                ParameterExpression param1 = Expression.Parameter(typeof(BssomReader).MakeByRefType(), "reader");
                ParameterExpression param2 = Expression.Parameter(typeof(BssomDeserializeContext).MakeByRefType(), "context");

                MethodInfo deserializeMethod = formatterType.GetRuntimeMethod(nameof(Deserialize), new[] { typeof(BssomReader).MakeByRefType(), typeof(BssomDeserializeContext).MakeByRefType() });

                //(object)IBssomFormatter<T>.Deserialize(ref reader,option);
                UnaryExpression body = Expression.Convert(Expression.Call(
                    Expression.Convert(param0, formatterType),
                    deserializeMethod,
                    param1,
                    param2), typeof(object));

                deserializerDelegate = Expression.Lambda<DeserializeMethod>(body, param0, param1, param2).Compile();
                DeserializerDelegates.TryAdd(type, deserializerDelegate);
            }

            return deserializerDelegate(formatter, ref reader, ref context);
        }

19 Source : NativeDecimalGetterHelper.cs
with MIT License
from 1996v

private static Func<Decimal, DecimalBinaryBits> Build()
        {
            ParameterExpression de = Expression.Parameter(typeof(Decimal));
            Expression low, mid, high, flags;
            try
            {
                //FRAMEWORK
                low = Expression.Field(de, typeof(Decimal).GetField("lo", BindingFlags.Instance | BindingFlags.NonPublic));
                mid = Expression.Field(de, typeof(Decimal).GetField("mid", BindingFlags.Instance | BindingFlags.NonPublic));
                high = Expression.Field(de, typeof(Decimal).GetField("hi", BindingFlags.Instance | BindingFlags.NonPublic));
                flags = Expression.Field(de, typeof(Decimal).GetField("flags", BindingFlags.Instance | BindingFlags.NonPublic));
            }
            catch
            {
                try
                {
                    low = Expression.Convert(Expression.Field(de, typeof(Decimal).GetField("Low", BindingFlags.Instance | BindingFlags.NonPublic)), typeof(int));
                    mid = Expression.Convert(Expression.Field(de, typeof(Decimal).GetField("Mid", BindingFlags.Instance | BindingFlags.NonPublic)), typeof(int));
                    high = Expression.Convert(Expression.Field(de, typeof(Decimal).GetField("High", BindingFlags.Instance | BindingFlags.NonPublic)), typeof(int));
                    flags = Expression.Field(de, typeof(Decimal).GetField("_flags", BindingFlags.Instance | BindingFlags.NonPublic));
                }
                catch (Exception ex)
                {
                    throw BssomSerializationTypeFormatterException.TypeFormatterError(typeof(decimal), ex.Message);
                }
            }

            NewExpression body = Expression.New(typeof(DecimalBinaryBits).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int), typeof(int) }), low, mid, high, flags);
            return Expression.Lambda<Func<Decimal, DecimalBinaryBits>>(body, de).Compile();
        }

19 Source : ICollectionResolver.cs
with MIT License
from 1996v

public static void ConstructorInit(ConstructorInfo ctor)
        {
            ParameterInfo[] paras = ctor.GetParameters();
            ParameterExpression count = Expression.Parameter(typeof(int));
            Expression body;
            if (paras.Length == 0)
            {
                body = Expression.New(ctor);
            }
            else
            {
                body = Expression.New(ctor, count);
            }

            constructor = Expression.Lambda<Ctor>(body, CommonExpressionMeta.Par_Reader, count).Compile();
        }

19 Source : ICollectionResolver.cs
with MIT License
from 1996v

public static void GenerateInjectCtor(ConstructorInfo constructor, Type injectType)
        {
            Deserialize = Expression.Lambda<Deserialize<T>>(CommonExpressionMeta.GenerateInjectCtor(typeof(T), constructor, injectType), CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
        }

19 Source : Array3CodeGenResolver.cs
with MIT License
from 1996v

internal static void Factory(DynamicFormatterreplacedembly replacedembly, ObjectSerializationInfo objectSerializationInfo)
        {
            ParameterExpression instance = Expression.Parameter(objectSerializationInfo.Type, "value");

            Expression<Serialize<T>> serializeExpression = Array3DynamicExpressionBuild.BuildSerializeLambda<T>(objectSerializationInfo, instance);
            Expression<Size<T>> sizeExpression = Array3DynamicExpressionBuild.BuildSizeLambda<T>(objectSerializationInfo, instance);
            Expression<Deserialize<T>> deserializeExpression = Array3DynamicExpressionBuild.BuildDeserializeLambda<T>(objectSerializationInfo);

            Serialize = serializeExpression.Compile();
            Size = sizeExpression.Compile();
            Deserialize = deserializeExpression.Compile();

#if NETFRAMEWORK
            TypeBuilder typeBuilder = replacedembly.DefineFormatterDelegateType(objectSerializationInfo.Type);
            MethodBuilder serializeDelegate = TypeBuildHelper.DefineSerializeDelegate(typeBuilder, typeof(T));
            serializeExpression.CompileToMethod(serializeDelegate);
            MethodBuilder sizeDelegate = TypeBuildHelper.DefineSizeDelegate(typeBuilder, typeof(T));
            sizeExpression.CompileToMethod(sizeDelegate);
            MethodBuilder deserializeDelegate = TypeBuildHelper.DefineDeserializeDelegate(typeBuilder, typeof(T));
            deserializeExpression.CompileToMethod(deserializeDelegate);
            typeBuilder.CreateTypeInfo();
#endif
        }

19 Source : ICollectionResolver.cs
with MIT License
from 1996v

private static void GenerateDeserializeWithCore(bool isImplGenerICollec, Type itemType, Func<Expression, Expression> ctor)
        {
            /*
               if (reader.TryReadNullWithEnsureArray1BuildInType(BssomType.Int8Code))/TryReadNullWithEnsureArray1NativeType(NativeBssomType.CharCode)/TryReadNullWithEnsureBuildInType(BssomType.Array2)
                    return default;
               context.option.Security.DepthStep(ref reader);
               reader.SkipVariableNumber();
               int len = reader.ReadVariableNumber();
               T t = new T(len);
               Fill<T>(ref t,ref reader,ref context,len);
               context.Depth--;
               return t;  
            */

            bool isArray1Type = Array1FormatterHelper.IsArray1Type(itemType, out bool isNativeType, out byte typeCode, out string typeCodeName);
            Type t = typeof(T);
            List<Expression> ary = new List<Expression>(7);
            LabelTarget returnTarget = Expression.Label(t, "returnLable");

            if (isArray1Type)
            {
                if (isNativeType)
                {
                    //if (reader.ryReadNullWithEnsureArray1NativeType(NativeType))
                    //      goto label;
                    ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1NativeType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
                }
                else
                {
                    //if (reader.Call_Reader_TryReadNullWithEnsureArray1BuildInType(BuildInType))
                    //      goto label;
                    ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1BuildInType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
                }
            }
            else
            {
                //if (reader.TryReadNullWithEnsureBuildInType(BssomType.Array2))
                //      goto label;
                ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureBuildInType(BssomType.Array2), Expression.Return(returnTarget, Expression.Default(t))));
            }

            //context.option.Security.DepthStep(ref reader);
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);

            //reader.SkipVariableNumber();
            ary.Add(CommonExpressionMeta.Call_Reader_SkipVariableNumber);

            //int len = reader.ReadVariableNumber();
            ParameterExpression len = Expression.Variable(typeof(int));
            ary.Add(Expression.replacedign(len, CommonExpressionMeta.Call_Reader_ReadVariableNumber));

            //T t = ctor(len);
            ParameterExpression instance = Expression.Variable(t);
            ary.Add(Expression.replacedign(instance, ctor(len)));
            MethodInfo method = null;
            if (isImplGenerICollec == false)
            {
                //IColloctionFormatterHelper.Fill_ImplIList<T>(ref t,ref reader,ref context,len)
                method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
            }
            else
            {
                if (isArray1Type)
                {
                    //IColloctionFormatterHelper.Fill{TypeCodeName}<T>(ref t,ref reader,ref context,len)
                    method = typeof(Array1FormatterHelper).GetMethod(Array1FormatterHelper.FillPrefix + typeCodeName.ToString().Replace("Code", ""), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
                }
                else
                {
                    //IColloctionFormatterHelper.Fill_ImplICollection<T,TElement>(ref t,ref reader,ref context,len)
                    method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplICollection), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { t, itemType });
                }
            }

            ary.Add(Expression.Call(null, method, instance, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext, len));
            //context.Depth--;
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
            //return t;
            ary.Add(Expression.Return(returnTarget, instance));
            //label default(T)
            ary.Add(Expression.Label(returnTarget, instance));

            BlockExpression block = Expression.Block(new ParameterExpression[] { instance, len }, ary);
            Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();


        }

19 Source : IDictionaryResolver.cs
with MIT License
from 1996v

private static void GenerateDeserializeWithGenericDictCore(Type keyType, Type valueType, Func<MemberExpression, Expression> ctor)
        {
            /*
               var map = MapFormatterHelper.Deserialize(ref reader,ref context);
               if (map == null)
                   return null;
               context.option.Security.DepthStep(ref reader);
               T t = new T();/new T(map.Count)
               Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
               reader = map.Reader; context = map.Context; 
               reader.Seek(map.EndPos);
               context.Depth--;
               return t;  
            */

            ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
            Type t = typeof(T);
            LabelTarget returnTarget = Expression.Label(t, "returnLable");
            ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(keyType, valueType));
            //map = MapFormatterHelper.Deserialize(ref reader,ref context);
            ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(keyType, valueType)));
            //if (map == null)
            //      goto label;
            ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
            //context.option.Security.DepthStep(ref reader);
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
            //T t = ctor(map.Count);
            ParameterExpression instance = Expression.Variable(t);
            ary.Add(Expression.replacedign(instance, ctor(Expression.Property(map, nameof(BssMapObjMarshalReader<int, int>.Count)))));
            //MapFormatterHelper.FillData(map,(ICollection<KeyValuePair<TKey, TValue>>)t)
            ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillGenericIDictionaryData), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(keyType, valueType), map, Expression.Convert(instance, typeof(ICollection<>).MakeGenericType(typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType)))));

            //reader = map.Reader; context = map.Context; 
            ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
            //reader.Seek(map.EndPos);
            ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
            //context.Depth--;
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
            //return t;
            ary.Add(Expression.Return(returnTarget, instance));
            //label default(T)
            ary.Add(Expression.Label(returnTarget, instance));

            BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
            Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
        }

19 Source : IDictionaryResolver.cs
with MIT License
from 1996v

public static void GenerateDeserializeWithIDictionaryEmptyCtor()
        {
            /*
              var map = MapFormatterHelper.Deserialize(ref reader,ref context);
              if (map == null)
                  return null;
              context.option.Security.DepthStep(ref reader);
              T t = new T();
              Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
              reader = map.Reader; context = map.Context; 
              reader.Seek(map.EndPos);
              context.Depth--;
              return t;  
           */

            ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
            Type t = typeof(T);
            LabelTarget returnTarget = Expression.Label(t, "returnLable");
            ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(typeof(object), typeof(object)));
            //map = MapFormatterHelper.Deserialize(ref reader,ref context);
            ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(typeof(object), typeof(object))));
            //if (map == null)
            //      goto label;
            ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
            //context.option.Security.DepthStep(ref reader);
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
            //T t = new T();
            ParameterExpression instance = Expression.Variable(t);
            ary.Add(Expression.replacedign(instance, Expression.New(t)));
            //MapFormatterHelper.FillData(map,(IDictionary)t)
            ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillIDictionaryData), BindingFlags.Public | BindingFlags.Static), map, Expression.Convert(instance, typeof(IDictionary))));

            //reader = map.Reader; context = map.Context; 
            ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
            //reader.Seek(map.EndPos);
            ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
            //context.Depth--;
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
            //return t;
            ary.Add(Expression.Return(returnTarget, instance));
            //label default(T)
            ary.Add(Expression.Label(returnTarget, instance));

            BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
            Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
        }

19 Source : IFormatterResolver.cs
with MIT License
from 1996v

public static IBssomFormatter GetFormatterWithVerify(this IFormatterResolver resolver, Type type)
        {
            if (resolver is null)
            {
                throw new ArgumentNullException(nameof(resolver));
            }

            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (!FormatterGetters.TryGetValue(type, out Func<IFormatterResolver, IBssomFormatter> formatterGetter))
            {
                MethodInfo genericMethod = GetFormatterMethodInfo.MakeGenericMethod(type);
                ParameterExpression inputResolver = Expression.Parameter(typeof(IFormatterResolver), "inputResolver");
                formatterGetter = Expression.Lambda<Func<IFormatterResolver, IBssomFormatter>>(
                    Expression.Call(inputResolver, genericMethod), inputResolver).Compile();
                FormatterGetters.TryAdd(type, formatterGetter);
            }

            return formatterGetter(resolver);
        }

19 Source : Serializer.cs
with MIT License
from 2881099

static Func<T, Dictionary<string, string>> CompilePropertySerializer()
        {
            var o_t = typeof(T);
            var o = Expression.Parameter(o_t, "o");

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Variable(d_t, "d");
            var d_init = Expression.MemberInit(Expression.New(d_t));
            var d_add = d_t.GetMethod("Add");
            var d_setters = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance) // build setters via Add(k,v)
                .Where(x => x.CanRead)
                .Select(x =>
                {
                    var prop = Expression.Property(o, x.Name);
                    var prop_mi_to_string = x.PropertyType.GetMethod("ToString", new Type[0]);
                    var add_to_dict = Expression.Call(d, d_add, Expression.Constant(x.Name), Expression.Call(prop, prop_mi_to_string));

                    if (!x.PropertyType.IsByRef)
                        return (Expression)add_to_dict;
                    else
                        return (Expression)Expression.IfThen(
                            Expression.Not(Expression.Equal(prop, Expression.Constant(null))),
                            add_to_dict);
                });

            // run this
            var body = Expression.Block(new[] { d }, // scope variables
                Expression.replacedign(d, d_init), // initialize
                Expression.Block(d_setters), // set
                d); // return

            return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
                .Compile();
        }

19 Source : Serializer.cs
with MIT License
from 2881099

static Func<Dictionary<string, string>, T> CompilePropertyDeserializer()
        {
            var o_t = typeof(T);
            var o = Expression.Variable(o_t, "o");
            var o_new = Expression.New(typeof(T));

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Parameter(d_t, "d");
            var d_mi_try_get_value = d_t.GetMethod("TryGetValue");

            var item_t = typeof(String);
            var item = Expression.Variable(item_t, "item");

            var tc_t = typeof(TypeConverter);
            var tc = Expression.Variable(tc_t, "tc");
            var tc_mi_can_convert_from = tc_t.GetMethod("CanConvertFrom", new[] { typeof(Type) });
            var tc_mi_convert_from = tc_t.GetMethod("ConvertFrom", new[] { typeof(Object) });

            var td_t = typeof(TypeDescriptor);
            var td_mi_get_converter = td_t.GetMethod("GetConverter", new[] { typeof(Type) });

            var binds = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(x => x.CanRead)
                .Select(x =>
                {
                    var value_t = x.PropertyType;
                    var value = Expression.Variable(value_t, "value");
                    var target = Expression.Label(x.PropertyType);

                    return Expression.Bind(x, Expression.Block(new[] { item, value },
                        Expression.replacedign(tc, Expression.Call(null, td_mi_get_converter, Expression.Constant(x.PropertyType))),
                        Expression.IfThen(
                            Expression.Call(d, d_mi_try_get_value, Expression.Constant(x.Name), item),
                            Expression.IfThen(
                                Expression.NotEqual(item, Expression.Constant(null)),
                                Expression.IfThen(
                                    Expression.Call(tc, tc_mi_can_convert_from, Expression.Constant(typeof(String))),
                                    Expression.Block(
                                        Expression.replacedign(value, Expression.Convert(Expression.Call(tc, tc_mi_convert_from, item), x.PropertyType)),
                                        Expression.Return(target, value, x.PropertyType))))),
                        Expression.Label(target, value)
                    ));
                }).ToArray();

            var body = Expression.Block(new[] { o, tc },
                Expression.MemberInit(o_new, binds)
            );

            return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
                .Compile();
        }

19 Source : Serializer.cs
with MIT License
from 2881099

static Func<Dictionary<string, string>, T> CompileDeserializer()
        {
            var o_t = typeof(T);
            var o_ctor = o_t.GetConstructor(new[] { typeof(SerializationInfo), typeof(StreamingContext) });

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Parameter(d_t, "d");
            var d_mi_get_enumerator = d_t.GetMethod("GetEnumerator");

            var fc_t = typeof(IFormatterConverter);// typeof(LocalVariableInfo);
            var fc = Expression.Variable(fc_t, "fc");
            var fc_init = Expression.MemberInit(Expression.New(typeof(System.Runtime.Serialization.FormatterConverter))); //Expression.MemberInit(Expression.New(fc_t));

            var info_t = typeof(SerializationInfo);
            var info = Expression.Variable(info_t, "info");
            var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
            var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
            var info_mi_add_value = info_t.GetMethod("AddValue", new[] { typeof(String), typeof(Object) });

            var ctx_t = typeof(StreamingContext);
            var ctx = Expression.Variable(ctx_t, "ctx");
            var ctx_init = Expression.MemberInit(Expression.New(ctx_t));

            var enumerator_t = typeof(Dictionary<string, string>.Enumerator);
            var enumerator = Expression.Variable(enumerator_t, "enumerator");
            var enumerator_mi_move_next = enumerator_t.GetMethod("MoveNext");
            var enumerator_current = Expression.Property(enumerator, "Current");

            var kvp_t = typeof(KeyValuePair<string, string>);
            var kvp_pi_key = kvp_t.GetProperty("Key");
            var kvp_pi_value = kvp_t.GetProperty("Value");

            var exit_loop = Expression.Label("exit_loop");

            var body = Expression.Block(new[] { fc, info, ctx, enumerator },
                Expression.replacedign(fc, fc_init),
                Expression.replacedign(info, info_init),
                Expression.replacedign(ctx, ctx_init),
                Expression.replacedign(enumerator, Expression.Call(d, d_mi_get_enumerator)),

                Expression.Loop(
                    Expression.IfThenElse(
                        Expression.Call(enumerator, enumerator_mi_move_next),
                        Expression.Call(info, info_mi_add_value, Expression.Property(enumerator_current, kvp_pi_key), Expression.Property(enumerator_current, kvp_pi_value)),
                        Expression.Break(exit_loop)),
                    exit_loop),

                Expression.MemberInit(Expression.New(o_ctor, info, ctx))
            );

            return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
                .Compile();
        }

19 Source : Serializer.cs
with MIT License
from 2881099

static Func<T, Dictionary<string, string>> CompileSerializer()
        {
            var o_t = typeof(T);
            var o = Expression.Parameter(o_t, "original");
            var o_get_object_data = o_t.GetMethod("GetObjectData");

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Variable(d_t, "d"); // define object variable
            var d_init = Expression.MemberInit(Expression.New(d_t)); // object ctor
            var d_add = d_t.GetMethod("Add"); // add method

            var fc_t = typeof(IFormatterConverter);// typeof(LocalVariableInfo);
            var fc = Expression.Variable(fc_t, "fc");
            var fc_init = Expression.MemberInit(Expression.New(typeof(System.Runtime.Serialization.FormatterConverter))); //Expression.MemberInit(Expression.New(fc_t));

            var info_t = typeof(SerializationInfo);
            var info = Expression.Variable(info_t, "info");
            var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
            var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
            var info_get_enumerator = info_t.GetMethod("GetEnumerator");

            var ctx_t = typeof(StreamingContext);
            var ctx = Expression.Variable(ctx_t, "ctx");
            var ctx_init = Expression.MemberInit(Expression.New(ctx_t));

            var enumerator_t = typeof(SerializationInfoEnumerator);
            var enumerator = Expression.Variable(enumerator_t, "enumerator");
            var enumerator_move_next = enumerator_t.GetMethod("MoveNext");
            var enumerator_name = Expression.Property(enumerator, "Name");
            var enumerator_value = Expression.Property(enumerator, "Value");
            var mi_to_string = typeof(Object).GetMethod("ToString", new Type[0]);
            var exit_loop = Expression.Label("exit_loop");
            var body = Expression.Block(new[] { d, fc, info, ctx },
                Expression.replacedign(d, d_init),
                Expression.replacedign(fc, fc_init),
                Expression.replacedign(info, info_init),
                Expression.replacedign(ctx, ctx_init),
                Expression.Call(o, o_get_object_data, info, ctx),

                Expression.Block(new[] { enumerator },
                    Expression.replacedign(enumerator, Expression.Call(info, info_get_enumerator)),
                    Expression.Loop(
                        Expression.IfThenElse(
                            Expression.Call(enumerator, enumerator_move_next), // test
                            Expression.IfThen(
                                Expression.NotEqual(enumerator_value, Expression.Constant(null)),
                                Expression.Call(d, d_add, enumerator_name, Expression.Call(enumerator_value, mi_to_string))
                            ),
                            Expression.Break(exit_loop)), // if false
                        exit_loop)),
                d); // return

            // compile
            return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
                .Compile();
        }

19 Source : InternalExtensions.cs
with MIT License
from 2881099

public static void SetPropertyOrFieldValue(this Type enreplacedyType, object enreplacedy, string propertyName, object value)
    {
        if (enreplacedy == null) return;
        if (enreplacedyType == null) enreplacedyType = enreplacedy.GetType();

        if (SetSetPropertyOrFieldValueSupportExpressionTreeFlag == 0)
        {
            if (GetPropertiesDictIgnoreCase(enreplacedyType).TryGetValue(propertyName, out var prop))
            {
                prop.SetValue(enreplacedy, value, null);
                return;
            }
            if (GetFieldsDictIgnoreCase(enreplacedyType).TryGetValue(propertyName, out var field))
            {
                field.SetValue(enreplacedy, value);
                return;
            }
            throw new Exception($"The property({propertyName}) was not found in the type({enreplacedyType.DisplayCsharp()})");
        }

        Action<object, string, object> func = null;
        try
        {
            func = _dicSetPropertyOrFieldValue
                .GetOrAdd(enreplacedyType, et => new ConcurrentDictionary<string, Action<object, string, object>>())
                .GetOrAdd(propertyName, pn =>
                {
                    var t = enreplacedyType;
                    MemberInfo memberinfo = enreplacedyType.GetPropertyOrFieldIgnoreCase(pn);
                    var parm1 = Expression.Parameter(typeof(object));
                    var parm2 = Expression.Parameter(typeof(string));
                    var parm3 = Expression.Parameter(typeof(object));
                    var var1Parm = Expression.Variable(t);
                    var exps = new List<Expression>(new Expression[] {
                            Expression.replacedign(var1Parm, Expression.TypeAs(parm1, t))
                    });
                    if (memberinfo != null)
                    {
                        exps.Add(
                            Expression.replacedign(
                                Expression.MakeMemberAccess(var1Parm, memberinfo),
                                Expression.Convert(
                                    parm3,
                                    memberinfo.GetPropertyOrFieldType()
                                )
                            )
                        );
                    }
                    return Expression.Lambda<Action<object, string, object>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile();
                });
        }
        catch
        {
            System.Threading.Interlocked.Exchange(ref SetSetPropertyOrFieldValueSupportExpressionTreeFlag, 0);
            SetPropertyOrFieldValue(enreplacedyType, enreplacedy, propertyName, value);
            return;
        }
        func(enreplacedy, propertyName, value);
    }

19 Source : DbContextAsync.cs
with MIT License
from 2881099

async internal Task ExecCommandAsync() {
			if (isExecCommanding) return;
			if (_actions.Any() == false) return;
			isExecCommanding = true;

			ExecCommandInfo oldinfo = null;
			var states = new List<object>();

			Func<string, Task<int>> dbContextBetch = methodName => {
				if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
					trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
				if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
					var arrType = oldinfo.stateType.MakeArrayType();
					var dbsetType = oldinfo.dbSet.GetType().BaseType;
					var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);

					var returnTarget = Expression.Label(typeof(Task<int>));
					var parm1DbSet = Expression.Parameter(typeof(object));
					var parm2Vals = Expression.Parameter(typeof(object[]));
					var var1Vals = Expression.Variable(arrType);
					tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
						new[] { var1Vals },
						Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
						Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
						Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
					), new[] { parm1DbSet, parm2Vals }).Compile();
					trydic.Add(methodName, tryfunc);
				}
				return tryfunc(oldinfo.dbSet, states.ToArray());
			};
			Func<Task> funcDelete = async () => {
				_affrows += await dbContextBetch("DbContextBetchRemoveAsync");
				states.Clear();
			};
			Func<Task> funcInsert = async  () => {
				_affrows += await dbContextBetch("DbContextBetchAddAsync");
				states.Clear();
			};
			Func<bool, Task> funcUpdate = async (isLiveUpdate) => {
				var affrows = 0;
				if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
				else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
				if (affrows == -999) { //最后一个元素已被删除
					states.RemoveAt(states.Count - 1);
					return;
				}
				if (affrows == -998 || affrows == -997) { //没有执行更新
					var laststate = states[states.Count - 1];
					states.Clear();
					if (affrows == -997) states.Add(laststate); //保留最后一个
				}
				if (affrows > 0) {
					_affrows += affrows;
					var islastNotUpdated = states.Count != affrows;
					var laststate = states[states.Count - 1];
					states.Clear();
					if (islastNotUpdated) states.Add(laststate); //保留最后一个
				}
			};

			while (_actions.Any() || states.Any()) {
				var info = _actions.Any() ? _actions.Dequeue() : null;
				if (oldinfo == null) oldinfo = info;
				var isLiveUpdate = false;

				if (_actions.Any() == false && states.Any() ||
					info != null && oldinfo.actionType != info.actionType ||
					info != null && oldinfo.stateType != info.stateType) {

					if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
						//最后一个,合起来发送
						states.Add(info.state);
						info = null;
					}

					switch (oldinfo.actionType) {
						case ExecCommandInfoType.Insert:
							await funcInsert();
							break;
						case ExecCommandInfoType.Delete:
							await funcDelete();
							break;
					}
					isLiveUpdate = true;
				}

				if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
					if (states.Any())
						await funcUpdate(isLiveUpdate);
				}

				if (info != null) {
					states.Add(info.state);
					oldinfo = info;
				}
			}
			isExecCommanding = false;
		}

19 Source : DbContextSync.cs
with MIT License
from 2881099

internal void ExecCommand() {
			if (isExecCommanding) return;
			if (_actions.Any() == false) return;
			isExecCommanding = true;

			ExecCommandInfo oldinfo = null;
			var states = new List<object>();

			Func<string, int> dbContextBetch = methodName => {
				if (_dicExecCommandDbContextBetch.TryGetValue(oldinfo.stateType, out var trydic) == false)
					trydic = new Dictionary<string, Func<object, object[], int>>();
				if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
					var arrType = oldinfo.stateType.MakeArrayType();
					var dbsetType = oldinfo.dbSet.GetType().BaseType;
					var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);

					var returnTarget = Expression.Label(typeof(int));
					var parm1DbSet = Expression.Parameter(typeof(object));
					var parm2Vals = Expression.Parameter(typeof(object[]));
					var var1Vals = Expression.Variable(arrType);
					tryfunc = Expression.Lambda<Func<object, object[], int>>(Expression.Block(
						new[] { var1Vals },
						Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
						Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
						Expression.Label(returnTarget, Expression.Default(typeof(int)))
					), new[] { parm1DbSet, parm2Vals }).Compile();
					trydic.Add(methodName, tryfunc);
				}
				return tryfunc(oldinfo.dbSet, states.ToArray());
			};
			Action funcDelete = () => {
				_affrows += dbContextBetch("DbContextBetchRemove");
				states.Clear();
			};
			Action funcInsert = () => {
				_affrows += dbContextBetch("DbContextBetchAdd");
				states.Clear();
			};
			Action<bool> funcUpdate = isLiveUpdate => {
				var affrows = 0;
				if (isLiveUpdate) affrows = dbContextBetch("DbContextBetchUpdateNow");
				else affrows = dbContextBetch("DbContextBetchUpdate");
				if (affrows == -999) { //最后一个元素已被删除
					states.RemoveAt(states.Count - 1);
					return;
				}
				if (affrows == -998 || affrows == -997) { //没有执行更新
					var laststate = states[states.Count - 1];
					states.Clear();
					if (affrows == -997) states.Add(laststate); //保留最后一个
				}
				if (affrows > 0) {
					_affrows += affrows;
					var islastNotUpdated = states.Count != affrows;
					var laststate = states[states.Count - 1];
					states.Clear();
					if (islastNotUpdated) states.Add(laststate); //保留最后一个
				}
			};

			while (_actions.Any() || states.Any()) {
				var info = _actions.Any() ? _actions.Dequeue() : null;
				if (oldinfo == null) oldinfo = info;
				var isLiveUpdate = false;

				if (_actions.Any() == false && states.Any() ||
					info != null && oldinfo.actionType != info.actionType ||
					info != null && oldinfo.stateType != info.stateType) {

					if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
						//最后一个,合起来发送
						states.Add(info.state);
						info = null;
					}

					switch (oldinfo.actionType) {
						case ExecCommandInfoType.Insert:
							funcInsert();
							break;
						case ExecCommandInfoType.Delete:
							funcDelete();
							break;
					}
					isLiveUpdate = true;
				}

				if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
					if (states.Any())
						funcUpdate(isLiveUpdate);
				}

				if (info != null) {
					states.Add(info.state);
					oldinfo = info;
				}
			}
			isExecCommanding = false;
		}

19 Source : DynamicProxyMeta.cs
with MIT License
from 2881099

public static void CopyData(Type sourceType, object source, object target)
        {
            if (source == null) return;
            if (target == null) return;
            _copyDataFunc.GetOrAdd(sourceType, type =>
            {
                var sourceParamExp = Expression.Parameter(typeof(object), "sourceObject");
                var targetParamExp = Expression.Parameter(typeof(object), "targetObject");
                var sourceExp = Expression.Variable(type, "source");
                var targetExp = Expression.Variable(type, "target");
                var copyExps = new List<Expression>();
                var sourceFields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                foreach (var field in sourceFields)
                    copyExps.Add(Expression.replacedign(Expression.MakeMemberAccess(targetExp, field), Expression.MakeMemberAccess(sourceExp, field)));

                if (copyExps.Any() == false) return _copyDataFuncEmpty;
                var bodyExp = Expression.Block(
                    new[] {
                            sourceExp, targetExp
                    },
                    new[] {
                            Expression.IfThen(
                                Expression.NotEqual(sourceParamExp, Expression.Constant(null)),
                                Expression.IfThen(
                                    Expression.NotEqual(targetParamExp, Expression.Constant(null)),
                                    Expression.Block(
                                        Expression.replacedign(sourceExp, Expression.TypeAs(sourceParamExp, sourceType)),
                                        Expression.replacedign(targetExp, Expression.TypeAs(targetParamExp, sourceType)),
                                        Expression.IfThen(
                                            Expression.NotEqual(sourceExp, Expression.Constant(null)),
                                            Expression.IfThen(
                                                Expression.NotEqual(sourceExp, Expression.Constant(null)),
                                                Expression.Block(
                                                    copyExps.ToArray()
                                                )
                                            )
                                        )
                                    )
                                )
                            )
                    }
                );
                return Expression.Lambda<Action<object, object>>(bodyExp, sourceParamExp, targetParamExp).Compile();
            })(source, target);
        }

19 Source : DynamicProxyMeta.cs
with MIT License
from 2881099

public static void SetPropertyValue(Type sourceType, object source, string propertyOrField, object value)
        {
            if (source == null) return;
            if (sourceType == null) sourceType = source.GetType();
            _dicSetEnreplacedyValueWithPropertyName
                .GetOrAdd(sourceType, et => new ConcurrentDictionary<string, Action<object, string, object>>())
                .GetOrAdd(propertyOrField, pf =>
                {
                    var t = sourceType;
                    var parm1 = Expression.Parameter(typeof(object));
                    var parm2 = Expression.Parameter(typeof(string));
                    var parm3 = Expression.Parameter(typeof(object));
                    var var1Parm = Expression.Variable(t);
                    var exps = new List<Expression>(new Expression[] {
                        Expression.replacedign(var1Parm, Expression.TypeAs(parm1, t))
                    });
                    var memberInfos = t.GetMember(pf, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.MemberType == MemberTypes.Field || a.MemberType == MemberTypes.Property);
                    foreach (var memberInfo in memberInfos) {
                        exps.Add(
                            Expression.replacedign(
                                Expression.MakeMemberAccess(var1Parm, memberInfo),
                                Expression.Convert(
                                    parm3,
                                    memberInfo.MemberType == MemberTypes.Field ? (memberInfo as FieldInfo)?.FieldType : (memberInfo as PropertyInfo)?.PropertyType
                                )
                            )
                        );
                    }
                    return Expression.Lambda<Action<object, string, object>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile();
                })(source, propertyOrField, value);
        }

19 Source : ExpressionVisitor`1.cs
with MIT License
from 71

protected void EnableDynamicVisiting()
        {
            if (dynamicVisit != null)
                return;

            Type returnType = typeof(T);
            ParameterExpression exprParam = Expression.Parameter(typeof(Expression), "node");
            Expression body = Expression.Call(Expression.Constant(this), nameof(DefaultVisit), null, exprParam);

            foreach (MethodInfo method in this.GetType().GetTypeInfo().DeclaredMethods)
            {
                if (method.ReturnType != returnType || !method.Name.StartsWith("Visit"))
                    continue;

                ParameterInfo[] parameters = method.GetParameters();

                if (parameters.Length != 1)
                    continue;

                ParameterInfo parameter = parameters[0];

                if (!parameter.ParameterType.IsreplacedignableTo(typeof(Expression)))
                    continue;

                // We got this far, it's a valid Visit*() method.
                ParameterExpression exprVar = Expression.Parameter(parameter.ParameterType, parameter.Name);

                // expr is TExpr newExpr ? newExpr : body
                body = Expression.Block(new[] { exprVar },
                    Expression.replacedign(exprVar, Expression.TypeAs(exprParam, parameter.ParameterType)),
                    Expression.Condition(
                        Expression.ReferenceNotEqual(exprVar, Expression.Constant(null)),
                        exprVar,
                        body
                    )
                );
            }

            dynamicVisit = Expression.Lambda<Func<Expression, T>>(body, exprParam).Compile();
        }

19 Source : Loops.cs
with MIT License
from 71

[Fact]
        public void ShouldRespectWhile()
        {
            ParameterExpression nbr = Expression.Variable(typeof(int), nameof(nbr));
            ParameterExpression output = Expression.Parameter(typeof(List<int>), "output");

            List<int> addedItems = new List<int>();

            WhileExpression loop = X.While(
                Expression.LessThan(Expression.PostIncrementreplacedign(nbr), Expression.Constant(10)),
                Expression.Call(output, nameof(List<int>.Add), null, nbr)
            );

            Expression
                .Lambda<Action<List<int>>>(Expression.Block(new[] { nbr }, loop), output)
                .Compile()(addedItems);

            addedItems.Count.ShouldBe(10);

            int index = 0;
            while (index++ < 10)
                addedItems[index - 1].ShouldBe(index);
        }

19 Source : OtherExpressions.cs
with MIT License
from 71

[Fact]
        public void ShouldCallDispose()
        {
            TrackingDisposable disposable = new TrackingDisposable();
            ConstantExpression disposableEx = Expression.Constant(disposable);

            disposable.HasBeenDisposed.ShouldBeFalse();

            Expression
                .Lambda<Action>(X.Using(disposableEx, Expression.Empty()))
                .Compile()();

            disposable.HasBeenDisposed.ShouldBeTrue();
        }

19 Source : OtherExpressions.cs
with MIT License
from 71

[Fact]
        public void ShouldReturnType()
        {
            Expression
                .Lambda<Func<Type>>(X.TypeOf<string>())
                .Compile()()
                .ShouldBe(typeof(string));

            Expression
                .Lambda<Func<Type>>(X.TypeOf(typeof(void)))
                .Compile()()
                .ShouldBe(typeof(void));
        }

19 Source : OtherExpressions.cs
with MIT License
from 71

[Fact]
        public void ShouldLockExecution()
        {
            object syncRoot = new object();
            Expression syncRootEx = syncRoot.AsExpression();

            Expression sleep = X.Express<Action>(() => Thread.Sleep(2000));

            Action compiledAction = Expression
                .Lambda<Action>(X.Lock(syncRootEx, sleep))
                .Compile();

            Task task = Task.Run(compiledAction);

            // Sleep to make sure the task has the time to start running
            while (task.Status != TaskStatus.Running)
                Thread.Sleep(50);

            DateTime beforeEntering = DateTime.Now;

            lock (syncRoot)
                DateTime.Now.ShouldBeGreaterThan(beforeEntering.AddMilliseconds(1000));
        }

19 Source : StateMachines.cs
with MIT License
from 71

[Fact]
        public void ShouldReduceAwaitToBlockingCall()
        {
            Task<string> sleepTask = new Task<string>(() =>
            {
                Thread.Sleep(1000);
                return "hey";
            });

            AwaitExpression expression = X.Await(X.Link(sleepTask));

            DateTime before = DateTime.Now;

            Action action = Expression.Lambda<Action>(expression).Compile();

            sleepTask.Start();
            action();

            TimeSpan timeTaken = DateTime.Now - before;

            timeTaken.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(1000));
        }

19 Source : Utils.cs
with MIT License
from 71

public static TDelegate Compile<TDelegate>(this Expression expr, params ParameterExpression[] parameters)
        {
            expr = expr.ReduceExtensions();

            return Expression.Lambda<TDelegate>(
                Expression.Block(
                    Expression.DebugInfo(Expression.SymbolDoreplacedent("debug"), 1, 1, 1, 1),
                    expr
                ), parameters
            ).Compile();
        }

19 Source : LinkedExpression.cs
with MIT License
from 71

private static Func<T> GetCompiledGetter(Expression<Func<T>> lambda)
        {
            return lambda.Compile();
        }

19 Source : LinkedExpression.cs
with MIT License
from 71

private static Action<T> GetCompiledSetter(Expression<Func<T>> lambda)
        {
            ParameterExpression parameter = Parameter(typeof(T), "value");

            return Lambda<Action<T>>(replacedign(lambda.Body, parameter), parameter).Compile();
        }

19 Source : Loops.cs
with MIT License
from 71

[Fact]
        public void ShouldIterateEnumerable()
        {
            ParameterExpression output = Expression.Parameter(typeof(List<string>), "output");
            ParameterExpression item = Expression.Variable(typeof(string), "item");
            ConstantExpression items = Expression.Constant(Enumerable.Repeat("hello world", 10));

            List<string> addedItems = new List<string>();

            ForEachExpression loop = X.ForEach(item, items,
                Expression.Call(output, nameof(List<string>.Add), null, item)
            );

            Expression
                .Lambda<Action<List<string>>>(loop, output)
                .Compile()(addedItems);

            addedItems.Count.ShouldBe(10);
            addedItems[0].ShouldBe("hello world");
        }

19 Source : Loops.cs
with MIT License
from 71

[Fact]
        public void ShouldIterateArray()
        {
            ParameterExpression output = Expression.Parameter(typeof(List<string>), "output");
            ParameterExpression item = Expression.Variable(typeof(string), "item");
            ConstantExpression items = Expression.Constant(new[] { "hello", "world" });

            List<string> addedItems = new List<string>();

            ForEachExpression loop = X.ForEach(item, items,
                Expression.Call(output, nameof(List<string>.Add), null, item)
            );

            Expression
                .Lambda<Action<List<string>>>(loop, output)
                .Compile()(addedItems);

            addedItems.Count.ShouldBe(2);
            addedItems[0].ShouldBe("hello");
            addedItems[1].ShouldBe("world");
        }

19 Source : OtherExpressions.cs
with MIT License
from 71

[Fact]
        public void ShouldCallDisposeAfterException()
        {
            TrackingDisposable disposable = new TrackingDisposable();
            ConstantExpression disposableEx = Expression.Constant(disposable);

            ConstantExpression exceptionEx = Expression.Constant(new Exception());

            disposable.HasBeenDisposed.ShouldBeFalse();

            Should.Throw<Exception>(() => Expression
                .Lambda<Action>(X.Using(disposableEx, Expression.Throw(exceptionEx)))
                .Compile()());

            disposable.HasBeenDisposed.ShouldBeTrue();
        }

19 Source : GameAttackTrigger.cs
with Apache License 2.0
from AantCoder

public static Pawn GetPawn(this Pawn_JobTracker keeper)
        {
            /*
            FieldInfo fieldInfo = typeof(Pawn_JobTracker).GetField("pawn", BindingFlags.Instance | BindingFlags.NonPublic);
            Pawn result = (Pawn)fieldInfo.GetValue(keeper);
            return result;
            */
            if (GetPawnFromPawn_JobTracker == null)
            {
                ParameterExpression keeperArg = Expression.Parameter(typeof(Pawn_JobTracker), "keeper"); // SecretKeeper keeper argument
                Expression secretAccessor = Expression.Field(keeperArg, "pawn"); // keeper._secret
                var lambda = Expression.Lambda<Func<Pawn_JobTracker, Pawn>>(secretAccessor, keeperArg);
                GetPawnFromPawn_JobTracker = lambda.Compile(); // Получается функция return result = keeper._secret;
            }
            return GetPawnFromPawn_JobTracker(keeper);
        }

19 Source : Remute.cs
with MIT License
from ababik

private Activator GetActivator(ConstructorInfo constructor)
        {
            var parameters = constructor.GetParameters();

            var parameterExpression = Expression.Parameter(typeof(object[]));
            var argumentExpressions = new Expression[parameters.Length];

            for (var i = 0; i < parameters.Length; i++)
            {
                var indexExpression = Expression.Constant(i);
                var paramType = parameters[i].ParameterType;
                var arrayExpression = Expression.ArrayIndex(parameterExpression, indexExpression);
                var arrayConvertExpression = Expression.Convert(arrayExpression, paramType);
                argumentExpressions[i] = arrayConvertExpression;
            }

            var constructorExpression = Expression.New(constructor, argumentExpressions);
            var constructorConvertExpression = Expression.Convert(constructorExpression, typeof(object));
            var lambdaExpression = Expression.Lambda<Activator>(constructorConvertExpression, parameterExpression);
            var compiledExpression = lambdaExpression.Compile();
            return compiledExpression;
        }

19 Source : TypeUtil.cs
with MIT License
from Abc-Arbitrage

private static Func<IntPtr, Type>? BuildGetTypeFromHandleFunc()
        {
            var method = typeof(Type).GetMethod("GetTypeFromHandleUnsafe", BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(IntPtr) }, null);
            if (method == null)
                return null;

            var param = Parameter(typeof(IntPtr));

            return Lambda<Func<IntPtr, Type>>(
                Call(method, param),
                param
            ).Compile();
        }

19 Source : Remute.cs
with MIT License
from ababik

private ParameterResolver[] GetParameterResolvers(Type type, ConstructorInfo constructor)
        {
            var properties = GetInstanceProperties(type);
            var parameters = constructor.GetParameters();

            var parameterResolvers = new ParameterResolver[parameters.Length];

            for (var i = 0; i < parameters.Length; i++)
            {
                var parameter = parameters[i];

                var property = FindProperty(type, parameter, properties);

                var parameterExpression = Expression.Parameter(typeof(object));
                var parameterConvertExpression = Expression.Convert(parameterExpression, type);
                var propertyExpression = Expression.Property(parameterConvertExpression, property);
                var propertyConvertExpression = Expression.Convert(propertyExpression, typeof(object));
                var lambdaExpression = Expression.Lambda<Func<object, object>>(propertyConvertExpression, parameterExpression);
                var compiledExpression = lambdaExpression.Compile();

                var parameterResolver = new ParameterResolver(parameter, property, compiledExpression);
                parameterResolvers[i] = parameterResolver;
            }

            return parameterResolvers;
        }

19 Source : Remute.cs
with MIT License
from ababik

private object ResolveInstance<TSource>(ProcessContext<TSource> processContext)
        {
            var key = new InstanceExpressionCacheKey(typeof(TSource), processContext.InstanceExpression);
            var compiledExpression = default(ResolveInstanceDelegate<TSource>);

            if (ResolveInstanceExpressionCache.TryGetValue(key, out var resolveInstanceDelegate))
            {
                compiledExpression = (ResolveInstanceDelegate<TSource>)resolveInstanceDelegate;
            }
            else
            {
                var instanceConvertExpression = Expression.Convert(processContext.InstanceExpression, typeof(object));
                var lambdaExpression = Expression.Lambda<ResolveInstanceDelegate<TSource>>(instanceConvertExpression, processContext.SourceParameterExpression);
                compiledExpression = lambdaExpression.Compile();
                ResolveInstanceExpressionCache[key] = compiledExpression;
            }

            return compiledExpression.Invoke(processContext.Source);
        }

19 Source : GenericInterface.cs
with MIT License
from Accelerider

private TDelegate GetActionWithParams<TDelegate>(string methodName, params Type[] argTypes)
            {
                var methodInfo = Type.GetMethod(methodName) ?? throw new ArgumentException(nameof(methodName));
                var argTypeList = argTypes.Any() ? argTypes : typeof(TDelegate).GetGenericArguments();
                (ParameterExpression expression, Type type)[] argObjectParameters = argTypeList
                    .Select(item => (Expression.Parameter(typeof(object)), item))
                    .ToArray();

                var method = Expression.Lambda<TDelegate>(
                        Expression.Call(
                            Expression.Constant(_instance),
                            methodInfo,
                            argObjectParameters.Select(item => Expression.Convert(item.expression, item.type))),
                        argObjectParameters.Select(item => item.expression))
                    .Compile();

                return method;
            }

19 Source : GenericInterface.cs
with MIT License
from Accelerider

private TDelegate GetAction<TDelegate>(string methodName)
            {
                var methodInfo = Type.GetMethod(methodName) ?? throw new ArgumentException(nameof(methodName));
                var method = Expression.Lambda<TDelegate>(
                        Expression.Call(
                            Expression.Constant(_instance),
                            methodInfo))
                    .Compile();

                return method;
            }

19 Source : PropertyObserverNode.cs
with MIT License
from Accelerider

private static Func<T> GetPropertyGetter<T>(object owner, string propertyName)
        {
            var propertyInfo = owner.GetType().GetProperty(propertyName);

            if (propertyInfo == null)
                throw new InvalidOperationException($"No the property named \"{propertyName}\" in the {owner.GetType()} type. ");

            var method = propertyInfo.GetGetMethod();

            return method.ReturnType != typeof(T) && method.ReturnType.IsValueType
                // Warning: Boxes the Value Type.
                ? Lambda<Func<T>>(Convert(Call(Constant(owner), method), typeof(T))).Compile()
                : (Func<T>)Delegate.CreateDelegate(typeof(Func<T>), owner, propertyInfo.GetGetMethod());
        }

19 Source : DataContext.cs
with MIT License
from Accelerider

public void Export<T>(Expression<Func<T>> propertyExpression, string key = null)
        {
            key = key ?? PropertySupport.ExtractPropertyName(propertyExpression);

            if (_exportPropertyGetterDictionary.ContainsKey(key))
                throw new ArgumentException(string.Format(Resources.DataContext_ExportHasBeenExported_Exception, propertyExpression), nameof(propertyExpression));

            var getter = propertyExpression.Compile();

            _exportPropertyGetterDictionary[key] = getter;

            PropertyObserver.Observes(propertyExpression, () =>
            {
                if (!_importPropertySetterDictionary.TryGetValue(key, out var setterDelegates)) return;

                foreach (var setterDelegate in setterDelegates)
                {
                    var setter = (Action<T>)setterDelegate;
                    setter(getter());
                }
            });
        }

19 Source : DataContext.cs
with MIT License
from Accelerider

public void Import<T>(Expression<Func<T>> propertyExpression, string key = null)
        {
            var parameter = Expression.Parameter(typeof(T));
            var setter = Expression.Lambda<Action<T>>(
                Expression.replacedign(
                    propertyExpression.Body,
                    parameter),
                parameter).Compile();

            key = key ?? PropertySupport.ExtractPropertyName(propertyExpression);
            if (!_importPropertySetterDictionary.ContainsKey(key))
            {
                _importPropertySetterDictionary.Add(key, new List<Delegate>());
            }
            _importPropertySetterDictionary[key].Add(setter);
        }

19 Source : TokenTypes.Keywords.cs
with MIT License
from adamant

private static Func<TextSpan, T> CompileFactory<T>(Type tokenType)
            where T : IToken
        {
            var spanParam = Expression.Parameter(typeof(TextSpan), "span");
            var newExpression = Expression.New(tokenType.GetConstructor(new[] { typeof(TextSpan) }), spanParam);
            var factory =
                Expression.Lambda<Func<TextSpan, T>>(
                    newExpression, spanParam);
            return factory.Compile();
        }

19 Source : PluralExpressionCompiler.cs
with MIT License
from adams85

public Func<int, int> Compile()
        {
            _param = Expression.Parameter(typeof(int), "n");

            Expression expression = Visit(_syntaxTree);

            var lambda = Expression.Lambda<Func<int, int>>(expression, _param);
            return lambda.Compile();
        }

19 Source : VerifyLogExpressionArgs.cs
with Apache License 2.0
from adrianiftode

public static VerifyLogExpressionArgs From(Expression expression) => new VerifyLogExpressionArgs
        {
            LogLevel = GetLogLevelFrom(expression),
            Message = ExpressionInspector.GetArgOf<string>(expression),
            MessageArgs = Expression.Lambda<Func<object[]>>(ExpressionInspector.GetArgExpressionOf<object[]>(expression)).Compile()(),
            Exception = GetException(expression),
            EventId = GetEventId(expression)
        };

19 Source : Serializer.cs
with Mozilla Public License 2.0
from agebullhu

static Func<T, Dictionary<string, string>> CompileSerializer()
        {
            var o_t = typeof(T);
            var o = Expression.Parameter(o_t, "original");
            var o_get_object_data = o_t.GetMethod("GetObjectData");

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Variable(d_t, "d"); // define object variable
            var d_init = Expression.MemberInit(Expression.New(d_t)); // object ctor
            var d_add = d_t.GetMethod("Add"); // add method

            var fc_t = typeof(LocalVariableInfo);
            var fc = Expression.Variable(fc_t, "fc");
            var fc_init = Expression.MemberInit(Expression.New(fc_t));

            var info_t = typeof(SerializationInfo);
            var info = Expression.Variable(info_t, "info");
            var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
            var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
            var info_get_enumerator = info_t.GetMethod("GetEnumerator");

            var ctx_t = typeof(StreamingContext);
            var ctx = Expression.Variable(ctx_t, "ctx");
            var ctx_init = Expression.MemberInit(Expression.New(ctx_t));

            var enumerator_t = typeof(SerializationInfoEnumerator);
            var enumerator = Expression.Variable(enumerator_t, "enumerator");
            var enumerator_move_next = enumerator_t.GetMethod("MoveNext");
            var enumerator_name = Expression.Property(enumerator, "Name");
            var enumerator_value = Expression.Property(enumerator, "Value");
            var mi_to_string = typeof(Object).GetMethod("ToString", new Type[0]);
            var exit_loop = Expression.Label("exit_loop");
            var body = Expression.Block(new[] { d, fc, info, ctx },
                Expression.replacedign(d, d_init),
                Expression.replacedign(fc, fc_init),
                Expression.replacedign(info, info_init),
                Expression.replacedign(ctx, ctx_init),
                Expression.Call(o, o_get_object_data, info, ctx),

                Expression.Block(new[] { enumerator },
                    Expression.replacedign(enumerator, Expression.Call(info, info_get_enumerator)),
                    Expression.Loop(
                        Expression.IfThenElse(
                            Expression.Call(enumerator, enumerator_move_next), // test
                            Expression.IfThen(
                                Expression.NotEqual(enumerator_value, Expression.Constant(null)),
                                Expression.Call(d, d_add, enumerator_name, Expression.Call(enumerator_value, mi_to_string))
                            ),
                            Expression.Break(exit_loop)), // if false
                        exit_loop)),
                d); // return

            // compile
            return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
                .Compile();
        }

19 Source : Serializer.cs
with Mozilla Public License 2.0
from agebullhu

static Func<Dictionary<string, string>, T> CompileDeserializer()
        {
            var o_t = typeof(T);
            var o_ctor = o_t.GetConstructor(new[] { typeof(SerializationInfo), typeof(StreamingContext) });

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Parameter(d_t, "d");
            var d_mi_get_enumerator = d_t.GetMethod("GetEnumerator");

            var fc_t = typeof(LocalVariableInfo);
            var fc = Expression.Variable(fc_t, "fc");
            var fc_init = Expression.MemberInit(Expression.New(fc_t));

            var info_t = typeof(SerializationInfo);
            var info = Expression.Variable(info_t, "info");
            var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
            var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
            var info_mi_add_value = info_t.GetMethod("AddValue", new[] { typeof(String), typeof(Object) });

            var ctx_t = typeof(StreamingContext);
            var ctx = Expression.Variable(ctx_t, "ctx");
            var ctx_init = Expression.MemberInit(Expression.New(ctx_t));

            var enumerator_t = typeof(Dictionary<string, string>.Enumerator);
            var enumerator = Expression.Variable(enumerator_t, "enumerator");
            var enumerator_mi_move_next = enumerator_t.GetMethod("MoveNext");
            var enumerator_current = Expression.Property(enumerator, "Current");

            var kvp_t = typeof(KeyValuePair<string, string>);
            var kvp_pi_key = kvp_t.GetProperty("Key");
            var kvp_pi_value = kvp_t.GetProperty("Value");

            var exit_loop = Expression.Label("exit_loop");

            var body = Expression.Block(new[] { fc, info, ctx, enumerator },
                Expression.replacedign(fc, fc_init),
                Expression.replacedign(info, info_init),
                Expression.replacedign(ctx, ctx_init),
                Expression.replacedign(enumerator, Expression.Call(d, d_mi_get_enumerator)),

                Expression.Loop(
                    Expression.IfThenElse(
                        Expression.Call(enumerator, enumerator_mi_move_next),
                        Expression.Call(info, info_mi_add_value, Expression.Property(enumerator_current, kvp_pi_key), Expression.Property(enumerator_current, kvp_pi_value)),
                        Expression.Break(exit_loop)),
                    exit_loop),

                Expression.MemberInit(Expression.New(o_ctor, info, ctx))
            );

            return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
                .Compile();
        }

19 Source : LazyNode.cs
with GNU General Public License v3.0
from agolaszewski

public virtual void Bind(Expression<Func<TResult>> action)
        {
            if (((MemberExpression)action.Body).Member is PropertyInfo)
            {
                var propertyInfo = ((MemberExpression)action.Body).Member as PropertyInfo;

                var body = action.Body as MemberExpression;
                object projection = Expression.Lambda<Func<object>>(body.Expression).Compile()();

                _then = answer => { propertyInfo.SetValue(projection, answer); };
            }

            if (((MemberExpression)action.Body).Member is FieldInfo)
            {
                var fieldInfo = ((MemberExpression)action.Body).Member as FieldInfo;

                var body = action.Body as MemberExpression;
                object projection = Expression.Lambda<Func<object>>(body.Expression).Compile()();

                _then = answer => { fieldInfo.SetValue(projection, answer); };
            }
        }

19 Source : Node.cs
with GNU General Public License v3.0
from agolaszewski

public virtual IThen Bind(Expression<Func<TResult>> action)
        {
            if (((MemberExpression)action.Body).Member is PropertyInfo)
            {
                var propertyInfo = ((MemberExpression)action.Body).Member as PropertyInfo;

                var body = action.Body as MemberExpression;
                object projection = Expression.Lambda<Func<object>>(body.Expression).Compile()();

                _then = answer => { propertyInfo.SetValue(projection, answer); };
            }

            if (((MemberExpression)action.Body).Member is FieldInfo)
            {
                var fieldInfo = ((MemberExpression)action.Body).Member as FieldInfo;

                var body = action.Body as MemberExpression;
                object projection = Expression.Lambda<Func<object>>(body.Expression).Compile()();

                _then = answer => { fieldInfo.SetValue(projection, answer); };
            }

            return new ThenComponent(this);
        }

See More Examples