public async Task <IActionResult> GetFilteredAddresses(AddressesCriteria addressesCriteria)
        {
            if (addressesCriteria == null)
            {
                addressesCriteria = new AddressesCriteria();
            }

            if (!addressesCriteria.StartAt.HasValue)
            {
                addressesCriteria.StartAt = 0;
            }

            if (!addressesCriteria.Count.HasValue)
            {
                addressesCriteria.Count = MaxPageSize;
            }

            var criteria = _mapper.Map <AddressFilterCriteria>(addressesCriteria);

            var addressResult = await _addressQuery.GetAddressLitesFilteredAsync(criteria,
                                                                                 addressesCriteria.StartAt.Value, addressesCriteria.Count.Value, true, MaxAddressesReults);

            var response = new FilterResponse <FilteredAddress, AddressesCriteria>
            {
                Criteria          = addressesCriteria,
                FilterResultCount = addressResult.ResultCount,
                Data = addressResult.Results.Select(x => _mapper.Map <FilteredAddress>(x)).ToList()
            };

            return(Ok(response));
        }
        public static FilterResponse <List <T> > CreatePagedReponse <T>(List <T> pagedData, int totalRecords)
        {
            var respose = new FilterResponse <List <T> >(pagedData);

            respose.TotalRecords = totalRecords;
            return(respose);
        }
Exemple #3
0
        public virtual CommonResponse GetSingleWhere(params Expression <Func <Entity, bool> >[] wheres)
        {
            CommonResponse response       = new CommonResponse();
            FilterResponse filterResponse = new FilterResponse();

            Entity entity;

            try
            {
                //repository.ByUserId = LoggedUser.UserID;

                entity = repository.GetSingle(null, wheres);
                if (entity != null)
                {
                    OnGetSingle(entity);
                    AdapterOut(entity);
                }
                return(response.Success(entity));
            }
            catch (Exception e)
            {
                var originalException = GetOriginalException(e);
                return(response.Error("Error " + originalException.Message));
            }
        }
Exemple #4
0
        private FilterResponse <TEntity> GetAllByFiltersChangeLimit(FilterRequest request)
        {
            int lastElementPos = request.Limit * request.CurrentPage.Value;
            int loops          = (int)Math.Floor((decimal)(lastElementPos / request.NewLimit.Value));

            loops = loops == 0 ? 1 : loops;

            FilterResponse <TEntity> resultList       = new FilterResponse <TEntity>();
            List <string>            paginationTokens = new List <string> {
                "{}"
            };

            for (int i = 0; i < loops; i++)
            {
                resultList = GetAllByFilters(request);
                if (!resultList.PaginationToken.Equals("{}"))
                {
                    paginationTokens.Add(resultList.PaginationToken);
                }
                else if (resultList.PaginationToken.Equals("{}"))
                {
                    break;
                }
            }

            return(new FilterResponse <TEntity>
            {
                Elements = resultList.Elements,
                Total = resultList.Total,
                PaginationToken = resultList.PaginationToken,
                PaginationTokens = paginationTokens
            });
        }
 public void Setup()
 {
     request  = new FilterRequest();
     response = new FilterResponse();
     filter   = new Filter();
     testData = new LinkedList <string[]>();
     testData.AddLast(new string[] { "d[\\s\\.-]*[u* ][\\s\\.-]*[c* ][\\s\\.-]*k", "yuck", "yuck", "yuck", "yuck" });
     testData.AddLast(new string[] { "s[\\s\\.-]*[n* ][\\s\\.-]*[i* ][\\s\\.-]*[t* ][\\s\\.-]*[c* ][\\s\\.-]*h", "lich", "lich", "lich", "lich" });
 }
 public string SaveString(FilterResponse inputString)
 {
     if (inputString == null)
     {
         throw new System.ArgumentNullException(nameof(inputString));
     }
     // Simulate saving a cleaned string and returning the ID since this is a simiple fake repository.
     // return inputString.inputString;
     return("str");
 }
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if ((await OnActionExecutionPermission(context)).Status)
            {
                await next();

                return;
            }
            FilterResponse.SetActionResult(context, ResponseContent);
        }
        public void ProcessRequestNoMatchFound()
        {
            //arrange
            request.stringToModify = "This is a safe string.";

            //act
            response = filter.ProcessRequest(request, testData);

            //assert
            Assert.AreEqual("this is a safe string.", response.modifiedString);
        }
        public void ProcessRequestMultipleMatchFound()
        {
            //arrange
            request.stringToModify = "What, the duck? You snitch.";

            //act
            response = filter.ProcessRequest(request, testData);

            //assert
            Assert.AreEqual("what, the yuck? you lich.", response.modifiedString);
        }
Exemple #10
0
        public FilterResponse ProcessRequest(FilterRequest request)
        {
            string newString = StringParser.generateNewString(request.stringToModify, "FILTER");

            FilterResponse response = new FilterResponse
            {
                originalString = request.stringToModify,
                modifiedString = newString
            };

            return(response);
        }
