System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])

Here are the examples of the csharp api System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

572 Examples 7

19 View Source File : SourceInjectedQueryProvider.cs
License : MIT License
Project Creator : AutoMapper

private static Expression Select(Expression source, LambdaExpression lambda)
        {
            return Call(
                    null,
                    QueryableSelectMethod.MakeGenericMethod(lambda.Parameters[0].Type, lambda.ReturnType),
                    new[] { source, Quote(lambda) }
                );
        }

19 View Source File : ConditionVisitor.cs
License : MIT License
Project Creator : Azure

Expression GetPropertyOrElse(Expression propertyBag, Expression property, Expression alternative, bool isBodyQuery)
        {
            Expression expression;

            if (propertyBag.Type != typeof(Undefined))
            {
                MethodInfo method = typeof(IReadOnlyDictionary<string, string>).GetMethod("ContainsKey");
                MethodCallExpression contains = Expression.Call(propertyBag, method, property);
                IndexExpression value = Expression.Property(propertyBag, "Item", property);

                // NOTE: Arguments to Expression.Condition need to be of the same type. So we will wrap to QueryValue if it could be a bodyquery

                // Review following cases before making changes here -
                // 1. It is an app property with no conflict => Convert to String and return value and alternative
                // 2. It is a system property with no conflict => Same as case 1. Property bag supplied by caller is sys property
                // 3. It is a Body query with no conflict => ifFalse Expression will be returned. Type is already QueryValue.
                // 4. It looks like a body query but is an app property ($body.propertyname) =>
                //              ifTrue will be evaluated. Just wrap contents to QueryValue so that Expression.Condition does not complain.
                // 5. Body Query and a conflicting app property => App property wins
                // 6. Body Query escaped and a conflicting app property => Body Query wins
                Expression ifTrue = isBodyQuery ? Expression.Convert(value, typeof(QueryValue)) : Expression.Convert(value, typeof(string));
                Expression ifFalse = isBodyQuery ? alternative : Expression.Convert(alternative, typeof(string));

                expression = Expression.Condition(
                    contains,
                    ifTrue,
                    ifFalse);
            }
            else
            {
                expression = UndefinedExpression;
            }

            return expression;
        }

19 View Source File : SyntaxTreeToQueryConvertor.cs
License : MIT License
Project Creator : alirezanet

private static LambdaExpression? GenerateExpression(
         Expression body,
         ParameterExpression parameter,
         ValueExpressionSyntax valueExpression,
         SyntaxNode op,
         bool allowNullSearch,
         Func<string, object>? convertor)
      {
         // Remove the boxing for value types
         if (body.NodeType == ExpressionType.Convert) body = ((UnaryExpression)body).Operand;

         object? value = valueExpression.ValueToken.Text;

         // execute user custom Convertor
         if (convertor != null)
            value = convertor.Invoke(valueExpression.ValueToken.Text) ?? null;

         // handle the `null` keyword in value
         if (allowNullSearch && op.Kind is SyntaxKind.Equal or SyntaxKind.NotEqual && value?.ToString() == "null")
            value = null;

         // type fixer
         if (value is not null && body.Type != value.GetType())
         {
            try
            {
               // handle broken guids,  github issue #2
               if (body.Type == typeof(Guid) && !Guid.TryParse(value!.ToString(), out _)) value = Guid.NewGuid().ToString();

               var converter = TypeDescriptor.GetConverter(body.Type);
               value = converter.ConvertFromString(value!.ToString())!;
            }
            catch (FormatException)
            {
               // return no records in case of any exception in formatting
               return Expression.Lambda(Expression.Constant(false), parameter); // q => false
            }
         }

         // handle case-Insensitive search 
         if (value is not null && valueExpression.IsCaseInsensitive
                               && op.Kind is not SyntaxKind.GreaterThan
                               && op.Kind is not SyntaxKind.LessThan
                               && op.Kind is not SyntaxKind.GreaterOrEqualThan
                               && op.Kind is not SyntaxKind.LessOrEqualThan)
         {
            value = value.ToString().ToLower();
            body = Expression.Call(body, GetToLowerMethod());
         }

         Expression be;

         // use string.Compare instead of operators if value and field are both strings
         var areBothStrings = body.Type == typeof(string) && value?.GetType() == typeof(string);

         switch (op.Kind)
         {
            case SyntaxKind.Equal when !valueExpression.IsNullOrDefault:
               be = Expression.Equal(body, GetValueExpression(body.Type, value));
               break;
            case SyntaxKind.Equal when valueExpression.IsNullOrDefault:
               if (body.Type == typeof(string))
                  be = Expression.Call(null, GetIsNullOrEmptyMethod(), body);
               else
               {
                  var canBeNull = !body.Type.IsValueType || (Nullable.GetUnderlyingType(body.Type) != null);
                  be = canBeNull
                     ? Expression.OrElse(Expression.Equal(body, Expression.Constant(null)), Expression.Equal(body, Expression.Default(body.Type)))
                     : Expression.Equal(body, Expression.Default(body.Type));
               }

               break;
            case SyntaxKind.NotEqual when !valueExpression.IsNullOrDefault:
               be = Expression.NotEqual(body, GetValueExpression(body.Type, value));
               break;
            case SyntaxKind.NotEqual when valueExpression.IsNullOrDefault:
               if (body.Type == typeof(string))
                  be = Expression.Not(Expression.Call(null, GetIsNullOrEmptyMethod(), body));
               else
               {
                  var canBeNull = !body.Type.IsValueType || (Nullable.GetUnderlyingType(body.Type) != null);
                  be = canBeNull
                     ? Expression.AndAlso(Expression.NotEqual(body, Expression.Constant(null)),
                        Expression.NotEqual(body, Expression.Default(body.Type)))
                     : Expression.NotEqual(body, Expression.Default(body.Type));
               }

               break;
            case SyntaxKind.GreaterThan when areBothStrings == false:
               be = Expression.GreaterThan(body, GetValueExpression(body.Type, value));
               break;
            case SyntaxKind.LessThan when areBothStrings == false:
               be = Expression.LessThan(body, GetValueExpression(body.Type, value));
               break;
            case SyntaxKind.GreaterOrEqualThan when areBothStrings == false:
               be = Expression.GreaterThanOrEqual(body, GetValueExpression(body.Type, value));
               break;
            case SyntaxKind.LessOrEqualThan when areBothStrings == false:
               be = Expression.LessThanOrEqual(body, GetValueExpression(body.Type, value));
               break;
            case SyntaxKind.GreaterThan when areBothStrings:
               be = GetGreaterThanExpression(body, valueExpression, value);
               break;
            case SyntaxKind.LessThan when areBothStrings:
               be = GetLessThanExpression(body, valueExpression, value);
               break;
            case SyntaxKind.GreaterOrEqualThan when areBothStrings:
               be = GetGreaterThanOrEqualExpression(body, valueExpression, value);
               break;
            case SyntaxKind.LessOrEqualThan when areBothStrings:
               be = GetLessThanOrEqualExpression(body, valueExpression, value);
               break;
            case SyntaxKind.Like:
               be = Expression.Call(body, GetContainsMethod(), GetValueExpression(body.Type, value));
               break;
            case SyntaxKind.NotLike:
               be = Expression.Not(Expression.Call(body, GetContainsMethod(), GetValueExpression(body.Type, value)));
               break;
            case SyntaxKind.StartsWith:
               if (body.Type != typeof(string))
               {
                  body = Expression.Call(body, GetToStringMethod());
                  be = Expression.Call(body, GetStartWithMethod(), GetValueExpression(body.Type, value?.ToString()));
               }
               else
                  be = Expression.Call(body, GetStartWithMethod(), GetValueExpression(body.Type, value));

               break;
            case SyntaxKind.EndsWith:
               if (body.Type != typeof(string))
               {
                  body = Expression.Call(body, GetToStringMethod());
                  be = Expression.Call(body, GetEndsWithMethod(), GetValueExpression(body.Type, value?.ToString()));
               }
               else
                  be = Expression.Call(body, GetEndsWithMethod(), GetValueExpression(body.Type, value));

               break;
            case SyntaxKind.NotStartsWith:
               if (body.Type != typeof(string))
               {
                  body = Expression.Call(body, GetToStringMethod());
                  be = Expression.Not(Expression.Call(body, GetStartWithMethod(), GetValueExpression(body.Type, value?.ToString())));
               }
               else
                  be = Expression.Not(Expression.Call(body, GetStartWithMethod(), GetValueExpression(body.Type, value)));

               break;
            case SyntaxKind.NotEndsWith:
               if (body.Type != typeof(string))
               {
                  body = Expression.Call(body, GetToStringMethod());
                  be = Expression.Not(Expression.Call(body, GetEndsWithMethod(), GetValueExpression(body.Type, value?.ToString())));
               }
               else
                  be = Expression.Not(Expression.Call(body, GetEndsWithMethod(), GetValueExpression(body.Type, value)));

               break;
            default:
               return null;
         }

         return Expression.Lambda(be, parameter);
      }

19 View Source File : LocalDateTimeRelationalTypeMapping.cs
License : MIT License
Project Creator : ARKlab

public override Expression CustomizeDataReaderExpression(Expression expression)
        {
            return Expression.Call(null, typeof(LocalDateTime).GetRuntimeMethod(nameof(LocalDateTime.FromDateTime), new[] { typeof(DateTime) })
                , expression
                );
        }

19 View Source File : ServiceMethodResolver.cs
License : Apache License 2.0
Project Creator : AmpScm

private MethodCallExpression GetMethodCall(Type fromInterface, MethodInfo methodInfo, object ob, out ParameterExpression[] args)
        {
            List<ParameterExpression> methodArgs = new List<ParameterExpression>();
            foreach (ParameterInfo pi in methodInfo.GetParameters())
            {
                methodArgs.Add(Expression.Parameter(pi.ParameterType, pi.Name));
            }

            args = methodArgs.ToArray();

            return Expression.Call(Expression.Convert(Expression.Constant(ob), fromInterface), methodInfo, (Expression[])args);
        }

