-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathFilter.cs
342 lines (300 loc) · 13.6 KB
/
Filter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization;
namespace Kendo.DynamicLinqCore
{
/// <summary>
/// Represents a filter expression of Kendo DataSource.
/// </summary>
[DataContract]
public class Filter
{
/// <summary>
/// Gets or sets the name of the sorted field (property). Set to null if the Filters property is set.
/// </summary>
[DataMember(Name = "field")]
public string Field { get; set; }
/// <summary>
/// Gets or sets the filtering operator. Set to null if the Filters property is set.
/// </summary>
[DataMember(Name = "operator")]
public string Operator { get; set; }
/// <summary>
/// Gets or sets the filtering value. Set to null if the Filters property is set.
/// </summary>
[DataMember(Name = "value")]
public object Value { get; set; }
/// <summary>
/// Gets or sets the filtering logic. Can be set to "or" or "and". Set to null unless Filters is set.
/// </summary>
[DataMember(Name = "logic")]
public string Logic { get; set; }
/// <summary>
/// Gets or sets the filtering logic. Can be set to "or" or "and". Set to null unless Filters is set.
/// </summary>
[DataMember(Name = "ignoreCase")]
public bool IgnoreCase { get; set; }
/// <summary>
/// Gets or sets the child filter expressions. Set to null if there are no child expressions.
/// </summary>
[DataMember(Name = "filters")]
public IEnumerable<Filter> Filters { get; set; }
/// <summary>
/// Mapping of Kendo DataSource filtering operators to Dynamic Linq
/// </summary>
private static readonly IDictionary<string, string> Operators = new Dictionary<string, string>
{
{"eq", "="},
{"neq", "!="},
{"lt", "<"},
{"lte", "<="},
{"gt", ">"},
{"gte", ">="},
{"startswith", "StartsWith"},
{"endswith", "EndsWith"},
{"contains", "Contains"},
{"doesnotcontain", "Contains"},
{"isnull", "="},
{"isnotnull", "!="},
{"isempty", "="},
{"isnotempty", "!="},
{"isnullorempty", ""},
{"isnotnullorempty", "!"}
};
/// <summary>
/// These operators only for string type.
/// </summary>
private static readonly string[] StringOperators = new []
{
"startswith",
"endswith",
"contains",
"doesnotcontain",
"isempty",
"isnotempty",
"isnullorempty",
"isnotnullorempty"
};
/// <summary>
/// Get a flattened list of all child filter expressions.
/// </summary>
public IList<Filter> All()
{
var filters = new List<Filter>();
Collect(filters);
return filters;
}
private void Collect(IList<Filter> filters)
{
if (Filters?.Any() == true)
{
foreach (var filter in Filters)
{
filter.Collect(filters);
}
}
else
{
filters.Add(this);
}
}
/// <summary>
/// Converts the filter expression to a predicate suitable for Dynamic Linq e.g. "Field1 = @1 and Field2.Contains(@2)"
/// </summary>
/// <param name="filters">A list of flattened filters.</param>
public string ToExpression(Type type, IList<Filter> filters)
{
if (Filters?.Any() == true)
{
return "(" + String.Join(" " + Logic + " ", Filters.Select(filter => filter.ToExpression(type,filters)).ToArray()) + ")";
}
var currentPropertyType = GetLastPropertyType(type, Field);
if(currentPropertyType != typeof(String) && StringOperators.Contains(Operator))
{
throw new NotSupportedException(string.Format("Operator {0} not support non-string type", Operator));
}
int index = filters.IndexOf(this);
var comparison = Operators[Operator];
//switch(Operator)
//{
// case "doesnotcontain":
// return String.Format("{0} != null && !{0}.{1}(@{2})", Field, comparison, index);
// case "isnull":
// case "isnotnull":
// return String.Format("{0} {1} null", Field, comparison);
// case "isempty":
// case "isnotempty":
// return String.Format("{0} {1} String.Empty", Field, comparison);
// case "isnullorempty":
// case "isnotnullorempty":
// return String.Format("{0}String.IsNullOrEmpty({1})", comparison, Field);
//}
if (Operator == "doesnotcontain")
{
return String.Format(!IgnoreCase ? "{0} != null && !{0}.{1}(@{2})" : "{0} != null && !{0}.ToLower().{1}(@{2}.ToLower())", Field, comparison, index);
}
if (Operator == "isnull" || Operator == "isnotnull")
{
return String.Format("{0} {1} null", Field, comparison);
}
if (Operator == "isempty" || Operator == "isnotempty")
{
return String.Format("{0} {1} String.Empty", Field, comparison);
}
if (Operator == "isnullorempty" || Operator == "isnotnullorempty")
{
return String.Format("{0}String.IsNullOrEmpty({1})", comparison, Field);
}
if (comparison == "StartsWith" || comparison == "EndsWith" || comparison == "Contains")
{
return String.Format(!IgnoreCase ? "{0} != null && {0}.{1}(@{2})" : "{0} != null && {0}.ToLower().{1}(@{2}.ToLower())", Field, comparison, index);
}
return String.Format("{0} {1} @{2}", Field, comparison, index);
}
/// <summary>
/// Converts the filter to a lambda expression suitable for IQueryable e.g. "(p.Field1.Name.Contains("AnyString")) AndAlso (p.Field2 > 100)"
/// </summary>
/// <param name="parameter">Parameter expression</param>
/// <param name="filters">A list of flattened filters.</param>
public Expression ToLambdaExpression<T>(ParameterExpression parameter, IList<Filter> filters)
{
if (Filters?.Any() == true)
{
Expression compositeExpression = null;
if(Logic == "and")
{
foreach (var exp in Filters.Select(filter => filter.ToLambdaExpression<T>(parameter, filters)).ToArray())
{
if(compositeExpression == null) compositeExpression = exp;
else compositeExpression = Expression.AndAlso(compositeExpression, exp);
}
}
if(Logic == "or")
{
foreach (var exp in Filters.Select(filter => filter.ToLambdaExpression<T>(parameter, filters)).ToArray())
{
if(compositeExpression == null) compositeExpression = exp;
else compositeExpression = Expression.OrElse(compositeExpression,exp);
}
}
return compositeExpression;
}
var currentPropertyType = GetLastPropertyType(typeof(T), Field);
if(currentPropertyType != typeof(String) && StringOperators.Contains(Operator))
{
throw new NotSupportedException(string.Format("Operator {0} not support non-string type", Operator));
}
var propertyChains = Field.Split('.');
Expression left = null;
foreach (var f in propertyChains)
{
if(left == null) Expression.PropertyOrField(parameter, f);
else Expression.PropertyOrField(left, f);
}
Expression right = Expression.Constant(Value, currentPropertyType);
Expression resultExpression;
switch(Operator)
{
case "contains":
case "doesnotcontain":
case "startswith":
case "endswith":
case "isnull":
case "isnotnull":
var nullCheckExpression = Expression.Equal(left, Expression.Constant(null, currentPropertyType));
if (Operator == "contains" || Operator == "doesnotcontain")
{
var containsMethod = typeof(String).GetMethod("Contains", new[] { typeof(String) });
var containsExpression = Expression.Call(left, containsMethod, right);
if (Operator == "contains")
resultExpression = Expression.AndAlso(Expression.Not(nullCheckExpression), containsExpression);
else
resultExpression = Expression.AndAlso(Expression.Not(nullCheckExpression), Expression.Not(containsExpression));
}
else if (Operator == "startswith")
{
var startswithMethod = typeof(String).GetMethod("StartsWith", new[] { typeof(String) });
var startswithExpression = Expression.Call(left, startswithMethod, right);
resultExpression = Expression.AndAlso(Expression.Not(nullCheckExpression), startswithExpression);
}
else if (Operator == "endswith")
{
var endswithMethod = typeof(String).GetMethod("EndsWith", new[] { typeof(String) });
var endswithExpression = Expression.Call(left, endswithMethod, right);
resultExpression = Expression.AndAlso(Expression.Not(nullCheckExpression), endswithExpression);
}
else if (Operator == "isnull")
{
resultExpression = nullCheckExpression;
}
else // Operator == "isnotnull"
{
resultExpression = Expression.Not(nullCheckExpression);
}
break;
case "isempty":
case "isnotempty":
var emptyCheckExpression = Expression.Equal(left, Expression.Constant(String.Empty, currentPropertyType));
if(Operator == "isempty")
resultExpression = emptyCheckExpression;
else
resultExpression = Expression.Not(emptyCheckExpression);
break;
case "isnullorempty":
case "isnotnullorempty":
var nullOrEmptyMethod = typeof(String).GetMethod("IsNullOrEmpty", new[] { typeof(String) });
var nullOrEmptyExpression = Expression.Call(left, nullOrEmptyMethod, right);
if(Operator == "isnullorempty")
resultExpression = nullOrEmptyExpression;
else
resultExpression = Expression.Not(nullOrEmptyExpression);
break;
case "eq":
case "neq":
var equalCheckExpression = Expression.Equal(left, right);
if(Operator == "eq")
resultExpression = equalCheckExpression;
else
resultExpression = Expression.Not(equalCheckExpression);
break;
case "lt":
resultExpression = Expression.LessThan(left, right);
break;
case "lte":
resultExpression = Expression.LessThanOrEqual(left, right);
break;
case "gt":
resultExpression = Expression.GreaterThan(left, right);
break;
case "gte":
resultExpression = Expression.GreaterThanOrEqual(left, right);
break;
default:
throw new NotSupportedException(string.Format("Not support Operator {0}!", Operator));
}
return resultExpression;
}
internal static Type GetLastPropertyType(Type type, string path)
{
Type currentType = type;
/* Searches for the public property with the specified name */
/* Used in versions above 3.1.0 */
foreach (string propertyName in path.Split('.'))
{
PropertyInfo property = currentType.GetProperty(propertyName);
currentType = property.PropertyType;
}
/* Retrieves all properties defined on the specified type, including inherited, non-public, instance, and static properties */
/* Used in versions under 2.2.2 */
//foreach (string propertyName in path.Split('.'))
//{
// var typeProperties = currentType.GetRuntimeProperties();
// currentType = typeProperties.FirstOrDefault(f => f.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase))?.PropertyType;
//}
return currentType;
}
}
}