Exemple #11
0
        public FilterResponse ProcessRequest(FilterRequest request, LinkedList <string[]> filterList)
        {
            string newString = StringParser.generateNewString(request.stringToModify, filterList);

            FilterResponse response = new FilterResponse
            {
                originalString = request.stringToModify,
                modifiedString = newString
            };

            return(response);
        }
        public void ProcessRequestMatchFound()
        {
            //arrange
            request.stringToModify = "That's a duck.";

            //act
            response = filter.ProcessRequest(request, testData);

            //assert
            Console.WriteLine(response.modifiedString);
            Assert.AreEqual("that's a yuck.", response.modifiedString);
        }
        ///start:slot:logic<<<

        public CommonResponse GetInventory()
        {
            var            response       = new CommonResponse();
            FilterResponse filterResponse = new FilterResponse();

            var ctx = context as MROContext;

            var inventory = ctx.InventoryInputs.GroupBy(e => new
            {
                e.CatMaterial
                //, e.CatUnitOfMeasure
            }).Select(e => new
            {
                e.Key,
                e.Key.CatMaterial.Value,
                e.Key.CatMaterial.MaterialDescription,
                e.Key.CatMaterial.Min,
                BalanceSum = e.Sum(b => b.Balance),
                id         = e.Key.CatMaterial.CatMaterialKey
            });
            var filter = HttpContext.Current.Request["filterGeneral"];

            if (!string.IsNullOrWhiteSpace(filter) && filter != null && filter != "undefined")
            {
                inventory = inventory.Where(e => e.Key.CatMaterial.Value.Contains(filter));
            }
            var page = HttpContext.Current.Request["page"];

            if (!string.IsNullOrWhiteSpace(page) && page != null && page != "undefined")
            {
                var perPage = HttpContext.Current.Request["perPage"];

                if (!string.IsNullOrWhiteSpace(perPage) && perPage != null && perPage != "undefined")
                {
                    int iPage    = int.Parse(page);
                    int iPerPage = int.Parse(perPage);


                    filterResponse.total_items = inventory.Count();
                    //TODO FILTER
                    filterResponse.total_filtered_items = inventory.Count();

                    inventory = inventory.OrderBy(e => e.Value).Skip((iPage - 1) * iPerPage).Take(iPerPage);
                }
            }


            return(response.Success(inventory.ToList(), filterResponse));
        }
Exemple #14
0
        private static void GetStatesByCountryPaginatedControl(IStateRepository stateRepository)
        {
            string paginationToken;
            int    option;

            string message = "Ingrese el Tamaño de Página";
            int?   limit   = GetOption(message);

            List <string> pagTokens = new List <string> {
                "{}"
            };
            int currentPage = 1;

            do
            {
                paginationToken = pagTokens[currentPage - 1];
                FilterResponse <State> response = stateRepository.GetStateByCountry("CO", limit, paginationToken);
                ListStates(response.Elements);
                Console.WriteLine($"Pagina: {currentPage} - {response.PaginationToken}");

                if (currentPage == 1)
                {
                    message = "1.Avanzar\n3.Salir";
                }
                else if (currentPage > 1 && response.PaginationToken.Equals("{}"))
                {
                    message = "2. Atras\n3. Salir";
                }
                else
                {
                    message = "1. Avanzar\n2. Atras\n3. Salir";
                }

                option = GetOption(message);

                if (option == 2 && currentPage > 1)
                {
                    currentPage -= 1;
                    pagTokens.RemoveAt(pagTokens.Count - 1);
                }
                else if (option == 1 && !response.PaginationToken.Equals("{}"))
                {
                    pagTokens.Add(response.PaginationToken);
                    currentPage++;
                }
            } while (option != 3);
        }
Exemple #15
0
        public static FilterResponse GetFilter()
        {
            var filterResponse = new FilterResponse();

            filterResponse.Version = 1;

            filterResponse.Filters.Add(new TextBoxFilter()
            {
                key     = "NumberInvoice",
                label   = "Numer faktury",
                order   = 1,
                visible = true
            });

            filterResponse.Filters.Add(new TextBoxFilter()
            {
                key     = "CompanyName",
                label   = "Firma",
                order   = 2,
                visible = true
            });

            var dropdownMenu = new List <FiltersBase <string> >();

            dropdownMenu.Add(new TextBoxFilter()
            {
                key = "", value = "Wybierz", order = 1
            });
            dropdownMenu.Add(new TextBoxFilter()
            {
                key = "Invoice", value = "Faktury", order = 2
            });
            dropdownMenu.Add(new TextBoxFilter()
            {
                key = "Correction", value = "Korekty", order = 3
            });
            filterResponse.Filters.Add(new DropdownFilter()
            {
                key     = "DocumentType",
                label   = "Typ dokumentu",
                order   = 25,
                visible = true,
                options = dropdownMenu,
            });

            return(filterResponse);
        }