19 View Source File : GreedyMetaDynamic.cs
License : MIT License
Project Creator : albahari

private DynamicMetaObject CallMethodNoResult<TBinder> (MethodInfo method, TBinder binder, Expression[] args, Fallback<TBinder> fallback)
				where TBinder : DynamicMetaObjectBinder
			{
				//
				// First, call fallback to do default binding
				// This produces either an error or a call to a .NET member
				//
				DynamicMetaObject fallbackResult = fallback (this, binder, null);
				ParameterExpression callArgs = Expression.Parameter (typeof (object[]), null);
				ReadOnlyCollection<Expression> callArgsValue = GetConvertedArgs (args);

				//
				// Build a new expression like:
				//   if (TryDeleteMember(payload)) { } else { fallbackResult }
				//
				var callDynamic = new DynamicMetaObject (
					Expression.Block (
						new TrueReadOnlyCollection<ParameterExpression> (callArgs),
						new TrueReadOnlyCollection<Expression> (
							Expression.replacedign (callArgs, Expression.NewArrayInit (typeof (object), callArgsValue)),
							Expression.Condition (
								Expression.Call (
									GetLimitedSelf (),
									method,
									BuildCallArgs (
										binder,
										method.Name == "TryInvokeMember", // JJA
										args,
										callArgs,
										null
									)
								),
								Expression.Block (
									ReferenceArgreplacedign (callArgs, args),
									AstUtils.Empty
								),
								fallbackResult.Expression,
								typeof (void)
							)
						)
					),
					GetRestrictions ().Merge (fallbackResult.Restrictions)
				);

				//
				// Now, call fallback again using our new MO as the error
				// When we do this, one of two things can happen:
				//   1. Binding will succeed, and it will ignore our call to
				//      the dynamic method, OR
				//   2. Binding will fail, and it will use the MO we created
				//      above.
				//
				return fallback (this, binder, callDynamic);
			}

19 View Source File : TypeSchema.cs
License : MIT License
Project Creator : azist

private dyn_serialize makeSerialize()
    {
      var _walkArrayWrite = typeof(TypeDescriptor).GetMethod("walkArrayWrite", BindingFlags.NonPublic | BindingFlags.Static);

      var pSchema   = Expression.Parameter(typeof(TypeSchema));
      var pWriter   = Expression.Parameter(typeof(SlimWriter));
      var pTReg     = Expression.Parameter(typeof(TypeRegistry));
      var pRefs     = Expression.Parameter(typeof(RefPool));
      var pInstance = Expression.Parameter(typeof(object));
      var pStreamingContext = Expression.Parameter(typeof(StreamingContext));

      var expressions = new List<Expression>();

      var instance = Expression.Variable(Type, "instance");

      expressions.Add( Expression.replacedign(instance, Expression.Convert(pInstance, Type)));


      if (IsPrimitive)
      {
        expressions.Add(  Expression.Call(pWriter,
                                Format.GetWriteMethodForType(Type),
                                instance) );
      }
      else if (IsArray)
      {
          var elmType = Type.GetElementType();

          if (Format.IsTypeSupported(elmType))//array element type
          {  //spool whole array into writer using primitive types

            var pElement = Expression.Parameter(typeof(object));
            expressions.Add( Expression.Call(_walkArrayWrite,
                                              instance,
                                              Expression.Lambda(Expression.Call(pWriter,
                                                                              Format.GetWriteMethodForType(elmType),
                                                                              Expression.Convert(pElement, elmType)), pElement)
                                            )
              );
          }
          else
          {  //spool whole array using TypeSchema because objects may change type
            var pElement = Expression.Parameter(typeof(object));

            if (!elmType.IsValueType)//reference type
              expressions.Add( Expression.Call(_walkArrayWrite,
                                              instance,
                                              Expression.Lambda(Expression.Call(pSchema,
                                                                typeof(TypeSchema).GetMethod("writeRefMetaHandle"),
                                                                pWriter,
                                                                pTReg,
                                                                pRefs,
                                                                Expression.Convert( pElement, typeof(object) ),
                                                                pStreamingContext),
                                                                pElement)
                                            )
                            );
            else
              expressions.Add( Expression.Call(_walkArrayWrite,
                                              instance,
                                              Expression.Lambda(Expression.Call(pSchema,
                                                                typeof(TypeSchema).GetMethod("Serialize"),
                                                                pWriter,
                                                                pTReg,
                                                                pRefs,
                                                                pElement,
                                                                pStreamingContext,
                                                                Expression.Constant(elmType)//valueType
                                                                ), pElement)
                                      )
              );
          }
      }
      else
      {
        foreach(var field in Fields)
        {
          Expression expr = null;
          Type t = field.FieldType;

          if (Format.IsTypeSupported(t))
          {
            expr = Expression.Call(pWriter,
                                    Format.GetWriteMethodForType(t),
                                    Expression.Field(instance, field));
          }
          else
          if (t.IsEnum)
          {
            expr = Expression.Call(pWriter,
                                    Format.GetWriteMethodForType(typeof(int)),
                                    Expression.Convert(Expression.Field(instance, field), typeof(int)));

          }
          else // complex type ->  struct or reference
          {
            if (!t.IsValueType)//reference type -> write metahandle
            {
              expr = Expression.Call(pSchema,
                                        typeof(TypeSchema).GetMethod("writeRefMetaHandle"),
                                        pWriter,
                                        pTReg,
                                        pRefs,
                                        Expression.Convert( Expression.Field(instance, field), typeof(object) ),
                                        pStreamingContext);
            }
            else
            expr = Expression.Call(pSchema,
                                    typeof(TypeSchema).GetMethod("Serialize"),
                                    pWriter,
                                    pTReg,
                                    pRefs,
                                    Expression.Convert( Expression.Field(instance, field), typeof(object) ),
                                    pStreamingContext,
                                    Expression.Constant(field.FieldType));//valueType

          }

          expressions.Add(expr);
        }//foreach
        }

      var body = Expression.Block(new ParameterExpression[]{instance}, expressions);

      return Expression.Lambda<dyn_serialize>(body, pSchema, pWriter, pTReg, pRefs, pInstance, pStreamingContext).Compile();
    }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_Reader_SeekAndSkipObject(Expression len)
        {
            return Expression.Call(Par_Reader, typeof(BssomReader).GetMethod(nameof(BssomReader.SeekAndSkipObject), instanceAndInternalFlag), len);
        }

19 View Source File : RecurringJobRegistry.cs
License : MIT License
Project Creator : bamotav

public void Register(string recurringJobId, MethodInfo method, string cron, TimeZoneInfo timeZone, string queue)
        {
            if (recurringJobId == null) throw new ArgumentNullException(nameof(recurringJobId));
            if (method == null) throw new ArgumentNullException(nameof(method));
            if (cron == null) throw new ArgumentNullException(nameof(cron));
            if (timeZone == null) throw new ArgumentNullException(nameof(timeZone));
            if (queue == null) throw new ArgumentNullException(nameof(queue));

            var parameters = method.GetParameters();

            Expression[] args = new Expression[parameters.Length];

            for (int i = 0; i < parameters.Length; i++)
            {
                args[i] = Expression.Default(parameters[i].ParameterType);
            }

            var x = Expression.Parameter(method.DeclaringType, "x");

            var methodCall = method.IsStatic ? Expression.Call(method, args) : Expression.Call(x, method, args);

            var addOrUpdate = Expression.Call(
                typeof(RecurringJob),
                nameof(RecurringJob.AddOrUpdate),
                new Type[] { method.DeclaringType },
                new Expression[]
                {
                    Expression.Constant(recurringJobId),
                    Expression.Lambda(methodCall, x),
                    Expression.Constant(cron),
                    Expression.Constant(timeZone),
                    Expression.Constant(queue)
                });

            Expression.Lambda(addOrUpdate).Compile().DynamicInvoke();
        }

19 View Source File : Serializer.cs
License : MIT License
Project Creator : 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 View Source File : InstantRelationalTypeMapping.cs
License : MIT License
Project Creator : ARKlab

public override Expression CustomizeDataReaderExpression(Expression expression)
        {
            var specifyKind = Expression.Call(null, 
                typeof(DateTime).GetRuntimeMethod(nameof(DateTime.SpecifyKind), new[] { typeof(DateTime), typeof(DateTimeKind) }),
                expression, 
                Expression.Constant(DateTimeKind.Utc, typeof(DateTimeKind))
                );

            return Expression.Call(null, typeof(Instant).GetRuntimeMethod(nameof(Instant.FromDateTimeUtc), new[] { typeof(DateTime) })
                , specifyKind
                );
        }

19 View Source File : DynamicLinqFactory.cs
License : Apache License 2.0
Project Creator : anjoy8

public static Expression Call(this Expression instance, string methodName, params Expression[] arguments)
        {
            if(instance.Type == typeof(string))
                return Expression.Call(instance, instance.Type.GetMethod(methodName,new Type[] { typeof(string)}), arguments);  //修复string contains 出现的问题 Ambiguous match found.
            else
                return Expression.Call(instance, instance.Type.GetMethod(methodName), arguments);
        }

19 View Source File : GreedyMetaDynamic.cs
License : MIT License
Project Creator : albahari

