/// <summary> /// Initializes a new instance of the <see cref="OKHOSTING.ORM.DataMember"/> class. /// <para xml:lang="es"> /// Inicializa una nueva instancia de la clase OKHOSTING.ORM.DataMember /// </para> /// </summary> /// <param name="type">Type. /// <para xml:lang="es">El tipo del dato.</para> /// </param> /// <param name="member">Member. /// <para xml:lang="es">El miembro.</para> /// </param> /// <param name="column">Column. /// <para xml:lang="es">La columna.</para> /// </param> public DataMember(DataType type, string member, Column column) { if (type == null) { throw new ArgumentNullException("type"); } if (string.IsNullOrWhiteSpace(member)) { throw new ArgumentNullException("member"); } DataType = type; Expression = new MemberExpression(type.InnerType, member); if (column == null) { CreateColumn(); } else { if (column.Table != type.Table) { throw new ArgumentOutOfRangeException("column", column, "This column does not belong the the Table that TypeMap is mapped to"); } Column = column; } }
public override Expression Visit(MemberExpression expression) { Expression previous = expression.Previous; if (previous != null) previous = Visit(previous); Expression statement = Visit(expression.Statement); if (statement == null) return previous; return updater.Update(expression, previous, statement); }
public override Expression MemberExpression(MemberExpression expression) { var type = _persistentClass; if (expression.Members.Count == 1) { Debug.Assert(expression.Members[0].IdExpression == null); return new ResolvedMemberExpression(expression.MemberType, ResolveName(expression.Members[0].Name, ref type)); } var sb = new StringBuilder(); string alias = null; for (int i = 0; i < expression.Members.Count - 1; i++) { if (i > 0) sb.Append('.'); Debug.Assert(expression.Members[i].IdExpression == null); sb.Append(ResolveName(expression.Members[i].Name, ref type)); string path = sb.ToString(); if (!Aliases.TryGetValue(path, out alias)) { alias = "t" + (Aliases.Count + 1); Aliases.Add(path, alias); } } return new ResolvedMemberExpression( expression.MemberType, alias + "." + ResolveName(expression.Members[expression.Members.Count - 1].Name, ref type) ); }
/// <summary> /// MemberExpression visit method /// </summary> /// <param name="m">The MemberExpression expression to visit</param> /// <returns>The visited MemberExpression expression </returns> internal override Expression VisitMemberAccess(MemberExpression m) { throw new NotSupportedException(Strings.ALinq_MemberAccessNotSupported(m.Member.Name)); }
protected override Expression VisitMember(MemberExpression node) { Invoke(node.Member); return(base.VisitMember(node)); }
// MemberExpression public override bool Walk(MemberExpression node) { return false; }
protected internal virtual void PostWalk(MemberExpression node) { }
public override bool Walk(MemberExpression node) { node.Parent = _currentScope; return base.Walk(node); }
public MemberExpressionProxy(MemberExpression node) { _node = node; }
private WriteBack AddressOfWriteBack(MemberExpression node) { var property = node.Member as PropertyInfo; if ((object)property == null || !property.CanWrite) { return null; } // emit instance, if any LocalBuilder instanceLocal = null; Type instanceType = null; if (node.Expression != null) { EmitInstance(node.Expression, instanceType = node.Expression.Type); // store in local _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Stloc, instanceLocal = GetLocal(instanceType)); } PropertyInfo pi = (PropertyInfo)node.Member; // emit the get EmitCall(instanceType, pi.GetGetMethod(true)); // emit the address of the value var valueLocal = GetLocal(node.Type); _ilg.Emit(OpCodes.Stloc, valueLocal); _ilg.Emit(OpCodes.Ldloca, valueLocal); // Set the property after the method call // don't re-evaluate anything return delegate () { if (instanceLocal != null) { _ilg.Emit(OpCodes.Ldloc, instanceLocal); FreeLocal(instanceLocal); } _ilg.Emit(OpCodes.Ldloc, valueLocal); FreeLocal(valueLocal); EmitCall(instanceType, pi.GetSetMethod(true)); }; }
private static string DealMemberExpression(MemberExpression exp, ref Dictionary <string, object> pms) { return(exp.Member.Name); }
public IValue ProcessMemberReference(MemberExpression expr, IGeneratedQueryCode gc, ICodeContext cc, System.ComponentModel.Composition.Hosting.CompositionContainer container) { return(null); }
static Tuple <UIView, NSLayoutAttribute> GetViewAndAttribute(Expression expr) { var attr = NSLayoutAttribute.NoAttribute; MemberExpression frameExpr = null; var fExpr = expr as MethodCallExpression; if (fExpr != null) { switch (fExpr.Method.Name) { case "GetMidX": case "GetCenterX": attr = NSLayoutAttribute.CenterX; break; case "GetMidY": case "GetCenterY": attr = NSLayoutAttribute.CenterY; break; case "GetBaseline": attr = NSLayoutAttribute.Baseline; break; default: throw new NotSupportedException("Method " + fExpr.Method.Name + " is not recognized."); } frameExpr = fExpr.Arguments.FirstOrDefault() as MemberExpression; } if (attr == NSLayoutAttribute.NoAttribute) { var memExpr = expr as MemberExpression; if (memExpr == null) { throw new NotSupportedException("Left hand side of a relation must be a member expression, instead it is " + expr); } switch (memExpr.Member.Name) { case "Width": attr = NSLayoutAttribute.Width; break; case "Height": attr = NSLayoutAttribute.Height; break; case "Left": case "X": attr = NSLayoutAttribute.Left; break; case "Top": case "Y": attr = NSLayoutAttribute.Top; break; case "Right": attr = NSLayoutAttribute.Right; break; case "Bottom": attr = NSLayoutAttribute.Bottom; break; default: throw new NotSupportedException("Property " + memExpr.Member.Name + " is not recognized."); } frameExpr = memExpr.Expression as MemberExpression; } if (frameExpr == null) { throw new NotSupportedException("Constraints should use the Frame or Bounds property of views."); } var viewExpr = frameExpr.Expression; var view = Eval(viewExpr) as UIView; if (view == null) { throw new NotSupportedException("Constraints only apply to views."); } return(Tuple.Create(view, attr)); }
protected override Expression VisitMemberAccess(MemberExpression m) { if (m.Member.DeclaringType == typeof(string)) { switch (m.Member.Name) { case "Length": this.Write("LENGTH("); this.Visit(m.Expression); this.Write(")"); return m; } } else if (m.Member.DeclaringType == typeof(DateTime) || m.Member.DeclaringType == typeof(DateTimeOffset)) { switch (m.Member.Name) { case "Day": this.Write("STRFTIME('%d', "); this.Visit(m.Expression); this.Write(")"); return m; case "Month": this.Write("STRFTIME('%m', "); this.Visit(m.Expression); this.Write(")"); return m; case "Year": this.Write("STRFTIME('%Y', "); this.Visit(m.Expression); this.Write(")"); return m; case "Hour": this.Write("STRFTIME('%H', "); this.Visit(m.Expression); this.Write(")"); return m; case "Minute": this.Write("STRFTIME('%M', "); this.Visit(m.Expression); this.Write(")"); return m; case "Second": this.Write("STRFTIME('%S', "); this.Visit(m.Expression); this.Write(")"); return m; case "Millisecond": this.Write("STRFTIME('%f', "); this.Visit(m.Expression); this.Write(")"); return m; case "DayOfWeek": this.Write("STRFTIME('%w', "); this.Visit(m.Expression); this.Write(")"); return m; case "DayOfYear": this.Write("(STRFTIME('%j', "); this.Visit(m.Expression); this.Write(") - 1)"); return m; } } return base.VisitMemberAccess(m); }
public static IQueryable <T> OrderQueryBy <T>(this IQueryable <T> query, string sortExpression, string sortDirection) { string methodName; string SortItem; string SortItemName; bool multipleSort = false; string[] ArraySortItems = null; if (sortExpression.IndexOf(GlobalConstants.Colon) == -1) { SortItem = sortExpression; methodName = string.Format("OrderBy{0}", sortDirection.ToLower() == "asc" ? string.Empty : "Descending"); } else { multipleSort = true; ArraySortItems = sortExpression.Split(GlobalConstants.ColonChar); SortItem = ArraySortItems[0]; methodName = string.Format("OrderBy{0}", SortItem.IndexOf("desc") > 0 ? "Descending" : string.Empty); } SortItemName = SortItem.Replace("asc", string.Empty).Replace("desc", string.Empty).Trim(); ParameterExpression parameter = Expression.Parameter(query.ElementType, "P"); MemberExpression memberAccess = null; foreach (var property in SortItemName.Split(GlobalConstants.PeriodChar)) { memberAccess = MemberExpression.Property(memberAccess ?? (parameter as Expression), property); } LambdaExpression orderByLambda = Expression.Lambda(memberAccess, parameter); MethodCallExpression result = Expression.Call( typeof(Queryable), methodName, new[] { query.ElementType, memberAccess.Type }, query.Expression, Expression.Quote(orderByLambda)); if (multipleSort) { byte pos = 1; while (pos < ArraySortItems.Length) { SortItem = ArraySortItems[pos].Trim(); methodName = string.Format("ThenBy{0}", SortItem.IndexOf("desc") > 0 ? "Descending" : string.Empty); SortItemName = SortItem.Replace("asc", string.Empty).Replace("desc", string.Empty).Trim(); memberAccess = null; foreach (var property in SortItemName.Split(GlobalConstants.PeriodChar)) { memberAccess = MemberExpression.Property(memberAccess ?? (parameter as Expression), property); } orderByLambda = Expression.Lambda(memberAccess, parameter); result = Expression.Call( typeof(Queryable), methodName, new[] { query.ElementType, memberAccess.Type }, result, Expression.Quote(orderByLambda)); pos++; } } return(query.Provider.CreateQuery <T>(result)); }
protected override Expression VisitMember(MemberExpression node) { return(Visit(node.Expression)); }
/// <summary> /// 添加已访问成员 /// </summary> public void Add(MemberExpression m) { _binaryMembers.Add(m); }
public virtual bool BeforeVisit(MemberExpression memberExpression) { return false; }
protected virtual T VisitMemberAccess(MemberExpression exp) { throw new NotImplementedException(exp.ToString()); }
public void Visit(MemberExpression node) { ReportError(node); }
/// <summary> /// Determines if a member expression represents a primary key /// <para xml:lang="es"> /// Determina si un MemberExpression es llave primaria /// </para> /// </summary> /// <returns> /// <c>true</c> if is primary key specified MemberExpression; otherwise, <c>false</c>. /// <para xml:lang="es"> /// Verdadero si el MemberExpression especificado es llave primaria /// </para> /// </returns> /// <param name="member"> /// A MemberExpression /// <para xml:lang="es">Un MemberExpression</para> /// </param> public static bool IsPrimaryKey(MemberExpression member) { return member.Expression.ToLower() == "id" || (member.FinalMemberInfo.Name == member.Expression && member.FinalMemberInfo.CustomAttributes.Where(att => att.AttributeType.Name.ToLower().Contains("key")).Count() > 0); }
/// <summary> /// Create combo date selector for date time. /// </summary> /// <exception cref="ArgumentNullException"> /// When expression is null. /// </exception> /// <typeparam name="TModel">Type of model.</typeparam> /// <param name="htmlHelper">HtmlHelper.</param> /// <param name="expression">Property selector expression.</param> /// <param name="yearRange">Range of years.</param> /// <param name="htmlAttributes">Html attributes to add to combo date.</param> /// <returns>Combo date selector.</returns> public static MvcHtmlString ComboDateFor <TModel>( this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, DateTime> > expression, IEnumerable <int> yearRange, object htmlAttributes) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } string comboDateCss = "combo-date"; string dayContainerCss = "day-container"; string monthContainerCss = "month-container"; string yearContainerCss = "year-container"; string errorCss = "combo-date__error"; string dayText = "Gün"; string monthText = "Ay"; string yearText = "İl"; // Initialize yearRange if has not been provided if (yearRange == null) { yearRange = Enumerable.Range(1900, 200); } // Get model metadata ModelMetadata metadata = ModelMetadata.FromLambdaExpression( expression, htmlHelper.ViewData); string modelName = ExpressionHelper.GetExpressionText(expression); // Append HtmlFieldPrefix if there is any string fieldPrefix = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix; if (!string.IsNullOrEmpty(fieldPrefix)) { modelName = string.Format("{0}.{1}", fieldPrefix, modelName); } // Convert html attributes RouteValueDictionary attributes = HtmlHelper .AnonymousObjectToHtmlAttributes(htmlAttributes); // Initialize container div FluentTagBuilder comboDate = new FluentTagBuilder("div") .MergeAttributes(attributes) .AddCssClass(comboDateCss); // Initialize hidden text box for client side validation FluentTagBuilder input = new FluentTagBuilder("input") .MergeAttribute("name", modelName) .MergeAttribute("id", modelName) .MergeAttribute("type", "date") .MergeAttribute("hidden", "hidden") .MergeAttribute("readonly", "readonly"); if (metadata.Model != null) { DateTime value = Convert.ToDateTime(metadata.Model); input.MergeAttribute("value", value.ToString("yyyy-MM-dd")); } //// Get validation attributes IDictionary <string, object> validationAttributes = htmlHelper.GetUnobtrusiveValidationAttributes(modelName, metadata); // Merge validation attributes input.MergeAttributes(validationAttributes); //contentBuilder.AppendLine(input.ToString()); comboDate.AppendChild(input); // Declare date property selector Expression <Func <TModel, Int32> > datePropertySelector; // Select day property of date MemberExpression dayExpression = Expression.Property(expression.Body, "Day"); datePropertySelector = Expression.Lambda <Func <TModel, Int32> >( dayExpression, expression.Parameters); // Create drop down button for day MvcHtmlString daySelector = htmlHelper .DropDownButtonFor <TModel, int>( datePropertySelector, new SelectList(Enumerable .Range(1, 31) .Select(m => new SelectListItem { Text = m.ToString("00"), Value = m.ToString() })), dayText); // Setup day container FluentTagBuilder dayContainer = new FluentTagBuilder("div") .AddCssClass(dayContainerCss) .AppendChild(daySelector); //contentBuilder.AppendLine(dayContainer.ToString()); comboDate.AppendChild(dayContainer); // Select month property of date MemberExpression monthExpression = Expression.Property(expression.Body, "Month"); datePropertySelector = Expression.Lambda <Func <TModel, Int32> >( monthExpression, expression.Parameters); // Create drop down button for month MvcHtmlString monthSelector = htmlHelper .DropDownButtonFor <TModel, int>( datePropertySelector, new SelectList(Enumerable.Range(1, 12) .Select(r => new SelectListItem { Value = r.ToString(), Text = DateTimeFormatInfo.CurrentInfo.GetMonthName(r) })), monthText); // Setup month container FluentTagBuilder monthContainer = new FluentTagBuilder("div") .AddCssClass(monthContainerCss) .AppendChild(monthSelector); //contentBuilder.AppendLine(monthContainer.ToString()); comboDate.AppendChild(monthContainer); // Select year property of date MemberExpression yearExpression = Expression.Property(expression.Body, "Year"); datePropertySelector = Expression.Lambda <Func <TModel, Int32> >( yearExpression, expression.Parameters); // Create drop down button for month MvcHtmlString yearSelector = htmlHelper .DropDownButtonFor <TModel, int>( datePropertySelector, new SelectList(yearRange .Select(r => new SelectListItem { Text = r.ToString(), Value = r.ToString() })), yearText); // Setup year container FluentTagBuilder yearContainer = new FluentTagBuilder("div") .AddCssClass(yearContainerCss) .AppendChild(yearSelector); comboDate.AppendChild(yearContainer); // Set up error span MvcHtmlString validationMessage = htmlHelper .ValidationMessageFor(expression); FluentTagBuilder errorSpan = new FluentTagBuilder("span") .AddCssClass(errorCss) .AppendChild(validationMessage); comboDate.AppendChild(errorSpan); return(new MvcHtmlString(comboDate.Render())); }
public virtual void Exit(MemberExpression node) { }
public static PropertyInfo GetProperty <TModel, T>(this Expression <Func <TModel, T> > expression) { MemberExpression memberExpression = GetMemberExpression(expression); return((PropertyInfo)memberExpression.Member); }
public override void Exit(MemberExpression node) { level--; }
protected override Expression VisitMember(MemberExpression node) { _all.Add(node.Member); return(base.VisitMember(node)); }
private WriteBack AddressOfWriteBack(MemberExpression node) { var property = node.Member as PropertyInfo; if ((object)property == null || !property.CanWrite) { return null; } return AddressOfWriteBackCore(node); // avoids closure allocation }
protected virtual bool CompareMemberAccess(MemberExpression a, MemberExpression b) { return a.Member == b.Member && this.Compare(a.Expression, b.Expression); }
// MemberExpression public virtual bool Walk(MemberExpression node) { return true; }
protected override Expression VisitMember(MemberExpression node) { if (!node.Member.DeclaringType.Name.Contains("<>")) return base.VisitMember(node); if (!_paramValues.ContainsKey(node.Member.Name)) return base.VisitMember(node); return Expression.Convert( Expression.Constant(_paramValues[node.Member.Name]), node.Member.GetMemberType()); }
protected override string VisitMemberAccess(MemberExpression m) { if (m.Expression != null && m.Expression.NodeType == ExpressionType.Parameter && m.Expression.Type == typeof(T)) { //don't execute if compiled if (Visited == false) { var field = _mapper.Map(m.Member.Name); if (field.IsNullOrWhiteSpace()) { throw new InvalidOperationException($"The mapper returned an empty field for the member name: {m.Member.Name} for type: {m.Expression.Type}."); } return(field); } //already compiled, return return(string.Empty); } if (m.Expression != null && m.Expression.NodeType == ExpressionType.Convert) { //don't execute if compiled if (Visited == false) { var field = _mapper.Map(m.Member.Name); if (field.IsNullOrWhiteSpace()) { throw new InvalidOperationException($"The mapper returned an empty field for the member name: {m.Member.Name} for type: {m.Expression.Type}."); } return(field); } //already compiled, return return(string.Empty); } if (m.Expression != null && m.Expression.Type != typeof(T) && EndsWithConstant(m) == false && _mappers.TryGetMapper(m.Expression.Type, out var subMapper)) { //if this is the case, it means we have a sub expression / nested property access, such as: x.ContentType.Alias == "Test"; //and since the sub type (x.ContentType) is not the same as x, we need to resolve a mapper for x.ContentType to get it's mapped SQL column //don't execute if compiled if (Visited == false) { var field = subMapper.Map(m.Member.Name); if (field.IsNullOrWhiteSpace()) { throw new InvalidOperationException($"The mapper returned an empty field for the member name: {m.Member.Name} for type: {m.Expression.Type}"); } return(field); } //already compiled, return return(string.Empty); } // TODO: When m.Expression.NodeType == ExpressionType.Constant and it's an expression like: content => aliases.Contains(content.ContentType.Alias); // then an SQL parameter will be added for aliases as an array, however in SqlIn on the subclass it will manually add these SqlParameters anyways, // however the query will still execute because the SQL that is written will only contain the correct indexes of SQL parameters, this would be ignored, // I'm just unsure right now due to time constraints how to make it correct. It won't matter right now and has been working already with this bug but I've // only just discovered what it is actually doing. // TODO // in most cases we want to convert the value to a plain object, // but for in some rare cases, we may want to do it differently, // for instance a Models.AuditType (an enum) may in some cases // need to be converted to its string value. // but - we cannot have specific code here, really - and how would // we configure this? is it even possible? /* * var toString = typeof(object).GetMethod("ToString"); * var member = Expression.Call(m, toString); */ var member = Expression.Convert(m, typeof(object)); var lambda = Expression.Lambda <Func <object> >(member); var getter = lambda.Compile(); var o = getter(); SqlParameters.Add(o); //don't execute if compiled if (Visited == false) { return($"@{SqlParameters.Count - 1}"); } //already compiled, return return(string.Empty); }
/// <summary> /// Visits the children of <see cref="System.Linq.Expressions.MemberExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; otherwise, /// returns the original expression.</returns> protected override Expression VisitMember(MemberExpression node) { if ((node.Member.DeclaringType == typeof(TDataObject) || typeof(TDataObject).IsSubclassOf(node.Member.DeclaringType)) && node.Expression != null && node.Expression is ParameterExpression) { string mappedFieldName = this.ResolveFieldName(node.Expression.Type, node.Member); Out(mappedFieldName); } //else if (node.Expression != null && // node.Expression is MemberExpression && // (node.Member.DeclaringType.IsAssignableFrom(node.Expression.Type) || // node.Expression.Type.IsSubclassOf(node.Member.DeclaringType))) //{ // string mappedFieldName = this.ResolveFieldName(node.Expression.Type, node.Member); // Out(mappedFieldName); //} else { object memberValue = null; if (node.Member is FieldInfo) { ConstantExpression ce = node.Expression as ConstantExpression; FieldInfo fi = node.Member as FieldInfo; memberValue = fi.GetValue(ce.Value); } else if (node.Member is PropertyInfo) { PropertyInfo pi = node.Member as PropertyInfo; if (pi.GetGetMethod().IsStatic) { memberValue = pi.GetValue(null, null); } else { List <PropertyInfo> piList = new List <PropertyInfo>(new PropertyInfo[] { pi }); Expression nodeExpression = node.Expression; while (nodeExpression is MemberExpression) { MemberExpression memberExpression = (MemberExpression)nodeExpression; if (memberExpression.Expression is ConstantExpression) { break; } else { if (memberExpression.Member is PropertyInfo) { PropertyInfo subPi = memberExpression.Member as PropertyInfo; piList.Add(subPi); } } nodeExpression = memberExpression.Expression; } MemberExpression lastMemberExpression = (MemberExpression)nodeExpression; ConstantExpression constantExpression = lastMemberExpression.Expression as ConstantExpression; FieldInfo fi = lastMemberExpression.Member as FieldInfo; memberValue = fi.GetValue(constantExpression.Value); piList.Reverse(); for (int piIndex = 0; piIndex < piList.Count; piIndex++) { memberValue = piList[piIndex].GetValue(memberValue, null); } //throw new NotSupportedException(string.Format(Resources.EX_MEMBER_TYPE_NOT_SUPPORT, node.Member.GetType().FullName)); } } Expression constantExpr = Expression.Constant(memberValue); Visit(constantExpr); } return(node); }
// MemberExpression public override bool Walk(MemberExpression node) { return Location >= node.StartIndex && Location <= node.EndIndex; }
/// <summary> /// Visit member access. /// </summary> /// <param name="expression">The expression to visit.</param> /// <returns>The visited expression.</returns> protected override Expression VisitMember(MemberExpression expression) => memberVisitor != null?memberVisitor(expression, e => base.VisitMember(e)) : base.VisitMember(expression);
public virtual Expression VisitMemberExpression(MemberExpression expression) { return expression; }
IQueryable <T> IOrder <T> .Arranged(IQueryable <T> source) { if (!orders.Any()) { return(source); } string methodAsc = "OrderBy"; string methodDesc = "OrderByDescending"; Expression queryExpr = source.Expression; foreach (var sort in orders) { MemberExpression selector = (sort.Expression as LambdaExpression).Body.RemoveConvert() as MemberExpression; if (selector == null) { throw new InvalidOperationException("不支持的排序类型。"); } Type resultType = selector.Type; Expression exp = Expression.Quote(Expression.Lambda(selector, selector.Parameter())); if (resultType.IsValueType || resultType == typeof(string)) { queryExpr = Expression.Call( typeof(Queryable), sort.SortOrder == SortOrder.Ascending ? methodAsc : methodDesc, new Type[] { source.ElementType, resultType }, queryExpr, exp); methodAsc = "ThenBy"; methodDesc = "ThenByDescending"; } else { throw new InvalidOperationException(string.Format("不支持的排序类型:{0}", resultType.FullName)); } } return(source.Provider.CreateQuery <T>(queryExpr)); //IOrderedQueryable<T> orderenumerable = null; //ISortItem<T> first = orders.First(); //switch (first.SortOrder) { // case SortOrder.Ascending: // orderenumerable = enumerable.OrderBy(first.Expression); // break; // case SortOrder.Descending: // orderenumerable = enumerable.OrderByDescending(first.Expression); // break; //} //foreach (ISortItem<T> sort in orders.Skip(1)) { // switch (sort.SortOrder) { // case SortOrder.Ascending: // orderenumerable = orderenumerable.ThenBy(sort.Expression); // break; // case SortOrder.Descending: // orderenumerable = orderenumerable.ThenByDescending(sort.Expression); // break; // } //} //return orderenumerable; }
public virtual void AfterVisit(MemberExpression memberExpression) { }
public static bool IsGroupingKey(this MemberExpression expression) { return(expression.Member.Name == "Key" && expression.Member.DeclaringType != null && expression.Member.DeclaringType.IsGenericType && expression.Member.DeclaringType.GetGenericTypeDefinition() == typeof(IGrouping <,>)); }
//CONFORMING private void AddressOf(MemberExpression node, Type type) { if (type == node.Type) { // emit "this", if any Type objectType = null; if (node.Expression != null) { EmitInstance(node.Expression, objectType = node.Expression.Type); } EmitMemberAddress(node.Member, objectType); } else { EmitExpressionAddress(node, type); } }
private static Expression GetExpression <T>(ParameterExpression param, FilterEngine filter) { var propertyName = filter.PropertyName.ToLower(); MemberExpression member = Expression.Property(param, propertyName); string filterValue = filter.Value.ToString().ToLower(); UnaryExpression constant; if (member.Type == typeof(Int32?) || member.Type == typeof(Int32)) { constant = Expression.Convert(Expression.Constant(Int32.Parse(filterValue)), member.Type); } else if (member.Type == typeof(DateTime?) || member.Type == typeof(DateTime)) { constant = Expression.Convert(Expression.Constant(DateTime.Parse(filterValue)), member.Type); } else if (member.Type == typeof(Guid?) || member.Type == typeof(Guid)) { constant = Expression.Convert(Expression.Constant(Guid.Parse(filterValue)), member.Type); } else if (member.Type == typeof(Boolean?) || member.Type == typeof(Boolean)) { constant = Expression.Convert(Expression.Constant(Boolean.Parse(filterValue)), member.Type); } else { constant = Expression.Convert(Expression.Constant(filterValue), member.Type); } switch (filter.Operation) { case Op.Equals: if (member.Type.Name == "String") { var expToLower = Expression.Call(member, ToLowerMethod); return(Expression.Equal(expToLower, constant)); } return(Expression.Equal(member, constant)); case Op.GreaterThan: return(Expression.GreaterThan(member, constant)); case Op.GreaterThanOrEqual: return(Expression.GreaterThanOrEqual(member, constant)); case Op.LessThan: return(Expression.LessThan(member, constant)); case Op.LessThanOrEqual: return(Expression.LessThanOrEqual(member, constant)); case Op.Contains: var expToLowerContains = Expression.Call(member, ToLowerMethod); return(Expression.Call(expToLowerContains, ContainsMethod, constant)); // call StartsWith() on the exp, which is property.ToLower() case Op.StartsWith: var expToLowerStartsWith = Expression.Call(member, ToLowerMethod); return(Expression.Call(expToLowerStartsWith, StartsWithMethod, constant)); case Op.EndsWith: var expToLowerEndsWith = Expression.Call(member, ToLowerMethod); return(Expression.Call(expToLowerEndsWith, EndsWithMethod, constant)); case Op.NotEquals: if (member.Type.Name == "String") { var expToLowerNotEqual = Expression.Call(member, ToLowerMethod); return(Expression.NotEqual(expToLowerNotEqual, constant)); } else { return(Expression.NotEqual(member, constant)); } } return(null); }
public override bool Walk(MemberExpression node) { node.Walk(_fc); return false; }
private Expression VisitField(MemberExpression node, FieldInfo field) { return(System.Activator.CreateInstance(typeof(ObservableReversableMemberExpression <,>).MakeGenericType(field.DeclaringType, field.FieldType), node, this, field.Name, field) as Expression); }
private TResult BindMemberExpression <TResult>( MemberExpression memberExpression, Func <IProperty, IQuerySource, SelectExpression, TResult> memberBinder) { return(BindMemberExpression(memberExpression, null, memberBinder)); }
protected override Node VisitMemberAccess(MemberExpression m) { return(this.VisitMemberAccess(m, null)); }
internal Expression InitializeArgumentVariant(MemberExpression variant, Expression parameter) { //NOTE: we must remember our variant //the reason is that argument order does not map exactly to the order of variants for invoke //and when we are doing clean-up we must be sure we are cleaning the variant we have initialized. _variant = variant; if (IsByRef) { // temp = argument // paramVariants._elementN.SetAsByrefT(ref temp) Debug.Assert(TempVariable == null); var argExpr = _argBuilder.MarshalToRef(parameter); TempVariable = Expression.Variable(argExpr.Type, null); return Expression.Block( Expression.Assign(TempVariable, argExpr), Expression.Call( variant, Variant.GetByrefSetter(_targetComType & ~VarEnum.VT_BYREF), TempVariable ) ); } Expression argument = _argBuilder.Marshal(parameter); // we are forced to special case ConvertibleArgBuilder since it does not have // a corresponding _targetComType. if (_argBuilder is ConvertibleArgBuilder) { return Expression.Call( variant, typeof(Variant).GetMethod("SetAsIConvertible"), argument ); } if (Variant.IsPrimitiveType(_targetComType) || (_targetComType == VarEnum.VT_DISPATCH) || (_targetComType == VarEnum.VT_UNKNOWN) || (_targetComType == VarEnum.VT_VARIANT) || (_targetComType == VarEnum.VT_RECORD) || (_targetComType == VarEnum.VT_ARRAY)) { // paramVariants._elementN.AsT = (cast)argN return Expression.Assign( Expression.Property( variant, Variant.GetAccessor(_targetComType) ), argument ); } switch (_targetComType) { case VarEnum.VT_EMPTY: return null; case VarEnum.VT_NULL: // paramVariants._elementN.SetAsNull(); return Expression.Call(variant, typeof(Variant).GetMethod("SetAsNull")); default: Debug.Assert(false, "Unexpected VarEnum"); return null; } }
public static MemberInfo GetMemberInfo <TResult>(Expression <Func <TResult> > expr) { MemberExpression member = expr.Body as MemberExpression; return(member.Member); }
public virtual bool Enter(MemberExpression node) { return true; }
private bool CompareMemberAccess(MemberExpression a, MemberExpression b) => Equals(a.Member, b.Member) && Compare(a.Expression, b.Expression);
public override bool Enter(MemberExpression node) { Print("MemberExpression"); level++; return true; }
protected override Expression VisitMember(MemberExpression node) { EnsureTypeAdded(node.Type); _parameterMemberChain.Push(node.Member); return(base.VisitMember(node)); }
// MemberExpression protected internal virtual bool Walk(MemberExpression node) { return true; }
protected override Expression VisitMember(MemberExpression node) { string sourcePath; var parameterExpression = node.GetParameterExpression(); if (parameterExpression == null) { return(base.VisitMember(node)); } InfoDictionary.Add(parameterExpression, TypeMappings); var sType = parameterExpression.Type; if (InfoDictionary.ContainsKey(parameterExpression) && node.IsMemberExpression()) { sourcePath = node.GetPropertyFullName(); } else { return(base.VisitMember(node)); } var propertyMapInfoList = new List <PropertyMapInfo>(); FindDestinationFullName(sType, InfoDictionary[parameterExpression].DestType, sourcePath, propertyMapInfoList); string fullName; if (propertyMapInfoList.Any(x => x.CustomExpression != null)) { var last = propertyMapInfoList.Last(x => x.CustomExpression != null); var beforeCustExpression = propertyMapInfoList.Aggregate(new List <PropertyMapInfo>(), (list, next) => { if (propertyMapInfoList.IndexOf(next) < propertyMapInfoList.IndexOf(last)) { list.Add(next); } return(list); }); var afterCustExpression = propertyMapInfoList.Aggregate(new List <PropertyMapInfo>(), (list, next) => { if (propertyMapInfoList.IndexOf(next) > propertyMapInfoList.IndexOf(last)) { list.Add(next); } return(list); }); fullName = BuildFullName(beforeCustExpression); var visitor = new PrependParentNameVisitor(last.CustomExpression.Parameters[0].Type /*Parent type of current property*/, fullName, InfoDictionary[parameterExpression].NewParameter); var ex = propertyMapInfoList[propertyMapInfoList.Count - 1] != last ? visitor.Visit(last.CustomExpression.Body.MemberAccesses(afterCustExpression)) : visitor.Visit(last.CustomExpression.Body); this.TypeMappings.AddTypeMapping(node.Type, ex.Type); return(ex); } fullName = BuildFullName(propertyMapInfoList); var me = ExpressionFactory.MemberAccesses(fullName, InfoDictionary[parameterExpression].NewParameter); this.TypeMappings.AddTypeMapping(node.Type, me.Type); return(me); }
private void AddressOf(MemberExpression node, Type type) { if (TypeUtils.AreEquivalent(type, node.Type)) { // emit "this", if any Type objectType = null; if (node.Expression != null) { EmitInstance(node.Expression, out objectType); } EmitMemberAddress(node.Member, objectType); } else { EmitExpressionAddress(node, type); } }
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual Expression Translate(MemberExpression memberExpression) { var member = memberExpression.Member.OnInterface(typeof(IGeometry)); if (_memberToFunctionName.TryGetValue(member, out var functionName)) { Expression newExpression = new SqlFunctionExpression( functionName, memberExpression.Type, new[] { memberExpression.Expression }); if (memberExpression.Type == typeof(bool)) { newExpression = new CaseExpression( new CaseWhenClause( Expression.Not(new IsNullExpression(memberExpression.Expression)), newExpression)); } return(newExpression); } if (Equals(member, _geometryType)) { return(new CaseExpression( new SqlFunctionExpression( "rtrim", memberExpression.Type, new Expression[] { new SqlFunctionExpression( "GeometryType", memberExpression.Type, new[] { memberExpression.Expression }), Expression.Constant(" ZM") }), new CaseWhenClause(Expression.Constant("POINT"), Expression.Constant("Point")), new CaseWhenClause(Expression.Constant("LINESTRING"), Expression.Constant("LineString")), new CaseWhenClause(Expression.Constant("POLYGON"), Expression.Constant("Polygon")), new CaseWhenClause(Expression.Constant("MULTIPOINT"), Expression.Constant("MultiPoint")), new CaseWhenClause(Expression.Constant("MULTILINESTRING"), Expression.Constant("MultiLineString")), new CaseWhenClause(Expression.Constant("MULTIPOLYGON"), Expression.Constant("MultiPolygon")), new CaseWhenClause(Expression.Constant("GEOMETRYCOLLECTION"), Expression.Constant("GeometryCollection")))); } if (Equals(member, _ogcGeometryType)) { return(new CaseExpression( new SqlFunctionExpression( "rtrim", typeof(string), new Expression[] { new SqlFunctionExpression( "GeometryType", typeof(string), new[] { memberExpression.Expression }), Expression.Constant(" ZM") }), new CaseWhenClause(Expression.Constant("POINT"), Expression.Constant(OgcGeometryType.Point)), new CaseWhenClause(Expression.Constant("LINESTRING"), Expression.Constant(OgcGeometryType.LineString)), new CaseWhenClause(Expression.Constant("POLYGON"), Expression.Constant(OgcGeometryType.Polygon)), new CaseWhenClause(Expression.Constant("MULTIPOINT"), Expression.Constant(OgcGeometryType.MultiPoint)), new CaseWhenClause(Expression.Constant("MULTILINESTRING"), Expression.Constant(OgcGeometryType.MultiLineString)), new CaseWhenClause(Expression.Constant("MULTIPOLYGON"), Expression.Constant(OgcGeometryType.MultiPolygon)), new CaseWhenClause(Expression.Constant("GEOMETRYCOLLECTION"), Expression.Constant(OgcGeometryType.GeometryCollection)))); } return(null); }
private WriteBack AddressOfWriteBackCore(MemberExpression node) { // emit instance, if any LocalBuilder instanceLocal = null; Type instanceType = null; if (node.Expression != null) { EmitInstance(node.Expression, out instanceType); // store in local _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Stloc, instanceLocal = GetInstanceLocal(instanceType)); } PropertyInfo pi = (PropertyInfo)node.Member; // emit the get EmitCall(instanceType, pi.GetGetMethod(nonPublic: true)); // emit the address of the value LocalBuilder valueLocal = GetLocal(node.Type); _ilg.Emit(OpCodes.Stloc, valueLocal); _ilg.Emit(OpCodes.Ldloca, valueLocal); // Set the property after the method call // don't re-evaluate anything return @this => { if (instanceLocal != null) { @this._ilg.Emit(OpCodes.Ldloc, instanceLocal); @this.FreeLocal(instanceLocal); } @this._ilg.Emit(OpCodes.Ldloc, valueLocal); @this.FreeLocal(valueLocal); @this.EmitCall(instanceLocal?.LocalType, pi.GetSetMethod(nonPublic: true)); }; }
protected override Expression VisitMember(MemberExpression node) { if (node.Expression == null) { throw new NotSupportedException($"The member '{node.Member.Name}' is not supported"); } object value; switch (node.Expression.NodeType) { case ExpressionType.Parameter: var parameterName = node.Member.Name; // Used for the KeyValuePair expressions, to replace the Key / Value in cases // of non complex types on these properties if (_parameterReplacementDictionary != null && _parameterReplacementDictionary.ContainsKey(parameterName)) { parameterName = _parameterReplacementDictionary[parameterName]; } _filter.Append(_databaseDriver.ParseIdentifier(parameterName)); _parameterNames.Enqueue(parameterName); return(node); case ExpressionType.MemberAccess: var memberExpression = (MemberExpression)node.Expression; Expression deepExpression = memberExpression; while (deepExpression is MemberExpression) { deepExpression = ((MemberExpression)deepExpression).Expression; } if (deepExpression is ConstantExpression) { var deepConstantExpression = (ConstantExpression)deepExpression; if (node.Member is PropertyInfo) { if (memberExpression.Member is FieldInfo) { var fieldInfoValue = ((FieldInfo)memberExpression.Member).GetValue(deepConstantExpression.Value); value = ((PropertyInfo)node.Member).GetValue(fieldInfoValue, null); _filter.Append(AddFilterValue(value, node.Type)); return(node); } if (memberExpression.Member is PropertyInfo) { var objectMember = Expression.Convert(node, typeof(object)); var getterLambda = Expression.Lambda <Func <object> >(objectMember); var getter = getterLambda.Compile(); value = getter(); _filter.Append(AddFilterValue(value, node.Type)); return(node); } } else { throw new NotSupportedException(); } } _filter.Append(_databaseDriver.ParseIdentifier(node.Member.Name)); return(node); case ExpressionType.Constant: var constantExpression = (ConstantExpression)node.Expression; var member = node.Member; value = null; if (member is FieldInfo) { value = ((FieldInfo)member).GetValue(constantExpression.Value); } if (member is PropertyInfo) { value = ((PropertyInfo)member).GetValue(constantExpression.Value, null); } _filter.Append(AddFilterValue(value, node.Type)); return(node); } throw new NotSupportedException($"The expression member '{node.Member.Name}' with node type '{node.Expression.NodeType}' is not supported"); }
public override void PostWalk(MemberExpression node) { }
private ExprNode ParseMemberExpression() { var exp = new MemberExpression {Token = Next()}; exp.Expression = Next().Is(TokenType.Func) ? ParseFunctionExpression() : ParsePrimaryExpression(); exp.Suffixes = ParseMemberExpressionSuffix(); return exp.Suffixes.Count == 0 ? exp.Expression : exp; }
public virtual void PostWalk(MemberExpression node) { }
public virtual void VisitMemberExpression(MemberExpression memberExpression) { VisitExpression(memberExpression.Object); }