SieveProcessor.cs 33.6 KB
Newer Older
thienvo's avatar
thienvo committed
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
using System;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.Extensions.Options;
using Sieve.Attributes;
using Sieve.Exceptions;
using Sieve.Extensions;
using Sieve.Models;

namespace Sieve.Services
{
    public class SieveProcessor : SieveProcessor<SieveModel, FilterTerm, SortTerm>, ISieveProcessor
    {
        public SieveProcessor(IOptions<SieveOptions> options) : base(options)
        {
        }

        public SieveProcessor(IOptions<SieveOptions> options, ISieveCustomSortMethods customSortMethods) : base(options, customSortMethods)
        {
        }

        public SieveProcessor(IOptions<SieveOptions> options, ISieveCustomFilterMethods customFilterMethods) : base(options, customFilterMethods)
        {
        }

        public SieveProcessor(IOptions<SieveOptions> options, ISieveCustomSortMethods customSortMethods, ISieveCustomFilterMethods customFilterMethods) : base(options, customSortMethods, customFilterMethods)
        {
        }
    }

    public class SieveProcessor<TFilterTerm, TSortTerm> : SieveProcessor<SieveModel<TFilterTerm, TSortTerm>, TFilterTerm, TSortTerm>, ISieveProcessor<TFilterTerm, TSortTerm>
        where TFilterTerm : IFilterTerm, new()
        where TSortTerm : ISortTerm, new()
    {
        public SieveProcessor(IOptions<SieveOptions> options) : base(options)
        {
        }

        public SieveProcessor(IOptions<SieveOptions> options, ISieveCustomSortMethods customSortMethods) : base(options, customSortMethods)
        {
        }

        public SieveProcessor(IOptions<SieveOptions> options, ISieveCustomFilterMethods customFilterMethods) : base(options, customFilterMethods)
        {
        }

        public SieveProcessor(IOptions<SieveOptions> options, ISieveCustomSortMethods customSortMethods, ISieveCustomFilterMethods customFilterMethods) : base(options, customSortMethods, customFilterMethods)
        {
        }
    }

