Here are the examples of the csharp api System.Linq.Expressions.Expression.Constant(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2073 Examples
19
Source : MethodInvoker.cs
with MIT License
from 1100100
with MIT License
from 1100100
private Func<object, object[], dynamic> BuildInvoker(MethodInfo methodInfo)
{
if (methodInfo == null)
throw new ArgumentNullException(nameof(methodInfo), "MethodInfo cannot be null.");
var instanceParameter = Expression.Parameter(typeof(object));
var argsParameter = Expression.Parameter(typeof(object[]));
var argsExpressions = methodInfo.GetParameters().Select((item, index) => Expression.Convert(Expression.ArrayIndex(argsParameter, Expression.Constant(index)), item.ParameterType));
var instanceObj = methodInfo.IsStatic ? null : Expression.Convert(instanceParameter, methodInfo.DeclaringType ?? throw new InvalidOperationException());
var methodCaller = Expression.Call(instanceObj, methodInfo, argsExpressions);
if (methodCaller.Type == typeof(Task))
{
var action = Expression.Lambda<Action<object, object[]>>(methodCaller, instanceParameter, argsParameter).Compile();
return (instance, args) => { action(instance, args); return Task.CompletedTask; };
}
var instanceMethodCaller = Expression.Convert(methodCaller, methodInfo.ReturnType);
return Expression.Lambda<Func<object, object[], object>>(instanceMethodCaller, instanceParameter, argsParameter).Compile();
}
19
Source : BooleanExpressionResovle.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (node.Method.DeclaringType == typeof(Operator))
{
if (node.Arguments.Count == 2)
{
_textBuilder.Append("(");
SetParameterName(node.Arguments[0] as MemberExpression);
var type = Operator.ResovleExpressionType(node.Method.Name);
_textBuilder.Append($" {type} ");
var value = VisitConstantValue(node.Arguments[1]);
if (node.Method.Name == nameof(Operator.StartsWith) || node.Method.Name == nameof(Operator.NotStartsWith))
{
SetParameterValue(Expression.Constant($"{value}%", typeof(string)));
}
else if (node.Method.Name == nameof(Operator.EndsWith) || node.Method.Name == nameof(Operator.NotEndsWith))
{
SetParameterValue(Expression.Constant($"%{value}", typeof(string)));
}
else if (node.Method.Name == nameof(Operator.Contains) || node.Method.Name == nameof(Operator.NotContains))
{
SetParameterValue(Expression.Constant($"%{value}%", typeof(string)));
}
else
{
SetParameterValue(Expression.Constant(value));
}
_textBuilder.Append(")");
}
}
else if (IsLikeExpression(node))
{
_textBuilder.Append("(");
object value = null;
if (IsParameterExpression(node.Object))
{
SetParameterName(node.Object as MemberExpression);
value = VisitConstantValue(node.Arguments[0]);
}
else
{
SetParameterName(node.Arguments[0] as MemberExpression);
value = VisitConstantValue(node.Object);
}
if (_isNotExpression)
{
_isNotExpression = false;
_textBuilder.Append(" NOT LIKE ");
}
else
{
_textBuilder.Append(" LIKE ");
}
if (node.Method.Name == nameof(string.Contains))
{
SetParameterValue(Expression.Constant($"%{value}%"));
}
else if (node.Method.Name == nameof(string.StartsWith))
{
SetParameterValue(Expression.Constant($"{value}%"));
}
else
{
SetParameterValue(Expression.Constant($"%{value}"));
}
_textBuilder.Append(")");
}
else if (IsInExpression(node))
{
_textBuilder.Append("(");
SetParameterName(node.Arguments[1] as MemberExpression);
if (_isNotExpression)
{
_isNotExpression = false;
_textBuilder.Append(" NOT IN ");
}
else
{
_textBuilder.Append(" IN ");
}
SetParameterValue(node.Arguments[0] as MemberExpression);
_textBuilder.Append(")");
}
else if (node.Method.DeclaringType.GetCustomAttribute(typeof(FunctionAttribute), true) != null)
{
var function = new FunctionExpressionResovle(node).Resovle();
_textBuilder.Append(function);
}
else
{
SetParameterValue(node);
}
return node;
}
19
Source : ExpressionActivator.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
private Expression CreateExpression(ParameterExpression parameter, string expression)
{
var expressions1 = Factorization(expression);
var expressions2 = new Dictionary<string, Expression>();
foreach (var item in expressions1)
{
var subexpr = item.Value.Trim('(', ')');
var @opterator = ResovleOperator(item.Value);
var opt = GetExpressionType(@opterator);
if (opt == ExpressionType.Not)
{
Expression exp;
var text = subexpr.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
if (expressions2.ContainsKey(text))
{
exp = expressions2[text];
}
else if (parameter.Type.GetProperties().Any(a => a.Name == text))
{
var property = parameter.Type.GetProperty(text);
exp = Expression.MakeMemberAccess(parameter, property);
}
else
{
exp = Expression.Constant(Convert.ToBoolean(text));
}
expressions2.Add(item.Key, Expression.MakeUnary(opt, exp, null));
}
else
{
var text1 = subexpr
.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0]
.Trim();
var text2 = subexpr
.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[1]
.Trim();
string temp = null;
Expression exp1, exp2;
//永远将变量放在第一个操作数
if (parameter.Type.GetProperties().Any(a => a.Name == text2))
{
temp = text1;
text1 = text2;
text2 = temp;
}
//是否为上一次的分式
if (expressions2.ContainsKey(text1))
{
exp1 = expressions2[text1];
}
else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
{
//是否为变量
var property = parameter.Type.GetProperty(text1);
exp1 = Expression.MakeMemberAccess(parameter, property);
}
else
{
exp1 = ResovleConstantExpression(text1);
}
//是否为上一次的分式
if (expressions2.ContainsKey(text2))
{
exp2 = expressions2[text2];
}
//如果第一个操作数是变量
else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
{
var constantType = parameter.Type.GetProperty(text1).PropertyType;
exp2 = ResovleConstantExpression(text2, constantType);
}
else
{
exp2 = ResovleConstantExpression(text1, (exp1 as ConstantExpression)?.Type);
}
expressions2.Add(item.Key, Expression.MakeBinary(opt, exp1, exp2));
}
}
return expressions2.Last().Value;
}
19
Source : DbQuerySync.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
public IDbQuery<T> Set<TResult>(Expression<Func<T, TResult>> column, TResult value, bool condition = true)
{
if (true)
{
_setExpressions.Add(new SetExpression
{
Column = column,
Expression = Expression.Constant(value)
});
}
return this;
}
19
Source : CommonExpressionMeta.cs
with MIT License
from 1996v
with MIT License
from 1996v
public static Expression Call_WriteDateTime(Expression value)
{
return Expression.Call(Par_Writer, typeof(BssomWriter).GetMethod(nameof(BssomWriter.Write), instanceAndInternalFlag, null, new Type[] { typeof(DateTime), typeof(bool), typeof(bool) }, null), value, Field_SerializeOption_IsUseStandardDateTime, Expression.Constant(true));
}
19
Source : CommonExpressionMeta.cs
with MIT License
from 1996v
with MIT License
from 1996v
public static Expression Call_WriteArray3Header(int count)
{
return Expression.Call(Par_Writer, Type_Writer_WriteArray3Header, Expression.Constant(count));
}
19
Source : CommonExpressionMeta.cs
with MIT License
from 1996v
with MIT License
from 1996v
public static Expression Call_WriteBackArray3Header(Expression basePosition, Expression offset1, int count)
{
return Expression.Call(Par_Writer, Type_Writer_WriteBackArray3Header, basePosition, offset1, Expression.Constant(count));
}
19
Source : Array3CodeGenResolver.cs
with MIT License
from 1996v
with MIT License
from 1996v
private static Expression BuildSerializeCore(Type type, ObjectSerializationInfo serializationInfo, ParameterExpression instance)
{
List<Expression> ary = new List<Expression>();
LabelTarget returnTarget = Expression.Label(typeof(void), "returnLable");
if (!type.IsValueType)
{
//if (value==null)
// writer.WriteNull(); goto label;
ary.Add(CommonExpressionMeta.Block_IfNullWriteNullWithReturn(instance, type, returnTarget));
}
ParameterExpression[] variables = null;
var keys = serializationInfo.SerializeMemberInfos;
if (keys.Length == 0)
{
//writer.WriteRaw(Array3Cache._EmptyBuffer);
ary.Add(CommonExpressionMeta.Call_WriteRaw(Expression.Field(null, Array3Cache._EmptyBuffer)));
}
else
{
int maxLen = keys[keys.Length - 1].KeyIndex + 1;
Type stackallocBlockType = StackallocBlockProvider.GetOrCreateType(maxLen * sizeof(uint));
//long position;
//Block{size} block;
//IntPtr blockPtr;
variables = new ParameterExpression[3];
variables[0] = Expression.Variable(typeof(long), "elementOffPosition");
variables[1] = Expression.Variable(stackallocBlockType, "block");
variables[2] = Expression.Variable(typeof(IntPtr),"blockPtr");
//position = writer.WriteArray3Header(keys.Length);
ary.Add(Expression.replacedign(variables[0], CommonExpressionMeta.Call_WriteArray3Header(maxLen)));
//block = new Block{size}();
ary.Add(Expression.replacedign(variables[1], Expression.New(stackallocBlockType)));
//blockPtr = AsPointer(ref block);
ary.Add(Expression.replacedign(variables[2], ExpressionTreeAux.AsPointerExpression(variables[1])));
//0,3,5 --> maxLen = 6
FieldInfo memFormatters = serializationInfo.StoreMemberFormatterInstances();
int realIndex = 0;
for (int i = 0; i < maxLen; i++)
{
//StackallocBlockHelper.WriteUInt(blockPtr, 0, (uint)(writer.Position - position));
ary.Add(Expression.Call(null, StackallocBlockHelper._WriteUIntMethodInfo, variables[2], Expression.Constant(i), Expression.Convert(Expression.Subtract(CommonExpressionMeta.Field_WriterPos, variables[0]), typeof(uint))));
if (keys[realIndex].KeyIndex != i)
{
//WriteNull()
ary.Add(CommonExpressionMeta.Call_Writer_WriteNull);
}
else
{
//Writer(mem.Value)
ary.Add(SpecialCodeGenExpression.WriteValues(keys[realIndex], instance, memFormatters));
realIndex++;
}
}
//writer.WriteBackArray3Header(blockPtr)
ary.Add(CommonExpressionMeta.Call_WriteBackArray3Header(variables[0], variables[2], maxLen));
}
ary.Add(Expression.Label(returnTarget));
if (variables != null)
return Expression.Block(variables, ary);
return Expression.Block(ary);
}
19
Source : Array3CodeGenResolver.cs
with MIT License
from 1996v
with MIT License
from 1996v
private static Expression BuildDeserializeCore(Type t, ObjectSerializationInfo serializationInfo)
{
List<Expression> ary = new List<Expression>();
LabelTarget returnTarget = Expression.Label(t, "returnLable");
//int num;
ParameterExpression num = Expression.Variable(typeof(int), "num");
//int for-i;
ParameterExpression forVariable = Expression.Variable(typeof(int), "i");
//context.option.Security.DepthStep(ref reader);
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
//if(reader.TryReadNullWithEnsureBuildInType(BssomType.Array3))
// return default(t);
ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureBuildInType(BssomType.Array3),
Expression.Return(returnTarget, Expression.Default(t))));
//T t = new T();
ParameterExpression instance = Expression.Parameter(t, "instance");
if (serializationInfo.IsDefaultNoArgsCtor)
{
ary.Add(Expression.replacedign(instance, Expression.New(t)));
}
else
{
ParameterInfo[] parInfos = serializationInfo.BestmatchConstructor.GetParameters();
Expression[] pars = new Expression[parInfos.Length];
if (serializationInfo.ConstructorParametersIsDefaultValue)
{
for (int i = 0; i < parInfos.Length; i++)
{
pars[i] = Expression.Default(parInfos[i].ParameterType);
}
ary.Add(Expression.replacedign(instance, Expression.New(serializationInfo.BestmatchConstructor, pars)));
}
else
{
object[] cps = serializationInfo.ConstructorParameters;
for (int i = 0; i < parInfos.Length; i++)
{
pars[i] = Expression.Constant(cps[i], parInfos[i].ParameterType);
}
ary.Add(Expression.replacedign(instance, Expression.New(serializationInfo.BestmatchConstructor, pars)));
}
}
//reader.SkipVariableNumber()
ary.Add(CommonExpressionMeta.Call_Reader_SkipVariableNumber);
//num = reader.ReadVariableNumber()
ary.Add(Expression.replacedign(num, CommonExpressionMeta.Call_Reader_ReadVariableNumber));
//i = 0;
ary.Add(Expression.replacedign(forVariable, Expression.Constant(0)));
var members = serializationInfo.SerializeMemberInfos;
if (members.Length > 0)
{
//reader.Buffer.Seek(offsetSegment, Current)
ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Convert(Expression.Multiply(num, Expression.Constant(BssomBinaryPrimitives.FixUInt32NumberSize)), typeof(Int64)), BssomSeekOrgin.Current));
//switch(i)
// case 0: instance.Key0 = readValue();
// case 3: instance.Key1 = readValue();
// case 5: instance.Key2 = readValue();
// default: skipObj();
FieldInfo memFormatters = serializationInfo.StoreMemberFormatterInstances();
SwitchCase[] switchCases = new SwitchCase[members.Length];
for (int i = 0; i < members.Length; i++)
{
switchCases[i] = Expression.SwitchCase(SpecialCodeGenExpression.ReadValues(members[i], instance, memFormatters), Expression.Constant(members[i].KeyIndex));
}
Expression content = Expression.Switch(
typeof(void),
forVariable,
CommonExpressionMeta.Call_Reader_SkipObject,
null,
switchCases
);
ary.Add(For(forVariable, Expression.LessThan(forVariable, num), Expression.replacedign(forVariable, Expression.Add(forVariable, Expression.Constant(1))), content));
}
//context.Depth--;
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
ary.Add(Expression.Return(returnTarget, instance));
ary.Add(Expression.Label(returnTarget, instance));
return Expression.Block(new ParameterExpression[] { instance, num, forVariable, }, ary);
}
19
Source : Array3CodeGenResolver.cs
with MIT License
from 1996v
with MIT License
from 1996v
private static Expression For(ParameterExpression loopVar, Expression condition, Expression increment, Expression loopContent)
{
var initreplacedign = Expression.replacedign(loopVar, Expression.Constant(0));
var breakLabel = Expression.Label("LoopBreak");
var loop = Expression.Block(
initreplacedign,
Expression.Loop(
Expression.IfThenElse(
condition,
Expression.Block(
loopContent,
increment
),
Expression.Break(breakLabel)
),
breakLabel)
);
return loop;
}
19
Source : Array3CodeGenResolver.cs
with MIT License
from 1996v
with MIT License
from 1996v
private static Expression BuildSizeCore(Type type, ObjectSerializationInfo serializationInfo, ParameterExpression instance)
{
List<Expression> ary = new List<Expression>();
LabelTarget returnTarget = Expression.Label(typeof(int), "returnLable");
if (!type.IsValueType)
{
//if (value==null)
// goto label: 1;
ary.Add(CommonExpressionMeta.Block_IfNullSize(instance, type, returnTarget));
}
ParameterExpression size = Expression.Variable(typeof(int));
SerializeMemberInfo[] mems = serializationInfo.SerializeMemberInfos;
if (mems.Length == 0)
{
ary.Add(Expression.replacedign(size, Expression.Constant(Array3Cache.Empty.Length)));
}
else
{
int maxLen = mems[mems.Length - 1].KeyIndex + 1;
ary.Add(Expression.replacedign(size, Expression.Constant(BssomBinaryPrimitives.Array3HeaderSize(maxLen))));
FieldInfo memFormatters = serializationInfo.StoreMemberFormatterInstances();
int nullNumber = 0;
int realIndex = 0;
for (int i = 0; i < maxLen; i++)
{
if (mems[realIndex].KeyIndex != i)
{
nullNumber++;
}
else
{
//Size(mem.Value)
ary.Add(SpecialCodeGenExpression.SizeValues(mems[realIndex], instance, size, memFormatters));
realIndex++;
}
}
if (nullNumber > 0)
ary.Add(Expression.Addreplacedign(size, Expression.Constant(nullNumber * BssomBinaryPrimitives.NullSize)));
}
ary.Add(Expression.Label(returnTarget, size));
return Expression.Block(new ParameterExpression[] { size }, ary);
}
19
Source : Serializer.cs
with MIT License
from 2881099
with MIT License
from 2881099
static Func<Dictionary<string, string>, T> CompilePropertyDeserializer()
{
var o_t = typeof(T);
var o = Expression.Variable(o_t, "o");
var o_new = Expression.New(typeof(T));
var d_t = typeof(Dictionary<string, string>);
var d = Expression.Parameter(d_t, "d");
var d_mi_try_get_value = d_t.GetMethod("TryGetValue");
var item_t = typeof(String);
var item = Expression.Variable(item_t, "item");
var tc_t = typeof(TypeConverter);
var tc = Expression.Variable(tc_t, "tc");
var tc_mi_can_convert_from = tc_t.GetMethod("CanConvertFrom", new[] { typeof(Type) });
var tc_mi_convert_from = tc_t.GetMethod("ConvertFrom", new[] { typeof(Object) });
var td_t = typeof(TypeDescriptor);
var td_mi_get_converter = td_t.GetMethod("GetConverter", new[] { typeof(Type) });
var binds = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.CanRead)
.Select(x =>
{
var value_t = x.PropertyType;
var value = Expression.Variable(value_t, "value");
var target = Expression.Label(x.PropertyType);
return Expression.Bind(x, Expression.Block(new[] { item, value },
Expression.replacedign(tc, Expression.Call(null, td_mi_get_converter, Expression.Constant(x.PropertyType))),
Expression.IfThen(
Expression.Call(d, d_mi_try_get_value, Expression.Constant(x.Name), item),
Expression.IfThen(
Expression.NotEqual(item, Expression.Constant(null)),
Expression.IfThen(
Expression.Call(tc, tc_mi_can_convert_from, Expression.Constant(typeof(String))),
Expression.Block(
Expression.replacedign(value, Expression.Convert(Expression.Call(tc, tc_mi_convert_from, item), x.PropertyType)),
Expression.Return(target, value, x.PropertyType))))),
Expression.Label(target, value)
));
}).ToArray();
var body = Expression.Block(new[] { o, tc },
Expression.MemberInit(o_new, binds)
);
return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
.Compile();
}
19
Source : Serializer.cs
with MIT License
from 2881099
with MIT License
from 2881099
static Func<T, Dictionary<string, string>> CompilePropertySerializer()
{
var o_t = typeof(T);
var o = Expression.Parameter(o_t, "o");
var d_t = typeof(Dictionary<string, string>);
var d = Expression.Variable(d_t, "d");
var d_init = Expression.MemberInit(Expression.New(d_t));
var d_add = d_t.GetMethod("Add");
var d_setters = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance) // build setters via Add(k,v)
.Where(x => x.CanRead)
.Select(x =>
{
var prop = Expression.Property(o, x.Name);
var prop_mi_to_string = x.PropertyType.GetMethod("ToString", new Type[0]);
var add_to_dict = Expression.Call(d, d_add, Expression.Constant(x.Name), Expression.Call(prop, prop_mi_to_string));
if (!x.PropertyType.IsByRef)
return (Expression)add_to_dict;
else
return (Expression)Expression.IfThen(
Expression.Not(Expression.Equal(prop, Expression.Constant(null))),
add_to_dict);
});
// run this
var body = Expression.Block(new[] { d }, // scope variables
Expression.replacedign(d, d_init), // initialize
Expression.Block(d_setters), // set
d); // return
return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
.Compile();
}
19
Source : Serializer.cs
with MIT License
from 2881099
with MIT License
from 2881099
static Func<T, Dictionary<string, string>> CompileSerializer()
{
var o_t = typeof(T);
var o = Expression.Parameter(o_t, "original");
var o_get_object_data = o_t.GetMethod("GetObjectData");
var d_t = typeof(Dictionary<string, string>);
var d = Expression.Variable(d_t, "d"); // define object variable
var d_init = Expression.MemberInit(Expression.New(d_t)); // object ctor
var d_add = d_t.GetMethod("Add"); // add method
var fc_t = typeof(IFormatterConverter);// typeof(LocalVariableInfo);
var fc = Expression.Variable(fc_t, "fc");
var fc_init = Expression.MemberInit(Expression.New(typeof(System.Runtime.Serialization.FormatterConverter))); //Expression.MemberInit(Expression.New(fc_t));
var info_t = typeof(SerializationInfo);
var info = Expression.Variable(info_t, "info");
var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
var info_get_enumerator = info_t.GetMethod("GetEnumerator");
var ctx_t = typeof(StreamingContext);
var ctx = Expression.Variable(ctx_t, "ctx");
var ctx_init = Expression.MemberInit(Expression.New(ctx_t));
var enumerator_t = typeof(SerializationInfoEnumerator);
var enumerator = Expression.Variable(enumerator_t, "enumerator");
var enumerator_move_next = enumerator_t.GetMethod("MoveNext");
var enumerator_name = Expression.Property(enumerator, "Name");
var enumerator_value = Expression.Property(enumerator, "Value");
var mi_to_string = typeof(Object).GetMethod("ToString", new Type[0]);
var exit_loop = Expression.Label("exit_loop");
var body = Expression.Block(new[] { d, fc, info, ctx },
Expression.replacedign(d, d_init),
Expression.replacedign(fc, fc_init),
Expression.replacedign(info, info_init),
Expression.replacedign(ctx, ctx_init),
Expression.Call(o, o_get_object_data, info, ctx),
Expression.Block(new[] { enumerator },
Expression.replacedign(enumerator, Expression.Call(info, info_get_enumerator)),
Expression.Loop(
Expression.IfThenElse(
Expression.Call(enumerator, enumerator_move_next), // test
Expression.IfThen(
Expression.NotEqual(enumerator_value, Expression.Constant(null)),
Expression.Call(d, d_add, enumerator_name, Expression.Call(enumerator_value, mi_to_string))
),
Expression.Break(exit_loop)), // if false
exit_loop)),
d); // return
// compile
return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
.Compile();
}
19
Source : Serializer.cs
with MIT License
from 2881099
with MIT License
from 2881099
static Func<Dictionary<string, string>, T> CompileDeserializer()
{
var o_t = typeof(T);
var o_ctor = o_t.GetConstructor(new[] { typeof(SerializationInfo), typeof(StreamingContext) });
var d_t = typeof(Dictionary<string, string>);
var d = Expression.Parameter(d_t, "d");
var d_mi_get_enumerator = d_t.GetMethod("GetEnumerator");
var fc_t = typeof(IFormatterConverter);// typeof(LocalVariableInfo);
var fc = Expression.Variable(fc_t, "fc");
var fc_init = Expression.MemberInit(Expression.New(typeof(System.Runtime.Serialization.FormatterConverter))); //Expression.MemberInit(Expression.New(fc_t));
var info_t = typeof(SerializationInfo);
var info = Expression.Variable(info_t, "info");
var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
var info_mi_add_value = info_t.GetMethod("AddValue", new[] { typeof(String), typeof(Object) });
var ctx_t = typeof(StreamingContext);
var ctx = Expression.Variable(ctx_t, "ctx");
var ctx_init = Expression.MemberInit(Expression.New(ctx_t));
var enumerator_t = typeof(Dictionary<string, string>.Enumerator);
var enumerator = Expression.Variable(enumerator_t, "enumerator");
var enumerator_mi_move_next = enumerator_t.GetMethod("MoveNext");
var enumerator_current = Expression.Property(enumerator, "Current");
var kvp_t = typeof(KeyValuePair<string, string>);
var kvp_pi_key = kvp_t.GetProperty("Key");
var kvp_pi_value = kvp_t.GetProperty("Value");
var exit_loop = Expression.Label("exit_loop");
var body = Expression.Block(new[] { fc, info, ctx, enumerator },
Expression.replacedign(fc, fc_init),
Expression.replacedign(info, info_init),
Expression.replacedign(ctx, ctx_init),
Expression.replacedign(enumerator, Expression.Call(d, d_mi_get_enumerator)),
Expression.Loop(
Expression.IfThenElse(
Expression.Call(enumerator, enumerator_mi_move_next),
Expression.Call(info, info_mi_add_value, Expression.Property(enumerator_current, kvp_pi_key), Expression.Property(enumerator_current, kvp_pi_value)),
Expression.Break(exit_loop)),
exit_loop),
Expression.MemberInit(Expression.New(o_ctor, info, ctx))
);
return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
.Compile();
}
19
Source : DynamicProxyMeta.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static void CopyData(Type sourceType, object source, object target)
{
if (source == null) return;
if (target == null) return;
_copyDataFunc.GetOrAdd(sourceType, type =>
{
var sourceParamExp = Expression.Parameter(typeof(object), "sourceObject");
var targetParamExp = Expression.Parameter(typeof(object), "targetObject");
var sourceExp = Expression.Variable(type, "source");
var targetExp = Expression.Variable(type, "target");
var copyExps = new List<Expression>();
var sourceFields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var field in sourceFields)
copyExps.Add(Expression.replacedign(Expression.MakeMemberAccess(targetExp, field), Expression.MakeMemberAccess(sourceExp, field)));
if (copyExps.Any() == false) return _copyDataFuncEmpty;
var bodyExp = Expression.Block(
new[] {
sourceExp, targetExp
},
new[] {
Expression.IfThen(
Expression.NotEqual(sourceParamExp, Expression.Constant(null)),
Expression.IfThen(
Expression.NotEqual(targetParamExp, Expression.Constant(null)),
Expression.Block(
Expression.replacedign(sourceExp, Expression.TypeAs(sourceParamExp, sourceType)),
Expression.replacedign(targetExp, Expression.TypeAs(targetParamExp, sourceType)),
Expression.IfThen(
Expression.NotEqual(sourceExp, Expression.Constant(null)),
Expression.IfThen(
Expression.NotEqual(sourceExp, Expression.Constant(null)),
Expression.Block(
copyExps.ToArray()
)
)
)
)
)
)
}
);
return Expression.Lambda<Action<object, object>>(bodyExp, sourceParamExp, targetParamExp).Compile();
})(source, target);
}
19
Source : Admin.cs
with MIT License
from 2881099
with MIT License
from 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
Source : Utils.cs
with MIT License
from 2881099
with MIT License
from 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
Source : Utils.cs
with MIT License
from 2881099
with MIT License
from 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
Source : ExpressionVisitor`1.cs
with MIT License
from 71
with MIT License
from 71
protected void EnableDynamicVisiting()
{
if (dynamicVisit != null)
return;
Type returnType = typeof(T);
ParameterExpression exprParam = Expression.Parameter(typeof(Expression), "node");
Expression body = Expression.Call(Expression.Constant(this), nameof(DefaultVisit), null, exprParam);
foreach (MethodInfo method in this.GetType().GetTypeInfo().DeclaredMethods)
{
if (method.ReturnType != returnType || !method.Name.StartsWith("Visit"))
continue;
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length != 1)
continue;
ParameterInfo parameter = parameters[0];
if (!parameter.ParameterType.IsreplacedignableTo(typeof(Expression)))
continue;
// We got this far, it's a valid Visit*() method.
ParameterExpression exprVar = Expression.Parameter(parameter.ParameterType, parameter.Name);
// expr is TExpr newExpr ? newExpr : body
body = Expression.Block(new[] { exprVar },
Expression.replacedign(exprVar, Expression.TypeAs(exprParam, parameter.ParameterType)),
Expression.Condition(
Expression.ReferenceNotEqual(exprVar, Expression.Constant(null)),
exprVar,
body
)
);
}
dynamicVisit = Expression.Lambda<Func<Expression, T>>(body, exprParam).Compile();
}
19
Source : ForEachExpression.cs
with MIT License
from 71
with MIT License
from 71
private static Expression CreateDisposeOperation (TypeInfo enumerator_type, ParameterExpression enumerator)
{
if (Reflection.IDisposable.IsreplacedignableFrom(enumerator_type))
return Call(enumerator, Reflection.IDisposable_Dispose);
if (enumerator_type.IsValueType)
return null;
ParameterExpression disposable = Variable(typeof(IDisposable));
return Block(
new [] { disposable },
replacedign(disposable, TypeAs(enumerator, typeof(IDisposable))),
IfThen(ReferenceNotEqual(disposable, Constant(null)),
Call(disposable, Reflection.IDisposable_Dispose)
)
);
}
19
Source : StateMachineExpression.cs
with MIT License
from 71
with MIT License
from 71
protected LambdaExpression GenerateLambda(Expression body, params ParameterExpression[] parameters)
{
body = trackingVisitor.Visit(body);
// Create the switch cases to go to our previous state.
LabelTarget[] targets = labelTargets.ToArray();
SwitchCase[] cases = new SwitchCase[targets.Length + 1];
LabelTarget startLabel = Label("start");
cases[0] = SwitchCase(Goto(startLabel), Constant(0));
for (int i = 1; i < cases.Length; i++)
{
cases[i] = SwitchCase(Goto(targets[i - 1]), Constant(i));
}
// Add a switch to the beginning of the body
body = Block(
Switch(
Field(State, VirtualStateMachine.StateField),
Throw(New(typeof(ArgumentOutOfRangeException))),
cases
),
Label(startLabel),
body,
replacedign(Field(State, VirtualStateMachine.StateField), Constant(cases.Length)),
Label(End, Default(End.Type))
);
return Lambda(
trackingVisitor.GenerateBody(body, State),
parameters.Prepend(State)
);
}
19
Source : Loops.cs
with MIT License
from 71
with MIT License
from 71
[Fact]
public void ShouldRespectWhile()
{
ParameterExpression nbr = Expression.Variable(typeof(int), nameof(nbr));
ParameterExpression output = Expression.Parameter(typeof(List<int>), "output");
List<int> addedItems = new List<int>();
WhileExpression loop = X.While(
Expression.LessThan(Expression.PostIncrementreplacedign(nbr), Expression.Constant(10)),
Expression.Call(output, nameof(List<int>.Add), null, nbr)
);
Expression
.Lambda<Action<List<int>>>(Expression.Block(new[] { nbr }, loop), output)
.Compile()(addedItems);
addedItems.Count.ShouldBe(10);
int index = 0;
while (index++ < 10)
addedItems[index - 1].ShouldBe(index);
}
19
Source : OtherExpressions.cs
with MIT License
from 71
with MIT License
from 71
[Fact]
public void ShouldCallDispose()
{
TrackingDisposable disposable = new TrackingDisposable();
ConstantExpression disposableEx = Expression.Constant(disposable);
disposable.HasBeenDisposed.ShouldBeFalse();
Expression
.Lambda<Action>(X.Using(disposableEx, Expression.Empty()))
.Compile()();
disposable.HasBeenDisposed.ShouldBeTrue();
}
19
Source : OtherExpressions.cs
with MIT License
from 71
with MIT License
from 71
[Fact]
public void ShouldCallDisposeAfterException()
{
TrackingDisposable disposable = new TrackingDisposable();
ConstantExpression disposableEx = Expression.Constant(disposable);
ConstantExpression exceptionEx = Expression.Constant(new Exception());
disposable.HasBeenDisposed.ShouldBeFalse();
Should.Throw<Exception>(() => Expression
.Lambda<Action>(X.Using(disposableEx, Expression.Throw(exceptionEx)))
.Compile()());
disposable.HasBeenDisposed.ShouldBeTrue();
}
19
Source : ForEachExpression.cs
with MIT License
from 71
with MIT License
from 71
private Expression ReduceForArray()
{
LabelTarget inner_loop_break = Label("inner_loop_break");
LabelTarget inner_loop_continue = Label("inner_loop_continue");
LabelTarget @continue = ContinueLabel ?? Label("continue");
LabelTarget @break = BreakLabel ?? Label("break");
ParameterExpression index = Variable(typeof(int), "i");
return Block(
new [] { index, Variable },
replacedign(index, Constant(0)),
Loop(
Block(
IfThen(
IsFalse(LessThan(index, ArrayLength(Enumerable))),
Break(inner_loop_break)
),
replacedign(Variable, Convert(ArrayIndex(Enumerable, index), Variable.Type)),
Body,
Label(@continue),
PreIncrementreplacedign(index)
),
inner_loop_break,
inner_loop_continue
),
Label(@break)
);
}
19
Source : FormatExpression.cs
with MIT License
from 71
with MIT License
from 71
public override Expression Reduce()
{
return Call(FormatMethod, Constant(Format), NewArrayInit(typeof(object), Expressions));
}
19
Source : StateMachineExpression.cs
with MIT License
from 71
with MIT License
from 71
protected Expression Return(Expression value)
{
int nth = labelTargets.Count + 1;
LabelTarget label = Label($"L{nth}");
labelTargets.Add(label);
return Block(
replacedign(Field(State, VirtualStateMachine.StateField), Constant(nth)),
Return(End, value),
Label(label)
);
}
19
Source : TypeOfExpression.cs
with MIT License
from 71
with MIT License
from 71
public override Expression Reduce() => Constant(TargetType);
19
Source : UsingExpression.cs
with MIT License
from 71
with MIT License
from 71
public override Expression Reduce()
{
var end_finally = Label("end_finally");
return Block (
new [] { Variable },
replacedign(Variable, Disposable),
TryFinally(
Body,
Block(
Condition(
NotEqual(Variable, Constant(null)),
Block(
Call(Convert(Variable, typeof(IDisposable)), Reflection.IDisposable_Dispose),
Goto(end_finally)
),
Goto(end_finally)
),
Label(end_finally)
)
)
);
}
19
Source : Loops.cs
with MIT License
from 71
with MIT License
from 71
[Fact]
public void ShouldIterateEnumerable()
{
ParameterExpression output = Expression.Parameter(typeof(List<string>), "output");
ParameterExpression item = Expression.Variable(typeof(string), "item");
ConstantExpression items = Expression.Constant(Enumerable.Repeat("hello world", 10));
List<string> addedItems = new List<string>();
ForEachExpression loop = X.ForEach(item, items,
Expression.Call(output, nameof(List<string>.Add), null, item)
);
Expression
.Lambda<Action<List<string>>>(loop, output)
.Compile()(addedItems);
addedItems.Count.ShouldBe(10);
addedItems[0].ShouldBe("hello world");
}
19
Source : TrackingExpressionVisitor.cs
with MIT License
from 71
with MIT License
from 71
public Expression GenerateBody(Expression body, Expression vsmExpression)
{
Debug.replacedert(vsmExpression.Type.IsreplacedignableTo<VirtualStateMachine>());
if (Variables.Count == 0)
return body;
Expression[] loadVariableExpressions = new Expression[Variables.Count];
Expression[] saveVariableExpressions = new Expression[Variables.Count];
Expression localsExpression = Expression.Field(vsmExpression, VirtualStateMachine.LocalsField);
for (int i = 0; i < Variables.Count; i++)
{
ParameterExpression variable = Variables[i];
loadVariableExpressions[i] = Expression.replacedign(
variable, Expression.Convert(
Expression.ArrayAccess(localsExpression, Expression.Constant(i)),
variable.Type
)
);
saveVariableExpressions[i] = Expression.replacedign(
Expression.ArrayAccess(localsExpression, Expression.Constant(i)),
Expression.Convert(variable, typeof(object))
);
}
Expression init = loadVariableExpressions.Length == 0
? (Expression)Expression.Empty() : Expression.Block(typeof(void), loadVariableExpressions);
Expression end = saveVariableExpressions.Length == 0
? (Expression)Expression.Empty() : Expression.Block(typeof(void), saveVariableExpressions);
if (body.Type == typeof(void))
return Expression.Block(Variables, init, body, end);
ParameterExpression result = Expression.Variable(body.Type, "result");
return Expression.Block(Variables.Prepend(result), init, Expression.replacedign(result, body), end, result);
}
19
Source : LINQ.cs
with MIT License
from 71
with MIT License
from 71
[Fact]
public void ShouldCreateValidQuery()
{
ParameterExpression item = Expression.Variable(typeof(int), "item");
ConstantExpression items = Expression.Constant(new[] { 0, 1, 1, 3 });
X.Query(
X.From(item, items),
X.Where(Expression.Equal(item, 1.AsExpression())),
X.Select(item)
).Compile<Func<IEnumerable<int>>>()().SequenceEqual(new[]{1, 1}).ShouldBeTrue();
}
19
Source : Loops.cs
with MIT License
from 71
with MIT License
from 71
[Fact]
public void ShouldIterateArray()
{
ParameterExpression output = Expression.Parameter(typeof(List<string>), "output");
ParameterExpression item = Expression.Variable(typeof(string), "item");
ConstantExpression items = Expression.Constant(new[] { "hello", "world" });
List<string> addedItems = new List<string>();
ForEachExpression loop = X.ForEach(item, items,
Expression.Call(output, nameof(List<string>.Add), null, item)
);
Expression
.Lambda<Action<List<string>>>(loop, output)
.Compile()(addedItems);
addedItems.Count.ShouldBe(2);
addedItems[0].ShouldBe("hello");
addedItems[1].ShouldBe("world");
}
19
Source : Remute.cs
with MIT License
from ababik
with MIT License
from ababik
private Activator GetActivator(ConstructorInfo constructor)
{
var parameters = constructor.GetParameters();
var parameterExpression = Expression.Parameter(typeof(object[]));
var argumentExpressions = new Expression[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
{
var indexExpression = Expression.Constant(i);
var paramType = parameters[i].ParameterType;
var arrayExpression = Expression.ArrayIndex(parameterExpression, indexExpression);
var arrayConvertExpression = Expression.Convert(arrayExpression, paramType);
argumentExpressions[i] = arrayConvertExpression;
}
var constructorExpression = Expression.New(constructor, argumentExpressions);
var constructorConvertExpression = Expression.Convert(constructorExpression, typeof(object));
var lambdaExpression = Expression.Lambda<Activator>(constructorConvertExpression, parameterExpression);
var compiledExpression = lambdaExpression.Compile();
return compiledExpression;
}
19
Source : FdbTuplePackers.cs
with MIT License
from abdullin
with MIT License
from 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
Source : GenericInterface.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
private TDelegate GetActionWithParams<TDelegate>(string methodName, params Type[] argTypes)
{
var methodInfo = Type.GetMethod(methodName) ?? throw new ArgumentException(nameof(methodName));
var argTypeList = argTypes.Any() ? argTypes : typeof(TDelegate).GetGenericArguments();
(ParameterExpression expression, Type type)[] argObjectParameters = argTypeList
.Select(item => (Expression.Parameter(typeof(object)), item))
.ToArray();
var method = Expression.Lambda<TDelegate>(
Expression.Call(
Expression.Constant(_instance),
methodInfo,
argObjectParameters.Select(item => Expression.Convert(item.expression, item.type))),
argObjectParameters.Select(item => item.expression))
.Compile();
return method;
}
19
Source : GenericInterface.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
private TDelegate GetAction<TDelegate>(string methodName)
{
var methodInfo = Type.GetMethod(methodName) ?? throw new ArgumentException(nameof(methodName));
var method = Expression.Lambda<TDelegate>(
Expression.Call(
Expression.Constant(_instance),
methodInfo))
.Compile();
return method;
}
19
Source : PropertyObserverNode.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
private static Func<T> GetPropertyGetter<T>(object owner, string propertyName)
{
var propertyInfo = owner.GetType().GetProperty(propertyName);
if (propertyInfo == null)
throw new InvalidOperationException($"No the property named \"{propertyName}\" in the {owner.GetType()} type. ");
var method = propertyInfo.GetGetMethod();
return method.ReturnType != typeof(T) && method.ReturnType.IsValueType
// Warning: Boxes the Value Type.
? Lambda<Func<T>>(Convert(Call(Constant(owner), method), typeof(T))).Compile()
: (Func<T>)Delegate.CreateDelegate(typeof(Func<T>), owner, propertyInfo.GetGetMethod());
}
19
Source : SqlServerAsOfQueryableExtensions.cs
with MIT License
from Adam-Langley
with MIT License
from Adam-Langley
public static IQueryable<TEnreplacedy> AsOf<TEnreplacedy>(this IQueryable<TEnreplacedy> source, DateTime date) where TEnreplacedy : clreplaced
{
return
source.Provider is EnreplacedyQueryProvider
? source.Provider.CreateQuery<TEnreplacedy>(
Expression.Call(
instance: null,
method: AsOfMethodInfo.MakeGenericMethod(typeof(TEnreplacedy)),
arg0: source.Expression,
arg1: Expression.Constant(date)))
: source;
}
19
Source : PluralExpressionCompiler.cs
with MIT License
from adams85
with MIT License
from adams85
private static Expression FromCBool(Expression expression)
{
return
expression.Type == typeof(int) ?
Expression.NotEqual(expression, Expression.Constant(0)) :
expression;
}
19
Source : PluralExpressionCompiler.cs
with MIT License
from adams85
with MIT License
from adams85
private static Expression ToCBool(Expression expression)
{
return
expression.Type == typeof(bool) ?
Expression.Condition(expression, Expression.Constant(1), Expression.Constant(0)) :
expression;
}
19
Source : PluralExpressionCompiler.cs
with MIT License
from adams85
with MIT License
from adams85
private Expression VisitInteger(ASTNode node)
{
return Expression.Constant(int.Parse(node.Value, CultureInfo.InvariantCulture));
}
19
Source : EnumerableExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static Expression In<TValue>(Expression selectorBody, IEnumerable<TValue> values)
{
return In(
selectorBody,
values.Skip(1),
Expression.Equal(selectorBody, Expression.Constant(values.First())));
}
19
Source : EnumerableExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static Expression In<TValue>(Expression selectorBody, IEnumerable<TValue> values, Expression expression)
{
return values.Any()
? In(
selectorBody,
values.Skip(1),
Expression.OrElse(expression, Expression.Equal(selectorBody, Expression.Constant(values.First()))))
: expression;
}
19
Source : IssueForumDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : CrmProfileProvider.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : CrmContactRoleProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static Expression PropertyValueEqual(Expression parameter, string crmPropertyName, object value)
{
var methodCall = Expression.Call(parameter, "GetAttributeValue", new[] { typeof(string) }, Expression.Constant(crmPropertyName));
return Expression.Equal(methodCall, Expression.Constant(value));
}
19
Source : XrmQueryExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static Expression PropertyValueEqual(Expression parameter, string crmPropertyName, string value)
{
var methodCall = Expression.Call(parameter, "GetAttributeValue", new[] { typeof(string) },
Expression.Constant(crmPropertyName));
return Expression.Equal(methodCall, Expression.Constant(value));
}
19
Source : MapController.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static Expression PropertyValueEqual(Expression parameter, string crmPropertyName, Guid value)
{
var methodCall = Expression.Call(parameter, "GetAttributeValue", new[] { typeof(Guid) }, Expression.Constant(crmPropertyName));
return Expression.Equal(methodCall, Expression.Constant(value));
}
See More Examples