private DynamicMetaObject BuildCallMethodWithResult<TBinder> (MethodInfo method, TBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback<TBinder> fallbackInvoke)
				where TBinder : DynamicMetaObjectBinder
			{
				if (!IsOverridden (method))
				{
					return fallbackResult;
				}

				//
				// Build a new expression like:
				// {
				//   object result;
				//   TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult
				// }
				//
				ParameterExpression result = Expression.Parameter (typeof (object), null);
				ParameterExpression callArgs = method != DynamicObject_TryBinaryOperation ? Expression.Parameter (typeof (object[]), null) : Expression.Parameter (typeof (object), null);
				ReadOnlyCollection<Expression> callArgsValue = GetConvertedArgs (args);

				var resultMO = new DynamicMetaObject (result, BindingRestrictions.Empty);

				// Need to add a conversion if calling TryConvert
				if (binder.ReturnType != typeof (object))
				{
					Debug.replacedert (binder is ConvertBinder && fallbackInvoke == null);

					UnaryExpression convert = Expression.Convert (resultMO.Expression, binder.ReturnType);
					// will always be a cast or unbox
					Debug.replacedert (convert.Method == null);


					// Prepare a good exception message in case the convert will fail
					// JJA - we don't have access to the Strings type:
					//string convertFailed = System.Linq.Expressions.Strings.DynamicObjectResultNotreplacedignable (
					//	"{0}",
					//	this.Value.GetType(),
					//	binder.GetType(),
					//	binder.ReturnType
					//);				
					string convertFailed = $"Dynamic conversion failed: Could not convert type '{Value.WrappedType}' to '{binder.ReturnType}'.";

					Expression condition;
					// If the return type can not be replacedigned null then just check for type replacedignability otherwise allow null.
					if (binder.ReturnType.IsValueType && Nullable.GetUnderlyingType (binder.ReturnType) == null)
					{
						condition = Expression.TypeIs (resultMO.Expression, binder.ReturnType);
					}
					else
					{
						condition = Expression.OrElse (
										Expression.Equal (resultMO.Expression, AstUtils.Null),
										Expression.TypeIs (resultMO.Expression, binder.ReturnType));
					}

					Expression checkedConvert = Expression.Condition (
						condition,
						convert,
						Expression.Throw (
							Expression.New (
								InvalidCastException_Ctor_String,
								new TrueReadOnlyCollection<Expression> (
									Expression.Call (
										String_Format_String_ObjectArray,
										Expression.Constant (convertFailed),
										Expression.NewArrayInit (
											typeof (object),
											new TrueReadOnlyCollection<Expression> (
												Expression.Condition (
													Expression.Equal (resultMO.Expression, AstUtils.Null),
													Expression.Constant ("null"),
													Expression.Call (
														resultMO.Expression,
														Object_GetType
													),
													typeof (object)
												)
											)
										)
									)
								)
							),
							binder.ReturnType
						),
						binder.ReturnType
					);

					resultMO = new DynamicMetaObject (checkedConvert, resultMO.Restrictions);
				}

				if (fallbackInvoke != null)
				{
					resultMO = fallbackInvoke (this, binder, resultMO);
				}

				var callDynamic = new DynamicMetaObject (
					Expression.Block (
						new TrueReadOnlyCollection<ParameterExpression> (result, callArgs),
						new TrueReadOnlyCollection<Expression> (
							method != DynamicObject_TryBinaryOperation ? Expression.replacedign (callArgs, Expression.NewArrayInit (typeof (object), callArgsValue)) : Expression.replacedign (callArgs, callArgsValue[0]),
							Expression.Condition (
								Expression.Call (
									GetLimitedSelf (),
									method,
									BuildCallArgs (
										binder,
										method.Name == "TryInvokeMember", // JJA
										args,
										callArgs,
										result
									)
								),
								Expression.Block (
									method != DynamicObject_TryBinaryOperation ? ReferenceArgreplacedign (callArgs, args) : AstUtils.Empty,
									resultMO.Expression
								),
								fallbackResult.Expression,
								binder.ReturnType
							)
						)
					),
					GetRestrictions ().Merge (resultMO.Restrictions).Merge (fallbackResult.Restrictions)
				);
				return callDynamic;
			}

19 View Source File : ModuleInfo.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

private static CommandInfo.CommandHandlerDelegate BuildCommandHandler(Type type, MethodInfo method)
        {
            var moduleParameter = Expression.Parameter(typeof(object));
            var convertedModuleParameter = Expression.Convert(moduleParameter, type);
            var commandParameter = Expression.Parameter(typeof(ICommand));
            var loggerParameter = Expression.Parameter(typeof(ILogger));
            var ctParameter = Expression.Parameter(typeof(CancellationToken));

            var parameters = method.GetParameters().Select(x => x.ParameterType).ToList();
            MethodCallExpression call;
            if (parameters.SequenceEqual(new[] { typeof(ICommand), typeof(ILogger), typeof(CancellationToken) }))
                call = Expression.Call(convertedModuleParameter, method, commandParameter, loggerParameter, ctParameter);
            if (parameters.SequenceEqual(new[] { typeof(ICommand), typeof(ILogger) }))
                call = Expression.Call(convertedModuleParameter, method, commandParameter, loggerParameter);
            else if (parameters.SequenceEqual(new[] { typeof(ICommand), typeof(CancellationToken) }))
                call = Expression.Call(convertedModuleParameter, method, commandParameter, ctParameter);
            else if (parameters.SequenceEqual(new[] { typeof(ICommand) }))
                call = Expression.Call(convertedModuleParameter, method, commandParameter);
            else
                throw new ArgumentException($"Invalid method signature of command {method.Name} on type {type}.");

            var lambda = Expression.Lambda<CommandInfo.CommandHandlerDelegate>(call, moduleParameter, commandParameter, loggerParameter, ctParameter);

            return lambda.Compile();
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_WriteArray3Header(int count)
        {
            return Expression.Call(Par_Writer, Type_Writer_WriteArray3Header, Expression.Constant(count));
        }

19 View Source File : StreamerFormats.cs
License : MIT License
Project Creator : azist

private Action<TWriter, object> compileWriter(Type tp, MethodInfo miWrite)
          {
              var pWritingStreamer = Expression.Parameter(typeof(TWriter));
              var pValue = Expression.Parameter(typeof(object));
              return Expression.Lambda<Action<TWriter, object>>(
                              Expression.Call(pWritingStreamer, miWrite,
                                                Expression.Convert( pValue, tp)
                                              ),
                              pWritingStreamer, pValue).Compile();
          }

19 View Source File : DelegateGenerator.cs
License : MIT License
Project Creator : albyho

protected override Expression VisitConstant(ConstantExpression c)
        {
            Expression exp = Expression.Call(
                _parametersExpression,
                IndexerInfo,
                Expression.Constant(_parameterCount++));
            return c.Type == typeof(object) ? exp : Expression.Convert(exp, c.Type);
        }

19 View Source File : DocumentQueryable.cs
License : MIT License
Project Creator : Azure

internal static IQueryable<TResult> replacedQL<TSource, TResult>(
            this IOrderedQueryable<TSource> source,
            SqlQuerySpec querySpec)
        {
            if (querySpec == null)
            {
                throw new ArgumentNullException("querySpec");
            }

            if (string.IsNullOrEmpty(querySpec.QueryText))
            {
                throw new ArgumentException("querySpec.QueryText");
            }
#if !(NETSTANDARD15 || NETSTANDARD16)
            return source.Provider.CreateQuery<TResult>(Expression.Call(null, ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(
                new Type[]
                {
                    typeof(TSource),
                    typeof(TResult)
                }), new Expression[]
                {
                    source.Expression,
                    Expression.Constant(querySpec)
                }));
#else
            return source.Provider.CreateQuery<TResult>(Expression.Call(null,
                GetMethodInfoOf(() => DoreplacedentQueryable.replacedQL(
                    default(IOrderedQueryable<TSource>),
                    default(SqlQuerySpec))),
                    new Expression[]
                    {
                        source.Expression,
                        Expression.Constant(querySpec)
                    }));
#endif
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_GetFormatterWithVerify(Expression resolver, Type formatterType)
        {
            return Expression.Call(null, typeof(FormatterResolverExtensions).GetMethod(nameof(FormatterResolverExtensions.GetFormatterWithVerify), new Type[] { typeof(IFormatterResolver) }).MakeGenericMethod(formatterType), resolver);
        }

19 View Source File : DocumentMetadata.cs
License : MIT License
Project Creator : Azure-Samples

public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value)
            {
                if (DoreplacedentDynamicMetaObject.IsResourceProperty(binder.Name))
                {
                    return base.BindSetMember(binder, value); //Base will bind it statically.
                }

                //For all non-resource property, thunk the call to this.SetProperty method in Doreplacedent.
                string methodName = "SetProperty";

                // setup the binding restrictions.
                BindingRestrictions restrictions = BindingRestrictions.GetTypeRestriction(this.Expression, this.LimitType);

                //Two params, Name & Value.
                Expression[] args = new Expression[2];
                args[0] = Expression.Constant(binder.Name);
                args[1] = Expression.Convert(value.Expression, typeof(object));

                // Setup the 'this' reference
                Expression self = Expression.Convert(this.Expression, this.LimitType);

                // Setup the method call expression
                Expression methodCall = Expression.Call(self,
                    typeof(DoreplacedentMetadata).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance),
                    args);

                // Create a meta object to invoke Set later:
                DynamicMetaObject setProperty = new DynamicMetaObject(
                    methodCall,
                    restrictions);
                // return that dynamic object
                return setProperty;
            }

19 View Source File : RecurringJobRegistry.cs
License : MIT License
Project Creator : AlphaYu