    public class SieveProcessor<TSieveModel, TFilterTerm, TSortTerm> : ISieveProcessor<TSieveModel, TFilterTerm, TSortTerm>
        where TSieveModel : class, ISieveModel<TFilterTerm, TSortTerm>
        where TFilterTerm : IFilterTerm, new()
        where TSortTerm : ISortTerm, new()
    {
        private readonly IOptions<SieveOptions> _options;
        private readonly ISieveCustomSortMethods _customSortMethods;
        private readonly ISieveCustomFilterMethods _customFilterMethods;
        private readonly SievePropertyMapper mapper = new SievePropertyMapper();

        public SieveProcessor(IOptions<SieveOptions> options,
            ISieveCustomSortMethods customSortMethods,
            ISieveCustomFilterMethods customFilterMethods)
        {
            mapper = MapProperties(mapper);
            _options = options;
            _customSortMethods = customSortMethods;
            _customFilterMethods = customFilterMethods;
        }

        public SieveProcessor(IOptions<SieveOptions> options,
            ISieveCustomSortMethods customSortMethods)
        {
            mapper = MapProperties(mapper);
            _options = options;
            _customSortMethods = customSortMethods;
        }

        public SieveProcessor(IOptions<SieveOptions> options,
            ISieveCustomFilterMethods customFilterMethods)
        {
            mapper = MapProperties(mapper);
            _options = options;
            _customFilterMethods = customFilterMethods;
        }

        public SieveProcessor(IOptions<SieveOptions> options)
        {
            mapper = MapProperties(mapper);
            _options = options;
        }

        /// <summary>
        /// Apply filtering, sorting, and pagination parameters found in `model` to `source`
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="model">An instance of ISieveModel</param>
        /// <param name="source">Data source</param>
        /// <param name="dataForCustomMethods">Additional data that will be passed down to custom methods</param>
        /// <param name="applyFiltering">Should the data be filtered? Defaults to true.</param>
        /// <param name="applySorting">Should the data be sorted? Defaults to true.</param>
        /// <param name="applyPagination">Should the data be paginated? Defaults to true.</param>
        /// <returns>Returns a transformed version of `source`</returns>
        public IQueryable<TEntity> Apply<TEntity>(
            TSieveModel model,
            IQueryable<TEntity> source,
            object[] dataForCustomMethods = null,
            bool applyFiltering = true,
            bool applySorting = true,
            bool applyPagination = true)
        {
            var result = source;

            if (model == null)
            {
                return result;
            }

            try
            {
                // Filter
                if (applyFiltering)
                {
                    result = ApplyFiltering(model, result, dataForCustomMethods);
                }

                // Sort
                if (applySorting)
                {
                    result = ApplySorting(model, result, dataForCustomMethods);
                }

                // Paginate
                if (applyPagination)
                {
                    result = ApplyPagination(model, result);
                }

                return result;
            }
            catch (Exception ex)
            {
                if (_options.Value.ThrowExceptions)
                {
                    if (ex is SieveException)
                    {
                        throw;
                    }

                    throw new SieveException(ex.Message, ex);
                }
                else
                {
                    return result;
                }
            }
        }
thienvo's avatar
thienvo committed
161

thienvo's avatar
thienvo committed
162 163 164
        public string GetExtendFilterString<TEntity>(
          TSieveModel model, 
          bool bCaseSensitive = false)
165
        {
thienvo's avatar
thienvo committed
166
            string fullQueryString = "";
thienvo's avatar
thienvo committed
167
            //string dynamicQuery = "";
168 169
            if (model?.GetFiltersParsed() == null)
            {
thienvo's avatar
thienvo committed
170
                return " id != null";
thienvo's avatar
thienvo committed
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
            }

            //Expression outerExpression = null;
            //var parameterExpression = Expression.Parameter(typeof(TEntity), "e");
            foreach (var filterTerm in model.GetFiltersParsed())
            {
               
                //Expression innerExpression = null;
                foreach (var filterTermName in filterTerm.Names)
                {
                    string searchPart = "";

                    string searchProperty = ""; ////////-----------------
                    var (fullName, property) = GetSieveProperty<TEntity>(false, true, filterTermName);
                    if (property != null)
                    {
                        var converter = TypeDescriptor.GetConverter(property.PropertyType);
                        //dynamic propertyValue = parameterExpression;
                        foreach (object attrib in property.GetCustomAttributes(true))
                        {
                            searchProperty = attrib.GetType().GetProperty("StringValue").GetValue(attrib, null).ToString();                           
                        }
                        //foreach (var part in fullName.Split('.'))
                        //{
                        //    propertyValue = Expression.PropertyOrField(propertyValue, part);
                        //}

                        if (filterTerm.Values == null) continue;

                        foreach (var filterTermValue in filterTerm.Values)
                        {
                            string dynamicQuery = ""; //////----------------
                            dynamic constantVal = converter.CanConvertFrom(typeof(string))
                                                      ? converter.ConvertFrom(filterTermValue)
                                                      : Convert.ChangeType(filterTermValue, property.PropertyType);

                            Expression filterValue = GetClosureOverConstant(constantVal, property.PropertyType);

                            if (!string.IsNullOrEmpty(searchProperty))
                            {
VTHIEN's avatar
VTHIEN committed
211 212
                                var data = RemoveSignAndLowerCase4VietnameseString(filterValue.ToString());
                                dynamicQuery = GetDynamicQueryString(filterTerm, searchProperty.ToString(), data);
thienvo's avatar
thienvo committed
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
                                if (string.IsNullOrEmpty(fullQueryString))
                                {
                                    searchPart = "(" + dynamicQuery + ")";
                                }
                                else
                                {
                                    searchPart += " Or " + "(" + dynamicQuery + ")";
                                }
                            }

                            #region advance
                            //if (filterTerm.OperatorIsCaseInsensitive)
                            //{
                            //    propertyValue = Expression.Call(propertyValue,
                            //        typeof(string).GetMethods()
                            //        .First(m => m.Name == "ToUpper" && m.GetParameters().Length == 0));

                            //    filterValue = Expression.Call(filterValue,
                            //        typeof(string).GetMethods()
                            //        .First(m => m.Name == "ToUpper" && m.GetParameters().Length == 0));
                            //}



                            //var expression = GetExpression(filterTerm, filterValue, propertyValue, bCaseSensitive);

                            //if (filterTerm.OperatorIsNegated)
                            //{
                            //    expression = Expression.Not(expression);
                            //}

                            //if (innerExpression == null)
                            //{
                            //    innerExpression = expression;
                            //}
                            //else
                            //{
                            //    innerExpression = Expression.Or(innerExpression, expression);
                            //}
                            #endregion

                        }
                    }

                    if (!string.IsNullOrEmpty(searchPart))
                    {
                        if (string.IsNullOrEmpty(fullQueryString))
                        {
                            fullQueryString = "(" + searchPart + ")";
                        }
                        else
                        {
                            fullQueryString += " And " + "(" + searchPart + ")";
                        }
                    }

                }
            }
            if (string.IsNullOrEmpty(fullQueryString))
            {
thienvo's avatar
thienvo committed
273
                fullQueryString = " id != null";
274
            }
VTHIEN's avatar
VTHIEN committed
275
            return  fullQueryString ;
thienvo's avatar
thienvo committed
276
        }
277

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
        protected object 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);
        }