Exemple #16
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            List <PipelineDTO> list = new List <PipelineDTO>();

            list = GetPipelines();

            var FilterResponse = list.Where(x => x.IsNoms || x.IsUPRD);

            if (FilterResponse == null)
            {
                FilterResponse = new List <PipelineDTO>();
            }

            if (FilterResponse != null)
            {
                var PipelineDuns = Request["pipelineDuns"] == null?Convert.ToString(FilterResponse.Select(a => a.DUNSNo).FirstOrDefault()) : Request["pipelineDuns"];

                string Absoluteurl     = HttpContext.Request.Url.AbsoluteUri;
                var    parpipelineDuns = HttpUtility.ParseQueryString(Absoluteurl.Substring(
                                                                          new[] { 0, Absoluteurl.IndexOf('?') }.Max()
                                                                          )).Get("pipelineDuns");
                PipelineDTO objPipeline = FilterResponse.Where(y => y.DUNSNo == parpipelineDuns).FirstOrDefault();

                if (objPipeline == null)
                {
                    objPipeline = FilterResponse.FirstOrDefault();
                }

                if (Absoluteurl.Contains("MOperationalCapacity") || Absoluteurl.Contains("MUnsubscribedCapacity") ||
                    Absoluteurl.Contains("Notices"))
                {
                    isPermission = (objPipeline.IsUPRD == true ? objPipeline.IsUPRD : false);
                }
                else if (Absoluteurl.Contains("PathedNomination") || Absoluteurl.Contains("NonPathed") || Absoluteurl.Contains("PNTNominations") ||
                         Absoluteurl.Contains("SQTSSummary") || Absoluteurl.Contains("Batch"))
                {
                    isPermission = (objPipeline.IsNoms == true ? objPipeline.IsNoms : false);
                }
                ViewBag.IsPermission = isPermission;

                ViewBag.objPipeline = objPipeline;

                base.OnActionExecuting(filterContext);
            }
        }
        public FilterResponse GetFilteredGraphData(FilterCriteriaRequest filterCriteria)
        {
            var vaccinationToQuery = string.Empty;
            var districtToQuery    = string.Empty;

            if (filterCriteria.VaccineIdList.Count > 0)
            {
                vaccinationToQuery = "SchId in (" + string.Join(",", filterCriteria.VaccineIdList) + ")";
            }
            if (filterCriteria.DistrictIdList.Count > 0)
            {
                districtToQuery = "DistrictId in (" + string.Join(",", filterCriteria.DistrictIdList) + ")";
            }

            FilterResponse filterres = new FilterResponse();

            if (filterCriteria.StatusList.Count > 0)
            {
                foreach (int status in filterCriteria.StatusList)
                {
                    if (status == 0)//Done
                    {
                        var query = string.Format(@"SELECT Count(*) FROM ListOfSuccessfullVacc WHERE VaccinatedDate>='{0}' AND VaccinatedDate<='{1}' AND {2} AND {3}", filterCriteria.FromYear, filterCriteria.ToYear, districtToQuery, vaccinationToQuery);
                        filterres.DoneCount = Convert.ToInt32(dbService.ExecuteScalar(query));
                    }
                    else if (status == 1)//Due
                    {
                        var query = string.Format(@"SELECT Count(*) FROM ListOfVaccinationDue WHERE VAccStartOn>='{0}' AND VAccStartOn<='{1}'AND {2} AND {3} ", filterCriteria.FromYear, filterCriteria.ToYear, districtToQuery, vaccinationToQuery);
                        filterres.DueCount = Convert.ToInt32(dbService.ExecuteScalar(query));
                    }
                    else if (status == 2)//OverDue/Missed
                    {
                        var query = string.Format(@"SELECT Count(*) FROM ListOfVaccinationOverDue WHERE VAccStartOn>='{0}' AND VAccStartOn<='{1}' AND {2} AND {3}", filterCriteria.FromYear, filterCriteria.ToYear, districtToQuery, vaccinationToQuery);
                        filterres.MissedCount = Convert.ToInt32(dbService.ExecuteScalar(query));
                    }
                }
            }

            //int Totalstatuscount = filterres.DueCount + filterres.DoneCount + filterres.MissedCount;
            //filterres.DoneCount = (filterres.DoneCount / Totalstatuscount) * 100;
            //filterres.DueCount = (filterres.DueCount / Totalstatuscount) * 100;
            //filterres.MissedCount = (filterres.MissedCount / Totalstatuscount) * 100;

            return(filterres);
        }
Exemple #18
0
        public FilterResponse GetFiltersData()
        {
            var filterResponse = new FilterResponse();
            var miniVipTypes   = GetVipTypes();

            if (miniVipTypes.Count > 0)
            {
                VipLine.AddRange(filterResponse.vipLines, miniVipTypes);
            }
            var miniSpecials = GetSpecials();

            if (miniSpecials.Count > 0)
            {
                SpecialLine.AddRange(filterResponse.specialLines, miniSpecials);
            }

            return(filterResponse);
        }
        public void Write(FilterResponse response, Stream sw, List <Field> fields)
        {
            sw.StartObject();
            sw.PropertyNameWithColon("accounts");
            sw.StartArray();
            var accounts = response.Ids;
            var limit    = Math.Min(accounts.Count, response.Limit);

            for (int i = 0; i < limit; i++)
            {
                Write(accounts[i], sw, fields);
                if (i < limit - 1)
                {
                    sw.Comma();
                }
            }
            sw.EndArray();
            sw.EndObject();
        }