public void Register(string recurringJobId, MethodInfo method, string cron, TimeZoneInfo timeZone, string queue)
		{
			if (recurringJobId == null) throw new ArgumentNullException(nameof(recurringJobId));
			if (method == null) throw new ArgumentNullException(nameof(method));
			if (cron == null) throw new ArgumentNullException(nameof(cron));
			if (timeZone == null) throw new ArgumentNullException(nameof(timeZone));
			if (queue == null) throw new ArgumentNullException(nameof(queue));

			var parameters = method.GetParameters();

			Expression[] args = new Expression[parameters.Length];

			for (int i = 0; i < parameters.Length; i++)
			{
				args[i] = Expression.Default(parameters[i].ParameterType);
			}

			var x = Expression.Parameter(method.DeclaringType, "x");

			var methodCall = method.IsStatic ? Expression.Call(method, args) : Expression.Call(x, method, args);

			var addOrUpdate = Expression.Call(
				typeof(RecurringJob),
				nameof(RecurringJob.AddOrUpdate),
				new Type[] { method.DeclaringType },
				new Expression[]
				{
					Expression.Constant(recurringJobId),
					Expression.Lambda(methodCall, x),
					Expression.Constant(cron),
					Expression.Constant(timeZone),
					Expression.Constant(queue)
				});

			Expression.Lambda(addOrUpdate).Compile().DynamicInvoke();
		}

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : AlphaYu

public static Action<object, object> GetValueSetter([NotNull] this PropertyInfo @this)
        {
            return ReflectionDictionary.PropertyValueSetters.GetOrAdd(@this, prop =>
            {
                if (!prop.CanWrite)
                    return null;

                var obj = Expression.Parameter(typeof(object), "o");
                var value = Expression.Parameter(typeof(object));

                Debug.replacedert(@this.DeclaringType != null);

                // Note that we are using Expression.Unbox for value types and Expression.Convert for reference types
                var expr =
                    Expression.Lambda<Action<object, object>>(
                        Expression.Call(
                            @this.DeclaringType.IsValueType
                                ? Expression.Unbox(obj, @this.DeclaringType)
                                : Expression.Convert(obj, @this.DeclaringType),
                            @this.GetSetMethod(),
                            Expression.Convert(value, @this.PropertyType)),
                        obj, value);
                return expr.Compile();
            });
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_DateTimeSize()
        {
            return Expression.Call(null, typeof(BssomBinaryPrimitives).GetMethod(nameof(BssomBinaryPrimitives.DateTimeSize)), Field_SizeOption_IsUseStandardDateTime);
        }

19 View Source File : SqlMapper.DapperRowMetaObject.cs
License : MIT License
Project Creator : anet-team

private System.Dynamic.DynamicMetaObject CallMethod(
                MethodInfo method,
                System.Linq.Expressions.Expression[] parameters
                )
            {
                var callMethod = new System.Dynamic.DynamicMetaObject(
                    System.Linq.Expressions.Expression.Call(
                        System.Linq.Expressions.Expression.Convert(Expression, LimitType),
                        method,
                        parameters),
                    System.Dynamic.BindingRestrictions.GetTypeRestriction(Expression, LimitType)
                    );
                return callMethod;
            }

19 View Source File : Admin.cs
License : MIT License
Project Creator : 2881099

async public static Task<bool> Use(HttpContext context, IFreeSql fsql, string requestPathBase, Dictionary<string, Type> dicEnreplacedyTypes) {
			HttpRequest req = context.Request;
			HttpResponse res = context.Response;

			var remUrl = req.Path.ToString().Substring(requestPathBase.Length).Trim(' ', '/').Split('/');
			var enreplacedyName = remUrl.FirstOrDefault();

			if (!string.IsNullOrEmpty(enreplacedyName)) {

				if (dicEnreplacedyTypes.TryGetValue(enreplacedyName, out var enreplacedyType) == false) throw new Exception($"UseFreeAdminLtePreview 错误,找不到实体类型:{enreplacedyName}");

				var tb = fsql.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
				if (tb == null) throw new Exception($"UseFreeAdminLtePreview 错误,实体类型无法映射:{enreplacedyType.FullName}");

				var tpl = _tpl.Value;

				switch (remUrl.ElementAtOrDefault(1)?.ToLower()) {
					case null:
						//首页
						if (true) {
							MakeTemplateFile($"{enreplacedyName}-list.html", Views.List);

							//ManyToOne/OneToOne
							var getlistFilter = new List<(TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
								}
							}

							int.TryParse(req.Query["page"].FirstOrDefault(), out var getpage);
							int.TryParse(req.Query["limit"].FirstOrDefault(), out var getlimit);
							if (getpage <= 0) getpage = 1;
							if (getlimit <= 0) getlimit = 20;

							var getselect = fsql.Select<object>().AsType(enreplacedyType);
							foreach (var getlistF in getlistFilter) {
								var qv = req.Query[getlistF.Item3].ToArray();
								if (qv.Any()) {
									switch (getlistF.Item1.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											getselect.Where(Utils.GetObjectWhereExpressionContains(tb, enreplacedyType, getlistF.Item1.Columns[0].CsName, qv));
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											if (true) {
												var midType = getlistF.Item1.RefMiddleEnreplacedyType;
												var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
												var midISelect = typeof(ISelect<>).MakeGenericType(midType);

												var funcType = typeof(Func<,>).MakeGenericType(typeof(object), typeof(bool));
												var expParam = Expression.Parameter(typeof(object), "a");
												var midParam = Expression.Parameter(midType, "mdtp");

												var anyMethod = midISelect.GetMethod("Any");
												var selectExp = qv.Select(c => Expression.Convert(Expression.Constant(FreeSql.Internal.Utils.GetDataReaderValue(getlistF.Item1.MiddleColumns[1].CsType, c)), getlistF.Item1.MiddleColumns[1].CsType)).ToArray();
												var expLambad = Expression.Lambda<Func<object, bool>>(
													Expression.Call(
														Expression.Call(
															Expression.Call(
																Expression.Constant(fsql),
																typeof(IFreeSql).GetMethod("Select", new Type[0]).MakeGenericMethod(midType)
															),
															midISelect.GetMethod("Where", new[] { typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(midType, typeof(bool))) }),
															Expression.Lambda(
																typeof(Func<,>).MakeGenericType(midType, typeof(bool)),
																Expression.AndAlso(
																	Expression.Equal(
																		Expression.MakeMemberAccess(Expression.TypeAs(expParam, enreplacedyType), tb.Properties[getlistF.Item1.Columns[0].CsName]),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[0].CsName])
																	),
																	Expression.Call(
																		Utils.GetLinqContains(getlistF.Item1.MiddleColumns[1].CsType),
																		Expression.NewArrayInit(
																			getlistF.Item1.MiddleColumns[1].CsType,
																			selectExp
																		),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[1].CsName])
																	)
																),
																midParam
															)
														),
														anyMethod,
														Expression.Default(anyMethod.GetParameters().FirstOrDefault().ParameterType)
													),
													expParam);

												getselect.Where(expLambad);
											}
											continue;
									}
								}
							}

							var getlistTotal = await getselect.CountAsync();
							var getlist = await getselect.Page(getpage, getlimit).ToListAsync();
							var gethashlists = new Dictionary<string, object>[getlist.Count];
							var gethashlistsIndex = 0;
							foreach (var getlisreplacedem in getlist) {
								var gethashlist = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethashlist.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(getlisreplacedem));
								}
								gethashlists[gethashlistsIndex++] = gethashlist;
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["getlist"] = gethashlists;
							options["getlistTotal"] = getlistTotal;
							options["getlistFilter"] = getlistFilter;
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-list.html", options);
							await res.WriteAsync(str);
						}
						return true;
					case "add":
					case "edit":
						//编辑页
						object gereplacedem = null;
						Dictionary<string, object> gethash = null;
						if (req.Query.Any()) {
							gereplacedem = Activator.CreateInstance(enreplacedyType);
							foreach (var getpk in tb.Primarys) {
								var reqv = req.Query[getpk.CsName].ToArray();
								if (reqv.Any())
									fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getpk.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
							}
							gereplacedem = await fsql.Select<object>().AsType(enreplacedyType).WhereDynamic(gereplacedem).FirstAsync();
							if (gereplacedem != null) {
								gethash = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
								}
							}
						}

						if (req.Method.ToLower() == "get") {
							MakeTemplateFile($"{enreplacedyName}-edit.html", Views.Edit);

							//ManyToOne/OneToOne
							var getlistFilter = new Dictionary<string, (TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							var getlistManyed = new Dictionary<string, IEnumerable<string>>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));

										if (gereplacedem != null) {
											var midType = tbref.RefMiddleEnreplacedyType;
											var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
											var manyed = await fsql.Select<object>().AsType(midType)
												.Where(Utils.GetObjectWhereExpression(midTb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]))
												.ToListAsync();
											getlistManyed.Add(prop.Key, manyed.Select(a => fsql.GetEnreplacedyValueWithPropertyName(midType, a, tbref.MiddleColumns[1].CsName).ToString()));
										}
										continue;
								}
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["gethash"] = gethash;
							options["getlistFilter"] = getlistFilter;
							options["getlistManyed"] = getlistManyed;
							options["postaction"] = $"{requestPathBase}restful-api/{enreplacedyName}";
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-edit.html", options);
							await res.WriteAsync(str);

						} else {
							if (gereplacedem == null) {
								gereplacedem = Activator.CreateInstance(enreplacedyType);
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);
								}
							}
							var manySave = new List<(TableRef, object[], List<object>)>();
							if (req.Form.Any()) {
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);

									var reqv = req.Form[getcol.CsName].ToArray();
									if (reqv.Any())
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
								}
								//ManyToMany
								foreach (var prop in tb.Properties) {
									if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
									var tbref = tb.GetTableRef(prop.Key, false);
									if (tbref == null) continue;
									switch (tbref.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											var midType = tbref.RefMiddleEnreplacedyType;
											var mtb = fsql.CodeFirst.GetTableByEnreplacedy(midType);

											var reqv = req.Form[$"mn_{prop.Key}"].ToArray();
											var reqvIndex = 0;
											var manyVals = new object[reqv.Length];
											foreach (var rv in reqv) {
												var miditem = Activator.CreateInstance(midType);
												foreach (var getcol in tb.Columns.Values) {
													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);

													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);
												}
												//fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
												fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[1].CsName, rv);
												manyVals[reqvIndex++] = miditem;
											}
											var molds = await fsql.Select<object>().AsType(midType).Where(Utils.GetObjectWhereExpression(mtb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0])).ToListAsync();
											manySave.Add((tbref, manyVals, molds));
											continue;
									}
								}
							}


							using (var db = fsql.CreateDbContext()) {

								var dbset = db.Set<object>();
								dbset.AsType(enreplacedyType);

								await dbset.AddOrUpdateAsync(gereplacedem);

								foreach (var ms in manySave) {
									var midType = ms.Item1.RefMiddleEnreplacedyType;
									var moldsDic = ms.Item3.ToDictionary(a => fsql.GetEnreplacedyKeyString(midType, a, true));

									var manyset = db.Set<object>();
									manyset.AsType(midType);
									
									foreach (var msVal in ms.Item2) {
										fsql.SetEnreplacedyValueWithPropertyName(midType, msVal, ms.Item1.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
										await manyset.AddOrUpdateAsync(msVal);
										moldsDic.Remove(fsql.GetEnreplacedyKeyString(midType, msVal, true));
									}
									manyset.RemoveRange(moldsDic.Values);
								}

								await db.SaveChangesAsync();
							}
							gethash = new Dictionary<string, object>();
							foreach (var getcol in tb.ColumnsByCs) {
								gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success", data = gethash });
						}
						return true;
					case "del":
						if (req.Method.ToLower() == "post") {

							var delitems = new List<object>();
							var reqv = new List<string[]>();
							foreach(var delpk in tb.Primarys) {
								var reqvs = req.Form[delpk.CsName].ToArray();
								if (reqv.Count > 0 && reqvs.Length != reqv[0].Length) throw new Exception("删除失败,联合主键参数传递不对等");
								reqv.Add(reqvs);
							}
							if (reqv[0].Length == 0) return true;

							using (var ctx = fsql.CreateDbContext()) {
								var dbset = ctx.Set<object>();
								dbset.AsType(enreplacedyType);

								for (var a = 0; a < reqv[0].Length; a++) {
									object delitem = Activator.CreateInstance(enreplacedyType);
									var delpkindex = 0;
									foreach (var delpk in tb.Primarys)
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, delitem, delpk.CsName, reqv[delpkindex++][a]);
									dbset.Remove(delitem);
								}
								await ctx.SaveChangesAsync();
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success" });
							return true;
						}
						break;
				}
			}
			return false;
		}

