private static Expression MakeStringContainment(FilterOperator filterOperator, IList <Expression> children) { var methodName = filterOperator.ToString(); var method = typeof(string).GetMethods().Single(x => x.Name == methodName && x.GetParameters().Length == 1 && x.GetParameters().Single().ParameterType == typeof(string)); if (children[1].Type == children[0].Type) { return(Expression.Call(children[0], method, children[1])); } var param = Expression.Parameter(typeof(string), "textItem"); var lambda = Expression.Lambda(Expression.Call(children[0], method, param), param); var anyMethod = typeof(Enumerable).GetMethods().Single(x => x.Name == nameof(Enumerable.Any) && x.GetParameters().Length == 2); anyMethod = anyMethod.MakeGenericMethod(typeof(string)); return(Expression.Call(anyMethod, children[1], lambda)); }
public static string ToOperatorStr(this FilterOperator value) { switch (value) { case FilterOperator.Contains: return("contains"); case FilterOperator.LessThanEqual: return("lte"); case FilterOperator.GreaterThanEqual: return("gte"); case FilterOperator.EqualTo: return("eq"); default: throw new NotImplementedException($"[{value.ToString()}] Operator not handled"); } }
private Expression CompileFilterFunction <T>(FilterOperator filtertype, ParameterExpression roottable, MemberExpression column, Expression valueExpression, object value) { Expression where = null; switch (filtertype.ToString()) { case "neq": where = Expression.NotEqual(column, valueExpression); break; case "eq": where = Expression.Equal(column, valueExpression); break; case "lt": where = Expression.LessThan(column, valueExpression); break; case "lte": where = Expression.LessThanOrEqual(column, valueExpression); break; case "gt": where = Expression.GreaterThan(column, valueExpression); break; case "gte": where = Expression.GreaterThanOrEqual(column, valueExpression); break; case "contains": where = CompileExpressionFunction <T>(roottable, column, "Contains", value.ToString()).Body; break; case "startswith": where = CompileExpressionFunction <T>(roottable, column, "StartsWith", value.ToString()).Body; break; case "endswith": where = CompileExpressionFunction <T>(roottable, column, "EndsWith", value.ToString()).Body; break; default: _logger.LogWarning($"Specified filter function '{filtertype}' is not supported by the dynamic expression service. Filter for field '{column.Member.Name}' has been ignored!"); break; } return(where); }
/// <summary> /// Renders a comaprison operator /// </summary> /// <param name="builder"></param> /// <param name="op"></param> protected virtual void Operator(StringBuilder builder, FilterOperator op) { if (op == FilterOperator.IsEqualTo) { builder.Append("="); } else if (op == FilterOperator.IsNotEqualTo) { builder.Append("<>"); } else if (op == FilterOperator.IsGreaterThan) { builder.Append(">"); } else if (op == FilterOperator.IsLessThan) { builder.Append("<"); } else if (op == FilterOperator.IsLessThanOrEqualTo) { builder.Append("<="); } else if (op == FilterOperator.IsGreaterThanOrEqualTo) { builder.Append(">="); } else if (op == FilterOperator.Contains) { builder.Append("like"); } else if (op == FilterOperator.IsNull) { builder.Append("is null"); } else if (op == FilterOperator.IsNotNull) { builder.Append("is not null"); } else { throw new InvalidQueryException("Unkown operator: " + op.ToString()); } }
private void FilterOperandMI_DropDownOpening(object sender, EventArgs e) { try { // check if the drop down has been initialized. if (Object.ReferenceEquals(sender, FilterOperandMI)) { if (FilterOperandMI.DropDownItems.Count == 0) { foreach (FilterOperator current in s_Operators) { ToolStripMenuItem item = new ToolStripMenuItem(current.ToString()); item.Tag = current; item.Click += new EventHandler(FilterOperandMI_DropDownOpening); FilterOperandMI.DropDownItems.Add(item); } } return; } // update the filter operator for all selected items. FilterOperator op = (FilterOperator)((ToolStripMenuItem)sender).Tag; foreach (ListViewItem item in EventFieldsLV.SelectedItems) { FilterItem field = item.Tag as FilterItem; if (field != null) { field.FilterOperator = op; item.SubItems[3].Text = op.ToString(); } } EventFieldsLV.Columns[3].Width = -2; } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
public static string ToString(FilterOperator value) { if( value==FilterOperator.Equal ) return "="; else if( value==FilterOperator.IsA ) return "is-a"; else if( value==FilterOperator.IsNotA ) return "is-not-a"; else if( value==FilterOperator.Regex ) return "regex"; else throw new ArgumentException("Unrecognized FilterOperator value: " + value.ToString()); }
public override bool Matches(IPMLEntity pmlEntity) { var evt = pmlEntity as PMLEvent; var actualValue = string.Empty; switch (PropertyName) { case "Operation": actualValue = evt.Operation; break; case "Result": actualValue = evt.Result; break; case "PID": actualValue = evt.PID.ToString(); break; case "TID": actualValue = evt.TID.ToString(); break; //case "Session": // actualValue = evt.ProcessIndex; // break; case "Path": actualValue = evt.Path; break; case "Detail": actualValue = evt.Detail; break; case "StackFramePath": if (FilterOperator != FilterOperators.Contains) { throw new Exception(string.Format("Filter Operator {0} is invalid when PropertyName is \"StackFramePath\"", FilterOperator.ToString())); } var sbStackFramePaths = new StringBuilder(); foreach (var frame in evt.CallStack) { if (!string.IsNullOrWhiteSpace(frame.Path)) { sbStackFramePaths.Append(frame.Path).Append(Environment.NewLine); } } actualValue = sbStackFramePaths.ToString(); break; case "StackFrameLocation": if (FilterOperator != FilterOperators.Contains) { throw new Exception(string.Format("Filter Operator {0} is invalid when PropertyName is \"StackFramePath\"", FilterOperator.ToString())); } var sbStackFrameLocations = new StringBuilder(); foreach (var frame in evt.CallStack) { if (!string.IsNullOrWhiteSpace(frame.Location)) { sbStackFrameLocations.Append(frame.Location).Append(Environment.NewLine); } } actualValue = sbStackFrameLocations.ToString(); break; case "": throw new Exception("PropertyName cannot be empty."); default: throw new Exception(string.Format("Unidentified PropertyName {0}.", PropertyName)); } return(CompareStringValuesAsPerFilterOperator(actualValue, this)); }
public static Exception InvalidFilterValue(Property property, FilterOperator op, string value, string validDescription) { return(new NotSupportedException($"Cannot filter where property '{property}' {op.ToString().ToLower()} '{value}'. PRTG only supports filters where {validDescription}.")); }
/// <summary> /// safe for Contains, StartsWith, Is Equal To, Is Not Equal To /// </summary> /// <param name="filterOperator"></param> /// <param name="logicalOperator"></param> /// <returns></returns> private string ConvertDescriptorOperator(FilterOperator filterOperator, string logicalOperator) { string result; switch (filterOperator) { case FilterOperator.IsEqualTo: result = string.Format("{{0}} == @{{1}} {0} ", logicalOperator); break; case FilterOperator.IsNotEqualTo: result = string.Format("{{0}} != @{{1}} {0} ", logicalOperator); break; case FilterOperator.IsGreaterThan: result = string.Format("{{0}} > @{{1}} {0} ", logicalOperator); break; case FilterOperator.IsGreaterThanOrEqualTo: result = string.Format("{{0}} >= @{{1}} {0} ", logicalOperator); break; case FilterOperator.IsLessThan: result = string.Format("{{0}} < @{{1}} {0} ", logicalOperator); break; case FilterOperator.IsLessThanOrEqualTo: result = string.Format("{{0}} <= @{{1}} {0} ", logicalOperator); break; default: result = string.Format("{{0}}.{0}(@{{1}}) {1} ", filterOperator.ToString(), logicalOperator); break; } return String.IsNullOrEmpty(logicalOperator) ? result.Trim() : result; }
public override string ToString() { return(_name + "~" + _operator.ToString().ToLowerInvariant().Replace("n", "!") + "~" + _value); }
public override bool Matches(IPMLEntity pmlEntity) { var evt = pmlEntity as PMLEvent; var proc = ConvertedXMLProcessor.FindProcessByPID(evt.PID); var actualValue = string.Empty; switch (PropertyName) { case "ProcessName": actualValue = ProcessNameList.GetProcessName(proc.ProcessNameIndex); break; case "ImagePath": actualValue = ModuleList.GetModulePath(proc.ImageIndex); break; case "FinishTime": if (proc.FinishTime == DateTimeZero) { actualValue = "0"; } else { actualValue = proc.FinishTime.ToString(); } break; case "Modules": if (FilterOperator != FilterOperators.Contains) { throw new Exception(string.Format("Filter Operator {0} is invalid when PropertyName is \"Modules\"", FilterOperator.ToString())); } var sbModules = new StringBuilder(); foreach (var i in proc.LoadedModuleList) { sbModules.Append(ModuleList.GetModulePath(i)).Append(Environment.NewLine); } actualValue = sbModules.ToString(); break; case "": throw new Exception("PropertyName cannot be empty."); default: throw new Exception(string.Format("Unidentified PropertyName {0}.", PropertyName)); } return(CompareStringValuesAsPerFilterOperator(actualValue, this)); }
/// <summary> /// Produces the Linq expression that represents a particular FilterDescriptor /// </summary> /// <param name="type">Entity type</param> /// <param name="propertyPath">Left operand: Property on the entity type</param> /// <param name="filterOperator">One of the FilterOperator enum value</param> /// <param name="value">Right operand</param> /// <param name="isCaseSensitive">Boolean that specifies if the string operations are case sensitive or not</param> /// <returns>Resulting linq expression</returns> /// <exception cref="ArgumentException">When a filter descriptor references a property that could not be found.</exception> /// <exception cref="ArgumentException">When an exception occurs attempting to evaluate a filter descriptor.</exception> /// <exception cref="ArgumentException">When the supplied filter value has a type that cannot be compared to the property type.</exception> /// <exception cref="NotSupportedException">When attempting to use a property type/operator pair that is not supported.</exception> public static Expression BuildFilterExpression( Type type, string propertyPath, FilterOperator filterOperator, object value, bool isCaseSensitive) { Debug.Assert(type != null, "Unexpected null type"); Debug.Assert(propertyPath != null, "Unexpected null propertyPath"); Expression filterExpression = null; PropertyInfo pi; Expression propertyExpression; Expression valueExpression; try { pi = type.GetPropertyInfo(propertyPath); if (pi == null) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, CommonResources.PropertyNotFound, propertyPath, type.GetTypeName())); } // TODO: Remove this check. // It's a duplicate of one done in the DDS, but it's still required for the BuildFilterExpressions Test. else if (!IsSupportedOperator(pi.PropertyType, filterOperator)) { throw new NotSupportedException(string.Format( CultureInfo.InvariantCulture, DomainDataSourceResources.FilterNotSupported, propertyPath, type.GetTypeName(), pi.PropertyType.GetTypeName(), filterOperator)); } propertyExpression = GenerateProperty(type, propertyPath, Expression.Parameter(type, string.Empty)); valueExpression = GenerateConstant(value); Debug.Assert(propertyExpression != null, "Unexpected null propertyExpression in LinqHelper.BuildFilterExpression"); } catch (Exception ex) { if (ex.IsFatal()) { throw; } throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, DomainDataSourceResources.CannotEvaluateDescriptor, propertyPath), ex); } try { bool isEquality = filterOperator == FilterOperator.IsEqualTo || filterOperator == FilterOperator.IsNotEqualTo; if (isEquality && !propertyExpression.Type.IsValueType && !valueExpression.Type.IsValueType) { if (propertyExpression.Type != valueExpression.Type) { if (propertyExpression.Type.IsAssignableFrom(valueExpression.Type)) { valueExpression = Expression.Convert(valueExpression, propertyExpression.Type); } else if (valueExpression.Type.IsAssignableFrom(propertyExpression.Type)) { propertyExpression = Expression.Convert(propertyExpression, valueExpression.Type); } else { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, DomainDataSourceResources.IncompatibleOperands, filterOperator.ToString(), propertyExpression.Type.GetTypeName(), valueExpression.Type.GetTypeName())); } } } else if (propertyExpression.Type.IsEnumType()) { // Convert the value to compare to the underlying type of the enum, // preserving nullable and following the same rules the C# compiler does. // Examples: // p.Enum > Enum.A => p.Enum > 1 // p.Enum > null => p.Enum > Convert(null, Nullable<int>) // p.NullableEnum > Enum.A => p.Enum > Convert(Enum.A, Nullable<int>) // p.NullableEnum > null => p.Enum > Convert(Enum.A, Nullable<int>) Type underlyingType = Enum.GetUnderlyingType(TypeUtility.GetNonNullableType(propertyExpression.Type)); bool propertyIsNullable = propertyExpression.Type.IsNullableType(); if (propertyIsNullable) { underlyingType = typeof(Nullable<>).MakeGenericType(underlyingType); } if (valueExpression.Type != underlyingType) { if (value != null && !propertyIsNullable) { // convert to the underlying value and create a new constant value = Convert.ChangeType(value, underlyingType, CultureInfo.InvariantCulture); valueExpression = GenerateConstant(value); } else { // for nulls or comparisons against a nullable enum, we inject // a conversion valueExpression = Expression.Convert(valueExpression, underlyingType); } } // Now that we've converted the enum value, we inject the appropriate conversion // on the property expression if (propertyExpression.Type != valueExpression.Type) { Expression e; if ((e = PromoteExpression(propertyExpression, valueExpression.Type, true)) != null) { propertyExpression = e; } else { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, DomainDataSourceResources.IncompatibleOperands, filterOperator.ToString(), propertyExpression.Type.GetTypeName(), valueExpression.Type.GetTypeName())); } } } else if (pi.PropertyType.IsNullableType() && propertyExpression.Type != valueExpression.Type) { ConstantExpression ce = valueExpression as ConstantExpression; if (ce != null) { valueExpression = Expression.Constant(ce.Value, propertyExpression.Type); } } filterExpression = BuildFilterExpression(propertyExpression, filterOperator, valueExpression, isCaseSensitive); } catch (Exception ex) { if (ex.IsFatal()) { throw; } throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, DomainDataSourceResources.IncompatibleOperands, filterOperator.ToString(), propertyExpression.Type.GetTypeName(), (valueExpression == nullLiteral) ? "null" : valueExpression.Type.GetTypeName()), ex); } return filterExpression; }
public static string ToString(FilterOperator value) { if (value == FilterOperator.Equal) { return("="); } else if (value == FilterOperator.IsA) { return("is-a"); } else if (value == FilterOperator.IsNotA) { return("is-not-a"); } else if (value == FilterOperator.Regex) { return("regex"); } else { throw new ArgumentException("Unrecognized FilterOperator value: " + value.ToString()); } }
private string GetOperator(FilterOperator foperator) { if (_opratorMapping.ContainsKey(foperator)) { return(_opratorMapping[foperator]); } else { throw new KeyNotFoundException(string.Format("FilterOperator key not found {0}", foperator.ToString())); } }
/// <summary> /// Produces the Linq expression that represents a particular FilterDescriptor /// </summary> /// <param name="type">Entity type</param> /// <param name="propertyPath">Left operand: Property on the entity type</param> /// <param name="filterOperator">One of the FilterOperator enum value</param> /// <param name="value">Right operand</param> /// <param name="isCaseSensitive">Boolean that specifies if the string operations are case sensitive or not</param> /// <returns>Resulting linq expression</returns> /// <exception cref="ArgumentException">When a filter descriptor references a property that could not be found.</exception> /// <exception cref="ArgumentException">When an exception occurs attempting to evaluate a filter descriptor.</exception> /// <exception cref="ArgumentException">When the supplied filter value has a type that cannot be compared to the property type.</exception> /// <exception cref="NotSupportedException">When attempting to use a property type/operator pair that is not supported.</exception> public static Expression BuildFilterExpression( Type type, string propertyPath, FilterOperator filterOperator, object value, bool isCaseSensitive) { Debug.Assert(type != null, "Unexpected null type"); Debug.Assert(propertyPath != null, "Unexpected null propertyPath"); Expression filterExpression = null; PropertyInfo pi; Expression propertyExpression; Expression valueExpression; try { pi = type.GetPropertyInfo(propertyPath); if (pi == null) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, CommonResources.PropertyNotFound, propertyPath, type.GetTypeName())); } // TODO: Remove this check. // It's a duplicate of one done in the DDS, but it's still required for the BuildFilterExpressions Test. else if (!IsSupportedOperator(pi.PropertyType, filterOperator)) { throw new NotSupportedException(string.Format( CultureInfo.InvariantCulture, DomainDataSourceResources.FilterNotSupported, propertyPath, type.GetTypeName(), pi.PropertyType.GetTypeName(), filterOperator)); } propertyExpression = GenerateProperty(type, propertyPath, Expression.Parameter(type, string.Empty)); valueExpression = GenerateConstant(value); Debug.Assert(propertyExpression != null, "Unexpected null propertyExpression in LinqHelper.BuildFilterExpression"); } catch (Exception ex) { if (ex.IsFatal()) { throw; } throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, DomainDataSourceResources.CannotEvaluateDescriptor, propertyPath), ex); } try { bool isEquality = filterOperator == FilterOperator.IsEqualTo || filterOperator == FilterOperator.IsNotEqualTo; if (isEquality && !propertyExpression.Type.IsValueType && !valueExpression.Type.IsValueType) { if (propertyExpression.Type != valueExpression.Type) { if (propertyExpression.Type.IsAssignableFrom(valueExpression.Type)) { valueExpression = Expression.Convert(valueExpression, propertyExpression.Type); } else if (valueExpression.Type.IsAssignableFrom(propertyExpression.Type)) { propertyExpression = Expression.Convert(propertyExpression, valueExpression.Type); } else { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, DomainDataSourceResources.IncompatibleOperands, filterOperator.ToString(), propertyExpression.Type.GetTypeName(), valueExpression.Type.GetTypeName())); } } } else if (propertyExpression.Type.IsEnumType()) { // Convert the value to compare to the underlying type of the enum, // preserving nullable and following the same rules the C# compiler does. // Examples: // p.Enum > Enum.A => p.Enum > 1 // p.Enum > null => p.Enum > Convert(null, Nullable<int>) // p.NullableEnum > Enum.A => p.Enum > Convert(Enum.A, Nullable<int>) // p.NullableEnum > null => p.Enum > Convert(Enum.A, Nullable<int>) Type underlyingType = Enum.GetUnderlyingType(TypeUtility.GetNonNullableType(propertyExpression.Type)); bool propertyIsNullable = propertyExpression.Type.IsNullableType(); if (propertyIsNullable) { underlyingType = typeof(Nullable <>).MakeGenericType(underlyingType); } if (valueExpression.Type != underlyingType) { if (value != null && !propertyIsNullable) { // convert to the underlying value and create a new constant value = Convert.ChangeType(value, underlyingType, CultureInfo.InvariantCulture); valueExpression = GenerateConstant(value); } else { // for nulls or comparisons against a nullable enum, we inject // a conversion valueExpression = Expression.Convert(valueExpression, underlyingType); } } // Now that we've converted the enum value, we inject the appropriate conversion // on the property expression if (propertyExpression.Type != valueExpression.Type) { Expression e; if ((e = PromoteExpression(propertyExpression, valueExpression.Type, true)) != null) { propertyExpression = e; } else { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, DomainDataSourceResources.IncompatibleOperands, filterOperator.ToString(), propertyExpression.Type.GetTypeName(), valueExpression.Type.GetTypeName())); } } } else if (pi.PropertyType.IsNullableType() && propertyExpression.Type != valueExpression.Type) { ConstantExpression ce = valueExpression as ConstantExpression; if (ce != null) { valueExpression = Expression.Constant(ce.Value, propertyExpression.Type); } } filterExpression = BuildFilterExpression(propertyExpression, filterOperator, valueExpression, isCaseSensitive); } catch (Exception ex) { if (ex.IsFatal()) { throw; } throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, DomainDataSourceResources.IncompatibleOperands, filterOperator.ToString(), propertyExpression.Type.GetTypeName(), (valueExpression == nullLiteral) ? "null" : valueExpression.Type.GetTypeName()), ex); } return(filterExpression); }
/// <summary> /// Converts the filter operator into a string as expected by the SendGrid Email Activities API. /// Can be overridden in subclasses if the operator needs special formatting. /// </summary> /// <returns>The string representation of the operator.</returns> public virtual string ConvertOperatorToString() { return(FilterOperator.GetAttributeOfType <EnumMemberAttribute>()?.Value ?? FilterOperator.ToString()); }
private static string GetFilter(string searchingName, FilterOperator searchingOperator, string searchingValue) { return(GetFilter(searchingName, searchingOperator.ToString().ToLower(), searchingValue)); }