-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathSpecificationBuilderExtensions.cs
More file actions
354 lines (296 loc) · 13.9 KB
/
SpecificationBuilderExtensions.cs
File metadata and controls
354 lines (296 loc) · 13.9 KB
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
343
344
345
346
347
348
349
350
351
352
353
354
using System.Linq.Expressions;
using System.Reflection;
using System.Text.Json;
using Ardalis.Specification;
using FSH.Framework.Core.Exceptions;
using FSH.Framework.Core.Paging;
namespace FSH.Framework.Core.Specifications;
public static class SpecificationBuilderExtensions
{
public static ISpecificationBuilder<T> SearchBy<T>(this ISpecificationBuilder<T> query, BaseFilter filter) where T : class =>
query
.SearchByKeyword(filter.Keyword)
.AdvancedSearch(filter.AdvancedSearch)
.AdvancedFilter(filter.AdvancedFilter);
public static ISpecificationBuilder<T> PaginateBy<T>(this ISpecificationBuilder<T> query, PaginationFilter filter)
{
if (filter.PageNumber <= 0)
{
filter.PageNumber = 1;
}
if (filter.PageSize <= 0)
{
filter.PageSize = 10;
}
if (filter.PageNumber > 1)
{
query = query.Skip((filter.PageNumber - 1) * filter.PageSize);
}
return query
.Take(filter.PageSize)
.OrderBy(filter.OrderBy);
}
public static ISpecificationBuilder<T> SearchByKeyword<T>(
this ISpecificationBuilder<T> specificationBuilder,
string? keyword) where T : class =>
specificationBuilder.AdvancedSearch(new Search { Keyword = keyword });
public static ISpecificationBuilder<T> AdvancedSearch<T>(
this ISpecificationBuilder<T> specificationBuilder,
Search? search) where T : class
{
if (!string.IsNullOrEmpty(search?.Keyword))
{
if (search.Fields?.Any() is true)
{
// search selected fields (can contain deeper nested fields)
foreach (string field in search.Fields)
{
var paramExpr = Expression.Parameter(typeof(T));
MemberExpression propertyExpr = GetPropertyExpression(field, paramExpr);
specificationBuilder.AddSearchPropertyByKeyword(propertyExpr, paramExpr, search.Keyword);
}
}
else
{
// search all fields (only first level)
foreach (var property in typeof(T).GetProperties()
.Where(prop => (Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType) is { } propertyType
&& !propertyType.IsEnum
&& Type.GetTypeCode(propertyType) != TypeCode.Object))
{
var paramExpr = Expression.Parameter(typeof(T));
var propertyExpr = Expression.Property(paramExpr, property);
specificationBuilder.AddSearchPropertyByKeyword(propertyExpr, paramExpr, search.Keyword);
}
}
}
return specificationBuilder;
}
private static void AddSearchPropertyByKeyword<T>(
this ISpecificationBuilder<T> specificationBuilder,
Expression propertyExpr,
ParameterExpression paramExpr,
string keyword,
string operatorSearch = FilterOperator.CONTAINS) where T : class
{
if (propertyExpr is not MemberExpression memberExpr || memberExpr.Member is not PropertyInfo property)
{
throw new ArgumentException("propertyExpr must be a property expression.", nameof(propertyExpr));
}
string searchTerm = operatorSearch switch
{
FilterOperator.STARTSWITH => $"{keyword.ToLower()}%",
FilterOperator.ENDSWITH => $"%{keyword.ToLower()}",
FilterOperator.CONTAINS => $"%{keyword.ToLower()}%",
_ => throw new ArgumentException("operatorSearch is not valid.", nameof(operatorSearch))
};
// Generate lambda [ x => x.Property ] for string properties
// or [ x => ((object)x.Property) == null ? null : x.Property.ToString() ] for other properties
Expression selectorExpr =
property.PropertyType == typeof(string)
? propertyExpr
: Expression.Condition(
Expression.Equal(Expression.Convert(propertyExpr, typeof(object)), Expression.Constant(null, typeof(object))),
Expression.Constant(null, typeof(string)),
Expression.Call(propertyExpr, "ToString", null, null));
var toLowerMethod = typeof(string).GetMethod("ToLower", Type.EmptyTypes);
Expression callToLowerMethod = Expression.Call(selectorExpr, toLowerMethod!);
var selector = Expression.Lambda<Func<T, string?>>(callToLowerMethod, paramExpr);
specificationBuilder.Search(selector, searchTerm, 1);
}
public static ISpecificationBuilder<T> AdvancedFilter<T>(
this ISpecificationBuilder<T> specificationBuilder,
Filter? filter)
{
if (filter is not null)
{
var parameter = Expression.Parameter(typeof(T));
Expression binaryExpressionFilter;
if (!string.IsNullOrEmpty(filter.Logic))
{
if (filter.Filters is null) throw new CustomException("The Filters attribute is required when declaring a logic");
binaryExpressionFilter = CreateFilterExpression(filter.Logic, filter.Filters, parameter);
}
else
{
var filterValid = GetValidFilter(filter);
binaryExpressionFilter = CreateFilterExpression(filterValid.Field!, filterValid.Operator!, filterValid.Value, parameter);
}
var expr = Expression.Lambda<Func<T, bool>>(binaryExpressionFilter, parameter);
specificationBuilder.Where(expr);
}
return specificationBuilder;
}
private static Expression CreateFilterExpression(
string logic,
IEnumerable<Filter> filters,
ParameterExpression parameter)
{
Expression filterExpression = default!;
foreach (var filter in filters)
{
Expression bExpressionFilter;
if (!string.IsNullOrEmpty(filter.Logic))
{
if (filter.Filters is null) throw new CustomException("The Filters attribute is required when declaring a logic");
bExpressionFilter = CreateFilterExpression(filter.Logic, filter.Filters, parameter);
}
else
{
var filterValid = GetValidFilter(filter);
bExpressionFilter = CreateFilterExpression(filterValid.Field!, filterValid.Operator!, filterValid.Value, parameter);
}
filterExpression = filterExpression is null ? bExpressionFilter : CombineFilter(logic, filterExpression, bExpressionFilter);
}
return filterExpression;
}
private static Expression CreateFilterExpression(
string field,
string filterOperator,
object? value,
ParameterExpression parameter)
{
var propertyExpression = GetPropertyExpression(field, parameter);
var valueExpression = GeValueExpression(field, value, propertyExpression.Type);
return CreateFilterExpression(propertyExpression, valueExpression, filterOperator);
}
private static Expression CreateFilterExpression(
Expression memberExpression,
Expression constantExpression,
string filterOperator)
{
if (memberExpression.Type == typeof(string))
{
constantExpression = Expression.Call(constantExpression, "ToLower", null);
memberExpression = Expression.Call(memberExpression, "ToLower", null);
}
return filterOperator switch
{
FilterOperator.EQ => Expression.Equal(memberExpression, constantExpression),
FilterOperator.NEQ => Expression.NotEqual(memberExpression, constantExpression),
FilterOperator.LT => Expression.LessThan(memberExpression, constantExpression),
FilterOperator.LTE => Expression.LessThanOrEqual(memberExpression, constantExpression),
FilterOperator.GT => Expression.GreaterThan(memberExpression, constantExpression),
FilterOperator.GTE => Expression.GreaterThanOrEqual(memberExpression, constantExpression),
FilterOperator.CONTAINS => Expression.Call(memberExpression, "Contains", null, constantExpression),
FilterOperator.STARTSWITH => Expression.Call(memberExpression, "StartsWith", null, constantExpression),
FilterOperator.ENDSWITH => Expression.Call(memberExpression, "EndsWith", null, constantExpression),
_ => throw new CustomException("Filter Operator is not valid."),
};
}
private static BinaryExpression CombineFilter(
string filterOperator,
Expression bExpressionBase,
Expression bExpression) => filterOperator switch
{
FilterLogic.AND => Expression.And(bExpressionBase, bExpression),
FilterLogic.OR => Expression.Or(bExpressionBase, bExpression),
FilterLogic.XOR => Expression.ExclusiveOr(bExpressionBase, bExpression),
_ => throw new ArgumentException("FilterLogic is not valid."),
};
private static MemberExpression GetPropertyExpression(
string propertyName,
ParameterExpression parameter)
{
Expression propertyExpression = parameter;
foreach (string member in propertyName.Split('.'))
{
propertyExpression = Expression.PropertyOrField(propertyExpression, member);
}
return (MemberExpression)propertyExpression;
}
private static string GetStringFromJsonElement(object value)
=> ((JsonElement)value).GetString()!;
private static ConstantExpression GeValueExpression(
string field,
object? value,
Type propertyType)
{
if (value == null) return Expression.Constant(null, propertyType);
if (propertyType.IsEnum)
{
string? stringEnum = GetStringFromJsonElement(value);
if (!Enum.TryParse(propertyType, stringEnum, true, out object? valueparsed)) throw new CustomException(string.Format("Value {0} is not valid for {1}", value, field));
return Expression.Constant(valueparsed, propertyType);
}
if (propertyType == typeof(Guid))
{
string? stringGuid = GetStringFromJsonElement(value);
if (!Guid.TryParse(stringGuid, out Guid valueparsed)) throw new CustomException(string.Format("Value {0} is not valid for {1}", value, field));
return Expression.Constant(valueparsed, propertyType);
}
if (propertyType == typeof(string))
{
string? text = GetStringFromJsonElement(value);
return Expression.Constant(text, propertyType);
}
if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
{
string? text = GetStringFromJsonElement(value);
return Expression.Constant(ChangeType(text, propertyType), propertyType);
}
return Expression.Constant(ChangeType(((JsonElement)value).GetRawText(), propertyType), propertyType);
}
public static dynamic? ChangeType(object value, Type conversion)
{
var t = conversion;
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return null;
}
t = Nullable.GetUnderlyingType(t);
}
return Convert.ChangeType(value, t!);
}
private static Filter GetValidFilter(Filter filter)
{
if (string.IsNullOrEmpty(filter.Field)) throw new CustomException("The field attribute is required when declaring a filter");
if (string.IsNullOrEmpty(filter.Operator)) throw new CustomException("The Operator attribute is required when declaring a filter");
return filter;
}
public static ISpecificationBuilder<T> OrderBy<T>(
this ISpecificationBuilder<T> specificationBuilder,
string[]? orderByFields)
{
IOrderedSpecificationBuilder<T> orderedBuilder = null!;
if (orderByFields is not null)
{
foreach (var field in ParseOrderBy(orderByFields))
{
var paramExpr = Expression.Parameter(typeof(T));
Expression propertyExpr = paramExpr;
foreach (string member in field.Key.Split('.'))
{
propertyExpr = Expression.PropertyOrField(propertyExpr, member);
}
var keySelector = Expression.Lambda<Func<T, object?>>(
Expression.Convert(propertyExpr, typeof(object)),
paramExpr);
orderedBuilder = field.Value switch
{
OrderTypeEnum.OrderBy => specificationBuilder.OrderBy(keySelector),
OrderTypeEnum.OrderByDescending => specificationBuilder.OrderByDescending(keySelector),
OrderTypeEnum.ThenBy => orderedBuilder.ThenBy(keySelector),
OrderTypeEnum.ThenByDescending => orderedBuilder.ThenByDescending(keySelector),
_ => throw new CustomException("OrderTypeEnum is not valid."),
};
}
}
return specificationBuilder;
}
private static Dictionary<string, OrderTypeEnum> ParseOrderBy(string[] orderByFields) =>
new(orderByFields.Select((orderByfield, index) =>
{
string[] fieldParts = orderByfield.Split(' ');
string field = fieldParts[0];
bool descending = fieldParts.Length > 1 && fieldParts[1].StartsWith("Desc", StringComparison.OrdinalIgnoreCase);
var orderBy = index == 0
? descending ? OrderTypeEnum.OrderByDescending
: OrderTypeEnum.OrderBy
: descending ? OrderTypeEnum.ThenByDescending
: OrderTypeEnum.ThenBy;
return new KeyValuePair<string, OrderTypeEnum>(field, orderBy);
}));
}