Here are the examples of the csharp api System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, System.Collections.Generic.IEnumerable) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1171 Examples
19
View Source File : MethodInvoker.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
private Func<object, object[], dynamic> BuildInvoker(MethodInfo methodInfo)
{
if (methodInfo == null)
throw new ArgumentNullException(nameof(methodInfo), "MethodInfo cannot be null.");
var instanceParameter = Expression.Parameter(typeof(object));
var argsParameter = Expression.Parameter(typeof(object[]));
var argsExpressions = methodInfo.GetParameters().Select((item, index) => Expression.Convert(Expression.ArrayIndex(argsParameter, Expression.Constant(index)), item.ParameterType));
var instanceObj = methodInfo.IsStatic ? null : Expression.Convert(instanceParameter, methodInfo.DeclaringType ?? throw new InvalidOperationException());
var methodCaller = Expression.Call(instanceObj, methodInfo, argsExpressions);
if (methodCaller.Type == typeof(Task))
{
var action = Expression.Lambda<Action<object, object[]>>(methodCaller, instanceParameter, argsParameter).Compile();
return (instance, args) => { action(instance, args); return Task.CompletedTask; };
}
var instanceMethodCaller = Expression.Convert(methodCaller, methodInfo.ReturnType);
return Expression.Lambda<Func<object, object[], object>>(instanceMethodCaller, instanceParameter, argsParameter).Compile();
}
19
View Source File : Array3CodeGenResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 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
View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
private static void GenerateDeserializeWithCore(bool isImplGenerICollec, Type itemType, Func<Expression, Expression> ctor)
{
/*
if (reader.TryReadNullWithEnsureArray1BuildInType(BssomType.Int8Code))/TryReadNullWithEnsureArray1NativeType(NativeBssomType.CharCode)/TryReadNullWithEnsureBuildInType(BssomType.Array2)
return default;
context.option.Security.DepthStep(ref reader);
reader.SkipVariableNumber();
int len = reader.ReadVariableNumber();
T t = new T(len);
Fill<T>(ref t,ref reader,ref context,len);
context.Depth--;
return t;
*/
bool isArray1Type = Array1FormatterHelper.IsArray1Type(itemType, out bool isNativeType, out byte typeCode, out string typeCodeName);
Type t = typeof(T);
List<Expression> ary = new List<Expression>(7);
LabelTarget returnTarget = Expression.Label(t, "returnLable");
if (isArray1Type)
{
if (isNativeType)
{
//if (reader.ryReadNullWithEnsureArray1NativeType(NativeType))
// goto label;
ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1NativeType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
}
else
{
//if (reader.Call_Reader_TryReadNullWithEnsureArray1BuildInType(BuildInType))
// goto label;
ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1BuildInType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
}
}
else
{
//if (reader.TryReadNullWithEnsureBuildInType(BssomType.Array2))
// goto label;
ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureBuildInType(BssomType.Array2), Expression.Return(returnTarget, Expression.Default(t))));
}
//context.option.Security.DepthStep(ref reader);
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
//reader.SkipVariableNumber();
ary.Add(CommonExpressionMeta.Call_Reader_SkipVariableNumber);
//int len = reader.ReadVariableNumber();
ParameterExpression len = Expression.Variable(typeof(int));
ary.Add(Expression.replacedign(len, CommonExpressionMeta.Call_Reader_ReadVariableNumber));
//T t = ctor(len);
ParameterExpression instance = Expression.Variable(t);
ary.Add(Expression.replacedign(instance, ctor(len)));
MethodInfo method = null;
if (isImplGenerICollec == false)
{
//IColloctionFormatterHelper.Fill_ImplIList<T>(ref t,ref reader,ref context,len)
method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
}
else
{
if (isArray1Type)
{
//IColloctionFormatterHelper.Fill{TypeCodeName}<T>(ref t,ref reader,ref context,len)
method = typeof(Array1FormatterHelper).GetMethod(Array1FormatterHelper.FillPrefix + typeCodeName.ToString().Replace("Code", ""), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
}
else
{
//IColloctionFormatterHelper.Fill_ImplICollection<T,TElement>(ref t,ref reader,ref context,len)
method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplICollection), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { t, itemType });
}
}
ary.Add(Expression.Call(null, method, instance, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext, len));
//context.Depth--;
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
//return t;
ary.Add(Expression.Return(returnTarget, instance));
//label default(T)
ary.Add(Expression.Label(returnTarget, instance));
BlockExpression block = Expression.Block(new ParameterExpression[] { instance, len }, ary);
Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
}
19
View Source File : DbContextAsync.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
async internal Task ExecCommandAsync() {
if (isExecCommanding) return;
if (_actions.Any() == false) return;
isExecCommanding = true;
ExecCommandInfo oldinfo = null;
var states = new List<object>();
Func<string, Task<int>> dbContextBetch = methodName => {
if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
var arrType = oldinfo.stateType.MakeArrayType();
var dbsetType = oldinfo.dbSet.GetType().BaseType;
var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);
var returnTarget = Expression.Label(typeof(Task<int>));
var parm1DbSet = Expression.Parameter(typeof(object));
var parm2Vals = Expression.Parameter(typeof(object[]));
var var1Vals = Expression.Variable(arrType);
tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
new[] { var1Vals },
Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
), new[] { parm1DbSet, parm2Vals }).Compile();
trydic.Add(methodName, tryfunc);
}
return tryfunc(oldinfo.dbSet, states.ToArray());
};
Func<Task> funcDelete = async () => {
_affrows += await dbContextBetch("DbContextBetchRemoveAsync");
states.Clear();
};
Func<Task> funcInsert = async () => {
_affrows += await dbContextBetch("DbContextBetchAddAsync");
states.Clear();
};
Func<bool, Task> funcUpdate = async (isLiveUpdate) => {
var affrows = 0;
if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
if (affrows == -999) { //最后一个元素已被删除
states.RemoveAt(states.Count - 1);
return;
}
if (affrows == -998 || affrows == -997) { //没有执行更新
var laststate = states[states.Count - 1];
states.Clear();
if (affrows == -997) states.Add(laststate); //保留最后一个
}
if (affrows > 0) {
_affrows += affrows;
var islastNotUpdated = states.Count != affrows;
var laststate = states[states.Count - 1];
states.Clear();
if (islastNotUpdated) states.Add(laststate); //保留最后一个
}
};
while (_actions.Any() || states.Any()) {
var info = _actions.Any() ? _actions.Dequeue() : null;
if (oldinfo == null) oldinfo = info;
var isLiveUpdate = false;
if (_actions.Any() == false && states.Any() ||
info != null && oldinfo.actionType != info.actionType ||
info != null && oldinfo.stateType != info.stateType) {
if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
//最后一个,合起来发送
states.Add(info.state);
info = null;
}
switch (oldinfo.actionType) {
case ExecCommandInfoType.Insert:
await funcInsert();
break;
case ExecCommandInfoType.Delete:
await funcDelete();
break;
}
isLiveUpdate = true;
}
if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
if (states.Any())
await funcUpdate(isLiveUpdate);
}
if (info != null) {
states.Add(info.state);
oldinfo = info;
}
}
isExecCommanding = false;
}
19
View Source File : DbContextSync.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal void ExecCommand() {
if (isExecCommanding) return;
if (_actions.Any() == false) return;
isExecCommanding = true;
ExecCommandInfo oldinfo = null;
var states = new List<object>();
Func<string, int> dbContextBetch = methodName => {
if (_dicExecCommandDbContextBetch.TryGetValue(oldinfo.stateType, out var trydic) == false)
trydic = new Dictionary<string, Func<object, object[], int>>();
if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
var arrType = oldinfo.stateType.MakeArrayType();
var dbsetType = oldinfo.dbSet.GetType().BaseType;
var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);
var returnTarget = Expression.Label(typeof(int));
var parm1DbSet = Expression.Parameter(typeof(object));
var parm2Vals = Expression.Parameter(typeof(object[]));
var var1Vals = Expression.Variable(arrType);
tryfunc = Expression.Lambda<Func<object, object[], int>>(Expression.Block(
new[] { var1Vals },
Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
Expression.Label(returnTarget, Expression.Default(typeof(int)))
), new[] { parm1DbSet, parm2Vals }).Compile();
trydic.Add(methodName, tryfunc);
}
return tryfunc(oldinfo.dbSet, states.ToArray());
};
Action funcDelete = () => {
_affrows += dbContextBetch("DbContextBetchRemove");
states.Clear();
};
Action funcInsert = () => {
_affrows += dbContextBetch("DbContextBetchAdd");
states.Clear();
};
Action<bool> funcUpdate = isLiveUpdate => {
var affrows = 0;
if (isLiveUpdate) affrows = dbContextBetch("DbContextBetchUpdateNow");
else affrows = dbContextBetch("DbContextBetchUpdate");
if (affrows == -999) { //最后一个元素已被删除
states.RemoveAt(states.Count - 1);
return;
}
if (affrows == -998 || affrows == -997) { //没有执行更新
var laststate = states[states.Count - 1];
states.Clear();
if (affrows == -997) states.Add(laststate); //保留最后一个
}
if (affrows > 0) {
_affrows += affrows;
var islastNotUpdated = states.Count != affrows;
var laststate = states[states.Count - 1];
states.Clear();
if (islastNotUpdated) states.Add(laststate); //保留最后一个
}
};
while (_actions.Any() || states.Any()) {
var info = _actions.Any() ? _actions.Dequeue() : null;
if (oldinfo == null) oldinfo = info;
var isLiveUpdate = false;
if (_actions.Any() == false && states.Any() ||
info != null && oldinfo.actionType != info.actionType ||
info != null && oldinfo.stateType != info.stateType) {
if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
//最后一个,合起来发送
states.Add(info.state);
info = null;
}
switch (oldinfo.actionType) {
case ExecCommandInfoType.Insert:
funcInsert();
break;
case ExecCommandInfoType.Delete:
funcDelete();
break;
}
isLiveUpdate = true;
}
if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
if (states.Any())
funcUpdate(isLiveUpdate);
}
if (info != null) {
states.Add(info.state);
oldinfo = info;
}
}
isExecCommanding = false;
}
19
View Source File : Admin.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
async public static Task<bool> Use(HttpContext context, IFreeSql fsql, string requestPathBase, Dictionary<string, Type> dicEnreplacedyTypes) {
HttpRequest req = context.Request;
HttpResponse res = context.Response;
var remUrl = req.Path.ToString().Substring(requestPathBase.Length).Trim(' ', '/').Split('/');
var enreplacedyName = remUrl.FirstOrDefault();
if (!string.IsNullOrEmpty(enreplacedyName)) {
if (dicEnreplacedyTypes.TryGetValue(enreplacedyName, out var enreplacedyType) == false) throw new Exception($"UseFreeAdminLtePreview 错误,找不到实体类型:{enreplacedyName}");
var tb = fsql.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
if (tb == null) throw new Exception($"UseFreeAdminLtePreview 错误,实体类型无法映射:{enreplacedyType.FullName}");
var tpl = _tpl.Value;
switch (remUrl.ElementAtOrDefault(1)?.ToLower()) {
case null:
//首页
if (true) {
MakeTemplateFile($"{enreplacedyName}-list.html", Views.List);
//ManyToOne/OneToOne
var getlistFilter = new List<(TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
foreach (var prop in tb.Properties) {
if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
var tbref = tb.GetTableRef(prop.Key, false);
if (tbref == null) continue;
switch (tbref.RefType) {
case TableRefType.OneToMany: continue;
case TableRefType.ManyToOne:
getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
continue;
case TableRefType.OneToOne:
continue;
case TableRefType.ManyToMany:
getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
continue;
}
}
int.TryParse(req.Query["page"].FirstOrDefault(), out var getpage);
int.TryParse(req.Query["limit"].FirstOrDefault(), out var getlimit);
if (getpage <= 0) getpage = 1;
if (getlimit <= 0) getlimit = 20;
var getselect = fsql.Select<object>().AsType(enreplacedyType);
foreach (var getlistF in getlistFilter) {
var qv = req.Query[getlistF.Item3].ToArray();
if (qv.Any()) {
switch (getlistF.Item1.RefType) {
case TableRefType.OneToMany: continue;
case TableRefType.ManyToOne:
getselect.Where(Utils.GetObjectWhereExpressionContains(tb, enreplacedyType, getlistF.Item1.Columns[0].CsName, qv));
continue;
case TableRefType.OneToOne:
continue;
case TableRefType.ManyToMany:
if (true) {
var midType = getlistF.Item1.RefMiddleEnreplacedyType;
var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
var midISelect = typeof(ISelect<>).MakeGenericType(midType);
var funcType = typeof(Func<,>).MakeGenericType(typeof(object), typeof(bool));
var expParam = Expression.Parameter(typeof(object), "a");
var midParam = Expression.Parameter(midType, "mdtp");
var anyMethod = midISelect.GetMethod("Any");
var selectExp = qv.Select(c => Expression.Convert(Expression.Constant(FreeSql.Internal.Utils.GetDataReaderValue(getlistF.Item1.MiddleColumns[1].CsType, c)), getlistF.Item1.MiddleColumns[1].CsType)).ToArray();
var expLambad = Expression.Lambda<Func<object, bool>>(
Expression.Call(
Expression.Call(
Expression.Call(
Expression.Constant(fsql),
typeof(IFreeSql).GetMethod("Select", new Type[0]).MakeGenericMethod(midType)
),
midISelect.GetMethod("Where", new[] { typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(midType, typeof(bool))) }),
Expression.Lambda(
typeof(Func<,>).MakeGenericType(midType, typeof(bool)),
Expression.AndAlso(
Expression.Equal(
Expression.MakeMemberAccess(Expression.TypeAs(expParam, enreplacedyType), tb.Properties[getlistF.Item1.Columns[0].CsName]),
Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[0].CsName])
),
Expression.Call(
Utils.GetLinqContains(getlistF.Item1.MiddleColumns[1].CsType),
Expression.NewArrayInit(
getlistF.Item1.MiddleColumns[1].CsType,
selectExp
),
Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[1].CsName])
)
),
midParam
)
),
anyMethod,
Expression.Default(anyMethod.GetParameters().FirstOrDefault().ParameterType)
),
expParam);
getselect.Where(expLambad);
}
continue;
}
}
}
var getlistTotal = await getselect.CountAsync();
var getlist = await getselect.Page(getpage, getlimit).ToListAsync();
var gethashlists = new Dictionary<string, object>[getlist.Count];
var gethashlistsIndex = 0;
foreach (var getlisreplacedem in getlist) {
var gethashlist = new Dictionary<string, object>();
foreach (var getcol in tb.ColumnsByCs) {
gethashlist.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(getlisreplacedem));
}
gethashlists[gethashlistsIndex++] = gethashlist;
}
var options = new Dictionary<string, object>();
options["tb"] = tb;
options["getlist"] = gethashlists;
options["getlistTotal"] = getlistTotal;
options["getlistFilter"] = getlistFilter;
var str = _tpl.Value.RenderFile($"{enreplacedyName}-list.html", options);
await res.WriteAsync(str);
}
return true;
case "add":
case "edit":
//编辑页
object gereplacedem = null;
Dictionary<string, object> gethash = null;
if (req.Query.Any()) {
gereplacedem = Activator.CreateInstance(enreplacedyType);
foreach (var getpk in tb.Primarys) {
var reqv = req.Query[getpk.CsName].ToArray();
if (reqv.Any())
fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getpk.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
}
gereplacedem = await fsql.Select<object>().AsType(enreplacedyType).WhereDynamic(gereplacedem).FirstAsync();
if (gereplacedem != null) {
gethash = new Dictionary<string, object>();
foreach (var getcol in tb.ColumnsByCs) {
gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
}
}
}
if (req.Method.ToLower() == "get") {
MakeTemplateFile($"{enreplacedyName}-edit.html", Views.Edit);
//ManyToOne/OneToOne
var getlistFilter = new Dictionary<string, (TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
var getlistManyed = new Dictionary<string, IEnumerable<string>>();
foreach (var prop in tb.Properties) {
if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
var tbref = tb.GetTableRef(prop.Key, false);
if (tbref == null) continue;
switch (tbref.RefType) {
case TableRefType.OneToMany: continue;
case TableRefType.ManyToOne:
getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));
continue;
case TableRefType.OneToOne:
continue;
case TableRefType.ManyToMany:
getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));
if (gereplacedem != null) {
var midType = tbref.RefMiddleEnreplacedyType;
var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
var manyed = await fsql.Select<object>().AsType(midType)
.Where(Utils.GetObjectWhereExpression(midTb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]))
.ToListAsync();
getlistManyed.Add(prop.Key, manyed.Select(a => fsql.GetEnreplacedyValueWithPropertyName(midType, a, tbref.MiddleColumns[1].CsName).ToString()));
}
continue;
}
}
var options = new Dictionary<string, object>();
options["tb"] = tb;
options["gethash"] = gethash;
options["getlistFilter"] = getlistFilter;
options["getlistManyed"] = getlistManyed;
options["postaction"] = $"{requestPathBase}restful-api/{enreplacedyName}";
var str = _tpl.Value.RenderFile($"{enreplacedyName}-edit.html", options);
await res.WriteAsync(str);
} else {
if (gereplacedem == null) {
gereplacedem = Activator.CreateInstance(enreplacedyType);
foreach(var getcol in tb.Columns.Values) {
if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);
}
}
var manySave = new List<(TableRef, object[], List<object>)>();
if (req.Form.Any()) {
foreach(var getcol in tb.Columns.Values) {
if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);
var reqv = req.Form[getcol.CsName].ToArray();
if (reqv.Any())
fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
}
//ManyToMany
foreach (var prop in tb.Properties) {
if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
var tbref = tb.GetTableRef(prop.Key, false);
if (tbref == null) continue;
switch (tbref.RefType) {
case TableRefType.OneToMany: continue;
case TableRefType.ManyToOne:
continue;
case TableRefType.OneToOne:
continue;
case TableRefType.ManyToMany:
var midType = tbref.RefMiddleEnreplacedyType;
var mtb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
var reqv = req.Form[$"mn_{prop.Key}"].ToArray();
var reqvIndex = 0;
var manyVals = new object[reqv.Length];
foreach (var rv in reqv) {
var miditem = Activator.CreateInstance(midType);
foreach (var getcol in tb.Columns.Values) {
if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);
if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);
}
//fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[1].CsName, rv);
manyVals[reqvIndex++] = miditem;
}
var molds = await fsql.Select<object>().AsType(midType).Where(Utils.GetObjectWhereExpression(mtb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0])).ToListAsync();
manySave.Add((tbref, manyVals, molds));
continue;
}
}
}
using (var db = fsql.CreateDbContext()) {
var dbset = db.Set<object>();
dbset.AsType(enreplacedyType);
await dbset.AddOrUpdateAsync(gereplacedem);
foreach (var ms in manySave) {
var midType = ms.Item1.RefMiddleEnreplacedyType;
var moldsDic = ms.Item3.ToDictionary(a => fsql.GetEnreplacedyKeyString(midType, a, true));
var manyset = db.Set<object>();
manyset.AsType(midType);
foreach (var msVal in ms.Item2) {
fsql.SetEnreplacedyValueWithPropertyName(midType, msVal, ms.Item1.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
await manyset.AddOrUpdateAsync(msVal);
moldsDic.Remove(fsql.GetEnreplacedyKeyString(midType, msVal, true));
}
manyset.RemoveRange(moldsDic.Values);
}
await db.SaveChangesAsync();
}
gethash = new Dictionary<string, object>();
foreach (var getcol in tb.ColumnsByCs) {
gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
}
await Utils.Jsonp(context, new { code = 0, success = true, message = "Success", data = gethash });
}
return true;
case "del":
if (req.Method.ToLower() == "post") {
var delitems = new List<object>();
var reqv = new List<string[]>();
foreach(var delpk in tb.Primarys) {
var reqvs = req.Form[delpk.CsName].ToArray();
if (reqv.Count > 0 && reqvs.Length != reqv[0].Length) throw new Exception("删除失败,联合主键参数传递不对等");
reqv.Add(reqvs);
}
if (reqv[0].Length == 0) return true;
using (var ctx = fsql.CreateDbContext()) {
var dbset = ctx.Set<object>();
dbset.AsType(enreplacedyType);
for (var a = 0; a < reqv[0].Length; a++) {
object delitem = Activator.CreateInstance(enreplacedyType);
var delpkindex = 0;
foreach (var delpk in tb.Primarys)
fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, delitem, delpk.CsName, reqv[delpkindex++][a]);
dbset.Remove(delitem);
}
await ctx.SaveChangesAsync();
}
await Utils.Jsonp(context, new { code = 0, success = true, message = "Success" });
return true;
}
break;
}
}
return false;
}
19
View Source File : ForEachExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private Expression ReduceForEnumerable()
{
MethodInfo get_enumerator;
MethodInfo get_current;
ResolveEnumerationMembers(out get_enumerator, out get_current);
Type enumerator_type = get_enumerator.ReturnType;
ParameterExpression enumerator = Variable(enumerator_type);
LabelTarget inner_loop_continue = Label("inner_loop_continue");
LabelTarget inner_loop_break = Label("inner_loop_break");
LabelTarget @continue = ContinueLabel ?? Label("continue");
LabelTarget @break = BreakLabel ?? Label("break");
Expression variable_initializer = Property(enumerator, get_current);
if (!Variable.Type.GetTypeInfo().IsreplacedignableFrom(get_current.ReturnType.GetTypeInfo()))
variable_initializer = Convert(variable_initializer, Variable.Type);
Expression loop = Block(
new [] { Variable },
Goto(@continue),
Loop(
Block(
replacedign(Variable, variable_initializer),
Body,
Label(@continue),
Condition(
Call(enumerator, Reflection.IEnumerator_MoveNext),
Goto(inner_loop_continue),
Goto(inner_loop_break)
)
),
inner_loop_break,
inner_loop_continue
),
Label(@break)
);
Expression dispose = CreateDisposeOperation(enumerator_type.GetTypeInfo(), enumerator);
return Block(
new [] { enumerator },
replacedign(enumerator, Call(Enumerable, get_enumerator)),
dispose != null ? TryFinally(loop, dispose) : loop
);
}
19
View Source File : ForEachExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 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
View Source File : UsingExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 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
View Source File : GenericInterface.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : 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
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 : 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 : MethodInvoker.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
private static Func<object, object[], object> CreateInvokeDelegate(MethodInfo methodInfo)
{
// Target: ((TInstance)instance).Method((T0)parameters[0], (T1)parameters[1], ...)
// parameters to execute
var instanceParameter = Expression.Parameter(typeof(object), "instance");
var parametersParameter = Expression.Parameter(typeof(object[]), "parameters");
// build parameter list
var parameterExpressions = new List<Expression>();
var paramInfos = methodInfo.GetParameters();
for (int i = 0; i < paramInfos.Length; i++)
{
// (Ti)parameters[i]
BinaryExpression valueObj = Expression.ArrayIndex(
parametersParameter, Expression.Constant(i));
UnaryExpression valueCast = Expression.Convert(
valueObj, paramInfos[i].ParameterType);
parameterExpressions.Add(valueCast);
}
// non-instance for static method, or ((TInstance)instance)
var instanceCast = methodInfo.IsStatic ? null :
Expression.Convert(instanceParameter, methodInfo.ReflectedType);
// static invoke or ((TInstance)instance).Method
var methodCall = Expression.Call(instanceCast, methodInfo, parameterExpressions);
// ((TInstance)instance).Method((T0)parameters[0], (T1)parameters[1], ...)
if (methodCall.Type == typeof(void))
{
var lambda = Expression.Lambda<Action<object, object[]>>(
methodCall, instanceParameter, parametersParameter);
Action<object, object[]> execute = lambda.Compile();
return (instance, parameters) =>
{
execute(instance, parameters);
return null;
};
}
else
{
var castMethodCall = Expression.Convert(methodCall, typeof(object));
var lambda = Expression.Lambda<Func<object, object[], object>>(
castMethodCall, instanceParameter, parametersParameter);
return lambda.Compile();
}
}
19
View Source File : ExpressionVisitor.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
protected virtual Expression VisitMethodCall(MethodCallExpression m)
{
Expression obj = Visit(m.Object);
IEnumerable<Expression> args = VisitExpressionList(m.Arguments);
if (obj != m.Object || args != m.Arguments)
{
return Expression.Call(obj, m.Method, args);
}
return m;
}
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 : CustomPortIO.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
static void LoadCustomPortMethods()
{
BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
foreach (var type in AppDomain.CurrentDomain.GetAllTypes())
{
if (type.IsAbstract || type.ContainsGenericParameters)
continue ;
if (!(type.IsSubclreplacedOf(typeof(BaseNode))))
continue ;
var methods = type.GetMethods(bindingFlags);
foreach (var method in methods)
{
var portInputAttr = method.GetCustomAttribute< CustomPortInputAttribute >();
var portOutputAttr = method.GetCustomAttribute< CustomPortOutputAttribute >();
if (portInputAttr == null && portOutputAttr == null)
continue ;
var p = method.GetParameters();
bool nodePortSignature = false;
// Check if the function can take a NodePort in optional param
if (p.Length == 2 && p[1].ParameterType == typeof(NodePort))
nodePortSignature = true;
CustomPortIODelegate deleg;
#if ENABLE_IL2CPP
// IL2CPP doesn't support expression builders
if (nodePortSignature)
{
deleg = new CustomPortIODelegate((node, edges, port) => {
Debug.Log(port);
method.Invoke(node, new object[]{ edges, port});
});
}
else
{
deleg = new CustomPortIODelegate((node, edges, port) => {
method.Invoke(node, new object[]{ edges });
});
}
#else
var p1 = Expression.Parameter(typeof(BaseNode), "node");
var p2 = Expression.Parameter(typeof(List< SerializableEdge >), "edges");
var p3 = Expression.Parameter(typeof(NodePort), "port");
MethodCallExpression ex;
if (nodePortSignature)
ex = Expression.Call(Expression.Convert(p1, type), method, p2, p3);
else
ex = Expression.Call(Expression.Convert(p1, type), method, p2);
deleg = Expression.Lambda< CustomPortIODelegate >(ex, p1, p2, p3).Compile();
#endif
if (deleg == null)
{
Debug.LogWarning("Can't use custom IO port function " + method + ": The method have to respect this format: " + typeof(CustomPortIODelegate));
continue ;
}
string fieldName = (portInputAttr == null) ? portOutputAttr.fieldName : portInputAttr.fieldName;
Type customType = (portInputAttr == null) ? portOutputAttr.outputType : portInputAttr.inputType;
Type fieldType = type.GetField(fieldName, bindingFlags).FieldType;
AddCustomIOMethod(type, fieldName, deleg);
AddreplacedignableTypes(customType, fieldType);
AddreplacedignableTypes(fieldType, customType);
}
}
}
19
View Source File : TypeExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public static Func<object, object> GetValueGetter([NotNull] this PropertyInfo @this)
{
return ReflectionDictionary.PropertyValueGetters.GetOrAdd(@this, prop =>
{
if (!prop.CanRead)
return null;
Debug.replacedert(@this.DeclaringType != null);
var instance = Expression.Parameter(typeof(object), "obj");
var getterCall = Expression.Call(@this.DeclaringType.IsValueType
? Expression.Unbox(instance, @this.DeclaringType)
: Expression.Convert(instance, @this.DeclaringType), prop.GetGetMethod());
var castToObject = Expression.Convert(getterCall, typeof(object));
return (Func<object, object>)Expression.Lambda(castToObject, instance).Compile();
});
}
19
View Source File : ReflectionExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
[CanBeNull]
public static Action<T, object> GetValueSetter<T>(this PropertyInfo propertyInfo) where T : clreplaced
{
return StrongTypedCache<T>.PropertyValueSetters.GetOrAdd(propertyInfo, prop =>
{
if (!prop.CanWrite)
return null;
var instance = Expression.Parameter(typeof(T), "i");
var argument = Expression.Parameter(typeof(object), "a");
var setterCall = Expression.Call(instance, prop.GetSetMethod(), Expression.Convert(argument, prop.PropertyType));
return (Action<T, object>)Expression.Lambda(setterCall, instance, argument).Compile();
});
}
19
View Source File : ReflectionExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
[CanBeNull]
public static Func<object, object> GetValueGetter([NotNull] this PropertyInfo propertyInfo)
{
return CacheUtil.PropertyValueGetters.GetOrAdd(propertyInfo, prop =>
{
if (!prop.CanRead)
return null;
Debug.replacedert(propertyInfo.DeclaringType != null);
var instance = Expression.Parameter(typeof(object), "obj");
var getterCall = Expression.Call(propertyInfo.DeclaringType.IsValueType
? Expression.Unbox(instance, propertyInfo.DeclaringType)
: Expression.Convert(instance, propertyInfo.DeclaringType), prop.GetGetMethod());
var castToObject = Expression.Convert(getterCall, typeof(object));
return (Func<object, object>)Expression.Lambda(castToObject, instance).Compile();
});
}
19
View Source File : TypeExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public static Action<T, object> GetValueSetter<T>([NotNull] this PropertyInfo @this) where T : clreplaced
{
return StrongTypedDictionary<T>.PropertyValueSetters.GetOrAdd(@this, prop =>
{
if (!prop.CanWrite)
return null;
var instance = Expression.Parameter(typeof(T), "i");
var argument = Expression.Parameter(typeof(object), "a");
var setterCall = Expression.Call(instance, prop.GetSetMethod(), Expression.Convert(argument, prop.PropertyType));
return (Action<T, object>)Expression.Lambda(setterCall, instance, argument).Compile();
});
}
19
View Source File : Engine.cs
License : GNU Affero General Public License v3.0
Project Creator : ankenyr
License : GNU Affero General Public License v3.0
Project Creator : ankenyr
static System.Linq.Expressions.Expression BuildExpr<T>(Expression r, ParameterExpression param)
{
var left = MemberExpression.Property(param, r.MemberName);
var tProp = typeof(T).GetProperty(r.MemberName).PropertyType;
ExpressionType tBinary;
// is the operator a known .NET operator?
if (ExpressionType.TryParse(r.Operator, out tBinary))
{
var right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(r.TargetValue, tProp));
// use a binary operation, e.g. 'Equal' -> 'u.Age == 15'
return System.Linq.Expressions.Expression.MakeBinary(tBinary, left, right);
}
if (r.Operator == "MatchRegex" || r.Operator == "NotMatchRegex")
{
var regex = new Regex(r.TargetValue);
var method = typeof(Regex).GetMethod("IsMatch", new[] {typeof(string)});
Debug.replacedert(method != null, nameof(method) + " != null");
var callInstance = System.Linq.Expressions.Expression.Constant(regex);
var toStringMethod = tProp.GetMethod("ToString", new Type[0]);
Debug.replacedert(toStringMethod != null, nameof(toStringMethod) + " != null");
var methodParam = System.Linq.Expressions.Expression.Call(left, toStringMethod);
var call = System.Linq.Expressions.Expression.Call(callInstance, method, methodParam);
if (r.Operator == "MatchRegex") return call;
if (r.Operator == "NotMatchRegex") return System.Linq.Expressions.Expression.Not(call);
}
if (tProp.Name == "String")
{
var method = tProp.GetMethod(r.Operator, new Type[] { typeof(string) });
var tParam = method.GetParameters()[0].ParameterType;
var right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(r.TargetValue, tParam));
// use a method call, e.g. 'Contains' -> 'u.Tags.Contains(some_tag)'
return System.Linq.Expressions.Expression.Call(left, method, right);
}
else {
var method = tProp.GetMethod(r.Operator);
var tParam = method.GetParameters()[0].ParameterType;
var right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(r.TargetValue, tParam));
// use a method call, e.g. 'Contains' -> 'u.Tags.Contains(some_tag)'
return System.Linq.Expressions.Expression.Call(left, method, right);
}
}
19
View Source File : FunctionCall.cs
License : MIT License
Project Creator : ansel86castro
License : MIT License
Project Creator : ansel86castro
public override System.Linq.Expressions.Expression GenerateLinqExpression(IASTContext context)
{
if (Function.IsQueryMethod)
{
var genArg = Instance.NetType.GetGenericArguments();
var method = Function.Method.MakeGenericMethod(genArg[0]);
if (Parameters.Length > 0)
{
var lambdaExp = Parameters[0].GenerateLinqExpression(new QueryASTContext
{
ModelType = genArg[0],
Parameter = _parameter
});
var lambda = System.Linq.Expressions.Expression.Lambda(method.GetParameters()[1].ParameterType, lambdaExp, _parameter);
return System.Linq.Expressions.Expression.Call(Function.Method.DeclaringType, Function.Method.Name, new Type[] { genArg[0] },
new System.Linq.Expressions.Expression[]
{
Instance?.GenerateLinqExpression(context),
lambda
});
}
else
{
return System.Linq.Expressions.Expression.Call(Function.Method.DeclaringType, Function.Method.Name, new Type[] { genArg[0] },
new System.Linq.Expressions.Expression[]
{
Instance?.GenerateLinqExpression(context)
});
}
}
else
{
System.Linq.Expressions.Expression[] argsExp = new System.Linq.Expressions.Expression[Parameters.Length];
for (int i = 0; i < Parameters.Length; i++)
{
argsExp[i] = Parameters[i].GenerateLinqExpression(context);
}
System.Linq.Expressions.Expression instanceExp = Function.Target != null ?
System.Linq.Expressions.Expression.Constant(Function.Target)
: Instance?.GenerateLinqExpression(context);
var callExp = System.Linq.Expressions.Expression.Call(instanceExp, Function.Method);
return System.Linq.Expressions.Expression.Invoke(callExp, argsExp);
}
}
19
View Source File : ExpressionVisitor.cs
License : MIT License
Project Creator : anthonyreilly
License : MIT License
Project Creator : anthonyreilly
protected MethodCallExpression UpdateMethodCall(MethodCallExpression m, Expression obj, MethodInfo method, IEnumerable<Expression> args)
{
if (obj != m.Object || method != m.Method || args != m.Arguments)
{
return Expression.Call(obj, method, args);
}
return m;
}
19
View Source File : AssertArguments.cs
License : MIT License
Project Creator : Archomeda
License : MIT License
Project Creator : Archomeda
public static void ThrowsWhenNull(Expression<Action> expression, params bool[] paramsNull)
{
// Original: https://www.thomaslevesque.com/2014/11/02/easy-unit-testing-of-null-argument-validation/
MemberInfo callMethod;
ParameterInfo[] callParams;
IReadOnlyCollection<Expression> callArgs;
Expression? callObj = null;
switch (expression.Body.NodeType)
{
case ExpressionType.Call:
callMethod = ((MethodCallExpression)expression.Body).Method;
callParams = ((MethodCallExpression)expression.Body).Method.GetParameters();
callArgs = ((MethodCallExpression)expression.Body).Arguments;
callObj = ((MethodCallExpression)expression.Body).Object;
break;
case ExpressionType.New:
callMethod = ((NewExpression)expression.Body).Constructor;
callParams = ((NewExpression)expression.Body).Constructor.GetParameters();
callArgs = ((NewExpression)expression.Body).Arguments;
break;
default:
throw new ArgumentException("Expression body is not a method or constructor call", nameof(expression));
}
for (int i = 0; i < paramsNull.Length && i < callArgs.Count; i++)
{
if (!paramsNull[i])
continue;
var args = callArgs.ToArray();
args[i] = Expression.Constant(null, callParams[i].ParameterType);
Expression? callExpr = null;
switch (expression.Body.NodeType)
{
case ExpressionType.Call:
callExpr = Expression.Call(callObj, callMethod as MethodInfo, args);
break;
case ExpressionType.New:
callExpr = Expression.New(callMethod as ConstructorInfo, args);
break;
}
var action = Expression.Lambda<Action>(callExpr).Compile();
replacedert.Throws<ArgumentNullException>(callParams[i].Name, action);
}
}
19
View Source File : AssertArguments.cs
License : MIT License
Project Creator : Archomeda
License : MIT License
Project Creator : Archomeda
public static Task ThrowsWhenNullAsync(Expression<Func<Task>> expression, params bool[] paramsNull)
{
// Original: https://www.thomaslevesque.com/2014/11/02/easy-unit-testing-of-null-argument-validation/
MemberInfo callMethod;
ParameterInfo[] callParams;
IReadOnlyCollection<Expression> callArgs;
Expression? callObj = null;
switch (expression.Body.NodeType)
{
case ExpressionType.Call:
callMethod = ((MethodCallExpression)expression.Body).Method;
callParams = ((MethodCallExpression)expression.Body).Method.GetParameters();
callArgs = ((MethodCallExpression)expression.Body).Arguments;
callObj = ((MethodCallExpression)expression.Body).Object;
break;
case ExpressionType.New:
callMethod = ((NewExpression)expression.Body).Constructor;
callParams = ((NewExpression)expression.Body).Constructor.GetParameters();
callArgs = ((NewExpression)expression.Body).Arguments;
break;
default:
throw new ArgumentException("Expression body is not a method or constructor call", nameof(expression));
}
var tasks = new List<Task>();
for (int i = 0; i < paramsNull.Length && i < callArgs.Count; i++)
{
if (!paramsNull[i])
continue;
var args = callArgs.ToArray();
args[i] = Expression.Constant(null, callParams[i].ParameterType);
Expression? callExpr = null;
switch (expression.Body.NodeType)
{
case ExpressionType.Call:
callExpr = Expression.Call(callObj, callMethod as MethodInfo, args);
break;
case ExpressionType.New:
callExpr = Expression.New(callMethod as ConstructorInfo, args);
break;
}
var action = Expression.Lambda<Func<Task>>(callExpr).Compile();
tasks.Add(replacedert.ThrowsAsync<ArgumentNullException>(callParams[i].Name, action));
}
return Task.WhenAll(tasks);
}
19
View Source File : IncludeExtensions.cs
License : MIT License
Project Creator : ardalis
License : MIT License
Project Creator : ardalis
public static IQueryable<T> Include<T>(this IQueryable<T> source, IncludeExpressionInfo info)
{
_ = info ?? throw new ArgumentNullException(nameof(info));
var queryExpr = Expression.Call(
typeof(EnreplacedyFrameworkQueryableExtensions),
"Include",
new Type[] {
info.EnreplacedyType,
info.PropertyType
},
source.Expression,
info.LambdaExpression
);
return source.Provider.CreateQuery<T>(queryExpr);
}
19
View Source File : IncludeExtensions.cs
License : MIT License
Project Creator : ardalis
License : MIT License
Project Creator : ardalis
public static IQueryable<T> ThenInclude<T>(this IQueryable<T> source, IncludeExpressionInfo info)
{
_ = info ?? throw new ArgumentNullException(nameof(info));
_ = info.PreviousPropertyType ?? throw new ArgumentNullException(nameof(info.PreviousPropertyType));
var queryExpr = Expression.Call(
typeof(EnreplacedyFrameworkQueryableExtensions),
"ThenInclude",
new Type[] {
info.EnreplacedyType,
info.PreviousPropertyType,
info.PropertyType
},
source.Expression,
info.LambdaExpression
);
return source.Provider.CreateQuery<T>(queryExpr);
}
19
View Source File : SearchExtension.cs
License : MIT License
Project Creator : ardalis
License : MIT License
Project Creator : ardalis
public static IQueryable<T> Search<T>(this IQueryable<T> source, IEnumerable<(Expression<Func<T, string>> selector, string searchTerm)> criterias)
{
Expression? expr = null;
var parameter = Expression.Parameter(typeof(T), "x");
foreach (var criteria in criterias)
{
if (criteria.selector == null || string.IsNullOrEmpty(criteria.searchTerm))
continue;
var functions = Expression.Property(null, typeof(EF).GetProperty(nameof(EF.Functions)));
var like = typeof(DbFunctionsExtensions).GetMethod(nameof(DbFunctionsExtensions.Like), new Type[] { functions.Type, typeof(string), typeof(string) });
var propertySelector = ParameterReplacerVisitor.Replace(criteria.selector, criteria.selector.Parameters[0], parameter);
var likeExpression = Expression.Call(
null,
like,
functions,
(propertySelector as LambdaExpression)?.Body,
Expression.Constant(criteria.searchTerm));
expr = expr == null ? (Expression)likeExpression : Expression.OrElse(expr, likeExpression);
}
return expr == null
? source
: source.Where(Expression.Lambda<Func<T, bool>>(expr, parameter));
}
19
View Source File : SearchExtension.cs
License : MIT License
Project Creator : ardalis
License : MIT License
Project Creator : ardalis
public static IQueryable<T> Search<T>(this IQueryable<T> source, IEnumerable<(Expression<Func<T, string>> selector, string searchTerm)> criterias)
{
Expression expr = null;
var parameter = Expression.Parameter(typeof(T), "x");
foreach (var (selector, searchTerm) in criterias)
{
if (selector == null || string.IsNullOrEmpty(searchTerm))
continue;
var like = typeof(DbFunctions).GetMethod(nameof(DbFunctions.Like), new Type[] { typeof(string), typeof(string) });
var propertySelector = ParameterReplacerVisitor.Replace(selector, selector.Parameters[0], parameter);
var likeExpression = Expression.Call(
null,
like,
(propertySelector as LambdaExpression)?.Body,
Expression.Constant(searchTerm));
expr = expr == null ? (Expression)likeExpression : Expression.OrElse(expr, likeExpression);
}
return expr == null
? source
: source.Where(Expression.Lambda<Func<T, bool>>(expr, parameter));
}
19
View Source File : DataRecordExtensions.cs
License : MIT License
Project Creator : arttonoyan
License : MIT License
Project Creator : arttonoyan
private static Expression<Func<IDataRecord, TModel>> Map<TModel>(IReadOnlyDictionary<string, string> bindings)
where TModel : clreplaced, new()
{
Type modelType = typeof(TModel);
IEnumerable<PropertyInfo> properties = modelType.GetProperties(bindings);
var parameter = Expression.Parameter(typeof(IDataRecord), "ireader");
var mi = typeof(IDataRecord).GetProperties()
.FirstOrDefault(p => p.GetIndexParameters().Any(p1 => p1.ParameterType == typeof(string)))
?.GetMethod;
var memberBindings = new List<MemberBinding>();
foreach (PropertyInfo member in properties)
{
string name = member.Name;
if (!bindings.IsNullOrEmpty())
{
if (bindings.ContainsKey(member.Name))
name = bindings[member.Name];
}
var indexatorExp = Expression.Call(parameter, mi, Expression.Constant(name, typeof(string)));
Expression valueExp;
if (member.PropertyType.IsPrimitive)
{
MethodInfo asTypeMethodInfo = typeof(Check).GetMethods().Single(p => p.Name == $"As{member.PropertyType.Name}");
valueExp = Expression.Call(asTypeMethodInfo, indexatorExp);
}
else
{
if (Check.Nullable(member.PropertyType))
{
MethodInfo asTypeMethodInfo = typeof(Check).GetMethods().Single(p => p.Name == $"AsNullable{Check.GetUnderlyingType(member.PropertyType).Name}");
valueExp = Expression.Call(asTypeMethodInfo, indexatorExp);
}
else
{
MethodInfo dBNullValueMethodInfo = typeof(Check).GetMethods().Single(p => p.Name == nameof(Check.DBNullValue));
var nullableExp = Expression.Call(dBNullValueMethodInfo, indexatorExp);
valueExp = Expression.Convert(nullableExp, member.PropertyType);
}
}
memberBindings.Add(Expression.Bind(member, valueExp));
}
NewExpression model = Expression.New(modelType);
MemberInitExpression memberInitExpression = Expression.MemberInit(model, memberBindings);
return Expression.Lambda<Func<IDataRecord, TModel>>(memberInitExpression, parameter);
}
19
View Source File : CompilationProtocol.cs
License : MIT License
Project Creator : asc-community
License : MIT License
Project Creator : asc-community
public virtual Expression ConvertUnaryNode(Expression e, Enreplacedy typeHolder)
{
if (UnaryNodeConverter is not null)
return UnaryNodeConverter(e, typeHolder);
return typeHolder switch
{
Sinf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("Sin", 1, newE.Type), newE),
Cosf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("Cos", 1, newE.Type), newE),
Tanf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("Tan", 1, newE.Type), newE),
Cotanf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("Cot", 1, newE.Type), newE),
Secantf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("Sec", 1, newE.Type), newE),
Cosecantf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("Csc", 1, newE.Type), newE),
Arcsinf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("Asin", 1, newE.Type), newE),
Arccosf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("Acos", 1, newE.Type), newE),
Arctanf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("Atan", 1, newE.Type), newE),
Arccotanf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("Acot", 1, newE.Type), newE),
Arcsecantf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("Asec", 1, newE.Type), newE),
Arccosecantf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("Acsc", 1, newE.Type), newE),
Absf => Expression.Call(GetDef("Abs", 1, e.Type), e),
Signumf => Expression.Call(GetDef("Sgn", 1, e.Type), e),
Notf => Expression.Not(e),
_ => throw new AngouriBugException("An unary node seems to be not added")
};
19
View Source File : CompilationProtocol.cs
License : MIT License
Project Creator : asc-community
License : MIT License
Project Creator : asc-community
public virtual Expression ConvertBinaryNode(Expression left, Expression right, Enreplacedy typeHolder)
{
if (BinaryNodeConverter is not null)
return BinaryNodeConverter(left, right, typeHolder);
(left, right) = EqualizeTypesIfAble(left, right);
return typeHolder switch
{
Sumf => Expression.Add(left, right),
Minusf => Expression.Subtract(left, right),
Mulf => Expression.Multiply(left, right),
Divf => Expression.Divide(ShouldBeAtLeastDouble(left), ShouldBeAtLeastDouble(right)),
Powf when
ShouldBeAtLeastDouble(left) is var newLeft
&& ShouldBeAtLeastDouble(right) is var newRight
=> Expression.Call(GetDef("Pow", 2, newLeft.Type), newLeft, newRight),
Logf when
ShouldBeAtLeastDouble(left) is var newLeft
&& ShouldBeAtLeastDouble(right) is var newRight
=> Expression.Call(GetDef("Log", 2, newRight.Type), newLeft, newRight),
Andf => Expression.And(left, right),
Orf => Expression.Or(left, right),
Xorf => Expression.ExclusiveOr(left, right),
Impliesf => Expression.Or(Expression.Not(left), right),
Lessf => Expression.LessThan(left, right),
LessOrEqualf => Expression.LessThanOrEqual(left, right),
Greaterf => Expression.GreaterThan(left, right),
GreaterOrEqualf => Expression.GreaterThanOrEqual(left, right),
Equalsf => Expression.Equal(left, right),
Providedf => HandleProvidedf(left, right),
_ => throw new AngouriBugException("A binary node seems to be not added")
};
19
View Source File : SourceInjectedQueryProvider.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
protected override Expression VisitMethodCall(MethodCallExpression node)
{
// only replace first occurrence
if (ReplacedMethod != null || _foundExpression == null)
{
return base.VisitMethodCall(node);
}
if (node == _foundExpression)
{
// if method has invalid type
var parameters = node.Method.GetParameters();
if (parameters.Length > 1 &&
typeof(Expression).IsreplacedignableFrom(parameters[1].ParameterType))
{
FoundElementOperator = true;
ReplacedMethod = node.Method.GetGenericMethodDefinition();
return Call(null, QueryableWhereMethod.MakeGenericMethod(typeof(TDestination)),
node.Arguments);
}
// no predicate
if (parameters.Length == 1)
{
FoundElementOperator = true;
ElementOperator = node.Method.GetGenericMethodDefinition();
return node.Arguments[0];
}
}
return base.VisitMethodCall(node);
}
19
View Source File : XpressionMapperVisitor.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
protected override Expression VisitMethodCall(MethodCallExpression node)
{
var parameterExpression = node.GetParameterExpression();
if (parameterExpression != null)
InfoDictionary.Add(parameterExpression, TypeMappings);
var listOfArgumentsForNewMethod = node.Arguments.Aggregate(new List<Expression>(), (lst, next) =>
{
var mappedNext = this.Visit(next);
TypeMappings.AddTypeMapping(ConfigurationProvider, next.Type, mappedNext.Type);
lst.Add(mappedNext);
return lst;
});//Arguments could be expressions or other objects. e.g. s => s.UserId or a string "ZZZ". For extention methods node.Arguments[0] is usually the helper object itself
//type args are the generic type args e.g. T1 and T2 MethodName<T1, T2>(method arguments);
var typeArgsForNewMethod = node.Method.IsGenericMethod
? node.Method.GetGenericArguments().Select(type => this.TypeMappings.ReplaceType(type)).ToList()//not converting the type it is not in the typeMappings dictionary
: null;
ConvertTypesIfNecessary(node.Method.GetParameters(), listOfArgumentsForNewMethod, node.Method);
return node.Method.IsStatic
? GetStaticExpression()
: GetInstanceExpression(this.Visit(node.Object));
MethodCallExpression GetInstanceExpression(Expression instance)
=> node.Method.IsGenericMethod
? Expression.Call(instance, node.Method.Name, typeArgsForNewMethod.ToArray(), listOfArgumentsForNewMethod.ToArray())
: Expression.Call(instance, node.Method, listOfArgumentsForNewMethod.ToArray());
MethodCallExpression GetStaticExpression()
=> node.Method.IsGenericMethod
? Expression.Call(node.Method.DeclaringType, node.Method.Name, typeArgsForNewMethod.ToArray(), listOfArgumentsForNewMethod.ToArray())
: Expression.Call(node.Method, listOfArgumentsForNewMethod.ToArray());
}
19
View Source File : ExpressionMapper.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
protected override Expression VisitBinary(BinaryExpression node)
{
var newLeft = Visit(node.Left);
var newRight = Visit(node.Right);
// check if the non-string expression is a null constent
// as this would lead to a "null.ToString()" and thus an error when executing the expression
if (newLeft.Type != newRight.Type && newRight.Type == typeof(string) && !IsNullConstant(newLeft))
newLeft = Call(newLeft, typeof(object).GetDeclaredMethod("ToString"));
if (newRight.Type != newLeft.Type && newLeft.Type == typeof(string) && !IsNullConstant(newRight))
newRight = Call(newRight, typeof(object).GetDeclaredMethod("ToString"));
CheckNullableToNonNullableChanges(node.Left, node.Right, ref newLeft, ref newRight);
CheckNullableToNonNullableChanges(node.Right, node.Left, ref newRight, ref newLeft);
return MakeBinary(node.NodeType, newLeft, newRight);
bool IsNullConstant(Expression expression) => expression is ConstantExpression constant && constant.Value == null;
}
19
View Source File : FilterAppender.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
protected override Expression VisitMethodCall(MethodCallExpression node)
{
Type elementType = expansion.MemberType.GetUnderlyingElementType();
if (node.Method.Name == "Select"
&& elementType == node.Type.GetUnderlyingElementType()
&& this.expression.ToString().StartsWith(node.ToString()))//makes sure we're not updating some nested "Select"
{
return Expression.Call
(
node.Method.DeclaringType,
"Where",
new Type[] { node.GetUnderlyingElementType() },
node,
expansion.FilterOptions.FilterClause.GetFilterExpression(elementType)
);
}
return base.VisitMethodCall(node);
}
19
View Source File : PrependParentNameVisitor.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (!IsParentParameterExpression())
return base.VisitMethodCall(node);
if (!object.ReferenceEquals(CurrentParameter, node.GetParameterExpression()))
return base.VisitMethodCall(node);
if (node.Method.IsStatic)
{
if (!IsExtentionMethod())
return base.VisitMethodCall(node);
if (node.Method.IsGenericMethod)
return Expression.Call
(
node.Method.DeclaringType,
node.Method.Name,
node.Method.GetGenericArguments(),
GetNewArgumentsForExtensionMethod()
);
else
return Expression.Call(node.Method, GetNewArgumentsForExtensionMethod());
}
//instance method
if (node.Method.IsGenericMethod)
{
return Expression.Call
(
GetNewParent(),
node.Method.Name,
node.Method.GetGenericArguments(),
node.Arguments.ToArray()
);
}
else
{
return Expression.Call
(
GetNewParent(),
node.Method,
node.Arguments
);
}
Expression[] GetNewArgumentsForExtensionMethod()
{
Expression[] arguments = node.Arguments.ToArray();
arguments[0] = GetNewParent();
return arguments.ToArray();
}
Expression GetNewParent()
=> string.IsNullOrEmpty(ParentFullName)
? NewParameter
: ExpressionHelpers.MemberAccesses(ParentFullName, NewParameter);
bool IsParentParameterExpression()
{
if (node.Method.IsStatic)
return node.Arguments[0] is ParameterExpression;
if (!node.Method.IsStatic)
return node.Object is ParameterExpression;
return false;
}
bool IsExtentionMethod()
=> node.Method.IsDefined(typeof(ExtensionAttribute), true);
}
19
View Source File : LinqExtensions.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
public static Expression GetSkipCall(this Expression expression, int? skip)
{
if (skip == null) return expression;
return Expression.Call
(
expression.Type.IsIQueryable() ? typeof(Queryable) : typeof(Enumerable),
"Skip",
new[] { expression.GetUnderlyingElementType() },
expression,
Expression.Constant(skip.Value)
);
}
19
View Source File : LinqExtensions.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
public static Expression GetTakeCall(this Expression expression, int? top)
{
if (top == null) return expression;
return Expression.Call
(
expression.Type.IsIQueryable() ? typeof(Queryable) : typeof(Enumerable),
"Take",
new[] { expression.GetUnderlyingElementType() },
expression,
Expression.Constant(top.Value)
);
}
19
View Source File : LinqExtensions.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
public static Expression GetOrderByCountCall(this Expression expression, string memberFullName, string methodName, string selectorParameterName = "a")
{
Type sourceType = expression.GetUnderlyingElementType();
ParameterExpression param = Expression.Parameter(sourceType, selectorParameterName);
Expression countSelector = param.MakeSelector(memberFullName).GetCountCall();
return Expression.Call
(
expression.Type.IsIQueryable() ? typeof(Queryable) : typeof(Enumerable),
methodName,
new Type[] { sourceType, countSelector.Type },
expression,
param.MakeLambdaExpression
(
countSelector
)
);
}
19
View Source File : LinqExtensions.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
public static Expression GetOrderByCall(this Expression expression, string memberFullName, string methodName, string selectorParameterName = "a")
{
Type sourceType = expression.GetUnderlyingElementType();
MemberInfo memberInfo = sourceType.GetMemberInfoFromFullName(memberFullName);
return Expression.Call
(
expression.Type.IsIQueryable() ? typeof(Queryable) : typeof(Enumerable),
methodName,
new Type[] { sourceType, memberInfo.GetMemberType() },
expression,
memberFullName.GetTypedSelector(sourceType, selectorParameterName)
);
}
19
View Source File : TypeSchema.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
private dyn_serialize makeSerialize()
{
var _walkArrayWrite = typeof(TypeDescriptor).GetMethod("walkArrayWrite", BindingFlags.NonPublic | BindingFlags.Static);
var pSchema = Expression.Parameter(typeof(TypeSchema));
var pWriter = Expression.Parameter(typeof(SlimWriter));
var pTReg = Expression.Parameter(typeof(TypeRegistry));
var pRefs = Expression.Parameter(typeof(RefPool));
var pInstance = Expression.Parameter(typeof(object));
var pStreamingContext = Expression.Parameter(typeof(StreamingContext));
var expressions = new List<Expression>();
var instance = Expression.Variable(Type, "instance");
expressions.Add( Expression.replacedign(instance, Expression.Convert(pInstance, Type)));
if (IsPrimitive)
{
expressions.Add( Expression.Call(pWriter,
Format.GetWriteMethodForType(Type),
instance) );
}
else if (IsArray)
{
var elmType = Type.GetElementType();
if (Format.IsTypeSupported(elmType))//array element type
{ //spool whole array into writer using primitive types
var pElement = Expression.Parameter(typeof(object));
expressions.Add( Expression.Call(_walkArrayWrite,
instance,
Expression.Lambda(Expression.Call(pWriter,
Format.GetWriteMethodForType(elmType),
Expression.Convert(pElement, elmType)), pElement)
)
);
}
else
{ //spool whole array using TypeSchema because objects may change type
var pElement = Expression.Parameter(typeof(object));
if (!elmType.IsValueType)//reference type
expressions.Add( Expression.Call(_walkArrayWrite,
instance,
Expression.Lambda(Expression.Call(pSchema,
typeof(TypeSchema).GetMethod("writeRefMetaHandle"),
pWriter,
pTReg,
pRefs,
Expression.Convert( pElement, typeof(object) ),
pStreamingContext),
pElement)
)
);
else
expressions.Add( Expression.Call(_walkArrayWrite,
instance,
Expression.Lambda(Expression.Call(pSchema,
typeof(TypeSchema).GetMethod("Serialize"),
pWriter,
pTReg,
pRefs,
pElement,
pStreamingContext,
Expression.Constant(elmType)//valueType
), pElement)
)
);
}
}
else
{
foreach(var field in Fields)
{
Expression expr = null;
Type t = field.FieldType;
if (Format.IsTypeSupported(t))
{
expr = Expression.Call(pWriter,
Format.GetWriteMethodForType(t),
Expression.Field(instance, field));
}
else
if (t.IsEnum)
{
expr = Expression.Call(pWriter,
Format.GetWriteMethodForType(typeof(int)),
Expression.Convert(Expression.Field(instance, field), typeof(int)));
}
else // complex type -> struct or reference
{
if (!t.IsValueType)//reference type -> write metahandle
{
expr = Expression.Call(pSchema,
typeof(TypeSchema).GetMethod("writeRefMetaHandle"),
pWriter,
pTReg,
pRefs,
Expression.Convert( Expression.Field(instance, field), typeof(object) ),
pStreamingContext);
}
else
expr = Expression.Call(pSchema,
typeof(TypeSchema).GetMethod("Serialize"),
pWriter,
pTReg,
pRefs,
Expression.Convert( Expression.Field(instance, field), typeof(object) ),
pStreamingContext,
Expression.Constant(field.FieldType));//valueType
}
expressions.Add(expr);
}//foreach
}
var body = Expression.Block(new ParameterExpression[]{instance}, expressions);
return Expression.Lambda<dyn_serialize>(body, pSchema, pWriter, pTReg, pRefs, pInstance, pStreamingContext).Compile();
}
19
View Source File : TypeSchema.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
private dyn_deserialize makeDeserialize()
{
var pSchema = Expression.Parameter(typeof(TypeSchema));
var pReader = Expression.Parameter(typeof(SlimReader));
var pTReg = Expression.Parameter(typeof(TypeRegistry));
var pRefs = Expression.Parameter(typeof(RefPool));
var pInstance = Expression.Parameter(typeof(object).MakeByRefType());
var pStreamingContext = Expression.Parameter(typeof(StreamingContext));
var expressions = new List<Expression>();
var instance = Expression.Variable(Type, "instance");
expressions.Add( Expression.replacedign(instance, Expression.Convert(pInstance, Type)));
if (IsPrimitive)
{
expressions.Add( Expression.replacedign
(instance, Expression.Call(pReader, Format.GetReadMethodForType(Type)) )
);
}
else if (IsArray)
{
var elmType = Type.GetElementType();
var _walkArrayRead = typeof(TypeDescriptor).GetMethod("walkArrayRead", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(elmType);
if (Format.IsTypeSupported(elmType))//array element type
{
//spool whole array from reader using primitive types
expressions.Add( Expression.Call(_walkArrayRead,
instance,
Expression.Lambda(Expression.Call(pReader, Format.GetReadMethodForType(elmType)))
)
);
}
else
{ //spool whole array using TypeSchema because objects may change type
if (!elmType.IsValueType)//reference type
expressions.Add( Expression.Call(_walkArrayRead,
instance,
Expression.Lambda(
Expression.Convert(
Expression.Call(pSchema,
typeof(TypeSchema).GetMethod("readRefMetaHandle"),
pReader,
pTReg,
pRefs,
pStreamingContext),
elmType
)
)
)
);
else
expressions.Add( Expression.Call(_walkArrayRead,
instance,
Expression.Lambda(
Expression.Convert(
Expression.Call(pSchema,
typeof(TypeSchema).GetMethod("Deserialize"),
pReader,
pTReg,
pRefs,
pStreamingContext,
Expression.Constant(elmType)),//valueType
elmType
)
)
)
);
}
}
else//loop through fields
{
foreach(var field in Fields)
{
Expression expr = null;
Type t = field.FieldType;
Expression replacedignmentTargetExpression;
if (field.IsInitOnly)//readonly fields must be replacedigned using reflection
{
replacedignmentTargetExpression = Expression.Variable(t, "readonlyFieldValue");
}
else
replacedignmentTargetExpression = Expression.Field(instance, field);
if (Format.IsTypeSupported(t))
{
expr = Expression.replacedign(
replacedignmentTargetExpression,
Expression.Call(pReader, Format.GetReadMethodForType(t))
);
}
else
if (t.IsEnum)
{
expr = Expression.replacedign(
replacedignmentTargetExpression,
Expression.Convert(
Expression.Call(pReader, Format.GetReadMethodForType(typeof(int))),
field.FieldType
)
);
}
else // complex type -> struct or reference
{
if (!t.IsValueType)//reference type -> read metahandle
{
expr = Expression.replacedign(
replacedignmentTargetExpression,
Expression.Convert(
Expression.Call(pSchema,
typeof(TypeSchema).GetMethod("readRefMetaHandle"),
pReader,
pTReg,
pRefs,
pStreamingContext),
field.FieldType)
);
}
else
{
expr = Expression.replacedign(
replacedignmentTargetExpression,
Expression.Convert(
Expression.Call(pSchema,
typeof(TypeSchema).GetMethod("Deserialize"),
pReader,
pTReg,
pRefs,
pStreamingContext,
Expression.Constant(field.FieldType)),//valueType
field.FieldType)
);
}
}
if (replacedignmentTargetExpression is ParameterExpression)//readonly fields
{
if (Type.IsValueType)//20150405DKh added
{
var vBoxed = Expression.Variable(typeof(object), "vBoxed");
var box = Expression.replacedign(vBoxed, Expression.TypeAs( instance, typeof(object)));//box the value type
var setField = Expression.Call( Expression.Constant(field),
typeof(FieldInfo).GetMethod("SetValue", new Type[]{typeof(object), typeof(object)}),
vBoxed, //on boxed struct
Expression.Convert( replacedignmentTargetExpression, typeof(object))
);
var swap = Expression.replacedign( instance, Expression.Unbox(vBoxed, Type));
expressions.Add(
Expression.Block
(new ParameterExpression[]{(ParameterExpression)replacedignmentTargetExpression, vBoxed},
box,
expr,
setField,
swap
)
);
}
else
{
var setField = Expression.Call( Expression.Constant(field),
typeof(FieldInfo).GetMethod("SetValue", new Type[]{typeof(object), typeof(object)}),
instance,
Expression.Convert( replacedignmentTargetExpression, typeof(object))
);
expressions.Add( Expression.Block(new ParameterExpression[]{(ParameterExpression)replacedignmentTargetExpression}, expr, setField) );
}
}
else
expressions.Add(expr);
}//foreach
}//loop through fields
expressions.Add( Expression.replacedign(pInstance, Expression.Convert(instance, typeof(object))));
var body = Expression.Block(new ParameterExpression[]{instance}, expressions);
return Expression.Lambda<dyn_deserialize>(body, pSchema, pReader, pTReg, pRefs, pInstance, pStreamingContext).Compile();
}
19
View Source File : ConstantFolding.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
public static Expression FoldMethodCall(MethodCallExpression inputExpression)
{
Expression obj = ConstantFolding.Fold(inputExpression.Object);
ReadOnlyCollection<Expression> args = ConstantFolding.FoldExpressionList(inputExpression.Arguments);
Expression resultExpression;
if (obj != inputExpression.Object || args != inputExpression.Arguments)
{
resultExpression = Expression.Call(obj, inputExpression.Method, args);
}
else
{
resultExpression = inputExpression;
}
if (!IsConstant(obj))
{
return resultExpression;
}
foreach (Expression arg in args)
{
if (!IsConstant(arg))
{
return resultExpression;
}
}
// skip simplifying .Take(Constant)
if (inputExpression.Method.IsStatic &&
inputExpression.Method.DeclaringType.IsreplacedignableFrom(typeof(Queryable)) &&
inputExpression.Method.Name.Equals("Take"))
{
return resultExpression;
}
resultExpression = ExpressionSimplifier.EvaluateToExpression(resultExpression);
return resultExpression;
}
19
View Source File : DefaultMethodInvokerFactory.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
public IMethodInvoker<TInstance, TReturn> Create<TInstance, TReturn>(MethodInfo method)
{
if (method == null)
{
throw new ArgumentNullException(nameof(method));
}
if (typeof(TInstance) != method.ReflectedType)
{
throw new InvalidOperationException("The Type must match the method's ReflectedType.");
}
// Parameter to invoker: TInstance instance
ParameterExpression instanceParameter = Expression.Parameter(typeof(TInstance), "instance");
// Parameter to invoker: object[] arguments
ParameterExpression argumentsParameter = Expression.Parameter(typeof(object[]), "arguments");
// Local variables preplaceded as arguments to Call
List<ParameterExpression> localVariables = new List<ParameterExpression>();
// Pre-Call, copy from arguments array to local variables.
List<Expression> arrayToLocalsreplacedignments = new List<Expression>();
// Post-Call, copy from local variables back to arguments array.
List<Expression> localsToArrayreplacedignments = new List<Expression>();
// If the method returns a value: T returnValue
ParameterExpression returnValue;
Type returnType = method.ReturnType;
if (returnType == typeof(void))
{
returnValue = null;
}
else
{
returnValue = Expression.Parameter(returnType);
}
ParameterInfo[] parameterInfos = method.GetParameters();
Debug.replacedert(parameterInfos != null);
for (int index = 0; index < parameterInfos.Length; index++)
{
ParameterInfo parameterInfo = parameterInfos[index];
Type argumentType = parameterInfo.ParameterType;
if (argumentType.IsByRef)
{
// The type of the local variable (and object in the arguments array) should be T rather than T&.
argumentType = argumentType.GetElementType()!;
}
// T argumentN
ParameterExpression localVariable = Expression.Parameter(argumentType);
localVariables.Add(localVariable);
// arguments[index]
Expression arrayAccess = Expression.ArrayAccess(argumentsParameter, Expression.Constant(index));
// Pre-Call:
// T argumentN = (T)arguments[index];
Expression arrayAccessAsT = Expression.Convert(arrayAccess, argumentType);
Expression replacedignArrayToLocal = Expression.replacedign(localVariable, arrayAccessAsT);
arrayToLocalsreplacedignments.Add(replacedignArrayToLocal);
// Post-Call:
// arguments[index] = (object)argumentN;
Expression localAsObject = Expression.Convert(localVariable, typeof(object));
Expression replacedignLocalToArray = Expression.replacedign(arrayAccess, localAsObject);
localsToArrayreplacedignments.Add(replacedignLocalToArray);
}
Expression callInstance;
if (method.IsStatic)
{
callInstance = null;
}
else
{
callInstance = instanceParameter;
}
// Instance call:
// instance.method(param0, param1, ...);
// Static call:
// method(param0, param1, ...);
Expression call = Expression.Call(callInstance, method, localVariables);
Expression callResult;
if (returnType == typeof(void))
{
callResult = call;
}
else
{
// T returnValue = method(param0, param1, ...);
callResult = Expression.replacedign(returnValue, call);
}
List<Expression> blockExpressions = new List<Expression>();
// T0 argument0 = (T0)arguments[0];
// T1 argument1 = (T1)arguments[1];
// ...
blockExpressions.AddRange(arrayToLocalsreplacedignments);
// Call(argument0, argument1, ...);
// or
// T returnValue = Call(param0, param1, ...);
blockExpressions.Add(callResult);
// arguments[0] = (object)argument0;
// arguments[1] = (object)argument1;
// ...
blockExpressions.AddRange(localsToArrayreplacedignments);
if (returnValue != null)
{
// return returnValue;
blockExpressions.Add(returnValue);
}
List<ParameterExpression> blockVariables = new List<ParameterExpression>();
blockVariables.AddRange(localVariables);
if (returnValue != null)
{
blockVariables.Add(returnValue);
}
Expression block = Expression.Block(blockVariables, blockExpressions);
if (call.Type == typeof(void))
{
// for: public void Function()
var lambda = Expression.Lambda<Action<TInstance, object[]>>(
block,
instanceParameter,
argumentsParameter);
Action<TInstance, object[]> compiled = lambda.Compile();
return new VoidMethodInvoker<TInstance, TReturn>(compiled);
}
else if (call.Type == typeof(Task))
{
// for: public Task Function()
var lambda = Expression.Lambda<Func<TInstance, object[], Task>>(
block,
instanceParameter,
argumentsParameter);
Func<TInstance, object[], Task> compiled = lambda.Compile();
return new VoidTaskMethodInvoker<TInstance, TReturn>(compiled);
}
else if (typeof(Task).IsreplacedignableFrom(call.Type))
{
// for: public Task<TReturn> Function()
var lambda = Expression.Lambda<Func<TInstance, object[], Task<TReturn>>>(
block,
instanceParameter,
argumentsParameter);
Func<TInstance, object[], Task<TReturn>> compiled = lambda.Compile();
return new TaskMethodInvoker<TInstance, TReturn>(compiled);
}
else
{
// for: public TReturn Function()
var lambda = Expression.Lambda<Func<TInstance, object[], TReturn>>(
block,
instanceParameter,
argumentsParameter);
Func<TInstance, object[], TReturn> compiled = lambda.Compile();
return new MethodInvokerWithReturnValue<TInstance, TReturn>(compiled);
}
}
19
View Source File : BodyQuery.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
static Expression Create(Expression[] args, Expression[] contextArgs)
{
var inputExpression = args.FirstOrDefault() as ConstantExpression;
string queryString = inputExpression?.Value as string;
if (string.IsNullOrEmpty(queryString))
{
throw new ArgumentException("$body query cannot be empty");
}
// Validate input string as JsonPath
if (!JsonPathValidator.IsSupportedJsonPath(queryString, out string errorDetails))
{
throw new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
"Error in $body query. {0}",
errorDetails));
}
return Expression.Call(typeof(BodyQuery).GetMethod("Runtime", BindingFlags.NonPublic | BindingFlags.Static), args.Union(contextArgs));
}
19
View Source File : TwinChangeIncludes.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
static Expression Create(Expression[] args, Expression[] contextArgs)
{
var inputExpression = args.FirstOrDefault() as ConstantExpression;
string queryString = inputExpression?.Value as string;
if (string.IsNullOrEmpty(queryString))
{
throw new ArgumentException("twin_change_includes argument cannot be empty");
}
// Validate query string as JsonPath
string errorDetails;
if (!TwinChangeJsonPathValidator.IsSupportedJsonPath(queryString, out errorDetails))
{
throw new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
"{0}",
errorDetails));
}
return Expression.Call(typeof(TwinChangeIncludes).GetMethod("Runtime", BindingFlags.NonPublic | BindingFlags.Static), args.Union(contextArgs));
}
19
View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : baratgabor
License : MIT License
Project Creator : baratgabor
private static IQueryable<T> ApplyOrderInternal<T>(IQueryable<T> query, string oDataOrderByString, int maximumNumberOfOrdering)
{
if (string.IsNullOrWhiteSpace(oDataOrderByString))
{
return query;
}
bool firstOrdering = true;
foreach (var (propertyName, order) in GetOrderEntries(oDataOrderByString, maximumNumberOfOrdering))
{
query = ApplyOrdering(query, propertyName, order, firstOrdering);
firstOrdering = false;
}
//TODO: Look into the necessity (or lack thereof) of filtering out multiple orderBy on the same property.
return query;
static IEnumerable<(string propertyPath, SortOrder order)> GetOrderEntries(string orderByString, int maxOrders)
{
return orderByString
.Split(',', count: maxOrders, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(orderStr =>
{
var divider = orderStr.IndexOf(' ');
if (divider < 0) return (propertyPath: orderStr, order: SortOrder.Asc);
else return (
propertyPath: orderStr[0..divider],
order: Enum.Parse<SortOrder>(orderStr[divider..].Trim(), ignoreCase: true)
);
});
}
static IQueryable<T> ApplyOrdering(IQueryable<T> query, string propertyPath, SortOrder order, bool firstOrdering)
{
var param = Expression.Parameter(typeof(T), "p");
var member = (MemberExpression)propertyPath.Split('/').Aggregate((Expression)param, Expression.Property); //Expression.Property(param, propertyPath);
var exp = Expression.Lambda(member, param);
string methodName = order switch
{
SortOrder.Asc => firstOrdering ? "OrderBy" : "ThenBy",
SortOrder.Desc => firstOrdering ? "OrderByDescending" : "ThenByDescending"
};
Type[] types = new Type[] { query.ElementType, exp.Body.Type };
var orderByExpression = Expression.Call(typeof(Queryable), methodName, types, query.Expression, exp);
return query.Provider.CreateQuery<T>(orderByExpression);
}
19
View Source File : InvokableFactory.cs
License : MIT License
Project Creator : Bannerlord-Coop-Team
License : MIT License
Project Creator : Bannerlord-Coop-Team
public static Action<object, object[]> CreateStandInCaller(MethodInfo method)
{
var parameters = method.GetParameters();
var argInstance = Expression.Parameter(typeof(object), "instance");
var argInstanceConverted = Expression.Convert(
argInstance,
parameters[0].ParameterType);
var args = Expression.Parameter(typeof(object[]), "args");
// Unpack parameters
var exArgs = new List<Expression>
{
argInstanceConverted
};
for (var i = 1; i < method.GetParameters().Length; ++i)
{
var param = method.GetParameters()[i];
var arrayElement = Expression.ArrayIndex(
args,
Expression.Constant(i - 1));
var arrayElementConverted =
Expression.Convert(arrayElement, param.ParameterType);
exArgs.Add(arrayElementConverted);
}
// Standins are always static with the first argument being the instance.
var exCall = Expression.Call(null, method, exArgs);
var lambda =
Expression.Lambda<Action<object, object[]>>(exCall, argInstance, args);
return lambda.Compile();
}
See More Examples