private Expression ReduceCore(DynamicCSharpArgument left) { var functionalOp = new Func <Expression, Expression>(lhs => { var operation = default(ExpressionType); switch (OperationNodeType) { case CSharpExpressionType.AddAssign: case CSharpExpressionType.AddAssignChecked: operation = ExpressionType.AddAssign; break; case CSharpExpressionType.SubtractAssign: case CSharpExpressionType.SubtractAssignChecked: operation = ExpressionType.SubtractAssign; break; case CSharpExpressionType.MultiplyAssign: case CSharpExpressionType.MultiplyAssignChecked: operation = ExpressionType.MultiplyAssign; break; case CSharpExpressionType.DivideAssign: operation = ExpressionType.DivideAssign; break; case CSharpExpressionType.ModuloAssign: operation = ExpressionType.ModuloAssign; break; case CSharpExpressionType.AndAssign: operation = ExpressionType.AndAssign; break; case CSharpExpressionType.OrAssign: operation = ExpressionType.OrAssign; break; case CSharpExpressionType.ExclusiveOrAssign: operation = ExpressionType.ExclusiveOrAssign; break; case CSharpExpressionType.LeftShiftAssign: operation = ExpressionType.LeftShiftAssign; break; case CSharpExpressionType.RightShiftAssign: operation = ExpressionType.RightShiftAssign; break; default: throw ContractUtils.Unreachable; } var args = new[] { CSharpArgumentInfo.Create(GetArgumentInfoFlags(Left), null), CSharpArgumentInfo.Create(GetArgumentInfoFlags(Right), null), }; var binder = Binder.BinaryOperation(Flags, operation, Context, args); var dynamic = DynamicHelpers.MakeDynamic(typeof(object), binder, new[] { lhs, Right.Expression }, new[] { lhs.Type, Right.Expression.Type }); var leftType = Left.Expression.Type; if (leftType != dynamic.Type) { var convert = Binder.Convert(CSharpBinderFlags.ConvertExplicit, leftType, Context); dynamic = DynamicHelpers.MakeDynamic(leftType, convert, new[] { dynamic }, null); } return(dynamic); }); var flags = Flags | CSharpBinderFlags.ValueFromCompoundAssignment; var res = DynamicHelpers.ReduceDynamicAssignment(left, functionalOp, flags); return(res); }
private static object GetDynamic(object obj, string key) { try { var binder = Binder.GetMember(CSharpBinderFlags.None, key, obj.GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); var callsite = CallSite <Func <CallSite, object, object> > .Create(binder); return(callsite.Target(callsite, obj)); } catch (RuntimeBinderException) { return(null); } }
private static CSharpArgumentInfo CreateStaticTypeArgInfo() { return(CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.IsStaticType, null)); }
private void ensureInvokerP() { if (this.invoker_p == null) { this.invoker_p = CallSite <Func <CallSite, object, object, object, object, object, object, object, object> > .Create(Binder.SetIndex(CSharpBinderFlags.None, typeof(jxshell.dotnet4.invoker), (IEnumerable <CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); } }
private static object GetDynamicMember(object obj, string memberName) { var binder = Binder.GetMember(CSharpBinderFlags.None, memberName, null, new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); var callsite = CallSite <Func <CallSite, object, object> > .Create(binder); return(callsite.Target(callsite, obj)); }
private static Action <object, T> CreateDynamicSetter <T>(string propertyName) { var binder = Binder.SetMember(CSharpBinderFlags.None, propertyName, typeof(DynamicAccessTests), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) }); var callsite = CallSite <Func <CallSite, object, T, object> > .Create(binder); return((self, value) => callsite.Target(callsite, self, value)); }
/// <summary> /// Builds a <see cref="BinaryDeserializer{T}" /> for a <see cref="RecordSchema" />. /// </summary> /// <returns> /// A successful <see cref="BinaryDeserializerBuilderCaseResult" /> if <paramref name="type" /> /// is not an array or primitive type and <paramref name="schema" /> is a <see cref="RecordSchema" />; /// an unsuccessful <see cref="BinaryDeserializerBuilderCaseResult" /> otherwise. /// </returns> /// <inheritdoc /> public virtual BinaryDeserializerBuilderCaseResult BuildExpression(Type type, Schema schema, BinaryDeserializerBuilderContext context) { if (schema is RecordSchema recordSchema) { var underlying = Nullable.GetUnderlyingType(type) ?? type; if (!underlying.IsArray && !underlying.IsPrimitive) { // since record deserialization is potentially recursive, create a top-level // reference: var parameter = Expression.Parameter( Expression.GetDelegateType(context.Reader.Type.MakeByRefType(), underlying)); if (!context.References.TryGetValue((recordSchema, type), out var reference)) { context.References.Add((recordSchema, type), reference = parameter); } // then build/set the delegate if it hasn’t been built yet: if (parameter == reference) { Expression expression; if (GetRecordConstructor(underlying, recordSchema) is ConstructorInfo constructor) { var parameters = constructor.GetParameters(); // map constructor parameters to fields: var mapping = recordSchema.Fields .Select(field => { // there will be a match or we wouldn’t have made it this far: var match = parameters.Single(parameter => IsMatch(field, parameter.Name)); var parameter = Expression.Parameter(match.ParameterType); return( Match: match, Parameter: parameter, Assignment: (Expression)Expression.Assign( parameter, DeserializerBuilder.BuildExpression(match.ParameterType, field.Type, context))); }) .ToDictionary(r => r.Match, r => (r.Parameter, r.Assignment)); expression = Expression.Block( mapping .Select(d => d.Value.Parameter), mapping .Select(d => d.Value.Assignment) .Concat(new[] { Expression.New( constructor, parameters .Select(parameter => mapping.ContainsKey(parameter) ? (Expression)mapping[parameter].Parameter : Expression.Constant(parameter.DefaultValue))), })); } else { var members = underlying.GetMembers(MemberVisibility); // support dynamic deserialization: var value = Expression.Parameter( underlying.IsAssignableFrom(typeof(ExpandoObject)) ? typeof(ExpandoObject) : underlying); expression = Expression.Block( new[] { value }, new[] { (Expression)Expression.Assign(value, Expression.New(value.Type)) } .Concat(recordSchema.Fields.Select(field => { var match = members.SingleOrDefault(member => IsMatch(field, member)); Expression expression; if (match == null) { // always deserialize fields to advance the reader: expression = DeserializerBuilder.BuildExpression(typeof(object), field.Type, context); // fall back to a dynamic setter if the value supports it: if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(value.Type)) { var flags = CSharpBinderFlags.None; var infos = new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }; var binder = Binder.SetMember(flags, field.Name, value.Type, infos); expression = Expression.Dynamic(binder, typeof(void), value, expression); } } else { Expression inner; try { inner = DeserializerBuilder.BuildExpression( match switch { FieldInfo fieldMatch => fieldMatch.FieldType, PropertyInfo propertyMatch => propertyMatch.PropertyType, MemberInfo unknown => throw new InvalidOperationException($"Record fields can only be mapped to fields and properties."), }, field.Type, context); } catch (Exception exception) { throw new UnsupportedTypeException(type, $"The {match.Name} member on {type} could not be mapped to the {field.Name} field on {recordSchema.FullName}.", exception); } expression = Expression.Assign( Expression.PropertyOrField(value, match.Name), inner); } return(expression); }))
/// <summary> /// Gets a property of the dynamic object. /// </summary> /// <param name="source">Source object.</param> /// <param name="member">Member to retrieve.</param> /// <returns>The requested property value.</returns> /// <exception cref="ArgumentNullException">If source or member are null.</exception> public static object GetProperty(this object source, string member) { if (source == null) { throw new ArgumentNullException("source"); } if (member == null) { throw new ArgumentNullException("member"); } Type scope = source.GetType(); var provider = source as IDynamicMetaObjectProvider; if (provider != null) { var objectType = typeof(object); var cacheKey = objectType.FullName + member; Delegate del; if (!_delegateCache.TryGetValue(cacheKey, out del)) { ParameterExpression param = Expression.Parameter(typeof(object)); DynamicMetaObject mobj = provider.GetMetaObject(param); var binder = (GetMemberBinder)Binder.GetMember(0, member, scope, new[] { CSharpArgumentInfo.Create(0, null) }); DynamicMetaObject ret = mobj.BindGetMember(binder); BlockExpression final = Expression.Block(Expression.Label(CallSiteBinder.UpdateLabel), ret.Expression); LambdaExpression lambda = Expression.Lambda(final, param); del = lambda.Compile(); _delegateCache.TryAdd(cacheKey, del); } return(del.DynamicInvoke(source)); } return(source.GetType().GetProperty(member, BindingFlags.Public | BindingFlags.Instance).GetValue(source, null)); }
private IQueryable <dynamic> Sort(IQueryable <dynamic> data, Type elementType, SortInfo sort) { Debug.Assert(data != null); if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(elementType)) { // IDynamicMetaObjectProvider properties are only available through a runtime binder, so we // must build a custom LINQ expression for getting the dynamic property value. // Lambda: o => o.Property (where Property is obtained by runtime binder) // NOTE: lambda must not use internals otherwise this will fail in partial trust when Helpers assembly is in GAC var binder = Binder.GetMember(CSharpBinderFlags.None, sort.SortColumn, typeof(WebGrid), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); var param = Expression.Parameter(typeof(IDynamicMetaObjectProvider), "o"); var getter = Expression.Dynamic(binder, typeof(object), param); return(SortGenericExpression <IDynamicMetaObjectProvider, object>(data, getter, param, sort.SortDirection)); } Expression sorterFunctionBody; ParameterExpression sorterFunctionParameter; Expression sorter; if (_grid.CustomSorters.TryGetValue(sort.SortColumn, out sorter)) { var lambda = sorter as LambdaExpression; Debug.Assert(lambda != null); sorterFunctionBody = lambda.Body; sorterFunctionParameter = lambda.Parameters[0]; } else { // The IQueryable<dynamic> data source is cast as IQueryable<object> at runtime. We must call // SortGenericExpression using reflection so that the LINQ expressions use the actual element type. // Lambda: o => o.Property[.NavigationProperty,etc] sorterFunctionParameter = Expression.Parameter(elementType, "o"); Expression member = sorterFunctionParameter; var type = elementType; var sorts = sort.SortColumn.Split('.'); foreach (var name in sorts) { PropertyInfo prop = type.GetProperty(name); if (prop == null) { // no-op in case navigation property came from querystring (falls back to default sort) if ((DefaultSort != null) && !sort.Equals(DefaultSort) && !String.IsNullOrEmpty(DefaultSort.SortColumn)) { return(Sort(data, elementType, DefaultSort)); } return(data); } member = Expression.Property(member, prop); type = prop.PropertyType; } sorterFunctionBody = member; } var actualSortMethod = SortGenericExpressionMethod.MakeGenericMethod(elementType, sorterFunctionBody.Type); return((IQueryable <dynamic>)actualSortMethod.Invoke(null, new object[] { data, sorterFunctionBody, sorterFunctionParameter, sort.SortDirection })); }
public object GetPropertyValue(object o, string member) { // check inputs if (o == null) { throw new ArgumentNullException(nameof(o)); } if (member == null) { throw new ArgumentNullException(nameof(member)); } // get the type of the object var scope = o.GetType(); // convert to metadata provider var provider = o as IDynamicMetaObjectProvider; // if object is a provider if (provider != null) { // check object contains requested property if (!((IDictionary <string, object>)provider).ContainsKey(member)) { throw new ArgumentException($"'{member}' could not be found in this object."); } // get the parameter var param = Expression.Parameter(typeof(object)); // get the meta data object var mobj = provider.GetMetaObject(param); // get the binder var binder = (GetMemberBinder)Microsoft.CSharp.RuntimeBinder.Binder.GetMember(0, member, scope, new[] { CSharpArgumentInfo.Create(0, null) }); // bind the member var ret = mobj.BindGetMember(binder); // create expression var final = Expression.Block( Expression.Label(CallSiteBinder.UpdateLabel), ret.Expression ); // create lambda var lambda = Expression.Lambda(final, param); // compile lambda var del = lambda.Compile(); // invoke lambda and return return(del.DynamicInvoke(o)); } // get member type var memberObj = o.GetType().GetProperty(member, BindingFlags.Public | BindingFlags.Instance); if (memberObj == null) { throw new ArgumentException($"'{member}' could not be found in this object."); } // get value from member var value = memberObj.GetValue(o, null); // check if value is null if (value != null) { // get the underlying type var underlyingType = memberObj.PropertyType; // check if property is nullable var isNullable = IsNullableType(underlyingType); // if its nullable if (isNullable) { // get underlying top underlyingType = Nullable.GetUnderlyingType(underlyingType); // if there isn't one, re-set if (underlyingType == null) { underlyingType = memberObj.PropertyType; } } // if underlying type is object if (underlyingType == typeof(object) || underlyingType == typeof(Object)) { // get the value type underlyingType = value.GetType(); } // convert the value to the underlying type value = Convert.ChangeType(value, underlyingType); } // return value return(value); }
public ActionResult FlowCopyFor(FormCollection collection) { RoadFlow.Platform.WorkFlow workFlow = new RoadFlow.Platform.WorkFlow(); RoadFlow.Platform.WorkFlowTask workFlowTask1 = new RoadFlow.Platform.WorkFlowTask(); string str1 = this.Request.QueryString["flowid"]; string stepid = this.Request.QueryString["stepid"]; string str2 = this.Request.QueryString["groupid"]; string str3 = this.Request.QueryString["instanceid"]; string flowID = str1; int num = 1; WorkFlowInstalled workFlowRunModel = workFlow.GetWorkFlowRunModel(flowID, num != 0); if (workFlowRunModel == null) { this.Response.Write("未找到流程运行实体"); this.Response.End(); return((ActionResult)null); } if (workFlowRunModel.Steps.Where <Step>((Func <Step, bool>)(p => p.ID == stepid.ToGuid())).Count <Step>() == 0) { this.Response.Write("未找到当前步骤"); this.Response.End(); return((ActionResult)null); } RoadFlow.Data.Model.WorkFlowTask workFlowTask2 = workFlowTask1.Get(this.Request.QueryString["taskid"].ToGuid()); if (workFlowTask2 == null) { this.Response.Write("当前任务为空,请先保存再抄送!"); this.Response.End(); return((ActionResult)null); } if (collection != null) { List <RoadFlow.Data.Model.WorkFlowTask> taskList = workFlowTask1.GetTaskList(workFlowTask2.ID, true); List <RoadFlow.Data.Model.Users> allUsers = new RoadFlow.Platform.Organize().GetAllUsers(this.Request.Form["user"] ?? ""); StringBuilder stringBuilder = new StringBuilder(); foreach (RoadFlow.Data.Model.Users users in allUsers) { RoadFlow.Data.Model.Users user = users; if (taskList.Find((Predicate <RoadFlow.Data.Model.WorkFlowTask>)(p => p.ReceiveID == user.ID)) == null) { Step step = workFlowRunModel.Steps.Where <Step>((Func <Step, bool>)(p => p.ID == this.Request.QueryString["stepid"].ToGuid())).First <Step>(); RoadFlow.Data.Model.WorkFlowTask model = new RoadFlow.Data.Model.WorkFlowTask(); if (step.WorkTime > Decimal.Zero) { model.CompletedTime = new DateTime?(DateTimeNew.Now.AddHours((double)step.WorkTime)); } model.FlowID = workFlowTask2.FlowID; model.GroupID = workFlowTask2.GroupID; model.ID = Guid.NewGuid(); model.Type = 5; model.InstanceID = workFlowTask2.InstanceID; model.Note = "抄送任务"; model.PrevID = workFlowTask2.PrevID; model.PrevStepID = workFlowTask2.PrevStepID; model.ReceiveID = user.ID; model.ReceiveName = user.Name; model.ReceiveTime = DateTimeNew.Now; model.SenderID = workFlowTask2.ReceiveID; model.SenderName = workFlowTask2.ReceiveName; model.SenderTime = model.ReceiveTime; model.Status = 0; model.StepID = workFlowTask2.StepID; model.StepName = workFlowTask2.StepName; model.Sort = workFlowTask2.Sort; model.Title = workFlowTask2.Title; workFlowTask1.Add(model); stringBuilder.Append(model.ReceiveName); stringBuilder.Append(","); } } // ISSUE: reference to a compiler-generated field if (WorkFlowRunController.\u003C\u003Eo__18.\u003C\u003Ep__0 == null) { // ISSUE: reference to a compiler-generated field WorkFlowRunController.\u003C\u003Eo__18.\u003C\u003Ep__0 = CallSite <Func <CallSite, object, string, object> > .Create(Binder.SetMember(CSharpBinderFlags.None, "script", typeof(WorkFlowRunController), (IEnumerable <CSharpArgumentInfo>) new CSharpArgumentInfo[2] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, (string)null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, (string)null) })); } // ISSUE: reference to a compiler-generated field // ISSUE: reference to a compiler-generated field object obj = WorkFlowRunController.\u003C\u003Eo__18.\u003C\u003Ep__0.Target((CallSite)WorkFlowRunController.\u003C\u003Eo__18.\u003C\u003Ep__0, this.ViewBag, "alert('成功抄送给:" + stringBuilder.ToString().TrimEnd(',') + "');new RoadUI.Window().close();"); } return((ActionResult)this.View()); }
private void InvokeSetter <T>(object o, string propertyName, T propertyValue) { if (_mode == DynamicTestObjectType.DynamicRealmObject) { var binder = Binder.SetMember(CSharpBinderFlags.None, propertyName, typeof(DynamicAccessTests), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) }); var callsite = CallSite <Func <CallSite, object, T, object> > .Create(binder); callsite.Target(callsite, o, propertyValue); } else { TestHelpers.SetPropertyValue(o, propertyName, propertyValue); } }
private object InvokeGetter(object o, string propertyName) { if (_mode == DynamicTestObjectType.DynamicRealmObject) { var binder = Binder.GetMember(CSharpBinderFlags.None, propertyName, typeof(DynamicAccessTests), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); var callsite = CallSite <Func <CallSite, object, object> > .Create(binder); return(callsite.Target(callsite, o)); } return(TestHelpers.GetPropertyValue(o, propertyName)); }
public ActionResult Index(FormCollection collection) { RoadFlow.Data.MSSQL.WorkCalendar workCalendar = new RoadFlow.Data.MSSQL.WorkCalendar(); int year = this.Request.Form["DropDownList1"].IsNullOrEmpty() ? DateTimeNew.Now.Year : this.Request.Form["DropDownList1"].ToInt(); if (!this.Request.Form["saveBut"].IsNullOrEmpty()) { string contents = this.Request.Form["workdate"] ?? ""; string str1 = this.Request.Form["year1"]; using (TransactionScope transactionScope = new TransactionScope()) { workCalendar.Delete(str1.ToInt()); foreach (string str2 in ((IEnumerable <string>)contents.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries)).Distinct <string>()) { if (str2.IsDateTime()) { workCalendar.Add(new RoadFlow.Data.Model.WorkCalendar() { WorkDate = str2.ToDateTime() }); } } transactionScope.Complete(); } Opation.Remove("WorkCalendar_" + str1); RoadFlow.Platform.Log.Add("设置了工作日历", contents, RoadFlow.Platform.Log.Types.系统管理, "", "", (RoadFlow.Data.Model.Users)null); // ISSUE: reference to a compiler-generated field if (WorkCalendarController.\u003C\u003Eo__1.\u003C\u003Ep__0 == null) { // ISSUE: reference to a compiler-generated field WorkCalendarController.\u003C\u003Eo__1.\u003C\u003Ep__0 = CallSite <Func <CallSite, object, string, object> > .Create(Binder.SetMember(CSharpBinderFlags.None, "script", typeof(WorkCalendarController), (IEnumerable <CSharpArgumentInfo>) new CSharpArgumentInfo[2] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, (string)null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.Constant, (string)null) })); } // ISSUE: reference to a compiler-generated field // ISSUE: reference to a compiler-generated field object obj = WorkCalendarController.\u003C\u003Eo__1.\u003C\u003Ep__0.Target((CallSite)WorkCalendarController.\u003C\u003Eo__1.\u003C\u003Ep__0, this.ViewBag, "alert('保存成功!')"); } StringBuilder stringBuilder = new StringBuilder(); for (int index = 2016; index < 2099; ++index) { stringBuilder.Append("<option value='" + (object)index + "'" + (index == year ? (object)"selected='selected'" : (object)"") + ">" + (object)index + "</option>"); } List <RoadFlow.Data.Model.WorkCalendar> all = workCalendar.GetAll(year); // ISSUE: reference to a compiler-generated field if (WorkCalendarController.\u003C\u003Eo__1.\u003C\u003Ep__1 == null) { // ISSUE: reference to a compiler-generated field WorkCalendarController.\u003C\u003Eo__1.\u003C\u003Ep__1 = CallSite <Func <CallSite, object, StringBuilder, object> > .Create(Binder.SetMember(CSharpBinderFlags.None, "options", typeof(WorkCalendarController), (IEnumerable <CSharpArgumentInfo>) new CSharpArgumentInfo[2] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, (string)null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, (string)null) })); } // ISSUE: reference to a compiler-generated field // ISSUE: reference to a compiler-generated field object obj1 = WorkCalendarController.\u003C\u003Eo__1.\u003C\u003Ep__1.Target((CallSite)WorkCalendarController.\u003C\u003Eo__1.\u003C\u003Ep__1, this.ViewBag, stringBuilder); // ISSUE: reference to a compiler-generated field if (WorkCalendarController.\u003C\u003Eo__1.\u003C\u003Ep__2 == null) { // ISSUE: reference to a compiler-generated field WorkCalendarController.\u003C\u003Eo__1.\u003C\u003Ep__2 = CallSite <Func <CallSite, object, int, object> > .Create(Binder.SetMember(CSharpBinderFlags.None, "year", typeof(WorkCalendarController), (IEnumerable <CSharpArgumentInfo>) new CSharpArgumentInfo[2] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, (string)null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, (string)null) })); } // ISSUE: reference to a compiler-generated field // ISSUE: reference to a compiler-generated field object obj2 = WorkCalendarController.\u003C\u003Eo__1.\u003C\u003Ep__2.Target((CallSite)WorkCalendarController.\u003C\u003Eo__1.\u003C\u003Ep__2, this.ViewBag, year); return((ActionResult)this.View((object)all)); }
public void NullDMO() { BinaryOperationBinder binder = Binder.BinaryOperation( CSharpBinderFlags.None, ExpressionType.Add, GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) } ) as BinaryOperationBinder; DynamicMetaObject dmo2 = new DynamicMetaObject(Expression.Parameter(typeof(object)), BindingRestrictions.Empty, 2); DynamicMetaObject dmoNoVal = new DynamicMetaObject(Expression.Parameter(typeof(object)), BindingRestrictions.Empty); AssertExtensions.Throws <ArgumentNullException>("target", () => binder.FallbackBinaryOperation(null, null)); AssertExtensions.Throws <ArgumentNullException>("arg", () => binder.FallbackBinaryOperation(dmo2, null)); AssertExtensions.Throws <ArgumentException>("target", () => binder.FallbackBinaryOperation(dmoNoVal, null)); AssertExtensions.Throws <ArgumentException>("arg", () => binder.FallbackBinaryOperation(dmo2, dmoNoVal)); }
/// <summary> /// Returns an Expression that accesses a member on an Expression /// </summary> /// <param name="isFunction">Determines whether the member being accessed is a function or a property</param> /// <param name="isCall">Determines whether the member returns void</param> /// <param name="le">The expression that contains the member to be accessed</param> /// <param name="membername">The name of the member to access</param> /// <param name="args">Optional list of arguments to be passed if the member is a method</param> /// <returns></returns> public static Expression MemberAccess(bool isFunction, bool isCall, Expression le, string membername, List <Expression> args) { var argTypes = args.Select(x => x.Type); Expression instance = null; Type type = null; var isDynamic = false; var isRuntimeType = false; if (le.Type.Name == "RuntimeType") { isRuntimeType = true; type = ((Type)((ConstantExpression)le).Value); } else { type = le.Type; instance = le; isDynamic = type.IsDynamic(); } if (isFunction) { if (isDynamic) { var expArgs = new List <Expression> { instance }; expArgs.AddRange(args); if (isCall) { var binderMC = Binder.InvokeMember( CSharpBinderFlags.ResultDiscarded, membername, null, type, expArgs.Select(x => CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)) ); return(Expression.Dynamic(binderMC, typeof(void), expArgs)); } var binderM = Binder.InvokeMember( CSharpBinderFlags.None, membername, null, type, expArgs.Select(x => CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)) ); return(Expression.Dynamic(binderM, typeof(object), expArgs)); } else { var mis = MethodResolution.GetApplicableMembers(type, membername, args); var methodInfo = (MethodInfo)mis[0]; if (methodInfo != null) { var parameterInfos = methodInfo.GetParameters(); foreach (var parameterInfo in parameterInfos) { var index = parameterInfo.Position; args[index] = TypeConversion.Convert(args[index], parameterInfo.ParameterType); } return(Expression.Call(instance, methodInfo, args.ToArray())); } var match = MethodResolution.GetExactMatch(type, instance, membername, args) ?? MethodResolution.GetParamsMatch(type, instance, membername, args); if (match != null) { return(match); } } } else { if (isDynamic) { var binder = Binder.GetMember( CSharpBinderFlags.None, membername, type, new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) } ); var result = Expression.Dynamic(binder, typeof(object), instance); if (args.Count > 0) { var expArgs = new List <Expression>() { result }; expArgs.AddRange(args); var indexedBinder = Binder.GetIndex( CSharpBinderFlags.None, type, expArgs.Select(x => CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)) ); result = Expression.Dynamic(indexedBinder, typeof(object), expArgs); } return(result); } else { Expression exp = null; var propertyInfo = type.GetProperty(membername); if (propertyInfo != null) { exp = Expression.Property(instance, propertyInfo); } else { var fieldInfo = type.GetField(membername); if (fieldInfo != null) { exp = Expression.Field(instance, fieldInfo); } } if (exp != null) { if (args.Count > 0) { return(Expression.ArrayAccess(exp, args)); } else { return(exp); } } } } throw new Exception(string.Format("Member not found: {0}.{1}", le.Type.Name, membername)); }
private static Func <object, dynamic> CreateDynamicGetter(string propertyName) { var binder = Binder.GetMember(CSharpBinderFlags.None, propertyName, typeof(DynamicAccessTests), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); var callsite = CallSite <Func <CallSite, object, object> > .Create(binder); return((self) => callsite.Target(callsite, self)); }
internal static object InvokeGetCallSite(object target, string name, Type context, bool staticContext, ref CallSite callsite) { if (callsite == null) { var tTargetFlag = CSharpArgumentInfoFlags.None; LazyBinder tBinder; Type tBinderType; int tKnownType; if (staticContext) //CSharp Binder won't call Static properties, grrr. { var tStaticFlag = CSharpBinderFlags.None; if ((target is Type && ((Type)target).GetTypeInfo().IsPublic)) { tBinder = () => Binder.InvokeMember(tStaticFlag, "get_" + name, null, context, new List <CSharpArgumentInfo> { CSharpArgumentInfo.Create( CSharpArgumentInfoFlags.IsStaticType | CSharpArgumentInfoFlags.UseCompileTimeType, null) }); tBinderType = typeof(InvokeMemberBinder); tKnownType = KnownMember; } else { tBinder = () => Binder.GetMember(tStaticFlag, name, context, new List <CSharpArgumentInfo> { CSharpArgumentInfo.Create( CSharpArgumentInfoFlags.IsStaticType, null) }); tBinderType = typeof(InvokeMemberBinder); tKnownType = KnownMember; } } else { tBinder = () => Binder.GetMember(CSharpBinderFlags.None, name, context, new List <CSharpArgumentInfo> { CSharpArgumentInfo.Create( tTargetFlag, null) }); tBinderType = typeof(GetMemberBinder); tKnownType = KnownGet; } callsite = CreateCallSite <Func <CallSite, object, object> >(tBinderType, tKnownType, tBinder, name, context, staticContext: staticContext); } var tCallSite = (CallSite <Func <CallSite, object, object> >)callsite; return(tCallSite.Target(tCallSite, target)); }
private static Accessor GetDynamicObjectAcessor(Type type, string attributeName) { var getterBinder = Binder.GetMember(CSharpBinderFlags.None, attributeName, type, new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); var callsiteGetter = CallSite <Func <CallSite, object, object> > .Create(getterBinder); var setterBinder = Binder.SetMember(CSharpBinderFlags.None, attributeName, type, new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); var callsiteSetter = CallSite <Func <CallSite, object, object, object> > .Create(setterBinder); return(new Accessor { Setter = (@object, value) => callsiteSetter.Target(callsiteSetter, @object, value), Getter = (@object) => callsiteGetter.Target(callsiteGetter, @object) }); }
internal static object InvokeSetCallSite(object target, string name, object value, Type context, bool staticContext, ref CallSite callSite) { if (callSite == null) { LazyBinder tBinder; Type tBinderType; if (staticContext) //CSharp Binder won't call Static properties, grrr. { tBinder = () => { var tStaticFlag = CSharpBinderFlags.ResultDiscarded; return(Binder.InvokeMember(tStaticFlag, "set_" + name, null, context, new List <CSharpArgumentInfo> { CSharpArgumentInfo.Create( CSharpArgumentInfoFlags.IsStaticType | CSharpArgumentInfoFlags.UseCompileTimeType, null), CSharpArgumentInfo.Create( CSharpArgumentInfoFlags.None , null) })); }; tBinderType = typeof(InvokeMemberBinder); callSite = CreateCallSite <Action <CallSite, object, object> >(tBinderType, KnownMember, tBinder, name, context, staticContext: true); } else { tBinder = () => Binder.SetMember(CSharpBinderFlags.None, name, context, new List <CSharpArgumentInfo> { CSharpArgumentInfo.Create( CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create( CSharpArgumentInfoFlags.None , null) }); tBinderType = typeof(SetMemberBinder); callSite = CreateCallSite <Func <CallSite, object, object, object> >(tBinderType, KnownSet, tBinder, name, context, staticContext: false); } } if (staticContext) { var tCallSite = (CallSite <Action <CallSite, object, object> >)callSite; tCallSite.Target(callSite, target, value); return(value); } else { var tCallSite = (CallSite <Func <CallSite, object, object, object> >)callSite; var tResult = tCallSite.Target(callSite, target, value); return(tResult); } }
private void ensureInvoker() { if (this.invoker == null) { if (!this.isProperty) { this.invoker = CallSite <Func <CallSite, object, object, object, object, object, object, object> > .Create(Binder.InvokeMember(CSharpBinderFlags.None, this.method, null, typeof(jxshell.dotnet4.invoker), (IEnumerable <CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); return; } this.invoker = CallSite <Func <CallSite, object, object, object, object, object, object, object> > .Create(Binder.GetIndex(CSharpBinderFlags.None, typeof(jxshell.dotnet4.invoker), (IEnumerable <CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); } }
internal static object GetValue(string name, object target) { CallSite <Func <CallSite, object, object> > callSite = (CallSite <Func <CallSite, object, object> >)getters[name]; if (callSite == null) { CallSite <Func <CallSite, object, object> > newSite = CallSite <Func <CallSite, object, object> > .Create(Binder.GetMember(CSharpBinderFlags.None, name, typeof(CallSiteCache), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); lock (getters) { callSite = (CallSite <Func <CallSite, object, object> >)getters[name]; if (callSite == null) { getters[name] = callSite = newSite; } } } return(callSite.Target(callSite, target)); }
private void ensureInvokerVoid() { if (this.invoker_v == null) { this.invoker_v = CallSite <Func <CallSite, object, object, object, object, object, object, object> > .Create(Binder.InvokeMember(CSharpBinderFlags.ResultDiscarded, this.method, null, typeof(jxshell.dotnet4.invoker), (IEnumerable <CSharpArgumentInfo>)(new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); } }
internal static void SetValue(string name, object target, object value) { CallSite <Func <CallSite, object, object, object> > callSite = (CallSite <Func <CallSite, object, object, object> >)setters[name]; if (callSite == null) { CallSite <Func <CallSite, object, object, object> > newSite = CallSite <Func <CallSite, object, object, object> > .Create(Binder.SetMember(CSharpBinderFlags.None, name, typeof(CallSiteCache), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) })); lock (setters) { callSite = (CallSite <Func <CallSite, object, object, object> >)setters[name]; if (callSite == null) { setters[name] = callSite = newSite; } } } callSite.Target(callSite, target, value); }
public void Create_ResultNotNull(CSharpArgumentInfoFlags flag, string name) { Assert.NotNull(CSharpArgumentInfo.Create(flag, name)); }
public static T GetDynamicMember <T>(this object obj, string memberName) { CallSite <Func <CallSite, object, object> > callsite = null; try { var binder = Binder.GetMember(CSharpBinderFlags.None, memberName, obj.GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); callsite = CallSite <Func <CallSite, object, object> > .Create(binder); } catch (Exception ex) { return(default(T)); } return((T)callsite.Target(callsite, obj)); }
private static void SetDynamic(object obj, string key, object value) { var binder = Binder.SetMember(CSharpBinderFlags.None, key, obj.GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); var callsite = CallSite <Func <CallSite, object, object, object> > .Create(binder); callsite.Target(callsite, obj, value); }
private static ValueTypeAccessor CreateGetMethodForValueType(PropertyInfo prop, Type type) { var binder = Microsoft.CSharp.RuntimeBinder.Binder.GetMember(CSharpBinderFlags.None, prop.Name, type, new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); return(new ValueTypeAccessor(CallSite <Func <CallSite, object, object> > .Create(binder))); }
private object BindParameter(DisplayContext displayContext, ParameterInfo parameter) { if (String.Equals(parameter.Name, "Shape", StringComparison.OrdinalIgnoreCase)) { return(displayContext.Value); } if (String.Equals(parameter.Name, "Display", StringComparison.OrdinalIgnoreCase)) { return(displayContext.Display); } if (String.Equals(parameter.Name, "New", StringComparison.OrdinalIgnoreCase)) { var httpContext = _httpContextAccessor.HttpContext; return(httpContext.RequestServices.GetService <IShapeFactory>()); } if (String.Equals(parameter.Name, "Html", StringComparison.OrdinalIgnoreCase)) { return(MakeHtmlHelper(displayContext.ViewContext, displayContext.ViewContext.ViewData)); } if (String.Equals(parameter.Name, "Url", StringComparison.OrdinalIgnoreCase) && parameter.ParameterType.IsAssignableFrom(typeof(UrlHelper))) { var httpContext = _httpContextAccessor.HttpContext; var urlHelperFactory = httpContext.RequestServices.GetService <IUrlHelperFactory>(); return(urlHelperFactory.GetUrlHelper(displayContext.ViewContext)); } if (String.Equals(parameter.Name, "Output", StringComparison.OrdinalIgnoreCase) && parameter.ParameterType == typeof(TextWriter)) { throw new InvalidOperationException("Output is no more a valid Shape method parameter. Return an IHtmlContent instead."); } if (String.Equals(parameter.Name, "Output", StringComparison.OrdinalIgnoreCase) && parameter.ParameterType == typeof(Action <object>)) { throw new InvalidOperationException("Output is no more a valid Shape method parameter. Return an IHtmlContent instead."); } var getter = _getters.GetOrAdd(parameter.Name, n => CallSite <Func <CallSite, object, dynamic> > .Create( Binder.GetMember( CSharpBinderFlags.None, n, null, new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); object result = getter.Target(getter, displayContext.Value); if (result == null) { return(null); } if (parameter.ParameterType.IsAssignableFrom(result.GetType())) { return(result); } return(Convert.ChangeType(result, parameter.ParameterType)); }
private static SetMemberBinder CreateSetMemberBinder(Type type, string memberName) { return((SetMemberBinder)Microsoft.CSharp.RuntimeBinder.Binder.SetMember(CSharpBinderFlags.None, memberName, type, new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); }