thienvo's avatar
thienvo committed
293 294 295 296
        public Expression<Func<TEntity, bool>> GetFilterExpressionQuery<TEntity>(
           TSieveModel model,
           bool bCaseSensitive = false)
        {
297 298
            Expression outerExpression = null;
            var parameterExpression = Expression.Parameter(typeof(TEntity), "e");
thienvo's avatar
thienvo committed
299 300 301 302
            //string dynamicQuery = "";
            if (model?.GetFiltersParsed() == null)
            {
                var property = Expression.Property(parameterExpression, "id");
thienvo's avatar
thienvo committed
303 304
                ConstantExpression constant = Expression.Constant(new Guid("{00000000-0000-0000-0000-000000000000}"), typeof(Guid));
                var rst = Expression.NotEqual(property, constant);
305

thienvo's avatar
thienvo committed
306 307 308 309
                return Expression.Lambda<Func<TEntity, bool>>(rst, parameterExpression);
            }

          
310 311 312 313 314 315 316 317 318
            foreach (var filterTerm in model.GetFiltersParsed())
            {
                Expression innerExpression = null;
                foreach (var filterTermName in filterTerm.Names)
                {
                    var (fullName, property) = GetSieveProperty<TEntity>(false, true, filterTermName);
                    if (property != null)
                    {
                        var converter = TypeDescriptor.GetConverter(property.PropertyType);
thienvo's avatar
thienvo committed
319

320
                        dynamic propertyValue = parameterExpression;
thienvo's avatar
thienvo committed
321
                     
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
                        foreach (var part in fullName.Split('.'))
                        {
                            propertyValue = Expression.PropertyOrField(propertyValue, part);
                        }

                        if (filterTerm.Values == null) continue;

                        foreach (var filterTermValue in filterTerm.Values)
                        {

                            dynamic constantVal = converter.CanConvertFrom(typeof(string))
                                                      ? converter.ConvertFrom(filterTermValue)
                                                      : Convert.ChangeType(filterTermValue, property.PropertyType);

                            Expression filterValue = GetClosureOverConstant(constantVal, property.PropertyType);

thienvo's avatar
thienvo committed
338
                           
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
                            if (filterTerm.OperatorIsCaseInsensitive)
                            {
                                propertyValue = Expression.Call(propertyValue,
                                    typeof(string).GetMethods()
                                    .First(m => m.Name == "ToUpper" && m.GetParameters().Length == 0));

                                filterValue = Expression.Call(filterValue,
                                    typeof(string).GetMethods()
                                    .First(m => m.Name == "ToUpper" && m.GetParameters().Length == 0));
                            }

                            var expression = GetExpression(filterTerm, filterValue, propertyValue, bCaseSensitive);

                            if (filterTerm.OperatorIsNegated)
                            {
                                expression = Expression.Not(expression);
                            }

                            if (innerExpression == null)
                            {
                                innerExpression = expression;
                            }
                            else
                            {
                                innerExpression = Expression.Or(innerExpression, expression);
                            }
                        }
                    }
thienvo's avatar
thienvo committed
367 368

                }
369 370 371 372 373 374 375 376 377 378 379
                if (outerExpression == null)
                {
                    outerExpression = innerExpression;
                    continue;
                }
                if (innerExpression == null)
                {
                    continue;
                }
                outerExpression = Expression.And(outerExpression, innerExpression);
            }
thienvo's avatar
thienvo committed
380
            if (outerExpression == null)
thienvo's avatar
thienvo committed
381
            {
thienvo's avatar
thienvo committed
382
                var property = Expression.Property(parameterExpression, "id");
thienvo's avatar
thienvo committed
383 384
                ConstantExpression constant = Expression.Constant(new Guid("{00000000-0000-0000-0000-000000000000}"), typeof(Guid));
                var rst = Expression.NotEqual(property, constant);
thienvo's avatar
thienvo committed
385
                return Expression.Lambda<Func<TEntity, bool>>(rst, parameterExpression);
thienvo's avatar
thienvo committed
386
            }
387 388
            return Expression.Lambda<Func<TEntity, bool>>(outerExpression, parameterExpression);
        }