Exemple #20
0
        private static FilterResponse <MobilePhone> RunTemplate(List <CrunchItem <MobilePhone> > phoneItems)
        {
            CrunchRequest <MobilePhone> request = new CrunchRequest <MobilePhone>();

            request.One = phoneItems.ToArray();

            // In case you want to run a template with multiple rules set the TemplateId property to the Id of the template.
            // Otherwise if you run a single rule set the RuleId property. You can either have the TemplateId or the RuleId set at any given time not both.
            request.TemplateId = 1;
            // request.RuleId = 4;

            FilterResponse <MobilePhone> response = Task.Run(async() =>
            {
                ApiClient api = new ApiClient();

                return(await api.SendAsync <CrunchRequest <MobilePhone>, FilterResponse <MobilePhone> >(request, "/api/1.0/crunch/run"));
            }).GetAwaiter().GetResult();

            return(response);
        }
Exemple #21
0
        private static FilterResponse <MobilePhone> FindBestHardwareAndCameraPhones(List <CrunchItem <MobilePhone> > phoneItems)
        {
            CrunchRequest <MobilePhone> request = new CrunchRequest <MobilePhone>();

            request.One    = phoneItems.ToArray();
            request.Filter = new Filter()
            {
                Expression = "$1.status != \"Discontinued\" AND ISBLANK($1.internal_memory_mb) == FALSE AND ISBLANK($1.primary_camera_mp) == FALSE AND TONUMBER($1.internal_memory_mb) >= 8192 AND TONUMBER($1.primary_camera_mp) >= 8"
            };
            request.FieldTypes = typeof(MobilePhone).GetProperties()
                                 .SelectMany(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute), false).Cast <JsonPropertyAttribute>())
                                 .ToDictionary(p => p.PropertyName, p => "String");

            FilterResponse <MobilePhone> response = Task.Run(async() =>
            {
                ApiClient api = new ApiClient();

                return(await api.SendAsync <CrunchRequest <MobilePhone>, FilterResponse <MobilePhone> >(request, "/api/1.0/crunch/run"));
            }).GetAwaiter().GetResult();

            return(response);
        }
Exemple #22
0
        private static FilterResponse <MobilePhone> FindDualSimPhones(List <CrunchItem <MobilePhone> > phoneItems)
        {
            CrunchRequest <MobilePhone> request = new CrunchRequest <MobilePhone>();

            request.One    = phoneItems.ToArray();
            request.Filter = new Filter()
            {
                Expression = "$1.status != \"Discontinued\" AND FIND(\"Dual SIM\", $1.sim) >= 1 AND $1.card_slot != \"No\""
            };
            request.FieldTypes = typeof(MobilePhone).GetProperties()
                                 .SelectMany(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute), false).Cast <JsonPropertyAttribute>())
                                 .ToDictionary(p => p.PropertyName, p => "String");

            FilterResponse <MobilePhone> response = Task.Run(async() =>
            {
                ApiClient api = new ApiClient();

                return(await api.SendAsync <CrunchRequest <MobilePhone>, FilterResponse <MobilePhone> >(request, "/api/1.0/crunch/run"));
            }).GetAwaiter().GetResult();

            return(response);
        }
Exemple #23
0
        private static FilterResponse <MobilePhone> FindMostDurableBatteryPhones(List <CrunchItem <MobilePhone> > phoneItems)
        {
            CrunchRequest <MobilePhone> request = new CrunchRequest <MobilePhone>();

            request.One    = phoneItems.ToArray();
            request.Filter = new Filter()
            {
                Expression = "$1.status != \"Discontinued\" AND ISBLANK($1.stand_by_hours) == FALSE AND ISBLANK($1.talk_time_hours) == FALSE " +
                             "AND TONUMBER($1.stand_by_hours) >= 400 AND TONUMBER($1.talk_time_hours) >= 10"
            };
            request.FieldTypes = typeof(MobilePhone).GetProperties()
                                 .SelectMany(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute), false).Cast <JsonPropertyAttribute>())
                                 .ToDictionary(p => p.PropertyName, p => "String");

            FilterResponse <MobilePhone> response = Task.Run(async() =>
            {
                ApiClient api = new ApiClient();

                return(await api.SendAsync <CrunchRequest <MobilePhone>, FilterResponse <MobilePhone> >(request, "/api/1.0/crunch/run"));
            }).GetAwaiter().GetResult();

            return(response);
        }
Exemple #24
0
        public virtual CommonResponse GetSingleWhere(params Expression <Func <Entity, bool> >[] wheres)
        {
            CommonResponse response       = new CommonResponse();
            FilterResponse filterResponse = new FilterResponse();

            Entity entity;

            try
            {
                repository.byUserId = loggedUser.UserID;

                entity = repository.GetSingle(wheres);
                if (entity != null)
                {
                    loadNavigationProperties(entity);
                }

                return(response.Success(entity));
            }
            catch (Exception e)
            {
                return(response.Error("ERROR: " + e.ToString()));
            }
        }
Exemple #25
0
        public static List <FilterResponse> GetFilterResultForDocument(Document document, RestScoringResult scoringResult)
        {
            var searchResult = new List <FilterResponse>();

            if (document != null)
            {
                foreach (var file in document.Files)
                {
                    foreach (var paragraphUnit in file.ParagraphUnits)
                    {
                        if (paragraphUnit.IsStructure)
                        {
                            continue;
                        }
                        foreach (var pair in paragraphUnit.SegmentPairs)
                        {
                            var sourceText = FilterExpression.ConvertSegmentPair(pair.Source);
                            var targetText = FilterExpression.ConvertSegmentPair(pair.Target);
                            var matchScore = string.Empty;
                            if (scoringResult != null)
                            {
                                matchScore = scoringResult.Match.ToString();
                            }
                            var result = new FilterResponse
                            {
                                Source     = sourceText,
                                Target     = targetText,
                                MatchScore = matchScore
                            };
                            searchResult.Add(result);
                        }
                    }
                }
            }
            return(searchResult);
        }
