System.Linq.Expressions.Expression.Lambda(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])

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

2399 Examples 7

19 View Source File : DataContext.cs
License : MIT License
Project Creator : Accelerider

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

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

19 View Source File : MapController.cs
License : MIT License
Project Creator : Adoxio

private static Expression<Func<TParameter, bool>> ContainsPropertyValueEqual<TParameter>(string crmPropertyName, IEnumerable<Guid> values)
		{
			var parameterType = typeof(TParameter);

			var parameter = Expression.Parameter(parameterType, parameterType.Name.ToLowerInvariant());

			var expression = ContainsPropertyValueEqual(crmPropertyName, values, parameter);

			return Expression.Lambda<Func<TParameter, bool>>(expression, parameter);
		}

19 View Source File : QueryableExtension.cs
License : GNU General Public License v3.0
Project Creator : 2dust

static Expression<Func<T, TProp>> _GetLamba<T, TProp>(PropertyInfo memberProperty)
        {
            if (memberProperty.PropertyType != typeof(TProp)) throw new Exception();

            var thisArg = Expression.Parameter(typeof(T));
            var lamba = Expression.Lambda<Func<T, TProp>>(Expression.Property(thisArg, memberProperty), thisArg);

            return lamba;
        }

19 View Source File : Remute.cs
License : MIT License
Project Creator : ababik

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

            var parameterResolvers = new ParameterResolver[parameters.Length];

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

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

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

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

            return parameterResolvers;
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : 71

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

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

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

public static Expression<Func<object, bool>> GetObjectWhereExpression(TableInfo tb, Type enreplacedyType, string csName, object constValue) {
			var mwhereParamExp = Expression.Parameter(typeof(object), "a");
			var mwhereExp = Expression.Lambda<Func<object, bool>>(
				Expression.Equal(
					Expression.MakeMemberAccess(
						Expression.TypeAs(mwhereParamExp, enreplacedyType),
						tb.Properties[csName]
					),
					Expression.Constant(constValue)
				),
				mwhereParamExp
			);
			return mwhereExp;
		}

19 View Source File : IssueForumDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public virtual IEnumerable<IIssue> SelectIssues(int startRowIndex = 0, int maximumRows = -1)
		{
			if (startRowIndex < 0)
			{
				throw new ArgumentException("Value must be a positive integer.", "startRowIndex");
			}

			if (maximumRows == 0)
			{
				return new IIssue[] { };
			}

			var serviceContext = Dependencies.GetServiceContext();

			var includeUnapprovedIssues = TryreplacedertIssuePreviewPermission(serviceContext);

			var query = serviceContext.CreateQuery("adx_issue")
				.Where(issue => issue.GetAttributeValue<EnreplacedyReference>("adx_issueforumid") == IssueForum
					&& issue.GetAttributeValue<OptionSetValue>("statecode") != null && issue.GetAttributeValue<OptionSetValue>("statecode").Value == 0);

			if (!includeUnapprovedIssues)
			{
				query = query.Where(issue => issue.GetAttributeValue<bool?>("adx_approved").GetValueOrDefault(false));
			}

			if (Priority.HasValue)
			{
				query = query.Where(issue => issue.GetAttributeValue<OptionSetValue>("adx_priority") != null && issue.GetAttributeValue<OptionSetValue>("adx_priority").Value == Priority.Value);
			}

			if (Status.Any())
			{
				var param = Expression.Parameter(typeof(Enreplacedy), "issue");

				var left =
					Expression.Call(
						param,
						"GetAttributeValue",
						new[] { typeof(int) },
						Expression.Constant("statuscode"));

				var statusEquals = Status.Aggregate<int, Expression>(null, (current, status) =>
					current == null
						? Expression.Equal(left, Expression.Constant(status))
						: Expression.OrElse(current, Expression.Equal(left, Expression.Constant(status))));

				var statusPredicate = Expression.Lambda(statusEquals, param) as Expression<Func<Enreplacedy, bool>>;

				query = query.Where(statusPredicate);
			}

			query = query.OrderByDescending(issue => issue.GetAttributeValue<DateTime?>("adx_date"));

			if (startRowIndex > 0)
			{
				query = query.Skip(startRowIndex);
			}

			if (maximumRows > 0)
			{
				query = query.Take(maximumRows);
			}

			return new IssueFactory(serviceContext, Dependencies.GetHttpContext()).Create(query);
		}

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

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

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

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

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

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

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

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

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