389 390

       
thienvo's avatar
thienvo committed
391 392 393
        private IQueryable<TEntity> ApplyFiltering<TEntity>(
            TSieveModel model,
            IQueryable<TEntity> result,
thienvo's avatar
thienvo committed
394 395
            object[] dataForCustomMethods = null,
            bool bCaseSensitive = false)
thienvo's avatar
thienvo committed
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
        {
            if (model?.GetFiltersParsed() == null)
            {
                return result;
            }

            Expression outerExpression = null;
            var parameterExpression = Expression.Parameter(typeof(TEntity), "e");
            foreach (var filterTerm in model.GetFiltersParsed())
            {
                Expression innerExpression = null;
                foreach (var filterTermName in filterTerm.Names)
                {
                    var (fullName, property) = GetSieveProperty<TEntity>(false, true, filterTermName);
                    if (property != null)
                    {
                        var converter = TypeDescriptor.GetConverter(property.PropertyType);

                        dynamic propertyValue = parameterExpression;
                        foreach (var part in fullName.Split('.'))
                        {
                            propertyValue = Expression.PropertyOrField(propertyValue, part);
                        }

                        if (filterTerm.Values == null) continue;

VTHIEN's avatar
VTHIEN committed
422
                        foreach (var filterTermValue1 in filterTerm.Values)
thienvo's avatar
thienvo committed
423
                        {
VTHIEN's avatar
VTHIEN committed
424
                            var filterTermValue = (new RemoveVietNamSign()).RemoveSignVietnameseString(filterTermValue1);
425
                            //string filterTermValue = this.RemoveSign4VietnameseString(filterTermValue1); //Added by thien to emove vietnam
thienvo's avatar
thienvo committed
426 427 428 429 430 431 432 433

                            dynamic constantVal = converter.CanConvertFrom(typeof(string))
                                                      ? converter.ConvertFrom(filterTermValue)
                                                      : Convert.ChangeType(filterTermValue, property.PropertyType);

                            Expression filterValue = GetClosureOverConstant(constantVal, property.PropertyType);


434
                            if (true)//filterTerm.OperatorIsCaseInsensitive Make search insensitive case //comment by thien
thienvo's avatar
thienvo committed
435
                            {
436
                                var upperData = Expression.Call(propertyValue,
thienvo's avatar
thienvo committed
437 438
                                    typeof(string).GetMethods()
                                    .First(m => m.Name == "ToUpper" && m.GetParameters().Length == 0));
439 440 441 442 443 444 445 446 447
                                propertyValue = Expression.Call(
                                Expression.New(typeof(RemoveVietNamSign)),
                                typeof(RemoveVietNamSign).GetMethod("RemoveSignVietnameseString", new Type[] { typeof(string)}),
                                upperData
                                );

                                /*propertyValue = Expression.Call(propertyValue,
                                    typeof(string).GetMethods()
                                    .First(m => m.Name == "ToUpper" && m.GetParameters().Length == 0));*/
thienvo's avatar
thienvo committed
448

449
                                
thienvo's avatar
thienvo committed
450 451 452
                                filterValue = Expression.Call(filterValue,
                                    typeof(string).GetMethods()
                                    .First(m => m.Name == "ToUpper" && m.GetParameters().Length == 0));
VTHIEN's avatar
VTHIEN committed
453
                            }
thienvo's avatar
thienvo committed
454

thienvo's avatar
thienvo committed
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
                            var expression = GetExpression(filterTerm, filterValue, propertyValue, bCaseSensitive);

                            if (filterTerm.OperatorIsNegated)
                            {
                                expression = Expression.Not(expression);
                            }

                            if (innerExpression == null)
                            {
                                innerExpression = expression;
                            }
                            else
                            {
                                innerExpression = Expression.Or(innerExpression, expression);
                            }
                        }
                    }
                    else
                    {
                        result = ApplyCustomMethod(result, filterTermName, _customFilterMethods,
                            new object[] {
                                            result,
                                            filterTerm.Operator,
                                            filterTerm.Values
                            }, dataForCustomMethods);

                    }
                }
                if (outerExpression == null)
                {
                    outerExpression = innerExpression;
                    continue;
                }
                if (innerExpression == null)
                {
                    continue;
                }
                outerExpression = Expression.And(outerExpression, innerExpression);
            }
thienvo's avatar
thienvo committed
494
            
thienvo's avatar
thienvo committed
495
            var data = outerExpression == null
thienvo's avatar
thienvo committed
496 497
                ? result
                : result.Where(Expression.Lambda<Func<TEntity, bool>>(outerExpression, parameterExpression));
thienvo's avatar
thienvo committed
498
            return data;
thienvo's avatar
thienvo committed
499
        }