Exemple #26
0
        public virtual CommonResponse GetPage(int perPage, int page, string filterGeneral, Expression <Func <Entity, bool> >[] wheres, Expression <Func <Entity, object> > orderby, params Expression <Func <Entity, bool> >[] database_wheres)
        {
            CommonResponse response       = new CommonResponse();
            FilterResponse filterResponse = new FilterResponse();

            IEnumerable <Entity> entities;  //Entities comming from DB
            IQueryable <Entity>  resultset; //To filter properties not in DB

            try
            {
                //repository.ByUserId = LoggedUser.UserID;

                //Apply Database Filtering and Fetch
                entities = StaticDbQueryForList(repository.GetList(orderby, null, database_wheres).AsQueryable()).AsNoTracking().ToList();

                //Apply Roles Filtering

                //Applying Non-Database Wheres

                resultset = entities.AsQueryable();
                if (wheres != null)
                {
                    foreach (var where in wheres)
                    {
                        resultset = resultset.Where(where);
                    }
                }

                filterResponse.total_items = resultset.Count();


                #region Apply General Search Filter

                bool PopulateForSearchEqualsAdapterOut = false;
                PopulateForSearchEqualsAdapterOut = PopulateForSearch(resultset.ToArray());

                HashSet <Entity> filteredResultSet = new HashSet <Entity>();
                if (!string.IsNullOrWhiteSpace(filterGeneral))
                {
                    string[] arrFilterGeneral = filterGeneral.ToLower().Split(' ');

                    var searchableProps = typeof(Entity).GetProperties().Where(prop => new[] { "String" }.Contains(prop.PropertyType.Name));

                    foreach (var e in resultset)
                    {
                        bool bAllKeywordsFound = true;
                        foreach (var keyword in arrFilterGeneral)
                        {
                            bool bAtLeastOnePropertyContainsIt = false;
                            foreach (var prop in searchableProps)
                            {
                                string a = (string)prop.GetValue(e, null);
                                if (a != null && a.ToLower().Contains(keyword.Trim()))
                                {
                                    bAtLeastOnePropertyContainsIt = true;
                                    break;
                                }
                            }
                            if (!bAtLeastOnePropertyContainsIt)
                            {
                                bAllKeywordsFound = false;
                                break;
                            }
                        }
                        if (bAllKeywordsFound)
                        {
                            filteredResultSet.Add(e);
                        }
                    }

                    //DID NOT WORK ALL THE TIMES:
                    //resultset = resultset.Where(e => searchableProps.Any(prop =>
                    //                                    arrFilterGeneral.All(keyword =>
                    //                                        ((string)prop.GetValue(e, null) ?? "").ToString().ToLower()
                    //                                        .Contains(keyword))));
                }
                else
                {
                    filteredResultSet = new HashSet <Entity>(resultset);
                }

                #endregion

                filterResponse.total_filtered_items = filteredResultSet.Count();

                #region Pagination
                IEnumerable <Entity> afterPaginate;
                if (perPage != 0)
                {
                    afterPaginate = filteredResultSet.Skip((page - 1) * perPage).Take(perPage);
                }
                else
                {
                    afterPaginate = filteredResultSet;
                }
                #endregion

                if (!PopulateForSearchEqualsAdapterOut)
                {
                    AdapterOut(afterPaginate.ToArray());
                }
                return(response.Success(afterPaginate, filterResponse));
            }
            catch (Exception e)
            {
                var originalException = GetOriginalException(e);
                return(response.Error("Error " + originalException.Message));
            }
        }