19 View Source File : Serializer.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

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

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

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

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

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

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

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

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

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

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

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

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

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

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

19 View Source File : Remute.cs
License : MIT License
Project Creator : ababik

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

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

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

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

19 View Source File : InputCheckboxMultipleWithChildren.cs
License : MIT License
Project Creator : Aaltuj

protected static void RenderChildren(RenderTreeBuilder builder,
            int index,
            object dataContext,
            string fieldIdentifier,
            Type typeOfChildToRender)
        {
            builder.AddAttribute(index++, nameof(ChildContent),
               new RenderFragment(_builder =>
               {

                   // when type is a enum present them as an <option> element 
                   // by leveraging the component InputSelectOption
                   var values = FormElementReference<ValueReferences>.GetValue(dataContext, fieldIdentifier);
                   foreach (var val in values)
                   {
                       var _index = 0;

                       //  Open the InputSelectOption component
                       _builder.OpenComponent(_index++, typeOfChildToRender);

                       // Set the value of the enum as a value and key parameter
                       _builder.AddAttribute(_index++, nameof(VxInputCheckbox.Value), val.Value);

                       // Create the handler for ValueChanged. This wil update the model instance with the input
                       _builder.AddAttribute(_index++, nameof(ValueChanged),
                              Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck(
                                  EventCallback.Factory.Create<bool>(
                                      dataContext, EventCallback.Factory.
                                      CreateInferred(val.Value, __value => val.Value = __value, val.Value))));

                       // Create an expression to set the ValueExpression-attribute.
                       var constant = Expression.Constant(val, val.GetType());
                       var exp = Expression.Property(constant, nameof(ValueReference<string, bool>.Value));
                       var lamb = Expression.Lambda<Func<bool>>(exp);
                       _builder.AddAttribute(_index++, nameof(InputBase<bool>.ValueExpression), lamb);

                       _builder.AddAttribute(_index++, nameof(VxInputCheckbox.Label), val.Key);

                       // Close the component
                       _builder.CloseComponent();
                   }


               }));
        }

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

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

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

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

19 View Source File : GenericInterface.cs
License : MIT License
Project Creator : Accelerider

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

                return method;
            }

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

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

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

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

            return formatterGetter(resolver);
        }

19 View Source File : PluralExpressionCompiler.cs
License : MIT License
Project Creator : adams85

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

            Expression expression = Visit(_syntaxTree);

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

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

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

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

19 View Source File : CrmContactRoleProvider.cs
License : MIT License
Project Creator : Adoxio

private static Expression<Func<TParameter, bool>> ContainsPropertyValueEqual<TParameter>(string crmPropertyName, IEnumerable<object> values)
		{
			var parameterType = typeof(TParameter);

			var parameter = Expression.Parameter(parameterType, parameterType.Name.ToLowerInvariant());

			var expression = ContainsPropertyValueEqual(crmPropertyName, values, parameter);

			return Expression.Lambda<Func<TParameter, bool>>(expression, parameter);
		}

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

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

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

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

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

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

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

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

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

19 View Source File : PredicateConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static object GetValue(Expression expression)
        {
            var lambda = Expression.Lambda(expression);
            try
            {
                dynamic func = lambda.Compile();
                return func();
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e, expression.ToString());
                return null;
            }
        }