19 View Source File : BinaryExpression.cs
License : MIT License
Project Creator : ansel86castro

public LinqExpression CreateLike(LinqExpression expleft, LinqExpression expright)
        {
            LiteralExpression lit = (LiteralExpression)right;                        
            var value = lit.Value;
            
            if(string.IsNullOrWhiteSpace(value))
            {
                return LinqExpression.Equal(expleft, expright);
            }

            MethodInfo method = null;
            string compareValue = value;
            if(value[0] == '%' && value[value.Length-1]=='%')
            {
                method = typeof(string).GetMethod("Contains", new Type[] { typeof(string) });
                compareValue = value.Substring(1, value.Length-2);
            }
            else if(value[0] == '%')
            {                
                method = typeof(String).GetMethod("EndsWith", new Type[]{typeof(String)});
                compareValue = value.Substring(1, value.Length-1);
            }
            else if(value[value.Length-1] == '%')
            {                
                method = typeof(String).GetMethod("StartsWith", new Type[] { typeof(String) });
                compareValue = value.Substring(0, value.Length-1);                              
            }

            if(method !=null)
            {
                return LinqExpression.Call(expleft, method, LinqExpression.Constant(compareValue, typeof(String)));
            }

            return LinqExpression.Equal(expleft, expright);
        }

19 View Source File : Engine.cs
License : GNU Affero General Public License v3.0
Project Creator : ankenyr

static System.Linq.Expressions.Expression BuildExpr<T>(Expression r, ParameterExpression param)
        {
            var left = MemberExpression.Property(param, r.MemberName);
            var tProp = typeof(T).GetProperty(r.MemberName).PropertyType;
            ExpressionType tBinary;
            // is the operator a known .NET operator?
            if (ExpressionType.TryParse(r.Operator, out tBinary))
            {
                var right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(r.TargetValue, tProp));
                // use a binary operation, e.g. 'Equal' -> 'u.Age == 15'
                return System.Linq.Expressions.Expression.MakeBinary(tBinary, left, right);
            }

            if (r.Operator == "MatchRegex" || r.Operator == "NotMatchRegex")
            {
                var regex = new Regex(r.TargetValue);
                var method = typeof(Regex).GetMethod("IsMatch", new[] {typeof(string)});
                Debug.replacedert(method != null, nameof(method) + " != null");
                var callInstance = System.Linq.Expressions.Expression.Constant(regex);

                var toStringMethod = tProp.GetMethod("ToString", new Type[0]);
                Debug.replacedert(toStringMethod != null, nameof(toStringMethod) + " != null");
                var methodParam = System.Linq.Expressions.Expression.Call(left, toStringMethod);

                var call = System.Linq.Expressions.Expression.Call(callInstance, method, methodParam);
                if (r.Operator == "MatchRegex") return call;
                if (r.Operator == "NotMatchRegex") return System.Linq.Expressions.Expression.Not(call);
            }

            if (tProp.Name == "String")
            { 
                var method = tProp.GetMethod(r.Operator, new Type[] { typeof(string) });
                var tParam = method.GetParameters()[0].ParameterType;
                var right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(r.TargetValue, tParam));
                // use a method call, e.g. 'Contains' -> 'u.Tags.Contains(some_tag)'
                return System.Linq.Expressions.Expression.Call(left, method, right);
            }
            else { 
                var method = tProp.GetMethod(r.Operator);
                var tParam = method.GetParameters()[0].ParameterType;
                var right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(r.TargetValue, tParam));
                // use a method call, e.g. 'Contains' -> 'u.Tags.Contains(some_tag)'
                return System.Linq.Expressions.Expression.Call(left, method, right);
            }
        }

19 View Source File : ExpressionReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo)
        {
            ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));

            // use reflection for structs
            // expression doesn't correctly set value
            if (propertyInfo.DeclaringType.IsValueType())
            {
                return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(propertyInfo);
            }

            Type instanceType = typeof(T);
            Type valueType = typeof(object);

            ParameterExpression instanceParameter = Expression.Parameter(instanceType, "instance");

            ParameterExpression valueParameter = Expression.Parameter(valueType, "value");
            Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType);

            MethodInfo setMethod = propertyInfo.GetSetMethod(true);

            Expression setExpression;
            if (setMethod.IsStatic)
            {
                setExpression = Expression.Call(setMethod, readValueParameter);
            }
            else
            {
                Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType);

                setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter);
            }

            LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), setExpression, instanceParameter, valueParameter);

            Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
            return compiled;
        }

19 View Source File : LocalDateRelationalTypeMapping.cs
License : MIT License
Project Creator : ARKlab

