static void Main(string[] args) { var apple = new Product("Apple", Color.Green, Size.Small); var tree = new Product("Tree", Color.Green, Size.Large); var house = new Product("House", Color.Blue, Size.Large); Product[] products = new[] { apple, tree, house }; var pf = new ProductFilter(); Console.WriteLine("Green products (old): "); foreach (var p in pf.FilterByColor(products, Color.Green)) { Console.WriteLine($"Color is {p.Color}"); } var df = new DynamicFilter(); Console.WriteLine("Green products (new) :"); foreach (var p in df.Filter(products, new ColorSpecification(Color.Green))) { Console.WriteLine($"Color is {p.Color}"); } Console.WriteLine("Large blue items"); foreach (var p in df.Filter(products, new AndSpecification <Product>(new ColorSpecification(Color.Blue), new SizeSpecification(Size.Large)))) { Console.WriteLine($" - {p.Name} is big and blue"); } }
public void ShouldFilter() { var documentItFiltered = "document.it.filtered"; var commandFilterThis = "command.filter.this"; var consumedEvent = new AutoResetEvent(false); var storage = new InMemoryKeyValueStorage <ExpandoObject>(); var filter = new DynamicFilter <ExpandoObject>((m, s) => true, storage); this.StartBus( "pipeline", cfg => { cfg.On(commandFilterThis) .ReactWith(new PipelineConsumerOf <ExpandoObject>(filter, new StaticRouter(documentItFiltered))) .RequiresAccept(); cfg.Route(documentItFiltered); }); var producer = this.StartBus( "producer", cfg => { cfg.Route(commandFilterThis); }); this.StartBus( "consumer", cfg => { cfg.On(documentItFiltered) .ReactWith <ExpandoObject>((m, ctx) => { consumedEvent.Set(); }); }); producer.Emit(commandFilterThis, new { }); var consumed = consumedEvent.WaitOne(5000); consumed.Should().BeTrue("Должно быть получено сообщение обработанное фильтом."); }
private static BinaryExpression GetExpression <T>(ParameterExpression param, DynamicFilter filter1, DynamicFilter filter2) { Expression bin1 = GetExpression <T>(param, filter1); Expression bin2 = GetExpression <T>(param, filter2); return(Expression.AndAlso(bin1, bin2)); }
public Task <List <User> > Get(DynamicFilter <User> filter) { IEnumerable <User> result; if (filter.Filter != null) { result = users.Where(filter.Filter.Compile()); } else { result = users; } if (filter.Order != null) { if (filter.OrderType == OrderType.Asc) { result = result.OrderBy(filter.Order.Compile()); } else { result = result.OrderByDescending(filter.Order.Compile()); } } return(Task.FromResult(result.ToList())); }
public IEnumerable <Initiative> DownloadWord(DynamicFilter filter, List <string> roles, string userId) { IEnumerable <Initiative> query = Enumerable.Empty <Initiative>(); if (roles.Any(x => x.Equals(CommonConstants.ADMIN) || x.Equals(CommonConstants.ADVANCEDROLE))) { query = _initiativeRepository.GetMulti(x => !x.IsDeactive, new string[] { "Field" }); } else { query = _initiativeRepository.GetMulti(x => !x.IsDeactive && x.AccountId == userId, new string[] { "Field" }); } //if (!string.IsNullOrEmpty(filter.Keyword)) // query = query.Where(x => x.Title.ToLower().Contains(filter.Keyword.ToLower()) || x.KnowSolutionContent.ToLower().Contains(filter.Keyword.ToLower()) || // x.ImprovedContent.ToLower().Contains(filter.Keyword.ToLower())); //if (!string.IsNullOrEmpty(filter.Time)) // query = query.Where(x => x.DeploymentTime.Year.ToString() == filter.Time); //if (filter.Field != null) // query = query.Where(x => x.FieldId == filter.Field); return(query.OrderBy(x => x.Title)); }
public void ApplyFilterTo_ShouldFilterCorrect_WithMultiplePropertyCombiningOr(List <Book> list) { // Arrange DynamicFilter filter = new DynamicFilter { { "TotalPage", "5" }, { "IsPublished", "True" } }; filter.CombineWith = Enums.CombineType.Or; // Act var actualQuery = list.AsQueryable().ApplyFilter(filter); var exprectedQuery = list.AsQueryable().Where(x => x.TotalPage == 5 || x.IsPublished == true); var actualResult = actualQuery.ToList(); var expectedResult = exprectedQuery.ToList(); // Assert Assert.Equal(exprectedQuery.Expression.ToString(), actualQuery.Expression.ToString()); Assert.Equal(expectedResult.Count, actualResult.Count); foreach (var item in expectedResult) { Assert.Contains(item, actualResult); } }
public void SetFilter(Workbook workbook) { #region radspreadprocessing-features-filtering_6 Worksheet worksheet = workbook.ActiveWorksheet; CellRange filterRange = new CellRange(0, 1, 5, 2); worksheet.Filter.FilterRange = filterRange; #endregion #region radspreadprocessing-features-filtering_7 DynamicFilter filter = new DynamicFilter(1, DynamicFilterType.AboveAverage); #endregion #region radspreadprocessing-features-filtering_8 worksheet.Filter.SetFilter(filter); #endregion #region radspreadprocessing-features-filtering_9 worksheet.Cells[filterRange].Filter(filter); #endregion #region radspreadprocessing-features-filtering_10 worksheet.Filter.ReapplyFilter(1); #endregion }
public void TestMethod1() { var df = new DynamicFilter <Filter, Entity>(); var filter = new Filter { FilterName = "Andrey", IntFilter = 5 }; var entities = new List <Entity> { new Entity { Name = "Andrey", IntValue = 5 }, new Entity { Name = "Nikolay", IntValue = 5 }, new Entity { Name = "Danil", IntValue = 1 } }; var query = df.CreateWhereExpression(filter); var func = query.Compile(); var result = entities.Where(func).ToList(); Assert.AreEqual(1, result.Count); Assert.AreEqual("Andrey", result.First().Name); }
private static Expression GetExpression <T>(ParameterExpression param, DynamicFilter filter) { MemberExpression member = Expression.Property(param, filter.PropertyName); ConstantExpression constant = Expression.Constant(filter.Value); return(Expression.Equal(member, constant)); }
public IConsumePipe BuildConsumePipe() { var filter = new DynamicFilter <ConsumeContext, Guid>(new ConsumeContextConverterFactory(), GetRequestId); _consumePipeConfigurator.UseFilter(filter); return(new ConsumePipe(this, filter, _consumePipeConfigurator.Build(), AutoStart)); }
internal void FromDynamicFilter(DynamicFilter df) { this.SetAllNull(); this.Type = df.Type.Value; if (df.Val != null) this.Val = df.Val.Value; if (df.MaxVal != null) this.MaxVal = df.MaxVal.Value; }
internal DynamicFilter ToDynamicFilter() { DynamicFilter df = new DynamicFilter(); df.Type = this.Type; if (this.Val != null) df.Val = this.Val.Value; if (this.MaxVal != null) df.MaxVal = this.MaxVal.Value; return df; }
public void Apply(IPipeBuilder <TInput> builder) { var dispatchFilter = new DynamicFilter <TInput>(_pipeContextConverterFactory); foreach (Action <IPipeConnector> action in _connectActions) { action(dispatchFilter); } builder.AddFilter(dispatchFilter); }
protected void Label_PreRender(object sender, EventArgs e) { Label label = (Label)sender; DynamicFilter dynamicFilter = (DynamicFilter)label.FindControl("DynamicFilter"); QueryableFilterUserControl fuc = dynamicFilter.FilterTemplate as QueryableFilterUserControl; if (fuc != null && fuc.FilterControl != null) { label.AssociatedControlID = fuc.FilterControl.GetUniqueIDRelativeTo(label); } }
public void Apply(IPipeBuilder <TInput> builder) { var dispatchFilter = new DynamicFilter <TInput>(_pipeContextConverterFactory); foreach (var specification in _specifications) { specification.Connect(dispatchFilter); } builder.AddFilter(dispatchFilter); }
public IEnumerable <Initiative> GetAll(DynamicFilter filter, out int totalCount, List <string> roles, string userId) { IEnumerable <Initiative> query; // has permission to view all var keyword = filter.Keyword.ToLower(); DateTime startTime; if (!DateTime.TryParse(filter.StartDate, out startTime)) { // handle parse failure startTime = DateTime.MinValue; } DateTime endTime; if (!DateTime.TryParse(filter.EndDate, out endTime)) { // handle parse failure endTime = DateTime.MaxValue; } if (roles.Any(x => x.Equals(Role.ViewIntiniativeForAdmin))) { query = _initiativeRepository.GetMulti(x => !x.IsDeactive && DbFunctions.TruncateTime(x.DateCreated) >= startTime && DbFunctions.TruncateTime(x.DateCreated) <= endTime && x.AccountId.Contains(filter.AccountId) && (x.Title.ToLower().Contains(keyword) || x.KnowSolutionContent.ToLower().Contains(keyword) || x.ImprovedContent.ToLower().Contains(keyword)), new string[] { "Field", "ApplicationUser" }); } else { query = _initiativeRepository.GetMulti(x => !x.IsDeactive && x.AccountId == userId && DbFunctions.TruncateTime(x.DateCreated) >= startTime && DbFunctions.TruncateTime(x.DateCreated) <= endTime && (x.Title.ToLower().Contains(keyword) || x.KnowSolutionContent.ToLower().Contains(keyword) || x.ImprovedContent.ToLower().Contains(keyword)), new string[] { "Field", "ApplicationUser" }); } if (filter.FieldId > -1) { query = query.Where(_ => _.FieldId == filter.FieldId); } if (filter.FieldGroupId > -1) { query = query.Where(_ => _.FieldGroupId == filter.FieldGroupId); } totalCount = query.Count(); return(query.OrderByDescending(x => x.DateCreated).Skip(filter.Skip).Take(filter.Take)); }
public ActionResult ListAjax(IDataTablesRequest request) { request = request ?? new DefaultDataTablesRequest(); var query = carService.GetAll(HttpContextStorage.CurrentUser.Id); var res = DynamicFilter.Execute <Car>(query, FilteringParametersHelper.GetFilteringParams(typeof(CarsListViewModel), request)); var model = Mapper.Map <IList <Car>, IList <CarsListViewModel> >(res.Items); return(Json(new DataTablesResponse(request.Draw, model, res.TotalFilteredRecords, res.TotalRecords), JsonRequestBehavior.AllowGet)); }
public void Apply(IPipeBuilder <TInput> builder) { var dynamicFilter = new DynamicFilter <TInput>(_pipeContextConverterFactory); var count = _specifications.Count; for (var index = 0; index < count; index++) { _specifications[index].Connect(dynamicFilter); } builder.AddFilter(dynamicFilter); }
private void UpdateFilter() { string criteria = cmbFilterBy.Text == "Any field" ? "*" : cmbFilterBy.Text; filter = DynamicFilter.Create <LogEntryViewModel>(criteria, txtFilter.Text); lstLog.ExtraFilter = item => filter.IsMatch(item); CollectionViewSource source = GetCollectionViewSource(); if (source.View != null) { source.View.Refresh(); } }
internal void FromDynamicFilter(DynamicFilter df) { this.SetAllNull(); this.Type = df.Type.Value; if (df.Val != null) { this.Val = df.Val.Value; } if (df.MaxVal != null) { this.MaxVal = df.MaxVal.Value; } }
public async Task ModelBinder_ShouldBindCorrect_WithSingleParameter() { using (var client = _factory.CreateClient()) { var query = new DynamicFilter { { "Page", "1" } }; var expectedJson = "{\"Page\":\"1\"}"; var responseJson = await client.GetStringAsync("/_api/Tests/query-string-as-object?" + string.Join('&', query.Select(s => $"{s.Key}={s.Value}"))); Assert.Equal(expectedJson, responseJson); } }
public IConsumePipe BuildConsumePipe() { var filter = new DynamicFilter <ConsumeContext, Guid>(new ConsumeContextConverterFactory(), GetRequestId); var builder = new PipeBuilder <ConsumeContext>(); foreach (IPipeSpecification <ConsumeContext> specification in _consumeContextSpecifications) { specification.Apply(builder); } builder.AddFilter(filter); return(new ConsumePipe(filter, builder.Build())); }
internal DynamicFilter ToDynamicFilter() { var df = new DynamicFilter(); df.Type = Type; if (Val != null) { df.Val = Val.Value; } if (MaxVal != null) { df.MaxVal = MaxVal.Value; } return(df); }
internal DynamicFilter ToDynamicFilter() { DynamicFilter df = new DynamicFilter(); df.Type = this.Type; if (this.Val != null) { df.Val = this.Val.Value; } if (this.MaxVal != null) { df.MaxVal = this.MaxVal.Value; } return(df); }
private void ApplyPopupFilter() { try { ExecuteUpdateActivities(); //if (PopupFilterDictContains(Constants.MainviewPopupList, DictFilterPopup)) //{ UserProjects = DynamicFilter.FilterDataTable(masterprojectlist, Constants.MainviewPopupList, DictFilterPopup); //} //else // UserProjects = masterprojectlist; } catch { } GetSumSales(); }
internal void FromFilterColumn(FilterColumn fc) { SetAllNull(); if (fc.Filters != null) { Filters.FromFilters(fc.Filters); HasFilters = true; } if (fc.Top10 != null) { Top10.FromTop10(fc.Top10); HasTop10 = true; } if (fc.CustomFilters != null) { CustomFilters.FromCustomFilters(fc.CustomFilters); HasCustomFilters = true; } if (fc.DynamicFilter != null) { DynamicFilter.FromDynamicFilter(fc.DynamicFilter); HasDynamicFilter = true; } if (fc.ColorFilter != null) { ColorFilter.FromColorFilter(fc.ColorFilter); HasColorFilter = true; } if (fc.IconFilter != null) { IconFilter.FromIconFilter(fc.IconFilter); HasIconFilter = true; } ColumnId = fc.ColumnId.Value; if ((fc.HiddenButton != null) && fc.HiddenButton.Value) { HiddenButton = fc.HiddenButton.Value; } if ((fc.ShowButton != null) && !fc.ShowButton.Value) { ShowButton = fc.ShowButton.Value; } }
public PagedCollection GetPagedAndFiltered(DynamicFilter filterDef) { if (filterDef == null) { throw new ArgumentNullException("filterDef"); } IQueryable <TEntity> items = !string.IsNullOrWhiteSpace(filterDef.Filtro) ? GetSet().Where(filterDef.Filtro, filterDef.Valores) : GetSet(); if (filterDef.Includes != null && filterDef.Includes.Any()) { // Adding Includes to filter. items = filterDef.Includes.Aggregate(items, (current, include) => current.Include(include)); } int totalItems = items.Count(); if (filterDef.PageSize != 0) { // adding sort ceiteria. if (filterDef.SortFields != null && filterDef.SortFields.Any()) { string orderKey = filterDef.Ascending ? "ASC" : "DESC"; var order = String.Join(" " + orderKey + ", ", filterDef.SortFields.ToArray()); if (!order.EndsWith(orderKey)) { order += " " + orderKey; } items = items.OrderBy(order); items = items.Skip(filterDef.PageSize * filterDef.PageIndex); } items = items.Take(filterDef.PageSize); } var pagedItems = items.ToList(); return(new PagedCollection(filterDef.PageIndex, filterDef.PageSize, pagedItems, totalItems, pagedItems.Count)); }
public Expression BuildExpression(Type entityType, Expression body) { Expression finalExpression = body; foreach (var key in this.Keys) { var filterValue = new DynamicFilter(this[key]); if (IsPrimitive(key)) { var targetProperty = entityType.GetProperty(key); var value = Convert.ChangeType((string)filterValue, targetProperty.PropertyType); var exp = OperatorComparisonAttribute.Equal.BuildExpression(body, targetProperty, filterProperty: null, value); var combined = finalExpression.Combine(exp, CombineWith); finalExpression = body.Combine(combined, CombineWith); } else { var splitted = key.Split('.'); if (IsNotInnerObject(splitted)) { var propName = splitted[0]; var targetProperty = entityType.GetProperty(propName); var value = Convert.ChangeType((string)filterValue, targetProperty.PropertyType); var comparisonKeyword = splitted[1]; if (specialKeywords.TryGetValue(comparisonKeyword, out IFilterableType filterable)) { var exp = filterable.BuildExpression(body, targetProperty, filterProperty: null, value); var combined = finalExpression.Combine(exp, CombineWith); finalExpression = body.Combine(combined, CombineWith); } } else { throw new NotImplementedException("Inner objects are not supported yet!"); } } } return(finalExpression); bool IsNotInnerObject(string[] splitted) => splitted.Length == 2; }
public GraphingForm() { InitializeComponent(); tickTimer = new System.Timers.Timer(); tickTimer.Interval = 1000; tickTimer.Elapsed += OnTimedEvent; tickTimer.AutoReset = true; tickTimer.Enabled = false; aBar = null; mainFilter = new SinFilter(); // filter = new ScalingFilter(); // df = new ScalingDynamicFilter(); filter = new StaticWrapperFilter(mainFilter); UpdateForm(); }
private void ApplyPopupFilter() { try { //if (PopupFilterDictContains(Constants.MasterProjectsPopupList, DictFilterPopup)) //{ // Dictionary<string, List<string>> locdictFilterPopup = new Dictionary<string, List<string>>(); // foreach(string s in Constants.MasterProjectsPopupList) // locdictFilterPopup.Add(s, DictFilterPopup[s].FilterData.Where(y => y.IsChecked == true).Select(x => x.Description).ToList<string>()); // var c1 = tempsalesfunnel.AsEnumerable() // .Where(row => locdictFilterPopup["SalesDivision"].Contains(row["SalesDivision"].ToString()) // && locdictFilterPopup["IndustrySegment"].Contains(row["IndustrySegment"].ToString()) // && locdictFilterPopup["KPM"].Contains(row["KPM"].ToString()) // && locdictFilterPopup["Customer"].Contains(row["Customer"].ToString()) // && locdictFilterPopup["UserName"].Contains(row["UserName"].ToString()) // && locdictFilterPopup["DifferentiatedTechnology"].Contains(row["DifferentiatedTechnology"].ToString()) // && locdictFilterPopup["Application"].Contains(row["Application"].ToString()) // && locdictFilterPopup["ProjectStatus"].Contains(row["ProjectStatus"].ToString()) // && locdictFilterPopup["ProjectType"].Contains(row["ProjectType"].ToString()) // && locdictFilterPopup["SMCode"].Contains(row["SMCode"].ToString()) // && locdictFilterPopup["SalesFunnelStage"].Contains(row["SalesFunnelStage"].ToString()) // ); // if (c1.Count() > 0) // { // DataTable tblFiltered = c1.CopyToDataTable(); // ReFormatColumns(ref tempsalesfunnel, ref tblFiltered); // SalesFunnel = tblFiltered; // } // else // SalesFunnel = tempsalesfunnel.Clone(); //} //else // SalesFunnel = tempsalesfunnel; SalesFunnel = DynamicFilter.FilterDataTable(tempsalesfunnel, Constants.MasterProjectsPopupList, DictFilterPopup); } catch { } }
internal FilterColumn ToFilterColumn() { var fc = new FilterColumn(); if (HasFilters) { fc.Filters = Filters.ToFilters(); } if (HasTop10) { fc.Top10 = Top10.ToTop10(); } if (HasCustomFilters) { fc.CustomFilters = CustomFilters.ToCustomFilters(); } if (HasDynamicFilter) { fc.DynamicFilter = DynamicFilter.ToDynamicFilter(); } if (HasColorFilter) { fc.ColorFilter = ColorFilter.ToColorFilter(); } if (HasIconFilter) { fc.IconFilter = IconFilter.ToIconFilter(); } fc.ColumnId = ColumnId; if ((HiddenButton != null) && HiddenButton.Value) { fc.HiddenButton = HiddenButton.Value; } if ((ShowButton != null) && !ShowButton.Value) { fc.ShowButton = ShowButton.Value; } return(fc); }
// Set the filter controls. protected void Label_PreRender(object sender, EventArgs e) { Label label = (Label)sender; // Customize the filter label in case of custom enumerator. if (label.Text == "OrderQty") { label.Text = "Custom Enumeration " + label.Text; } // Get the current filter control from the ones contained by // the QueryableFilterRepeater control. DynamicFilter dynamicFilter = (DynamicFilter)label.FindControl("DynamicFilter"); // Assign the label name for the current filter. QueryableFilterUserControl fuc = dynamicFilter.FilterTemplate as QueryableFilterUserControl; if (fuc != null && fuc.FilterControl != null) { label.AssociatedControlID = fuc.FilterControl.GetUniqueIDRelativeTo(label); } }
private static void PopulateAutoFilter(XLAutoFilter xlAutoFilter, AutoFilter autoFilter) { var filterRange = xlAutoFilter.Range; autoFilter.Reference = filterRange.RangeAddress.ToString(); foreach (var kp in xlAutoFilter.Filters) { var filterColumn = new FilterColumn {ColumnId = (UInt32)kp.Key - 1}; var xlFilterColumn = xlAutoFilter.Column(kp.Key); var filterType = xlFilterColumn.FilterType; if (filterType == XLFilterType.Custom) { var customFilters = new CustomFilters(); foreach (var filter in kp.Value) { var customFilter = new CustomFilter {Val = filter.Value.ToString()}; if (filter.Operator != XLFilterOperator.Equal) customFilter.Operator = filter.Operator.ToOpenXml(); if (filter.Connector == XLConnector.And) customFilters.And = true; customFilters.Append(customFilter); } filterColumn.Append(customFilters); } else if (filterType == XLFilterType.TopBottom) { var top101 = new Top10 {Val = (double)xlFilterColumn.TopBottomValue}; if (xlFilterColumn.TopBottomType == XLTopBottomType.Percent) top101.Percent = true; if (xlFilterColumn.TopBottomPart == XLTopBottomPart.Bottom) top101.Top = false; filterColumn.Append(top101); } else if (filterType == XLFilterType.Dynamic) { var dynamicFilter = new DynamicFilter {Type = xlFilterColumn.DynamicType.ToOpenXml(), Val = xlFilterColumn.DynamicValue}; filterColumn.Append(dynamicFilter); } else { var filters = new Filters(); foreach (var filter in kp.Value) { filters.Append(new Filter {Val = filter.Value.ToString()}); } filterColumn.Append(filters); } autoFilter.Append(filterColumn); } if (xlAutoFilter.Sorted) { var sortState = new SortState { Reference = filterRange.Range(filterRange.FirstCell().CellBelow(), filterRange.LastCell()).RangeAddress. ToString() }; var sortCondition = new SortCondition { Reference = filterRange.Range(1, xlAutoFilter.SortColumn, filterRange.RowCount(), xlAutoFilter.SortColumn).RangeAddress.ToString() }; if (xlAutoFilter.SortOrder == XLSortOrder.Descending) sortCondition.Descending = true; sortState.Append(sortCondition); autoFilter.Append(sortState); } }