Here are the examples of the csharp api System.Linq.Expressions.Expression.Constant(object, System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1460 Examples
19
View Source File : BooleanExpressionResovle.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 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
View Source File : BooleanExpressionResovle.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 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
View Source File : ExpressionActivator.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
private Expression ResovleConstantExpression(string expression, Type type)
{
//生成指定类型的表达式
if (expression == "null")
{
return Expression.Constant(null, type);
}
else if (type == typeof(string))
{
return Expression.Constant(expression.Trim('\'', '\''), type);
}
else
{
if (Nullable.GetUnderlyingType(type) == null)
{
var value = Convert.ChangeType(expression, type);
return Expression.Constant(value, type);
}
else
{
var undertype = Nullable.GetUnderlyingType(type);
var value = Convert.ChangeType(expression, undertype);
var expr = Expression.Constant(value, undertype);
return Expression.MakeUnary(ExpressionType.Convert, expr, type);
}
}
}
19
View Source File : ExpressionActivator.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
private Expression ResovleConstantExpression(string expression)
{
//自动类型推断生成表达式
if (expression.StartsWith("'") && expression.EndsWith("'"))
{
//字符串常量
return Expression.Constant(expression.Trim('\''), typeof(string));
}
else if (expression == "true" || expression == "false")
{
return Expression.Constant(expression, typeof(bool));
}
else if (Regex.IsMatch(expression, @"^\d+$"))
{
//int类型常量
return Expression.Constant(expression, typeof(int));
}
else if (Regex.IsMatch(expression, @"^\d*\.\d*$"))
{
//double
return Expression.Constant(expression, typeof(int));
}
else if (expression == "null")
{
return Expression.Constant(null, typeof(object));
}
return Expression.Constant(expression, typeof(object));
}
19
View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Expression Call_Writer_Seek(Expression pos)
{
return Expression.Call(Field_WriterBufferWriter, typeof(IBssomBufferWriter).GetMethod(nameof(IBssomBufferWriter.Seek)), pos, Expression.Constant(BssomSeekOrgin.Begin, typeof(BssomSeekOrgin)));
}
19
View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Expression Call_Reader_BufferSeek(Expression pos, BssomSeekOrgin orgin = BssomSeekOrgin.Begin)
{
return Expression.Call(Field_ReaderBuffer, Type_Buffer_Seek, pos, Expression.Constant(orgin, typeof(BssomSeekOrgin)));
}
19
View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Expression Call_Reader_TryReadNullWithEnsureBuildInType(byte code)
{
return Expression.Call(Par_Reader, Type_Reader_TryReadNullWithEnsureBuildInType, Expression.Constant(code, typeof(byte)));
}
19
View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Expression Call_Reader_TryReadNullWithEnsureArray1BuildInType(byte code)
{
return Expression.Call(Par_Reader, typeof(BssomReader).GetMethod(nameof(BssomReader.TryReadNullWithEnsureArray1BuildInType), instanceAndInternalFlag), Expression.Constant(code, typeof(byte)));
}
19
View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Expression Call_Reader_TryReadNullWithEnsureArray1NativeType(byte code)
{
return Expression.Call(Par_Reader, typeof(BssomReader).GetMethod(nameof(BssomReader.TryReadNullWithEnsureArray1NativeType), instanceAndInternalFlag), Expression.Constant(code, typeof(byte)));
}
19
View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Expression Block_IfNullWriteNullWithReturn(Expression instance, Type t, LabelTarget label)
{
return Expression.IfThen(Expression.Equal(instance, Expression.Constant(null, t)), Expression.Block(Call_Writer_WriteNull, Expression.Return(label)));
}
19
View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Expression Block_IfNullSize(Expression instance, Type t, LabelTarget label)
{
return Expression.IfThen(Expression.Equal(instance, Expression.Constant(null, t)), Expression.Return(label, Expression.Constant(BssomBinaryPrimitives.NullSize)));
}
19
View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Expression Block_IfNullSize(Expression instance, Type t, LabelTarget label)
{
return Expression.IfThen(Expression.Equal(instance, Expression.Constant(null, t)), Expression.Return(label, Expression.Constant(BssomBinaryPrimitives.NullSize)));
}
19
View Source File : Array3CodeGenResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 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
View Source File : Array3CodeGenResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 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
View Source File : Array3CodeGenResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 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
View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
private static void GenerateDeserializeWithGenericDictCore(Type keyType, Type valueType, Func<MemberExpression, Expression> ctor)
{
/*
var map = MapFormatterHelper.Deserialize(ref reader,ref context);
if (map == null)
return null;
context.option.Security.DepthStep(ref reader);
T t = new T();/new T(map.Count)
Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
reader = map.Reader; context = map.Context;
reader.Seek(map.EndPos);
context.Depth--;
return t;
*/
ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
Type t = typeof(T);
LabelTarget returnTarget = Expression.Label(t, "returnLable");
ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(keyType, valueType));
//map = MapFormatterHelper.Deserialize(ref reader,ref context);
ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(keyType, valueType)));
//if (map == null)
// goto label;
ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
//context.option.Security.DepthStep(ref reader);
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
//T t = ctor(map.Count);
ParameterExpression instance = Expression.Variable(t);
ary.Add(Expression.replacedign(instance, ctor(Expression.Property(map, nameof(BssMapObjMarshalReader<int, int>.Count)))));
//MapFormatterHelper.FillData(map,(ICollection<KeyValuePair<TKey, TValue>>)t)
ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillGenericIDictionaryData), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(keyType, valueType), map, Expression.Convert(instance, typeof(ICollection<>).MakeGenericType(typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType)))));
//reader = map.Reader; context = map.Context;
ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
//reader.Seek(map.EndPos);
ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
//context.Depth--;
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
//return t;
ary.Add(Expression.Return(returnTarget, instance));
//label default(T)
ary.Add(Expression.Label(returnTarget, instance));
BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
}
19
View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static void GenerateDeserializeWithIDictionaryEmptyCtor()
{
/*
var map = MapFormatterHelper.Deserialize(ref reader,ref context);
if (map == null)
return null;
context.option.Security.DepthStep(ref reader);
T t = new T();
Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
reader = map.Reader; context = map.Context;
reader.Seek(map.EndPos);
context.Depth--;
return t;
*/
ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
Type t = typeof(T);
LabelTarget returnTarget = Expression.Label(t, "returnLable");
ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(typeof(object), typeof(object)));
//map = MapFormatterHelper.Deserialize(ref reader,ref context);
ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(typeof(object), typeof(object))));
//if (map == null)
// goto label;
ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
//context.option.Security.DepthStep(ref reader);
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
//T t = new T();
ParameterExpression instance = Expression.Variable(t);
ary.Add(Expression.replacedign(instance, Expression.New(t)));
//MapFormatterHelper.FillData(map,(IDictionary)t)
ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillIDictionaryData), BindingFlags.Public | BindingFlags.Static), map, Expression.Convert(instance, typeof(IDictionary))));
//reader = map.Reader; context = map.Context;
ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
//reader.Seek(map.EndPos);
ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
//context.Depth--;
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
//return t;
ary.Add(Expression.Return(returnTarget, instance));
//label default(T)
ary.Add(Expression.Label(returnTarget, instance));
BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
}
19
View Source File : DynamicProxyMeta.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal static NewExpression InternalNewExpression(Type that)
{
var ctor = InternalGetTypeConstructor0OrFirst(that);
return Expression.New(ctor, ctor.GetParameters().Select(a => Expression.Constant(CreateInstanceDefault(a.ParameterType), a.ParameterType)));
}
19
View Source File : ExpressionPipeline.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public static Expression ReplaceBoundVariableFields(Expression expr)
{
MemberExpression mx = expr as MemberExpression;
FieldInfo accessedField = mx?.Member as FieldInfo;
if (accessedField == null || !accessedField.DeclaringType.Name.StartsWith("<>c__"))
return expr;
ConstantExpression displayClreplacedConstant = mx.Expression as ConstantExpression;
if (displayClreplacedConstant == null)
return expr;
return Expression.Constant(
accessedField.GetValue(displayClreplacedConstant.Value),
displayClreplacedConstant.Type);
}
19
View Source File : Utils.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public static ConstantExpression AsExpression<T>(this T obj)
{
return Expression.Constant(obj, typeof(T));
}
19
View Source File : StateMachineExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public override Expression Reduce() => Constant(Compile());
19
View Source File : RepositoryBase.cs
License : MIT License
Project Creator : a34546
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 : InputCheckboxMultipleWithChildren.cs
License : MIT License
Project Creator : Aaltuj
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 : VxFormColumnBase.cs
License : MIT License
Project Creator : Aaltuj
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 : VxFormElementLoader.cs
License : MIT License
Project Creator : Aaltuj
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();
}
19
View Source File : DynamicProxyMetaObject.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private DynamicMetaObject CallMethodReturnLast(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
//
// Build a new expression like:
// {
// object result;
// TrySetMember(payload, result = value) ? result : fallbackResult
// }
//
ParameterExpression result = Expression.Parameter(typeof(object), null);
IList<Expression> callArgs = new List<Expression>();
callArgs.Add(Expression.Convert(Expression, typeof(T)));
callArgs.Add(Constant(binder));
callArgs.AddRange(args);
callArgs[args.Length + 1] = Expression.replacedign(result, callArgs[args.Length + 1]);
DynamicMetaObject callDynamic = new DynamicMetaObject(
Expression.Block(
new[] { result },
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
callArgs
),
result,
fallbackResult.Expression,
typeof(object)
)
),
GetRestrictions().Merge(fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
}
19
View Source File : DynamicProxyMetaObject.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private static ConstantExpression Constant(DynamicMetaObjectBinder binder)
{
Type t = binder.GetType();
while (!t.IsVisible())
{
t = t.BaseType();
}
return Expression.Constant(binder, t);
}
19
View Source File : DynamicProxyMetaObject.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke)
{
//
// Build a new expression like:
// {
// object result;
// TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult
// }
//
ParameterExpression result = Expression.Parameter(typeof(object), null);
IList<Expression> callArgs = new List<Expression>();
callArgs.Add(Expression.Convert(Expression, typeof(T)));
callArgs.Add(Constant(binder));
callArgs.AddRange(args);
callArgs.Add(result);
DynamicMetaObject resultMetaObject = new DynamicMetaObject(result, BindingRestrictions.Empty);
// Need to add a conversion if calling TryConvert
if (binder.ReturnType != typeof(object))
{
UnaryExpression convert = Expression.Convert(resultMetaObject.Expression, binder.ReturnType);
// will always be a cast or unbox
resultMetaObject = new DynamicMetaObject(convert, resultMetaObject.Restrictions);
}
if (fallbackInvoke != null)
{
resultMetaObject = fallbackInvoke(resultMetaObject);
}
DynamicMetaObject callDynamic = new DynamicMetaObject(
Expression.Block(
new[] { result },
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
callArgs
),
resultMetaObject.Expression,
fallbackResult.Expression,
binder.ReturnType
)
),
GetRestrictions().Merge(resultMetaObject.Restrictions).Merge(fallbackResult.Restrictions)
);
return callDynamic;
}
19
View Source File : DynamicProxyMetaObject.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private DynamicMetaObject CallMethodNoResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
IList<Expression> callArgs = new List<Expression>();
callArgs.Add(Expression.Convert(Expression, typeof(T)));
callArgs.Add(Constant(binder));
callArgs.AddRange(args);
//
// Build a new expression like:
// if (TryDeleteMember(payload)) { } else { fallbackResult }
//
DynamicMetaObject callDynamic = new DynamicMetaObject(
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
callArgs
),
Expression.Empty(),
fallbackResult.Expression,
typeof(void)
),
GetRestrictions().Merge(fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
}
19
View Source File : GreedyMetaDynamic.cs
License : MIT License
Project Creator : albahari
License : MIT License
Project Creator : albahari
private static ConstantExpression Constant<TBinder> (TBinder binder)
{
return Expression.Constant (binder, typeof (TBinder));
}
19
View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public static IQueryable<TEnreplacedy> WhereOrCollectionAnyEqual<TEnreplacedy, TValue, TMemberValue>
(
this IQueryable<TEnreplacedy> query,
Expression<Func<TEnreplacedy, IEnumerable<TValue>>> selector,
Expression<Func<TValue, TMemberValue>> memberSelector,
IEnumerable<TMemberValue> values
)
{
if (selector == null)
{
throw new ArgumentNullException(nameof(selector));
}
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
if (!values.Any()) return query;
ParameterExpression selectorParameter = selector.Parameters.Single();
ParameterExpression memberParameter = memberSelector.Parameters.Single();
var methodInfo = GetEnumerableMethod("Any", 2).MakeGenericMethod(typeof(TValue));
var anyExpressions = values.Select(value =>
(Expression)Expression.Call(null,
methodInfo,
selector.Body,
Expression.Lambda<Func<TValue, bool>>(Expression.Equal(memberSelector.Body,
Expression.Constant(value, typeof(TMemberValue))),
memberParameter
)
)
);
Expression body = anyExpressions.Aggregate((acreplacedulate, any) => Expression.Or(acreplacedulate, any));
return query.Where(Expression.Lambda<Func<TEnreplacedy, bool>>(body, selectorParameter));
}
19
View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public static IQueryable<TEnreplacedy> WhereIn<TEnreplacedy, TValue>
(
this IQueryable<TEnreplacedy> query,
Expression<Func<TEnreplacedy, TValue>> selector,
IEnumerable<TValue> values
)
{
/*
* 实现效果:
* var names = new[] { "A", "B", "C" };
* SELECT * FROM [User] Where Name='A' OR Name='B' OR Name='C'
* 实际上,可以直接这样:
* var query = DbContext.User.Where(m => names.Contains(m.Name));
*/
if (selector == null)
{
throw new ArgumentNullException(nameof(selector));
}
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
if (!values.Any()) return query;
ParameterExpression p = selector.Parameters.Single();
IEnumerable<Expression> equals = values.Select(value => (Expression)Expression.Equal(selector.Body, Expression.Constant(value, typeof(TValue))));
Expression body = equals.Aggregate((acreplacedulate, equal) => Expression.Or(acreplacedulate, equal));
return query.Where(Expression.Lambda<Func<TEnreplacedy, bool>>(body, p));
}
19
View Source File : PartialEvaluatorBase.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
protected override Expression Visit(Expression exp)
{
if (exp == null)
{
return null;
}
if (_candidates.Contains(exp))
{
return exp.NodeType == ExpressionType.Constant ? exp :
Expression.Constant(_evaluator.Eval(exp), exp.Type);
}
return base.Visit(exp);
}
19
View Source File : NodePort.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
PushDataDelegate CreatePushDataDelegateForEdge(SerializableEdge edge)
{
try
{
//Creation of the delegate to move the data from the input node to the output node:
FieldInfo inputField = edge.inputNode.GetType().GetField(edge.inputFieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo outputField = edge.outputNode.GetType().GetField(edge.outputFieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Type inType, outType;
#if DEBUG_LAMBDA
return new PushDataDelegate(() => {
var outValue = outputField.GetValue(edge.outputNode);
inType = edge.inputPort.portData.displayType ?? inputField.FieldType;
outType = edge.outputPort.portData.displayType ?? outputField.FieldType;
Debug.Log($"Push: {inType}({outValue}) -> {outType} | {owner.name}");
object convertedValue = outValue;
if (TypeAdapter.Arereplacedignable(outType, inType))
{
var convertionMethod = TypeAdapter.GetConvertionMethod(outType, inType);
Debug.Log("Convertion method: " + convertionMethod.Name);
convertedValue = convertionMethod.Invoke(null, new object[]{ outValue });
}
inputField.SetValue(edge.inputNode, convertedValue);
});
#endif
// We keep slow checks inside the editor
#if UNITY_EDITOR
if (!BaseGraph.TypesAreConnectable(inputField.FieldType, outputField.FieldType))
{
Debug.LogError("Can't convert from " + inputField.FieldType + " to " + outputField.FieldType + ", you must specify a custom port function (i.e CustomPortInput or CustomPortOutput) for non-implicit convertions");
return null;
}
#endif
Expression inputParamField = Expression.Field(Expression.Constant(edge.inputNode), inputField);
Expression outputParamField = Expression.Field(Expression.Constant(edge.outputNode), outputField);
inType = edge.inputPort.portData.displayType ?? inputField.FieldType;
outType = edge.outputPort.portData.displayType ?? outputField.FieldType;
// If there is a user defined convertion function, then we call it
if (TypeAdapter.Arereplacedignable(outType, inType))
{
// We add a cast in case there we're calling the conversion method with a base clreplaced parameter (like object)
var convertedParam = Expression.Convert(outputParamField, outType);
outputParamField = Expression.Call(TypeAdapter.GetConvertionMethod(outType, inType), convertedParam);
// In case there is a custom port behavior in the output, then we need to re-cast to the base type because
// the convertion method return type is not always replacedignable directly:
outputParamField = Expression.Convert(outputParamField, inputField.FieldType);
}
else // otherwise we cast
outputParamField = Expression.Convert(outputParamField, inputField.FieldType);
BinaryExpression replacedign = Expression.replacedign(inputParamField, outputParamField);
return Expression.Lambda< PushDataDelegate >(replacedign).Compile();
} catch (Exception e) {
Debug.LogError(e);
return null;
}
}
19
View Source File : Evaluator.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
private Expression Evaluate(Expression e)
{
Type type = e.Type;
if (e.NodeType == ExpressionType.Convert)
{
// check for unnecessary convert & strip them
var u = (UnaryExpression)e;
if (TypeHelper.GetNonNullableType(u.Operand.Type) == TypeHelper.GetNonNullableType(type))
{
e = ((UnaryExpression)e).Operand;
}
}
if (e.NodeType == ExpressionType.Constant)
{
// in case we actually threw out a nullable conversion above, simulate it here
// don't post-eval nodes that were already constants
if (e.Type == type)
{
return e;
}
else if (TypeHelper.GetNonNullableType(e.Type) == TypeHelper.GetNonNullableType(type))
{
return Expression.Constant(((ConstantExpression)e).Value, type);
}
}
var me = e as MemberExpression;
if (me != null)
{
// member accesses off of constant's are common, and yet since these partial evals
// are never re-used, using reflection to access the member is faster than compiling
// and invoking a lambda
var ce = me.Expression as ConstantExpression;
if (ce != null)
{
return this.PostEval(Expression.Constant(me.Member.GetValue(ce.Value), type));
}
}
if (type.IsValueType)
{
e = Expression.Convert(e, typeof(object));
}
Expression<Func<object>> lambda = Expression.Lambda<Func<object>>(e);
#if NOREFEMIT
Func<object> fn = ExpressionEvaluator.CreateDelegate(lambda);
#else
Func<object> fn = lambda.Compile();
#endif
return this.PostEval(Expression.Constant(fn(), type));
}
19
View Source File : Evaluator.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
private Expression Evaluate(Expression e)
{
Type type = e.Type;
if (e.NodeType == ExpressionType.Convert)
{
// check for unnecessary convert & strip them
var u = (UnaryExpression)e;
if (TypeHelper.GetNonNullableType(u.Operand.Type) == TypeHelper.GetNonNullableType(type))
{
e = ((UnaryExpression)e).Operand;
}
}
if (e.NodeType == ExpressionType.Constant)
{
// in case we actually threw out a nullable conversion above, simulate it here
// don't post-eval nodes that were already constants
if (e.Type == type)
{
return e;
}
else if (TypeHelper.GetNonNullableType(e.Type) == TypeHelper.GetNonNullableType(type))
{
return Expression.Constant(((ConstantExpression)e).Value, type);
}
}
var me = e as MemberExpression;
if (me != null)
{
// member accesses off of constant's are common, and yet since these partial evals
// are never re-used, using reflection to access the member is faster than compiling
// and invoking a lambda
var ce = me.Expression as ConstantExpression;
if (ce != null)
{
return this.PostEval(Expression.Constant(me.Member.GetValue(ce.Value), type));
}
}
if (type.IsValueType)
{
e = Expression.Convert(e, typeof(object));
}
Expression<Func<object>> lambda = Expression.Lambda<Func<object>>(e);
#if NOREFEMIT
Func<object> fn = ExpressionEvaluator.CreateDelegate(lambda);
#else
Func<object> fn = lambda.Compile();
#endif
return this.PostEval(Expression.Constant(fn(), type));
}
19
View Source File : TypeHelper.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
public static ConstantExpression GetNullConstant(Type type)
{
return Expression.Constant(null, GetNullreplacedignableType(type));
}
19
View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
static Expression IsSchemaType(JSchema schema, Expression o, JSchemaType t) =>
CallThis(nameof(IsSchemaTypeFunc), Expression.Constant(schema), o, Expression.Constant(t));
19
View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
Expression BuildContent(JSchema schema, Expression o)
{
// no content related validation
if (schema.ContentEncoding == null &&
schema.ContentMediaType == null)
return null;
switch (schema.ContentEncoding)
{
case Constants.ContentEncodings.Base64:
return
IfThenElseTrue(
IsTokenType(o, JTokenType.String),
CallThis(
nameof(ContentBase64),
Expression.Convert(o, typeof(string)),
Expression.Constant(schema.ContentMediaType, typeof(string))));
case null:
return IfThenElseTrue(
IsTokenType(o, JTokenType.String),
CallThis(
nameof(ContentMediaTypeString),
Expression.Convert(o, typeof(string)),
Expression.Constant(schema.ContentMediaType, typeof(string))));
default:
return null;
}
}
19
View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
Expression BuildItems(JSchema schema, Expression o)
{
Expression CompareExpr(Expression val, Expression off, JSchema sch) =>
CallThis(nameof(CompareLocal), val, off, EvalSchemaFunc(sch));
// returns an expression that returns true if the expression is not an array type
Expression TrueIfNotArray(Expression expression) =>
IfThenElseTrue(IsTokenType(o, JTokenType.Array), expression);
// convert target object into array
var val = Expression.Convert(o, typeof(JArray));
// compare single schema item to all array items
if (schema.ItemsPositionValidation == false && schema.Items.Count > 0)
return TrueIfNotArray(CompareExpr(val, Expression.Constant(0), schema.Items[0]));
if (schema.ItemsPositionValidation == true)
{
var len = Expression.Property(val, nameof(JArray.Count));
// compares the schema to the array from the beginning
var cmp = AllOf(schema.Items
.Select((i, j) =>
Expression.OrElse(
Expression.LessThanOrEqual(len, Expression.Constant(j)),
Eval(i, FromItemIndex(val, j)))));
// additional items are not allowed, esure size is equal, and match
if (schema.AllowAdditionalItems == false)
return TrueIfNotArray(
Expression.AndAlso(
Expression.LessThanOrEqual(len, Expression.Constant(schema.Items.Count)),
cmp));
// compare 1:1, but then also compare remaining items from end of schema as offset
if (schema.AdditionalItems != null)
return TrueIfNotArray(
Expression.AndAlso(
cmp,
CompareExpr(val, Expression.Constant(schema.Items.Count), schema.AdditionalItems)));
// basic comparison, additional items are allowed, but no validated
return TrueIfNotArray(cmp);
}
return null;
}
19
View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
static Expression BuildMaximum(JSchema schema, Expression o)
{
if (schema.Maximum == null)
return null;
Expression Comparer(Expression left, Expression right) =>
schema.ExclusiveMaximum ? Expression.LessThan(left, right) : Expression.LessThanOrEqual(left, right);
return Expression.Switch(
TokenType(o),
True,
Expression.SwitchCase(
Expression.Condition(
Expression.TypeIs(
Expression.Property(Expression.Convert(o, typeof(JValue)), nameof(JValue.Value)),
typeof(BigInteger)),
Comparer(
Expression.Convert(Expression.Property(Expression.Convert(o, typeof(JValue)), nameof(JValue.Value)), typeof(BigInteger)),
Expression.Constant(new BigInteger((double)schema.Maximum))),
Comparer(
Expression.Convert(o, typeof(int)),
Expression.Constant((int)schema.Maximum))),
Expression.Constant(JTokenType.Integer)),
Expression.SwitchCase(
Comparer(
Expression.Convert(o, typeof(double)),
Expression.Constant((double)schema.Maximum)),
Expression.Constant(JTokenType.Float)));
}
19
View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
static Expression BuildMinimum(JSchema schema, Expression o)
{
if (schema.Minimum == null)
return null;
Expression Comparer(Expression left, Expression right) =>
schema.ExclusiveMinimum ? Expression.GreaterThan(left, right) : Expression.GreaterThanOrEqual(left, right);
return Expression.Switch(
TokenType(o),
True,
Expression.SwitchCase(
Comparer(
Expression.Convert(o, typeof(int)),
Expression.Constant((int)schema.Minimum)),
Expression.Constant(JTokenType.Integer)),
Expression.SwitchCase(
Comparer(
Expression.Convert(o, typeof(double)),
Expression.Constant((double)schema.Minimum)),
Expression.Constant(JTokenType.Float)));
}
19
View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
static Expression BuildMinimumLength(JSchema schema, Expression o)
{
if (schema.MinimumLength == null)
return null;
return IfThenElseTrue(
IsTokenType(o, JTokenType.String),
Expression.GreaterThanOrEqual(
Expression.Convert(StringLength(o), typeof(long)),
Expression.Constant(schema.MinimumLength)));
}
19
View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
Expression BuildUniqueItems(JSchema schema, Expression o)
{
if (schema.UniqueItems == false)
return null;
return IfThenElseTrue(
IsTokenType(o, JTokenType.Array),
CallThis(nameof(UniqueItems), Expression.Constant(schema), Expression.Convert(o, typeof(JArray))));
}
19
View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
static Expression BuildMaximumLength(JSchema schema, Expression o)
{
if (schema.MaximumLength == null)
return null;
return IfThenElseTrue(
IsTokenType(o, JTokenType.String),
Expression.LessThanOrEqual(
Expression.Convert(StringLength(o), typeof(long)),
Expression.Constant(schema.MaximumLength)));
}
19
View Source File : ExpressionBuilderBase.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
protected static Expression IsTokenType(Expression o, JTokenType type) =>
Expression.Equal(TokenType(o), Expression.Constant(type));
19
View Source File : PropertyExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
IEnumerable<Expression> BuildPropertiesAll(JSchemaExpressionBuilder builder, JSchema schema, Expression o)
{
if (schema.Properties.Count > 0)
yield return IfThenElseTrue(
IsTokenType(o, JTokenType.Object),
AllOf(schema.Properties.Select(i =>
BuildProperty(builder, i.Key, i.Value, Expression.Convert(o, typeof(JObject))))));
if (schema.PatternProperties.Count > 0)
yield return IfThenElseTrue(
IsTokenType(o, JTokenType.Object),
AllOf(schema.PatternProperties.Select(i =>
BuildPatternProperty(builder, i.Key, i.Value, Expression.Convert(o, typeof(JObject))))));
if (schema.AllowAdditionalProperties == false)
{
yield return IfThenElseTrue(
IsTokenType(o, JTokenType.Object),
CallThis(
nameof(AllowAdditionalProperties),
Expression.Constant(schema),
Expression.Convert(o, typeof(JObject))));
}
else if (schema.AdditionalProperties != null)
{
var p = Expression.Parameter(typeof(JToken));
yield return IfThenElseTrue(
IsTokenType(o, JTokenType.Object),
CallThis(
nameof(AdditionalProperties),
Expression.Constant(schema),
Expression.Convert(o, typeof(JObject)),
EvalSchemaFunc(builder, schema.AdditionalProperties)));
}
}
19
View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
static Expression IsTokenType(Expression o, JTokenType type) =>
Expression.Equal(TokenType(o), Expression.Constant(type));
19
View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
Expression BuildPattern(JSchema schema, Expression o)
{
if (schema.Pattern == null)
return null;
return IfThenElseTrue(
IsTokenType(o, JTokenType.String),
CallThis(nameof(Pattern), Expression.Constant(schema.Pattern), Expression.Convert(o, typeof(string))));
}
19
View Source File : ExpressionCompilationTests.cs
License : Apache License 2.0
Project Creator : alexz76
License : Apache License 2.0
Project Creator : alexz76
[Fact]
public void ConstantExpression_Should_CompiledAndReturnResult()
{
// Arrange
const string value = "/api/get/{0}";
var constant = Expression.Constant(value, typeof(string));
// Act
var result = Expression.Lambda(constant).Compile().DynamicInvoke();
// replacedert
result.Should().Be(value);
}
See More Examples