public override Expression CustomizeDataReaderExpression(Expression expression)
        {
            return Expression.Call(null, typeof(LocalDate).GetRuntimeMethod(nameof(LocalDate.FromDateTime), new[] { typeof(DateTime) })
                , expression
                );
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_WriteRaw(Expression value)
        {
            return Expression.Call(Par_Writer, typeof(BssomWriter).GetMethod(nameof(BssomWriter.WriteRaw), new Type[] { value.Type }), value);
        }

19 View Source File : OffsetDateTimeRelationalTypeMapping.cs
License : MIT License
Project Creator : ARKlab

public override Expression CustomizeDataReaderExpression(Expression expression)
        {
            return Expression.Call(null, 
                typeof(OffsetDateTime).GetRuntimeMethod(nameof(OffsetDateTime.FromDateTimeOffset), new[] { typeof(DateTimeOffset) }),
                expression
                );
        }

19 View Source File : GreedyMetaDynamic.cs
License : MIT License
Project Creator : albahari

private DynamicMetaObject CallMethodReturnLast<TBinder> (MethodInfo method, TBinder binder, Expression[] args, Expression value, Fallback<TBinder> fallback)
				where TBinder : DynamicMetaObjectBinder
			{
				//
				// First, call fallback to do default binding
				// This produces either an error or a call to a .NET member
				//
				DynamicMetaObject fallbackResult = fallback (this, binder, null);

				//
				// Build a new expression like:
				// {
				//   object result;
				//   TrySetMember(payload, result = value) ? result : fallbackResult
				// }
				//

				ParameterExpression result = Expression.Parameter (typeof (object), null);
				ParameterExpression callArgs = Expression.Parameter (typeof (object[]), null);
				ReadOnlyCollection<Expression> callArgsValue = GetConvertedArgs (args);

				var callDynamic = new DynamicMetaObject (
					Expression.Block (
						new TrueReadOnlyCollection<ParameterExpression> (result, callArgs),
						new TrueReadOnlyCollection<Expression> (
							Expression.replacedign (callArgs, Expression.NewArrayInit (typeof (object), callArgsValue)),
							Expression.Condition (
								Expression.Call (
									GetLimitedSelf (),
									method,
									BuildCallArgs (
										binder,
										method.Name == "TryInvokeMember", // JJA
										args,
										callArgs,
										Expression.replacedign (result, Expression.Convert (value, typeof (object)))
									)
								),
								Expression.Block (
									ReferenceArgreplacedign (callArgs, args),
									result
								),
								fallbackResult.Expression,
								typeof (object)
							)
						)
					),
					GetRestrictions ().Merge (fallbackResult.Restrictions)
				);

				//
				// Now, call fallback again using our new MO as the error
				// When we do this, one of two things can happen:
				//   1. Binding will succeed, and it will ignore our call to
				//      the dynamic method, OR
				//   2. Binding will fail, and it will use the MO we created
				//      above.
				//
				return fallback (this, binder, callDynamic);
			}

19 View Source File : SourceInjectedQueryProvider.cs
License : MIT License
Project Creator : AutoMapper

public TResult Execute<TResult>(Expression expression)
        {
            try
            {
                var resultType = typeof(TResult);
                Inspector.StartQueryExecuteInterceptor(resultType, expression);

                var sourceExpression = ConvertDestinationExpressionToSourceExpression(expression);

                var destResultType = typeof(TResult);
                var sourceResultType = CreateSourceResultType(destResultType);

                object destResult = null;

                // case #1: query is a projection from complex Source to complex Destination
                // example: users.UseAsDataSource().For<UserDto>().Where(x => x.Age > 20).ToList()
                if (IsProjection<TDestination>(resultType))
                {
                    // in case of a projection, we need an IQueryable
                    var sourceResult = _dataSource.Provider.CreateQuery(sourceExpression);
                    Inspector.SourceResult(sourceExpression, sourceResult);
                    
                    var queryExpressions = _mapper.ConfigurationProvider.Internal().ProjectionBuilder.GetProjection
                    (
                        sourceResult.ElementType, 
                        typeof(TDestination),
                        _parameters,
                        _membersToExpand.Select
                        (
                            m => new MemberPath
                            (
                                m.Distinct().ToArray()
                            )
                        ).ToArray()
                    );

                    destResult = (IQueryable<TDestination>)GetMapExpressions(queryExpressions).Aggregate(sourceResult, Select);
                }
                // case #2: query is arbitrary ("manual") projection
                // exaple: users.UseAsDataSource().For<UserDto>().Select(user => user.Age).ToList()
                // in case an arbitrary select-statement is enumerated, we do not need to map the expression at all
                // and cann safely return it
                else if (IsProjection(resultType, sourceExpression))
                {
                    var sourceResult = _dataSource.Provider.CreateQuery(sourceExpression);
                    var enumerator = sourceResult.GetEnumerator();
                    var elementType = ElementTypeHelper.GetElementType(typeof(TResult));
                    var constructorInfo = typeof(List<>).MakeGenericType(elementType).GetDeclaredConstructor(new Type[0]);
                    if (constructorInfo != null)
                    {
                        var listInstance = (IList)constructorInfo.Invoke(null);
                        while (enumerator.MoveNext())
                        {
                            listInstance.Add(enumerator.Current);
                        }
                        destResult = listInstance;
                    }
                }
                // case #2: projection to simple type
                // example: users.UseAsDataSource().For<UserDto>().FirstOrDefault(user => user.Age > 20)
                else
                {
                    /* 
                        in case of an element result (so instead of IQueryable<TResult>, just TResult)
                        we still want to support parameters.
                        This is e.g. the case, when the developer writes "UseAsDataSource().For<TResult>().FirstOrDefault(x => ...)
                        To still be able to support parameters, we need to create a query from it. 
                        That said, we need to replace the "element" operator "FirstOrDefault" with a "Where" operator, then apply our "Select" 
                        to map from TSource to TResult and finally re-apply the "element" operator ("FirstOrDefault" in our case) so only
                        one element is returned by our "Execute<TResult>" method. Otherwise we'd get an InvalidCastException

                        * So first we visit the sourceExpression and replace "element operators" with "where"
                        * then we create our mapping expression from TSource to TDestination (select) and apply it
                        * finally, we search for the element expression overload of our replaced "element operator" that has no expression as parameter
                            this expression is not needed anymore as it has already been applied to the "Where" operation and can be safely omitted
                        * when we're done creating our new expression, we call the underlying provider to execute it
                    */

                    // as we need to replace the innermost element of the expression,
                    // we need to traverse it first in order to find the node to replace or potential caveats
                    // e.g. .UseAsDataSource().For<Dto>().Select(e => e.Name).First()
                    //      in the above case we cannot map anymore as the "select" operator overrides our mapping.
                    var searcher = new ReplaceableMethodNodeFinder<TSource>();
                    searcher.Visit(sourceExpression);
                    // provide the replacer with our found MethodNode or <null>
                    var replacer = new MethodNodeReplacer<TSource>(searcher.MethodNode);

                    // default back to simple mapping of object instance for backwards compatibility (e.g. mapping non-nullable to nullable fields)
                    sourceExpression = replacer.Visit(sourceExpression);

                    if (replacer.FoundElementOperator)
                    {
                        /*  in case of primitive element operators (e.g. Any(), Sum()...)
                            we need to map the originating types (e.g. Enreplacedy to Dto) in this query
                            as the final value will be projected automatically
                            
                            == example 1 ==
                            UseAsDataSource().For<Dto>().Any(enreplacedy => enreplacedy.Name == "thename")
                            ..in that case sourceResultType and destResultType would both be "Boolean" which is not mappable for AutoMapper

                            == example 2 ==
                            UseAsDataSource().For<Dto>().FirstOrDefault(enreplacedy => enreplacedy.Name == "thename")
                            ..in this case the sourceResultType would be Enreplacedy and the destResultType Dto, so we can map the query directly
                        */

                        if (sourceResultType == destResultType)// && destResultType.IsPrimitive)
                        {
                            sourceResultType = typeof(TSource);
                            destResultType = typeof(TDestination);
                        }

                        var queryExpressions = _mapper.ConfigurationProvider.Internal().ProjectionBuilder.GetProjection
                        (
                            sourceResultType, 
                            destResultType, 
                            _parameters,
                            _membersToExpand.Select
                            (
                                m => new MemberPath
                                (
                                    m.Distinct().ToArray()
                                )
                            ).ToArray()
                        );
                        // add projection via "select" operator
                        var expr = GetMapExpressions(queryExpressions).Aggregate(sourceExpression, (source, lambda) => Select(source, lambda));
                        // in case an element operator without predicate expression was found (and thus not replaced)
                        var replacementMethod = replacer.ElementOperator;
                        // in case an element operator with predicate expression was replaced
                        if (replacer.ReplacedMethod != null)
                        {
                            // find replacement method that has no more predicates
                            replacementMethod = typeof(Queryable).GetAllMethods()
                                .Single(m => m.Name == replacer.ReplacedMethod.Name
#if NET45
                                            && m.GetParameters().All(p => typeof(Queryable).IsreplacedignableFrom(p.Member.ReflectedType))
#endif
                                            && m.GetParameters().Length == replacer.ReplacedMethod.GetParameters().Length - 1);
                        }

                        // reintroduce element operator that was replaced with a "where" operator to make it queryable
                        expr = Call(null,
                            replacementMethod.MakeGenericMethod(destResultType), expr);

                        destResult = _dataSource.Provider.Execute(expr);
                    }
                    // If there was no element operator that needed to be replaced by "where", just map the result
                    else
                    {
                        var sourceResult = _dataSource.Provider.Execute(sourceExpression);
                        Inspector.SourceResult(sourceExpression, sourceResult);
                        destResult = _mapper.Map(sourceResult, sourceResultType, destResultType);
                    }
                }

                Inspector.DestResult(destResult);

                // implicitly convert types in case of valuetypes which cannot be casted explicitly
                if (typeof(TResult).IsValueType() && destResult?.GetType() != typeof(TResult))
                    return (TResult)System.Convert.ChangeType(destResult, typeof(TResult));

                // if it is not a valuetype, we can safely cast it
                return (TResult)destResult;
            }
            catch (Exception x)
            {
                _exceptionHandler(x);
                throw;
            }
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_Reader_ReadRaw64Ref(Expression remaining)
        {
            return Expression.Call(Par_Reader, typeof(BssomReader).GetMethod(nameof(BssomReader.ReadRaw64), instanceAndInternalFlag, null, new Type[] { typeof(int).MakeByRefType() }, null), remaining);
        }

19 View Source File : SourceInjectedQueryProvider.cs
License : MIT License
Project Creator : AutoMapper

private static IQueryable Select(IQueryable source, LambdaExpression lambda) => source.Provider.CreateQuery(
                Call(
                    null,
                    QueryableSelectMethod.MakeGenericMethod(source.ElementType, lambda.ReturnType),
                    new[] { source.Expression, Expression.Quote(lambda) }
                    )
                );

19 View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho

public static IQueryable<TEnreplacedy> WhereOrStringContains<TEnreplacedy, String>
            (
            this IQueryable<TEnreplacedy> query,
            Expression<Func<TEnreplacedy, String>> selector,
            IEnumerable<String> values
            )
        {
            /*
             * 实现效果:
             * var tags = new[] { "A", "B", "C" };
             * SELECT * FROM [User] Where Name='Test' AND (Tags LIKE '%A%' Or Tags LIKE  '%B%')
             */

            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            if (!values.Any()) return query;

            ParameterExpression p = selector.Parameters.Single();
            var containsExpressions = values.Select(value => (Expression)Expression.Call(selector.Body, typeof(String).GetMethod("Contains", new[] { typeof(String) }), Expression.Constant(value)));
            Expression body = containsExpressions.Aggregate((acreplacedulate, containsExpression) => Expression.Or(acreplacedulate, containsExpression));

            return query.Where(Expression.Lambda<Func<TEnreplacedy, bool>>(body, p));
        }

19 View Source File : ServerHandler.cs
License : MIT License
Project Creator : azist

private Func<object, RequestMsg, object> getFBody(MethodInfo miContract)
            {
               var attr = miContract.GetCustomAttribute(typeof(ArgsMarshallingAttribute)) as ArgsMarshallingAttribute;
               if (attr==null) return null;

               var tReqMsg = attr.RequestMsgType;

                var pInstance = Expression.Parameter(typeof(object));
                var pMsg = Expression.Parameter(typeof(RequestMsg));
                var pCastMsg = Expression.Variable(tReqMsg);

                var exprArgs = new List<Expression>();
                var pars = miContract.GetParameters();
                for(var i=0; i<pars.Length; i++)
                {
                   var par = pars[i];
                   if (par.ParameterType.IsByRef || par.IsOut || par.ParameterType.IsGenericParameter)
                     throw new ServerContractException(StringConsts.GLUE_METHOD_SPEC_UNSUPPORTED_ERROR.Args(miContract.DeclaringType.FullName, miContract.Name, par.Name));

                   var fName = "MethodArg_{0}_{1}".Args(i, par.Name);
                   exprArgs.Add( Expression.Field(pCastMsg, fName) );
                }

               try
               {
                 var isVoid = miContract.ReturnType==typeof(void);

                 if (isVoid)
                 {
                     return Expression.Lambda<Func<object, RequestMsg, object>>(
                                        Expression.Block(
                                                 new ParameterExpression[]{pCastMsg},
                                                 Expression.replacedign(pCastMsg, Expression.Convert( pMsg, tReqMsg ) ),
                                                 Expression.Call( Expression.Convert( pInstance, Contract), miContract, exprArgs.ToArray()),
                                                 Expression.Constant(null, typeof(object))
                                         ),//block
                                         pInstance, pMsg)
                                      .Compile();
                 }
                 else
                 {
                     return Expression.Lambda<Func<object, RequestMsg, object>>(
                                        Expression.Block(
                                                 new ParameterExpression[]{pCastMsg},
                                                 Expression.replacedign(pCastMsg, Expression.Convert( pMsg, tReqMsg ) ),
                                                 Expression.Convert(
                                                    Expression.Call( Expression.Convert( pInstance, Contract), miContract, exprArgs.ToArray()),
                                                    typeof(object)
                                                 )
                                         ),//block
                                         pInstance, pMsg)
                                      .Compile();
                 }
               }
               catch(Exception error)
               {
                 throw new ServerContractException(StringConsts.GLUE_METHOD_ARGS_MARSHAL_LAMBDA_ERROR.Args(miContract.DeclaringType.FullName, miContract.Name, error.ToMessageWithType()), error);
               }
            }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_WriteBuildInType(Expression value)
        {
            return Expression.Call(Par_Writer, typeof(BssomWriter).GetMethod(nameof(BssomWriter.WriteBuildInType), new Type[] { value.Type }), value);
            //return Expression.Call(Par_Writer, typeof(BssomWriter).GetMethod(nameof(BssomWriter.WriteBuildInType), instanceAndInternalFlag, null, new Type[] { value.Type }, null), value);
        }

19 View Source File : TypeSchema.cs
License : MIT License
Project Creator : azist

private dyn_deserialize makeDeserialize()
      {
          var pSchema   = Expression.Parameter(typeof(TypeSchema));
          var pReader   = Expression.Parameter(typeof(SlimReader));
          var pTReg     = Expression.Parameter(typeof(TypeRegistry));
          var pRefs     = Expression.Parameter(typeof(RefPool));
          var pInstance = Expression.Parameter(typeof(object).MakeByRefType());
          var pStreamingContext = Expression.Parameter(typeof(StreamingContext));

          var expressions = new List<Expression>();

          var instance = Expression.Variable(Type, "instance");

          expressions.Add( Expression.replacedign(instance, Expression.Convert(pInstance, Type)));


          if (IsPrimitive)
          {
            expressions.Add( Expression.replacedign
                                      (instance,  Expression.Call(pReader, Format.GetReadMethodForType(Type)) )
                            );

          }
          else if (IsArray)
          {
              var elmType = Type.GetElementType();
              var _walkArrayRead = typeof(TypeDescriptor).GetMethod("walkArrayRead", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(elmType);

              if (Format.IsTypeSupported(elmType))//array element type
              {
                //spool whole array from reader using primitive types
                expressions.Add( Expression.Call(_walkArrayRead,
                                                  instance,
                                                  Expression.Lambda(Expression.Call(pReader, Format.GetReadMethodForType(elmType)))
                                                )
                  );
              }
              else
              {  //spool whole array using TypeSchema because objects may change type
                if (!elmType.IsValueType)//reference type
                  expressions.Add( Expression.Call(_walkArrayRead,
                                                  instance,
                                                  Expression.Lambda(
                                                                  Expression.Convert(
                                                                                    Expression.Call(pSchema,
                                                                                                typeof(TypeSchema).GetMethod("readRefMetaHandle"),
                                                                                                pReader,
                                                                                                pTReg,
                                                                                                pRefs,
                                                                                                pStreamingContext),
                                                                                    elmType
                                                                                    )
                                                                  )
                                                )
                                );
                else
                  expressions.Add( Expression.Call(_walkArrayRead,
                                                  instance,
                                                  Expression.Lambda(
                                                                  Expression.Convert(
                                                                                    Expression.Call(pSchema,
                                                                                            typeof(TypeSchema).GetMethod("Deserialize"),
                                                                                            pReader,
                                                                                            pTReg,
                                                                                            pRefs,
                                                                                            pStreamingContext,
                                                                                            Expression.Constant(elmType)),//valueType
                                                                                  elmType
                                                                                  )
                                                                    )
                                                )
                                );
              }
          }
          else//loop through fields
          {
            foreach(var field in Fields)
            {
                      Expression expr = null;
                      Type t = field.FieldType;

                      Expression replacedignmentTargetExpression;
                      if (field.IsInitOnly)//readonly fields must be replacedigned using reflection
                      {
                        replacedignmentTargetExpression =  Expression.Variable(t, "readonlyFieldValue");
                      }
                      else
                        replacedignmentTargetExpression = Expression.Field(instance, field);


                      if (Format.IsTypeSupported(t))
                      {
                        expr =  Expression.replacedign(
                                                    replacedignmentTargetExpression,
                                                    Expression.Call(pReader, Format.GetReadMethodForType(t))
                                                  );
                      }
                      else
                      if (t.IsEnum)
                      {
                        expr =  Expression.replacedign(
                                                    replacedignmentTargetExpression,
                                                    Expression.Convert(
                                                          Expression.Call(pReader, Format.GetReadMethodForType(typeof(int))),
                                                          field.FieldType
                                                          )
                                                  );
                      }
                      else // complex type ->  struct or reference
                      {
                        if (!t.IsValueType)//reference type -> read metahandle
                        {
                          expr =  Expression.replacedign(
                                                    replacedignmentTargetExpression,

                                                    Expression.Convert(
                                                            Expression.Call(pSchema,
                                                                        typeof(TypeSchema).GetMethod("readRefMetaHandle"),
                                                                        pReader,
                                                                        pTReg,
                                                                        pRefs,
                                                                        pStreamingContext),
                                                        field.FieldType)
                                                    );
                        }
                        else
                        {
                          expr =  Expression.replacedign(
                                                    replacedignmentTargetExpression,
                                                    Expression.Convert(
                                                            Expression.Call(pSchema,
                                                                            typeof(TypeSchema).GetMethod("Deserialize"),
                                                                            pReader,
                                                                            pTReg,
                                                                            pRefs,
                                                                            pStreamingContext,
                                                                            Expression.Constant(field.FieldType)),//valueType
                                                            field.FieldType)
                                                    );
                        }
                      }

                      if (replacedignmentTargetExpression is ParameterExpression)//readonly fields
                      {
                        if (Type.IsValueType)//20150405DKh added
                        {
                          var vBoxed = Expression.Variable(typeof(object), "vBoxed");
                          var box = Expression.replacedign(vBoxed, Expression.TypeAs( instance, typeof(object)));//box the value type
                          var setField =  Expression.Call( Expression.Constant(field),
                                                              typeof(FieldInfo).GetMethod("SetValue", new Type[]{typeof(object), typeof(object)}),
                                                              vBoxed, //on boxed struct
                                                              Expression.Convert( replacedignmentTargetExpression, typeof(object))
                                                        );
                          var swap = Expression.replacedign( instance,  Expression.Unbox(vBoxed, Type));
                          expressions.Add(
                              Expression.Block
                              (new ParameterExpression[]{(ParameterExpression)replacedignmentTargetExpression, vBoxed},
                                box,
                                expr,
                                setField,
                                swap
                              )
                          );
                        }
                        else
                        {

                          var setField =  Expression.Call( Expression.Constant(field),
                                                              typeof(FieldInfo).GetMethod("SetValue", new Type[]{typeof(object), typeof(object)}),
                                                              instance,
                                                              Expression.Convert( replacedignmentTargetExpression, typeof(object))
                                                        );
                          expressions.Add( Expression.Block(new ParameterExpression[]{(ParameterExpression)replacedignmentTargetExpression}, expr, setField) );
                        }
                      }
                      else
                        expressions.Add(expr);
            }//foreach
            }//loop through fields


        expressions.Add( Expression.replacedign(pInstance, Expression.Convert(instance, typeof(object))));

        var body = Expression.Block(new ParameterExpression[]{instance}, expressions);
        return Expression.Lambda<dyn_deserialize>(body, pSchema, pReader, pTReg, pRefs, pInstance, pStreamingContext).Compile();
      }

19 View Source File : ExpressionCompilationTests.cs
License : Apache License 2.0
Project Creator : alexz76

[Fact]
		public void ExpressionTree_TestOne()
		{
			// Arrange
			var companies = new[]
			{
				"Consolidated Messenger", "Alpine Ski House", "Southridge Video", "City Power & Light", "Coho Winery", "Wide World Importers",
				"Graphic Design Insreplacedute", "Adventure Works", "Humongous Insurance", "Woodgrove Bank", "Margie's Travel", "Northwind Traders",
				"Blue Yonder Airlines", "Trey Research", "The Phone Company", "Wingtip Toys", "Lucerne Publishing", "Fourth Coffee"
			}.AsQueryable();

			var expParameter = Expression.Parameter(typeof(string), "company");
			var expArguments = Expression.Constant("ho");
			var expContains = Expression.Call(expParameter, typeof(string).GetMethod(nameof(string.Contains), new[] { typeof(string) }), new[] { expArguments });

			var expContainsIsTrue = Expression.IsTrue(expContains);

			var isTrueCall = Expression.Call(
				typeof(Queryable),
				nameof(Queryable.Where),
				new[] { companies.ElementType },
				companies.Expression,
				Expression.Lambda<Func<string, bool>>(expContainsIsTrue, new[] { expParameter }));

			// Act
			var results = companies.Provider.CreateQuery<string>(isTrueCall);

			// replacedert
			results.Any().Should().BeTrue();
			results.Count().Should().BeGreaterThan(0);
		}

19 View Source File : DocumentQueryable.cs
License : MIT License
Project Creator : Azure

internal static IQueryable<dynamic> replacedQL<TSource>(
            this IOrderedQueryable<TSource> source,
            SqlQuerySpec querySpec)
        {
            if (querySpec == null)
            {
                throw new ArgumentNullException("querySpec");
            }

            if (string.IsNullOrEmpty(querySpec.QueryText))
            {
                throw new ArgumentException("querySpec.QueryText");
            }
#if !(NETSTANDARD15 || NETSTANDARD16)
            return source.Provider.CreateQuery<dynamic>(Expression.Call(null, ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(
                new Type[]
                {
                    typeof(TSource)
                }), new Expression[]
                {
                    source.Expression,
                    Expression.Constant(querySpec)
                }));
#else
            return source.Provider.CreateQuery<dynamic>(Expression.Call(null,
               GetMethodInfoOf(() => DoreplacedentQueryable.replacedQL(
                   default(IOrderedQueryable<TSource>),
                   default(SqlQuerySpec))),
                   new Expression[]
                   {
                        source.Expression,
                        Expression.Constant(querySpec)
                   }));
#endif
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_Reader_TryReadNullWithEnsureArray1BuildInType(byte code)
        {
            return Expression.Call(Par_Reader, typeof(BssomReader).GetMethod(nameof(BssomReader.TryReadNullWithEnsureArray1BuildInType), instanceAndInternalFlag), Expression.Constant(code, typeof(byte)));
        }

19 View Source File : DocumentMetadata.cs
License : MIT License
Project Creator : Azure-Samples

public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
            {
                if (DoreplacedentDynamicMetaObject.IsResourceProperty(binder.Name))
                {
                    return base.BindGetMember(binder); //Base will bind it statically.
                }

                //For all non-resource property, thunk the call to GetProperty method in Doreplacedent.
                string methodName = "GetProperty";

                //Two parameters.
                Expression[] parameters = new Expression[]
                {
                    Expression.Constant(binder.Name), //PropertyName
                    Expression.Constant(binder.ReturnType) //Expected Return Type.
                };

                //Expression: this.
                Expression thisExpression = Expression.Convert(this.Expression, this.LimitType);

                //Expression: this.GetProperty(name, returnType);
                Expression getPropertyExpression = Expression.Call(
                    thisExpression,
                    typeof(DoreplacedentMetadata).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance),
                    parameters);

                DynamicMetaObject getProperty = new DynamicMetaObject(
                    getPropertyExpression,
                    BindingRestrictions.GetTypeRestriction(this.Expression, this.LimitType));

                return getProperty;
            }

19 View Source File : ReflectionExtension.cs
License : MIT License
Project Creator : AlphaYu

[CanBeNull]
        public static Action<object, object> GetValueSetter([NotNull] this PropertyInfo propertyInfo)
        {
            return CacheUtil.PropertyValueSetters.GetOrAdd(propertyInfo, prop =>
            {
                if (!prop.CanWrite)
                    return null;

                var obj = Expression.Parameter(typeof(object), "o");
                var value = Expression.Parameter(typeof(object));

                Debug.replacedert(propertyInfo.DeclaringType != null);

                // Note that we are using Expression.Unbox for value types and Expression.Convert for reference types
                var expr =
                    Expression.Lambda<Action<object, object>>(
                        Expression.Call(
                            propertyInfo.DeclaringType.IsValueType
                                ? Expression.Unbox(obj, propertyInfo.DeclaringType)
                                : Expression.Convert(obj, propertyInfo.DeclaringType),
                            propertyInfo.GetSetMethod(),
                            Expression.Convert(value, propertyInfo.PropertyType)),
                        obj, value);
                return expr.Compile();
            });
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression AsPointerExpression(Expression instance)
        {
            var asPointerMethodType = typeof(ExpressionTreeAux).GetMethod(nameof(ExpressionTreeAux.AsPointer)).MakeGenericMethod(instance.Type);
            return Expression.Call(null, asPointerMethodType, instance);
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_Reader_TryReadNullWithEnsureBuildInType(byte code)
        {
            return Expression.Call(Par_Reader, Type_Reader_TryReadNullWithEnsureBuildInType, Expression.Constant(code, typeof(byte)));
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_Reader_TryReadNullWithEnsureArray1NativeType(byte code)
        {
            return Expression.Call(Par_Reader, typeof(BssomReader).GetMethod(nameof(BssomReader.TryReadNullWithEnsureArray1NativeType), instanceAndInternalFlag), Expression.Constant(code, typeof(byte)));
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_Write(Expression value)
        {
            return Expression.Call(Par_Writer, typeof(BssomWriter).GetMethod(nameof(BssomWriter.Write), instanceAndInternalFlag, null, new Type[] { value.Type }, null), value);
        }

19 View Source File : ExpressionReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpression targetParameterExpression, ParameterExpression argsParameterExpression)
        {
            ParameterInfo[] parametersInfo = method.GetParameters();

            Expression[] argsExpression = new Expression[parametersInfo.Length];
            IList<ByRefParameter> refParameterMap = new List<ByRefParameter>();

            for (int i = 0; i < parametersInfo.Length; i++)
            {
                ParameterInfo parameter = parametersInfo[i];
                Type parameterType = parameter.ParameterType;
                bool isByRef = false;
                if (parameterType.IsByRef)
                {
                    parameterType = parameterType.GetElementType();
                    isByRef = true;
                }

                Expression indexExpression = Expression.Constant(i);

                Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression);

                Expression argExpression;

                if (parameterType.IsValueType())
                {
                    BinaryExpression ensureValueTypeNotNull = Expression.Coalesce(paramAccessorExpression, Expression.New(parameterType));

                    argExpression = EnsureCastExpression(ensureValueTypeNotNull, parameterType);
                }
                else
                {
                    argExpression = EnsureCastExpression(paramAccessorExpression, parameterType);
                }

                if (isByRef)
                {
                    ParameterExpression variable = Expression.Variable(parameterType);
                    refParameterMap.Add(new ByRefParameter
                    {
                        Value = argExpression,
                        Variable = variable,
                        IsOut = parameter.IsOut
                    });

                    argExpression = variable;
                }

                argsExpression[i] = argExpression;
            }

            Expression callExpression;
            if (method.IsConstructor)
            {
                callExpression = Expression.New((ConstructorInfo)method, argsExpression);
            }
            else if (method.IsStatic)
            {
                callExpression = Expression.Call((MethodInfo)method, argsExpression);
            }
            else
            {
                Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType);

                callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression);
            }

            if (method is MethodInfo)
            {
                MethodInfo m = (MethodInfo)method;
                if (m.ReturnType != typeof(void))
                {
                    callExpression = EnsureCastExpression(callExpression, type);
                }
                else
                {
                    callExpression = Expression.Block(callExpression, Expression.Constant(null));
                }
            }
            else
            {
                callExpression = EnsureCastExpression(callExpression, type);
            }

            if (refParameterMap.Count > 0)
            {
                IList<ParameterExpression> variableExpressions = new List<ParameterExpression>();
                IList<Expression> bodyExpressions = new List<Expression>();
                foreach (ByRefParameter p in refParameterMap)
                {
                    if (!p.IsOut)
                    {
                        bodyExpressions.Add(Expression.replacedign(p.Variable, p.Value));
                    }

                    variableExpressions.Add(p.Variable);
                }

                bodyExpressions.Add(callExpression);

                callExpression = Expression.Block(variableExpressions, bodyExpressions);
            }

            return callExpression;
        }

19 View Source File : ExpressionBuilder.cs
License : MIT License
Project Creator : ansel86castro

public IQueryable<T> OrderBy(IQueryable<T> query, string expression)
        {
            var method = typeof(Queryable).GetMember("OrderBy")[0] as MethodInfo;
            var methodDesc = typeof(Queryable).GetMember("OrderByDescending")[0] as MethodInfo;


            var thenBy = typeof(Queryable).GetMember("ThenBy")[0] as MethodInfo;
            var thenByDesc = typeof(Queryable).GetMember("ThenByDescending")[0] as MethodInfo;

            Expression current = Parameter;
            while (current != null && !(current is ParameterExpression))
            {
                current = ((MemberExpression)current).Expression;
            }

            var parts = expression.Split(',');
            IQueryable<T> ordered = query;

            var index = 0;

            QueryParser parser = new QueryParser();

            foreach (var part in parts)
            {
                var value = part.Trim();
                string property;
                bool descend = false;
                if (value.Contains(' '))
                {
                    var split = value.Split(' ');
                    descend = split[1].Trim().ToLowerInvariant() == "desc";
                    property = split[0].Trim();
                }
                else
                {
                    property = value;
                }


                var astExp = parser.Parse(property);

                astExp.CheckSemantic(this);
                Expression exp = astExp.GenerateLinqExpression(this);

                MethodInfo orderByMethod;
                if (index == 0)
                {
                    orderByMethod = descend ? methodDesc : method;
                }
                else
                {
                    orderByMethod = descend ? thenByDesc : thenBy;
                }
                index++;

                var lambda = Expression.Lambda(exp, (ParameterExpression)current);
                ordered = ordered.Provider.CreateQuery<T>(Expression.Call(null, orderByMethod.MakeGenericMethod(new Type[] { typeof(T), exp.Type }), new Expression[] { ordered.Expression, Expression.Quote(lambda) }));

            }
            return ordered;
        }

See More Examples