Exemple #27
0
        public virtual CommonResponse GetPage(int perPage, int page, string filterGeneral, Expression <Func <Entity, bool> >[] wheres, Expression <Func <Entity, object> > orderby, params Expression <Func <Entity, bool> >[] database_wheres)
        {
            CommonResponse response       = new CommonResponse();
            FilterResponse filterResponse = new FilterResponse();

            IEnumerable <Entity> entities;  //Entities comming from DB
            IQueryable <Entity>  resultset; //To filter properties not in DB

            try
            {
                repository.byUserId = loggedUser.UserID;

                var database_wheresList = database_wheres.ToList();
                addDbWheresWhenPaging(database_wheresList);

                #region Apply Database Filtering

                entities = repository.GetList(orderby, database_wheresList.ToArray());
                loadNavigationProperties(entities.ToArray());
                #endregion

                #region Apply Roles Filtering

                #endregion

                #region Applying Non-Database Properties Filtering
                resultset = entities.AsQueryable();
                foreach (var where in wheres)
                {
                    resultset = resultset.Where(where);
                }

                #endregion

                resultset = applyOrderByWhenPaging(resultset);

                filterResponse.total_items = resultset.Count();


                #region Apply General Search Filter

                HashSet <Entity> filteredResultSet = new HashSet <Entity>();
                if (!string.IsNullOrWhiteSpace(filterGeneral))
                {
                    string[] arrFilterGeneral = filterGeneral.ToLower().Split(' ');

                    var searchableProps = typeof(Entity).GetProperties().Where(prop => new[] { "String" }.Contains(prop.PropertyType.Name));

                    foreach (var e in resultset)
                    {
                        bool bAllKeywordsFound = true;
                        foreach (var keyword in arrFilterGeneral)
                        {
                            bool bAtLeastOnePropertyContainsIt = false;
                            foreach (var prop in searchableProps)
                            {
                                string a = (string)prop.GetValue(e, null);
                                if (a != null && a.ToLower().Contains(keyword.Trim()))
                                {
                                    bAtLeastOnePropertyContainsIt = true;
                                    break;
                                }
                            }
                            if (!bAtLeastOnePropertyContainsIt)
                            {
                                bAllKeywordsFound = false;
                                break;
                            }
                        }
                        if (bAllKeywordsFound)
                        {
                            filteredResultSet.Add(e);
                        }
                    }

                    //DID NOT WORK ALL THE TIMES:
                    //resultset = resultset.Where(e => searchableProps.Any(prop =>
                    //                                    arrFilterGeneral.All(keyword =>
                    //                                        ((string)prop.GetValue(e, null) ?? "").ToString().ToLower()
                    //                                        .Contains(keyword))));
                }
                else
                {
                    filteredResultSet = new HashSet <Entity>(resultset);
                }

                #endregion

                filterResponse.total_filtered_items = filteredResultSet.Count();

                #region Pagination
                List <Entity> afterPaginate = filteredResultSet.ToList();
                if (perPage != 0)
                {
                    afterPaginate = filteredResultSet.Skip((page - 1) * perPage).Take(perPage).ToList();
                }
                #endregion

                return(response.Success(afterPaginate, filterResponse));
            }
            catch (Exception e)
            {
                return(response.Error("ERROR: " + e.ToString()));
            }
        }