thienvo's avatar
thienvo committed
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
        private static string GetDynamicQueryString(TFilterTerm filterTerm, string property, string value)
        {
            string sResult = property;
            switch (filterTerm.OperatorParsed)
            {
                case FilterOperator.Equals:
                    return sResult + "=" + value;
                case FilterOperator.NotEquals:
                    return sResult + "!=" + value;
                case FilterOperator.GreaterThan:
                    return sResult + ">" + value;
                case FilterOperator.LessThan:
                    return sResult + "<" + value;
                case FilterOperator.GreaterThanOrEqualTo:
                    return sResult + ">=" + value;
                case FilterOperator.LessThanOrEqualTo:
                    return sResult + "<=" + value;
                case FilterOperator.Contains:
VTHIEN's avatar
VTHIEN committed
518
                    return sResult + ".Contains(" + value + ")";
thienvo's avatar
thienvo committed
519
                case FilterOperator.StartsWith:
VTHIEN's avatar
VTHIEN committed
520
                    return sResult + ".Contains(" + value + ")";
thienvo's avatar
thienvo committed
521 522 523 524
                default:
                    return sResult + "=" + value;
            }
        }
VTHIEN's avatar
VTHIEN committed
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570

        
            private static string[] VietnameseSigns = new string[]
            {

            "aAeEoOuUiIdDyY",

            "áàạảãâấầậẩẫăắằặẳẵ",

            "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ",

            "éèẹẻẽêếềệểễ",

            "ÉÈẸẺẼÊẾỀỆỂỄ",

            "óòọỏõôốồộổỗơớờợởỡ",

            "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ",

            "úùụủũưứừựửữ",

            "ÚÙỤỦŨƯỨỪỰỬỮ",

            "íìịỉĩ",

            "ÍÌỊỈĨ",

            "đ",

            "Đ",

            "ýỳỵỷỹ",

            "ÝỲỴỶỸ"
            };
            public static string RemoveSignAndLowerCase4VietnameseString(string str)
            {
                str = str.ToLower();
                for (int i = 1; i < VietnameseSigns.Length; i++)
                {
                    for (int j = 0; j < VietnameseSigns[i].Length; j++)
                        str = str.Replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);
                }
                return str;
            }
            private static Expression GetExpression(TFilterTerm filterTerm, dynamic filterValue, dynamic propertyValue, bool bCaseSensitive)