19 View Source File : ExpressionVisitor`1.cs
License : MIT License
Project Creator : 71

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

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

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

                ParameterInfo[] parameters = method.GetParameters();

                if (parameters.Length != 1)
                    continue;

                ParameterInfo parameter = parameters[0];

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

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

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

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

19 View Source File : LinkedExpression.cs
License : MIT License
Project Creator : 71

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

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

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

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

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

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

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

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

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

19 View Source File : RepositoryBase.cs
License : MIT License
Project Creator : a34546

protected static Expression<Func<TEnreplacedy, bool>> CreateEqualityExpressionForId(TPrimaryKey id)
        {
            var lambdaParam = Expression.Parameter(typeof(TEnreplacedy));

            var lambdaBody = Expression.Equal(
                Expression.PropertyOrField(lambdaParam, "Id"),
                Expression.Constant(id, typeof(TPrimaryKey))
            );

            return Expression.Lambda<Func<TEnreplacedy, bool>>(lambdaBody, lambdaParam);
        }

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 : GameAttackTrigger.cs
License : Apache License 2.0
Project Creator : AantCoder

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

19 View Source File : VxFormColumnBase.cs
License : MIT License
Project Creator : Aaltuj

private void CreateFormElementReferencePoco<TValue>(object model, PropertyInfo propertyInfo,
            RenderTreeBuilder builder, Layout.VxFormElementDefinition formColumnDefinition)
        {
            var valueChanged = Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck(
                        EventCallback.Factory.Create<TValue>(
                            this, EventCallback.Factory.
                            CreateInferred(this, __value => propertyInfo.SetValue(model, __value),

                            (TValue)propertyInfo.GetValue(model))));
            // Create an expression to set the ValueExpression-attribute.
            var constant = Expression.Constant(model, model.GetType());
            var exp = Expression.Property(constant, propertyInfo.Name);
            var lamb = Expression.Lambda<Func<TValue>>(exp);

            var formElementReference = new FormElementReference<TValue>()
            {
                Value = (TValue)propertyInfo.GetValue(model),
                ValueChanged = valueChanged,
                ValueExpression = lamb,
                FormColumnDefinition = formColumnDefinition
            };

            var elementType = typeof(VxFormElementLoader<TValue>);

            builder.OpenComponent(0, elementType);
            builder.AddAttribute(1, nameof(VxFormElementLoader<TValue>.ValueReference), formElementReference);
            builder.CloseComponent();
        }

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

public static Expression<Func<object, bool>> GetObjectWhereExpressionContains(TableInfo tb, Type enreplacedyType, string csName, object[] arrayValue) {
			var mwhereParamExp = Expression.Parameter(typeof(object), "a");
			var selectExp = arrayValue.Select(c => Expression.Convert(Expression.Constant(FreeSql.Internal.Utils.GetDataReaderValue(tb.Columns[csName].CsType, c)), tb.Columns[csName].CsType)).ToArray();
			var mwhereExp = Expression.Lambda<Func<object, bool>>(
				Expression.Call(
					Utils.GetLinqContains(tb.Columns[csName].CsType),
					Expression.NewArrayInit(
						tb.Columns[csName].CsType,
						selectExp
					),
					Expression.MakeMemberAccess(Expression.TypeAs(mwhereParamExp, enreplacedyType), tb.Properties[csName])
				),
				mwhereParamExp);
			return mwhereExp;
		}

19 View Source File : TypeUtil.cs
License : MIT License
Project Creator : Abc-Arbitrage

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

            var param = Parameter(typeof(IntPtr));

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

19 View Source File : ExpressionResolver.cs
License : MIT License
Project Creator : 17MKH

private static object ResolveDynamicInvoke(Expression exp)
    {
        var value = Expression.Lambda(exp).Compile().DynamicInvoke();
        if (exp.Type.IsEnum)
            value = value.ToInt();

        return value;
    }

19 View Source File : FdbTuplePackers.cs
License : MIT License
Project Creator : abdullin

private static Delegate MakeNullableDeserializer([NotNull] Type nullableType, [NotNull] Type type, [NotNull] Delegate decoder)
		{
			Contract.Requires(nullableType != null && type != null && decoder != null);
			// We have a Decoder of T, but we have to transform it into a Decoder for Nullable<T>, which returns null if the slice is "nil", or falls back to the underlying decoder if the slice contains something

			var prmSlice = Expression.Parameter(typeof(Slice), "slice");
			var body = Expression.Condition(
				// IsNilSegment(slice) ?
				Expression.Call(typeof(FdbTuplePackers).GetMethod("IsNilSegment", BindingFlags.Static | BindingFlags.NonPublic), prmSlice),
				// True => default(Nullable<T>)
				Expression.Default(nullableType),
				// False => decoder(slice)
				Expression.Convert(Expression.Invoke(Expression.Constant(decoder), prmSlice), nullableType)
			);

			return Expression.Lambda(body, prmSlice).Compile();
		}

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

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

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

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

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

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

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

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

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

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

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

19 View Source File : PropertyObserverNode.cs
License : MIT License
Project Creator : Accelerider

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

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

            var method = propertyInfo.GetGetMethod();

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

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

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

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

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

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

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

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

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

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

        }

19 View Source File : TokenTypes.Keywords.cs
License : MIT License
Project Creator : adamant

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

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

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

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

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

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

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

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

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

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

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

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

19 View Source File : EnumerableExtensions.cs
License : MIT License
Project Creator : Adoxio

private static Expression<Func<T, bool>> In<T, TValue>(Expression<Func<T, TValue>> selector, IEnumerable<TValue> values)
		{
			return Expression.Lambda<Func<T, bool>>(
				In(selector.Body, values),
				selector.Parameters.First());
		}

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 : CrmProfileProvider.cs
License : MIT License
Project Creator : Adoxio

private Expression<Func<Enreplacedy, bool>> CreateOrModifyWherePredicate(Expression<Func<Enreplacedy, bool>> wherePredicate, ProfileAuthenticationOption authenticationOption)
		{
			var isAnonymous = authenticationOption == ProfileAuthenticationOption.Anonymous;

			if (wherePredicate == null)
			{
				return enreplacedy => enreplacedy.GetAttributeValue<bool?>(_attributeMapIsAnonymous).GetValueOrDefault() == isAnonymous;
			}
			
			// Set the wherePredicate so that the clause is equivilant to:
			// enreplacedy => wherePreicate.Body && enreplacedy.GetAttributeValue<bool?>(_attributeMapIsAnonymous).GetValueOrDefault() == isAnonymous

			var enreplacedyParameter = wherePredicate.Parameters.Single();

			Expression getPropertyValue = Expression.Call(enreplacedyParameter, "GetPropertyValue", new[] { typeof(bool?) }, Expression.Constant(_attributeMapIsAnonymous));

			var left = Expression.Call(getPropertyValue, typeof(bool?).GetMethod("GetValueOrDefault", Type.EmptyTypes));

			var anonymousPredicateBody = Expression.Equal(left, Expression.Constant(isAnonymous));

			return Expression.Lambda<Func<Enreplacedy, bool>>(Expression.AndAlso(wherePredicate.Body, anonymousPredicateBody), enreplacedyParameter);
		}

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

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

19 View Source File : XrmQueryExtensions.cs
License : MIT License
Project Creator : Adoxio

private static Expression<Func<TParameter, bool>> ContainsPropertyValueEqual<TParameter>(string propertyName1,
			string propertyName2, IEnumerable<Tuple<string, string>> values)
		{
			var parameterType = typeof(TParameter);

			var parameter = Expression.Parameter(parameterType, parameterType.Name.ToLowerInvariant());

			var expression = ContainsPropertyValueEqual(propertyName1, propertyName2, values, parameter);

			return Expression.Lambda<Func<TParameter, bool>>(expression, parameter);
		}

19 View Source File : ExpressionActivator.cs
License : Apache License 2.0
Project Creator : 1448376744

public ExpressionContextResult<T> Create<T>(string expression)
        {
            expression = Initialization(expression);
            var parameter = Expression.Parameter(typeof(T), "p");
            var body = CreateExpression(parameter, expression);
            var lambda = Expression.Lambda(body, parameter);
            var func = lambda.Compile() as Func<T, bool>;
            return new ExpressionContextResult<T>()
            {
                Func = func,
                LambdaExpression = lambda
            };
        }

19 View Source File : PredicateConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static object GetValue(Expression expression)
        {
            var lambda = Expression.Lambda(expression);
            dynamic func = lambda.Compile();
            return func();
        }

19 View Source File : Loops.cs
License : MIT License
Project Creator : 71

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

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

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

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

            addedItems.Count.ShouldBe(10);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

19 View Source File : MethodInvoker.cs
License : MIT License
Project Creator : 1100100

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

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

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

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

19 View Source File : ExpressionResovle.cs
License : Apache License 2.0
Project Creator : 1448376744

public object VisitConstantValue(Expression expression)
        {
            var names = new Stack<string>();
            var exps = new Stack<Expression>();
            var mifs = new Stack<MemberInfo>();
            if (expression is ConstantExpression constant)
                return constant.Value;
            else if (expression is MemberExpression)
            {
                var temp = expression;
                object value = null;
                while (temp is MemberExpression memberExpression)
                {
                    names.Push(memberExpression.Member.Name);
                    exps.Push(memberExpression.Expression);
                    mifs.Push(memberExpression.Member);
                    temp = memberExpression.Expression;
                }
                foreach (var name in names)
                {
                    var exp = exps.Pop();
                    var mif = mifs.Pop();
                    if (exp is ConstantExpression cex)
                        value = cex.Value;
                    if (mif is PropertyInfo pif)
                        value = pif.GetValue(value);
                    else if (mif is FieldInfo fif)
                        value = fif.GetValue(value);
                }
                return value;
            }
            else
            {
                return Expression.Lambda(expression).Compile().DynamicInvoke();
            }
        }

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

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

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

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

internal static void SetRepositoryDataFilter(object repos, Action<FluentDataFilter> scopedDataFilter) {
			if (scopedDataFilter != null) {
				SetRepositoryDataFilter(repos, null);
			}
			if (scopedDataFilter == null) {
				scopedDataFilter = _globalDataFilter;
			}
			if (scopedDataFilter == null) return;
			using (var globalFilter = new FluentDataFilter()) {
				scopedDataFilter(globalFilter);

				var type = repos.GetType();
				Type enreplacedyType = (repos as IBaseRepository).EnreplacedyType;
				if (enreplacedyType == null) throw new Exception("FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository");

				var notExists = _dicSetRepositoryDataFilterConvertFilterNotExists.GetOrAdd(type, t => new ConcurrentDictionary<string, bool>());
				var newFilter = new Dictionary<string, LambdaExpression>();
				foreach (var gf in globalFilter._filters) {
					if (notExists.ContainsKey(gf.name)) continue;

					LambdaExpression newExp = null;
					var filterParameter1 = Expression.Parameter(enreplacedyType, gf.exp.Parameters[0].Name);
					try {
						newExp = Expression.Lambda(
							typeof(Func<,>).MakeGenericType(enreplacedyType, typeof(bool)),
							new ReplaceVisitor().Modify(gf.exp.Body, filterParameter1),
							filterParameter1
						);
					} catch {
						notExists.TryAdd(gf.name, true); //防止第二次错误
						continue;
					}
					newFilter.Add(gf.name, newExp);
				}
				if (newFilter.Any() == false) return;

				var del = _dicSetRepositoryDataFilterApplyDataFilterFunc.GetOrAdd(type, t => {
					var reposParameter = Expression.Parameter(type);
					var nameParameter = Expression.Parameter(typeof(string));
					var expressionParameter = Expression.Parameter(
						typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(enreplacedyType, typeof(bool)))
					);
					return Expression.Lambda(
						Expression.Block(
							Expression.Call(reposParameter, type.GetMethod("ApplyDataFilter", BindingFlags.Instance | BindingFlags.NonPublic), nameParameter, expressionParameter)
						),
						new[] {
						reposParameter, nameParameter, expressionParameter
						}
					).Compile();
				});
				foreach (var nf in newFilter) {
					del.DynamicInvoke(repos, nf.Key, nf.Value);
				}
				newFilter.Clear();
			}
		}

19 View Source File : VxFormElementLoader.cs
License : MIT License
Project Creator : Aaltuj

protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            base.BuildRenderTree(builder);

            // Get the registered FormElement component. 
            var elementType = Options.FormElementComponent;

            // When the elementType that is rendered is a generic Set the propertyType as the generic type
            if (elementType.IsGenericTypeDefinition)
            {
                Type[] typeArgs = { typeof(TValue) };
                elementType = elementType.MakeGenericType(typeArgs);
            }

            builder.OpenComponent(0, elementType);

            // Bind the value of the input base the the propery of the model instance
            builder.AddAttribute(1, nameof(FormElementBase<TValue>.Value), ValueReference.Value);

            // Create the handler for ValueChanged. This wil update the model instance with the input
            builder.AddAttribute(2, nameof(FormElementBase<TValue>.ValueChanged), ValueReference.ValueChanged);

            // if no explicit value expression create one based on the ValueReference
            if (ValueReference.ValueExpression == null)
            {
                // Create an expression to set the ValueExpression-attribute.
                var constant = Expression.Constant(ValueReference, ValueReference.GetType());
                var exp = Expression.Property(constant, nameof(ValueReference.Value));
                var lamb = Expression.Lambda<Func<TValue>>(exp);

                builder.AddAttribute(4, nameof(FormElementBase<TValue>.ValueExpression), lamb);
            }
            else
            {
                builder.AddAttribute(4, nameof(FormElementBase<TValue>.ValueExpression), ValueReference.ValueExpression);
            } 

            builder.AddAttribute(6, nameof(FormElementBase<TValue>.FormColumnDefinition), ValueReference.FormColumnDefinition);

            builder.CloseComponent();

        }

See More Examples