Exemple #28
0
        virtual public async Task <CommonResponse> GetPagedAsync(int perPage = 0, int page = 1, string generalFilter = "", SqlExpression <Entity> query = null, string cachePrefix = null, bool requiresKeysInJsons = false)
        {
            if (string.IsNullOrWhiteSpace(cachePrefix))
            {
                cachePrefix = CACHE_GET_PAGED;
            }
            cachePrefix += $"_{perPage}_{page}_{generalFilter}";

            if (requiresKeysInJsons)
            {
                cachePrefix += "_requiresKeysInJsons";
            }

            var cacheContainer = Cache.Get <Dictionary <string, CommonResponse> >(CACHE_CONTAINER_GET_PAGED);

            if (cacheContainer == null)
            {
                cacheContainer = new Dictionary <string, CommonResponse>();
            }

            var paramsNotFoundAsProps = new Dictionary <string, string>();

            //var cacheFromContainer = false;

            if (query == null)
            {
                query = Db.From <Entity>();
            }
            //    query = Db.From<Entity>();
            //else
            //    cacheFromContainer = true;

            #region Apply Database Filtering
            foreach (var queryParam in Request.QueryString.AllKeys)
            {
                string queryParamValue = Request.QueryString[queryParam];
                if (IsValidParam(queryParam) && IsValidJSValue(queryParamValue))
                {
                    cachePrefix += $"_{queryParam}_{queryParamValue}";

                    string sPropertyName = queryParam;

                    PropertyInfo oProp = typeof(Entity).GetProperty(sPropertyName);
                    if (oProp == null)
                    {
                        paramsNotFoundAsProps.Add(queryParam, queryParamValue);
                        continue; //Ignore non-existing properties, they could be just different query parameters.
                    }

                    Type tProp = oProp.PropertyType;
                    //Nullable properties have to be treated differently, since we
                    //  use their underlying property to set the value in the object
                    if (tProp.IsGenericType &&
                        tProp.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                    {
                        //Get the underlying type property instead of the nullable generic
                        tProp = new NullableConverter(oProp.PropertyType).UnderlyingType;
                    }

                    ParameterExpression entityParameter = Expression.Parameter(typeof(Entity), "entityParameter");
                    Expression          childProperty   = Expression.PropertyOrField(entityParameter, sPropertyName);

                    var value = Expression.Constant(Convert.ChangeType(queryParamValue, tProp));

                    //if (cacheFromContainer)
                    //{
                    if (tProp == typeof(string))
                    {
                        query.Where($"{query.SqlColumn(sPropertyName)} like '%{value.Value}%'");
                    }
                    else
                    {
                        query.Where($"{query.SqlColumn(sPropertyName)} = {value.Value}");
                    }
                    //}
                    //else //Cache From Memory
                    //{
                    //    // let's perform the conversion only if we really need it
                    //    var converted = value.Type != childProperty.Type
                    //        ? Expression.Convert(value, childProperty.Type)
                    //        : (Expression)value;

                    //    Expression<Func<Entity, bool>> lambda;
                    //    if (tProp == typeof(String))
                    //    {
                    //        MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
                    //        lambda = Expression.Lambda<Func<Entity, bool>>(Expression.Call(converted, method, childProperty), entityParameter);
                    //    }
                    //    else
                    //    {
                    //        Expression comparison = Expression.Equal(childProperty, converted);
                    //        lambda = Expression.Lambda<Func<Entity, bool>>(comparison, entityParameter);
                    //    }
                    //    allEntities = allEntities.Where(lambda);
                    //}
                }
            }
            #endregion

            #region From Container Cache
            //if (cacheFromContainer)
            //{
            cacheContainer.TryGetValue(cachePrefix, out CommonResponse cache);
            if (cache != null)
            {
                var cacheList = cache.Result as IEnumerable <Entity>;
                AdapterOut(cacheList.ToArray());
                return(cache);
            }
            //}
            #endregion

            query = OnGetList(query);
            var entities = await Db.LoadSelectAsync(query);

            //var entities = await GetAllAsync();
            var filterResponse = new FilterResponse
            {
                total_items = entities.Count()
            };

            #region Apply General Search Filter
            var usingBeforeSearch = BeforeSearch(entities);

            var filtered = new HashSet <Entity>();
            if (!string.IsNullOrEmpty(generalFilter) || (paramsNotFoundAsProps.Count > 0))
            {
                var searchableProps = typeof(Entity).GetProperties().Where(prop => !prop.HasAttribute <IsJson>() &&
                                                                           new[] { "String" }.Contains(prop.PropertyType.Name)).ToList();
                var jsonProps = typeof(Entity).GetPublicProperties().Where(p => p.HasAttribute <IsJson>()).ToList();

                foreach (var entity in entities)
                {
                    if (SearchInStringProps(entity, generalFilter) &&
                        SearchInJsonProps(entity, paramsNotFoundAsProps, requiresKeysInJsons, jsonProps))
                    {
                        filtered.Add(entity);
                    }
                }
            }
            else
            {
                filtered = new HashSet <Entity>(entities);
            }

            filterResponse.total_filtered_items = filtered.Count();
            #endregion

            #region Pagination
            IEnumerable <Entity> afterPaginate;
            if (perPage != 0)
            {
                var totalPagesCount = (filterResponse.total_filtered_items + perPage - 1) / perPage;
                if (page > totalPagesCount)
                {
                    page = totalPagesCount;
                }

                afterPaginate       = BeforePaginate(filtered.ToList()).Skip((page - 1) * perPage).Take(perPage);
                filterResponse.page = page;
            }
            else
            {
                afterPaginate = BeforePaginate(filtered.ToList());
            }
            #endregion

            #region AdapterOut Hook
            if (!usingBeforeSearch)
            {
                AdapterOut(afterPaginate.ToArray());
            }
            #endregion

            var response = new CommonResponse {
                Result = afterPaginate, AdditionalData = filterResponse
            };

            //if (cacheFromContainer)
            //{
            cacheContainer[cachePrefix] = response;
            Cache.Replace(CACHE_CONTAINER_GET_PAGED, cacheContainer);
            //}
            return(response);
        }
Exemple #29
0
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a bunch of digits separated by a coma: ");
            Console.WriteLine("Input should in format 9,3,6,4,12 ..........and so on...: ");

            var str = Console.ReadLine();

            Console.WriteLine("================================ ");

            Console.WriteLine($"original String ==  { str}");

            IFilterService stringService = new FilterService();
            AppSettings    appSettings   = new AppSettings();
            FilterResponse strResponse   = new FilterResponse(str);

            // Filter Prime Numbers
            if (appSettings.ProcessFilterPrimeNumbers)
            {
                try
                {
                    strResponse = stringService.ProcessFilter(strResponse);

                    if (strResponse.Error.HasValue)
                    {
                        Console.WriteLine($"After filtering the prime numbers  ==  { strResponse.Error.ToString()}");
                    }

                    if (!string.IsNullOrEmpty(strResponse.InputString))
                    {
                        Console.WriteLine($"After filtering the prime numbers ==  { strResponse.InputString}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Exceoption Occurred ==  { ex.InnerException.Message}");
                    Console.ReadLine();
                }
            }
            //Apply sort
            if (appSettings.ProcessSortDescending)
            {
                try {
                    strResponse = stringService.ProcessSort(strResponse);

                    if (strResponse.Error.HasValue)
                    {
                        Console.WriteLine($"After sorting in Descending order ==  { strResponse.Error.ToString()}");
                    }

                    if (!string.IsNullOrEmpty(strResponse.InputString))
                    {
                        Console.WriteLine($"After sorting in Descending order ==  { strResponse.InputString}");
                    }
                }
                catch (Exception ex) {
                    Console.WriteLine($"Exceoption Occurred ==  { ex.InnerException.Message}");
                    Console.ReadLine();
                }
            }
            Console.ReadLine();
        }
Exemple #30
0
        virtual public async Task <CommonResponse> GetPagedAsync(int perPage, int page, string filterGeneral, SqlExpression <Entity> query = null, string cacheKey = null)
        {
            var cacheContainer = Cache.Get <Dictionary <string, CommonResponse> >(CACHE_CONTAINER_GET_PAGED);

            if (cacheContainer == null)
            {
                cacheContainer = new Dictionary <string, CommonResponse>();
            }
            if (string.IsNullOrWhiteSpace(cacheKey))
            {
                cacheKey = CACHE_GET_PAGED;
            }
            cacheKey += $"_{ perPage}_{page}_{filterGeneral}";

            if (query == null)
            {
                query = Db.From <Entity>();
            }

            var filterResponse = new FilterResponse();

            #region Filter by User
            //if (request.FilterUser.HasValue && typeof(Entity).IsSubclassOf(typeof(BaseDocument)))
            //{
            //    query.LeftJoin<Track>()
            //        .LeftJoin<Track, User>((t, u) => t.User_AssignedToKey == u.Id)
            //        .Where<User>(u => u.Id == request.FilterUser);
            //}
            #endregion

            #region Apply Database Filtering
            foreach (var queryParam in Request.QueryString.AllKeys)
            {
                string queryParamValue = Request.QueryString[queryParam];
                if (IsValidParam(queryParam) && IsValidJSValue(queryParamValue))
                {
                    cacheKey += $"_{queryParam}_{queryParamValue}";

                    string sPropertyName = queryParam;

                    PropertyInfo oProp = typeof(Entity).GetProperty(sPropertyName);
                    if (oProp == null)
                    {
                        continue;                //Ignore non-existing properties, they could be just different query parameters.
                    }
                    Type tProp = oProp.PropertyType;
                    //Nullable properties have to be treated differently, since we
                    //  use their underlying property to set the value in the object
                    if (tProp.IsGenericType &&
                        tProp.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                    {
                        //Get the underlying type property instead of the nullable generic
                        tProp = new NullableConverter(oProp.PropertyType).UnderlyingType;
                    }

                    ParameterExpression entityParameter = Expression.Parameter(typeof(Entity), "entityParameter");
                    Expression          childProperty   = Expression.PropertyOrField(entityParameter, sPropertyName);

                    var value = Expression.Constant(Convert.ChangeType(queryParamValue, tProp));

                    if (tProp == typeof(string))
                    {
                        query.Where($"{query.SqlColumn(sPropertyName)} like '%{value.Value}%'");
                    }
                    else
                    {
                        query.Where($"{query.SqlColumn(sPropertyName)} = {value.Value}");
                    }
                }
            }

            #endregion

            #region From Cache
            cacheContainer.TryGetValue(cacheKey, out CommonResponse cache);
            if (cache != null)
            {
                var cacheList = cache.Result as IEnumerable <Entity>;
                AdapterOut(cacheList.ToArray());
                return(cache);
            }
            #endregion

            #region OnGetList Hook
            query = OnGetList(query);
            #endregion

            #region Non-Database Parameters Filters

            #endregion

            var entities = (await Db.LoadSelectAsync(query)).ToArray();

            filterResponse.total_items = entities.Count();

            #region Apply General Search Filter

            bool PopulateForSearchEqualsAdapterOut = false;
            PopulateForSearchEqualsAdapterOut = PopulateForSearch(entities);

            HashSet <Entity> filteredResultSet = new HashSet <Entity>();
            if (!string.IsNullOrWhiteSpace(filterGeneral))
            {
                string[] arrFilterGeneral = filterGeneral.ToLower().Split(' ');

                var searchableProps = typeof(Entity).GetProperties().Where(prop => new[] { "String" }.Contains(prop.PropertyType.Name));

                foreach (var e in entities)
                {
                    bool bAllKeywordsFound = true;
                    foreach (var keyword in arrFilterGeneral)
                    {
                        bool bAtLeastOnePropertyContainsIt = false;
                        foreach (var prop in searchableProps)
                        {
                            string a = (string)prop.GetValue(e, null);
                            if (a != null && a.ToLower().Contains(keyword.Trim()))
                            {
                                bAtLeastOnePropertyContainsIt = true;
                                break;
                            }
                        }
                        if (!bAtLeastOnePropertyContainsIt)
                        {
                            bAllKeywordsFound = false;
                            break;
                        }
                    }
                    if (bAllKeywordsFound)
                    {
                        filteredResultSet.Add(e);
                    }
                }

                //DID NOT WORK SOMETIMES:
                //resultset = resultset.Where(e => searchableProps.Any(prop =>
                //                                    arrFilterGeneral.All(keyword =>
                //                                        ((string)prop.GetValue(e, null) ?? "").ToString().ToLower()
                //                                        .Contains(keyword))));
            }
            else
            {
                filteredResultSet = new HashSet <Entity>(entities);
            }

            filterResponse.total_filtered_items = filteredResultSet.Count();
            #endregion

            #region Pagination
            IEnumerable <Entity> afterPaginate;
            if (perPage != 0)
            {
                afterPaginate = BeforePaginate(filteredResultSet.ToList()).Skip((page - 1) * perPage).Take(perPage);
            }
            else
            {
                afterPaginate = BeforePaginate(filteredResultSet.ToList());
            }
            #endregion

            #region AdapterOut Hook
            if (!PopulateForSearchEqualsAdapterOut)
            {
                AdapterOut(afterPaginate.ToArray());
            }
            #endregion

            var response = new CommonResponse {
                Result = afterPaginate.ToList(), AdditionalData = filterResponse
            };
            cacheContainer[cacheKey] = response;
            Cache.Replace(CACHE_CONTAINER_GET_PAGED, cacheContainer);
            return(response);
        }