thienvo's avatar
thienvo committed
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
        {
            switch (filterTerm.OperatorParsed)
            {
                case FilterOperator.Equals:
                    return Expression.Equal(propertyValue, filterValue);
                case FilterOperator.NotEquals:
                    return Expression.NotEqual(propertyValue, filterValue);
                case FilterOperator.GreaterThan:
                    return Expression.GreaterThan(propertyValue, filterValue);
                case FilterOperator.LessThan:
                    return Expression.LessThan(propertyValue, filterValue);
                case FilterOperator.GreaterThanOrEqualTo:
                    return Expression.GreaterThanOrEqual(propertyValue, filterValue);
                case FilterOperator.LessThanOrEqualTo:
                    return Expression.LessThanOrEqual(propertyValue, filterValue);
                case FilterOperator.Contains:
thienvo's avatar
thienvo committed
587 588
                    //fixed bug has null in data
                    return Expression.AndAlso(Expression.NotEqual(propertyValue, Expression.Constant(null, typeof(object))), Expression.Call(propertyValue,
thienvo's avatar
thienvo committed
589 590
                        typeof(string).GetMethods()
                        .First(m => m.Name == "Contains" && m.GetParameters().Length == 1),
thienvo's avatar
thienvo committed
591
                        filterValue));
thienvo's avatar
thienvo committed
592
                case FilterOperator.StartsWith:
thienvo's avatar
thienvo committed
593
                    return Expression.AndAlso(Expression.NotEqual(propertyValue, Expression.Constant(null, typeof(object))), Expression.Call(propertyValue,
thienvo's avatar
thienvo committed
594 595
                        typeof(string).GetMethods()
                        .First(m => m.Name == "StartsWith" && m.GetParameters().Length == 1),
thienvo's avatar
thienvo committed
596
                        filterValue));
thienvo's avatar
thienvo committed
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
                default:
                    return Expression.Equal(propertyValue, filterValue);
            }
        }

        // Workaround to ensure that the filter value gets passed as a parameter in generated SQL from EF Core
        // See https://github.com/aspnet/EntityFrameworkCore/issues/3361
        // Expression.Constant passed the target type to allow Nullable comparison
        // See http://bradwilson.typepad.com/blog/2008/07/creating-nullab.html
        private Expression GetClosureOverConstant<T>(T constant, Type targetType)
        {
            return Expression.Constant(constant, targetType);
        }

        private IQueryable<TEntity> ApplySorting<TEntity>(
            TSieveModel model,
            IQueryable<TEntity> result,
            object[] dataForCustomMethods = null)
        {
            if (model?.GetSortsParsed() == null)
            {
                return result;
            }

            var useThenBy = false;
            foreach (var sortTerm in model.GetSortsParsed())
            {
                var (fullName, property) = GetSieveProperty<TEntity>(true, false, sortTerm.Name);

                if (property != null)
                {
                    result = result.OrderByDynamic(fullName, property, sortTerm.Descending, useThenBy);
                }
                else
                {
                    result = ApplyCustomMethod(result, sortTerm.Name, _customSortMethods,
                        new object[]
                        {
thienvo's avatar
thienvo committed
635 636 637
                            result,
                            useThenBy,
                            sortTerm.Descending
thienvo's avatar
thienvo committed
638 639 640 641 642 643 644
                        }, dataForCustomMethods);
                }
                useThenBy = true;
            }

            return result;
        }
thienvo's avatar
thienvo committed
645
        public int ResultCountBeForeApplyPagination = 0;
thienvo's avatar
thienvo committed
646
        public void GetSkipAndTake( TSieveModel model, ref int skip, ref int take)
thienvo's avatar
thienvo committed
647 648 649 650 651 652 653
        {
            var page = model?.Page ?? 1;
            var pageSize = model?.PageSize ?? _options.Value.DefaultPageSize;
            var maxPageSize = _options.Value.MaxPageSize > 0 ? _options.Value.MaxPageSize : pageSize;
            skip = (page - 1) * pageSize;
            take = Math.Min(pageSize, maxPageSize);
        }
thienvo's avatar
thienvo committed
654
        public bool applyPageSize = true;
thienvo's avatar
thienvo committed
655 656 657
        private IQueryable<TEntity> ApplyPagination<TEntity>(
            TSieveModel model,
            IQueryable<TEntity> result)
thienvo's avatar
thienvo committed
658
        {            
thienvo's avatar
thienvo committed
659
            var page = model?.Page ?? 1;
660
            model.Page = page;
thienvo's avatar
thienvo committed
661
            var pageSize = model?.PageSize ?? _options.Value.DefaultPageSize;
662
            model.PageSize = pageSize;
thienvo's avatar
thienvo committed
663
            var maxPageSize = _options.Value.MaxPageSize > 0 ? _options.Value.MaxPageSize : pageSize;
664 665
            if (ResultCountBeForeApplyPagination==0)
            {
thienvo's avatar
thienvo committed
666 667 668 669 670 671 672 673 674
                try
                {
                    ResultCountBeForeApplyPagination = result != null ? result.Count() : 0;
                }
                catch (Exception)
                {
                    ResultCountBeForeApplyPagination = 0;
                }
               
675
            }
thienvo's avatar
thienvo committed
676
            
thienvo's avatar
thienvo committed
677 678
            if (pageSize > 0)
            {
thienvo's avatar
thienvo committed
679 680 681 682 683
                if (applyPageSize)
                {
                    result = result.Skip((page - 1) * pageSize);
                    result = result.Take(Math.Min(pageSize, maxPageSize));
                }                
thienvo's avatar
thienvo committed
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
            }

            return result;
        }

        protected virtual SievePropertyMapper MapProperties(SievePropertyMapper mapper)
        {
            return mapper;
        }

        private (string, PropertyInfo) GetSieveProperty<TEntity>(
            bool canSortRequired,
            bool canFilterRequired,
            string name)
        {
            var property = mapper.FindProperty<TEntity>(canSortRequired, canFilterRequired, name, _options.Value.CaseSensitive);
            if (property.Item1 == null)
            {
                var prop = FindPropertyBySieveAttribute<TEntity>(canSortRequired, canFilterRequired, name, _options.Value.CaseSensitive);
                return (prop?.Name, prop);
            }
            return property;

        }

        private PropertyInfo FindPropertyBySieveAttribute<TEntity>(
            bool canSortRequired,
            bool canFilterRequired,
            string name,
            bool isCaseSensitive)
        {
            return Array.Find(typeof(TEntity).GetProperties(), p =>
                {
                    if (p.GetCustomAttribute(typeof(SieveAttribute)) is SieveAttribute)
                    {
                        return p.GetCustomAttribute(typeof(SieveAttribute)) is SieveAttribute sieveAttribute
                        && (canSortRequired ? sieveAttribute.CanSort : true)
                        && (canFilterRequired ? sieveAttribute.CanFilter : true)
                        && ((sieveAttribute.Name ?? p.Name).Equals(name, isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase));
                    }
                    else
                    {
                        return (p.Name).Equals(name, isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
                    }
                   

                    /*Comment by thien vo to apply sort/filter by all property
                    return p.GetCustomAttribute(typeof(SieveAttribute)) is SieveAttribute sieveAttribute
                    && (canSortRequired ? sieveAttribute.CanSort : true)
                    && (canFilterRequired ? sieveAttribute.CanFilter : true)
                    && ((sieveAttribute.Name ?? p.Name).Equals(name, isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase));
                      */
                });
        }

        private IQueryable<TEntity> ApplyCustomMethod<TEntity>(IQueryable<TEntity> result, string name, object parent, object[] parameters, object[] optionalParameters = null)
        {
            var customMethod = parent?.GetType()
                .GetMethodExt(name,
                _options.Value.CaseSensitive ? BindingFlags.Default : BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance,
                typeof(IQueryable<TEntity>));


            if (customMethod == null)
            {
                // Find generic methods `public IQueryable<T> Filter<T>(IQueryable<T> source, ...)`
                var genericCustomMethod = parent?.GetType()
                .GetMethodExt(name,
                _options.Value.CaseSensitive ? BindingFlags.Default : BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance,
                typeof(IQueryable<>));

                if (genericCustomMethod != null &&
                    genericCustomMethod.ReturnType.IsGenericType &&
                    genericCustomMethod.ReturnType.GetGenericTypeDefinition() == typeof(IQueryable<>))
                {
                    var genericBaseType = genericCustomMethod.ReturnType.GenericTypeArguments[0];
                    var constraints = genericBaseType.GetGenericParameterConstraints();
                    if (constraints == null || constraints.Length == 0 || constraints.All((t) => t.IsAssignableFrom(typeof(TEntity))))
                    {
                        customMethod = genericCustomMethod.MakeGenericMethod(typeof(TEntity));
                    }
                }
            }

            if (customMethod != null)
            {
                try
                {
                    result = customMethod.Invoke(parent, parameters)
                        as IQueryable<TEntity>;
                }
                catch (TargetParameterCountException)
                {
                    if (optionalParameters != null)
                    {
                        result = customMethod.Invoke(parent, parameters.Concat(optionalParameters).ToArray())
                            as IQueryable<TEntity>;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            else
            {
                var incompatibleCustomMethod = parent?.GetType()
                    .GetMethod(name,
                    _options.Value.CaseSensitive ? BindingFlags.Default : BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

                if (incompatibleCustomMethod != null)
                {
                    var expected = typeof(IQueryable<TEntity>);
                    var actual = incompatibleCustomMethod.ReturnType;
                    throw new SieveIncompatibleMethodException(name, expected, actual,
                        $"{name} failed. Expected a custom method for type {expected} but only found for type {actual}");
                }
                else
                {
                    throw new SieveMethodNotFoundException(name, $"{name} not found.");
                }
            }

            return result;
        }
    }
}