Commit 457f108c authored by thienvo's avatar thienvo

add 2 project sieve and log

parents
# This is the Roslyn .EditorConfig
# top-most EditorConfig file
root = true
# Don't use tabs for indentation.
[*]
indent_style = space
# (Please don't specify an indent_size here; that has too many unintended consequences.)
# Code files
[*.{cs,csx,vb,vbx}]
indent_size = 4
insert_final_newline = true
charset = utf-8-bom
# Xml project files
[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
indent_size = 2
# Xml config files
[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
indent_size = 2
# JSON files
[*.json]
indent_size = 2
# Dotnet code style settings:
[*.{cs,vb}]
# Sort using and Import directives with System.* appearing first
dotnet_sort_system_directives_first = true
# Avoid "this." and "Me." if not necessary
dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
dotnet_style_qualification_for_method = false:suggestion
dotnet_style_qualification_for_event = false:suggestion
# Use language keywords instead of framework type names for type references
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion
# Suggest more modern language features when available
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
# CSharp code style settings:
[*.cs]
# Prefer "var" everywhere
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = true:suggestion
# Prefer method-like constructs to have a block body
csharp_style_expression_bodied_methods = false:none
csharp_style_expression_bodied_constructors = false:none
csharp_style_expression_bodied_operators = false:none
# Prefer property-like constructs to have an expression-body
csharp_style_expression_bodied_properties = true:none
csharp_style_expression_bodied_indexers = true:none
csharp_style_expression_bodied_accessors = true:none
# Suggest more modern language features when available
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_conditional_delegate_call = true:suggestion
# Newline settings
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
publishing_to_nuget.md
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
project.fragment.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
#*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
\ No newline at end of file
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at Biarity@outlook.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# Sieve
⚗️ Sieve is a simple, clean, and extensible framework for .NET Core that **adds sorting, filtering, and pagination functionality out of the box**.
Most common use case would be for serving ASP.NET Core GET queries.
[![NuGet Release](https://img.shields.io/nuget/v/Sieve.svg?style=flat-square)](https://www.nuget.org/packages/Sieve)
[Get Sieve on nuget](https://www.nuget.org/packages/Sieve/)
## Usage for ASP.NET Core
In this example, consider an app with a `Post` entity.
We'll use Sieve to add sorting, filtering, and pagination capabilities when GET-ing all available posts.
### 1. Add required services
Inject the `SieveProcessor` service. So in `Startup.cs` add:
```C#
services.AddScoped<SieveProcessor>();
```
### 2. Tell Sieve which properties you'd like to sort/filter in your models
Sieve will only sort/filter properties that have the attribute `[Sieve(CanSort = true, CanFilter = true)]` on them (they don't have to be both true).
So for our `Post` entity model example:
```C#
public int Id { get; set; }
[Sieve(CanFilter = true, CanSort = true)]
public string Title { get; set; }
[Sieve(CanFilter = true, CanSort = true)]
public int LikeCount { get; set; }
[Sieve(CanFilter = true, CanSort = true)]
public int CommentCount { get; set; }
[Sieve(CanFilter = true, CanSort = true, Name = "created")]
public DateTimeOffset DateCreated { get; set; } = DateTimeOffset.UtcNow;
```
There is also the `Name` parameter that you can use to have a different name for use by clients.
Alternatively, you can use [Fluent API](#fluent-api) to do the same. This is especially useful if you don't want to use attributes or have multiple APIs.
### 3. Get sort/filter/page queries by using the Sieve model in your controllers
In the action that handles returning Posts, use `SieveModel` to get the sort/filter/page query.
Apply it to your data by injecting `SieveProcessor` into the controller and using its `Apply<TEntity>` method. So for instance:
```C#
[HttpGet]
public JsonResult GetPosts(SieveModel sieveModel)
{
var result = _dbContext.Posts.AsNoTracking(); // Makes read-only queries faster
result = _sieveProcessor.Apply(sieveModel, result); // Returns `result` after applying the sort/filter/page query in `SieveModel` to it
return Json(result.ToList());
}
```
You can also explicitly specify if only filtering, sorting, and/or pagination should be applied via optional arguments.
### 4. Send a request
[Send a request](#send-a-request)
### Add custom sort/filter methods
If you want to add custom sort/filter methods, inject `ISieveCustomSortMethods` or `ISieveCustomFilterMethods` with the implementation being a class that has custom sort/filter methods that Sieve will search through.
For instance:
```C#
services.AddScoped<ISieveCustomSortMethods, SieveCustomSortMethods>();
services.AddScoped<ISieveCustomFilterMethods, SieveCustomFilterMethods>();
```
Where `SieveCustomSortMethodsOfPosts` for example is:
```C#
public class SieveCustomSortMethods : ISieveCustomSortMethods
{
public IQueryable<Post> Popularity(IQueryable<Post> source, bool useThenBy, bool desc) // The method is given an indicator of weather to use ThenBy(), and if the query is descending
{
var result = useThenBy ?
((IOrderedQueryable<Post>)source).ThenBy(p => p.LikeCount) : // ThenBy only works on IOrderedQueryable<TEntity>
source.OrderBy(p => p.LikeCount)
.ThenBy(p => p.CommentCount)
.ThenBy(p => p.DateCreated);
return result; // Must return modified IQueryable<TEntity>
}
public IQueryable<T> Oldest<T>(IQueryable<T> source, bool useThenBy, bool desc) where T : BaseEntity // Generic functions are allowed too
{
var result = useThenBy ?
((IOrderedQueryable<T>)source).ThenByDescending(p => p.DateCreated) :
source.OrderByDescending(p => p.DateCreated);
return result;
}
}
```
And `SieveCustomFilterMethods`:
```C#
public class SieveCustomFilterMethods : ISieveCustomFilterMethods
{
public IQueryable<Post> IsNew(IQueryable<Post> source, string op, string[] values) // The method is given the {Operator} & {Value}
{
var result = source.Where(p => p.LikeCount < 100 &&
p.CommentCount < 5);
return result; // Must return modified IQueryable<TEntity>
}
public IQueryable<T> Latest<T>(IQueryable<T> source, string op, string[] values) where T : BaseEntity // Generic functions are allowed too
{
var result = source.Where(c => c.DateCreated > DateTimeOffset.UtcNow.AddDays(-14));
return result;
}
}
```
## Configure Sieve
Use the [ASP.NET Core options pattern](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options) with `SieveOptions` to tell Sieve where to look for configuration. For example:
```C#
services.Configure<SieveOptions>(Configuration.GetSection("Sieve"));
```
Then you can add the configuration:
```json
{
"Sieve": {
"CaseSensitive": "boolean: should property names be case-sensitive? Defaults to false",
"DefaultPageSize": "int number: optional number to fallback to when no page argument is given. Set <=0 to disable paging if no pageSize is specified (default).",
"MaxPageSize": "int number: maximum allowed page size. Set <=0 to make infinite (default)",
"ThrowExceptions": "boolean: should Sieve throw exceptions instead of silently failing? Defaults to false"
}
}
```
## Send a request
With all the above in place, you can now send a GET request that includes a sort/filter/page query.
An example:
```curl
GET /GetPosts
?sorts= LikeCount,CommentCount,-created // sort by likes, then comments, then descendingly by date created
&filters= LikeCount>10, Title@=awesome title, // filter to posts with more than 10 likes, and a title that contains the phrase "awesome title"
&page= 1 // get the first page...
&pageSize= 10 // ...which contains 10 posts
```
More formally:
* `sorts` is a comma-delimited ordered list of property names to sort by. Adding a `-` before the name switches to sorting descendingly.
* `filters` is a comma-delimited list of `{Name}{Operator}{Value}` where
* `{Name}` is the name of a property with the Sieve attribute or the name of a custom filter method for TEntity
* You can also have multiple names (for OR logic) by enclosing them in brackets and using a pipe delimiter, eg. `(LikeCount|CommentCount)>10` asks if `LikeCount` or `CommentCount` is `>10`
* `{Operator}` is one of the [Operators](#operators)
* `{Value}` is the value to use for filtering
* You can also have multiple values (for OR logic) by using a pipe delimiter, eg. `Title@=new|hot` will return posts with titles that contain the text "`new`" or "`hot`"
* `page` is the number of page to return
* `pageSize` is the number of items returned per page
Notes:
* You can use backslashes to escape commas and pipes within value fields
* You can have spaces anywhere except *within* `{Name}` or `{Operator}` fields
* If you need to look at the data before applying pagination (eg. get total count), use the optional paramters on `Apply` to defer pagination (an [example](https://github.com/Biarity/Sieve/issues/34))
* Here's a [good example on how to work with enumerables](https://github.com/Biarity/Sieve/issues/2)
* Another example on [how to do OR logic](https://github.com/Biarity/Sieve/issues/8)
### Nested objects
You can filter/sort on a nested object's property by marking the property using the Fluent API.
Marking via attributes not currently supported.
For example, using this object model:
```C#
public class Post {
public User Creator { get; set; }
}
public class User {
public string Name { get; set; }
}
```
Mark `Post.User` to be filterable:
```C#
// in MapProperties
mapper.Property<Post>(p => p.Creator.Name)
.CanFilter();
```
Now you can make requests such as: `filters=User.Name==specific_name`.
### Creating your own DSL
You can replace this DSL with your own (eg. use JSON instead) by implementing an [ISieveModel](https://github.com/Biarity/Sieve/blob/master/Sieve/Models/ISieveModel.cs). You can use the default [SieveModel](https://github.com/Biarity/Sieve/blob/master/Sieve/Models/SieveModel.cs) for reference.
### Operators
| Operator | Meaning |
|------------|--------------------------|
| `==` | Equals |
| `!=` | Not equals |
| `>` | Greater than |
| `<` | Less than |
| `>=` | Greater than or equal to |
| `<=` | Less than or equal to |
| `@=` | Contains |
| `_=` | Starts with |
| `!@=` | Does not Contains |
| `!_=` | Does not Starts with |
| `@=*` | Case-insensitive string Contains |
| `_=*` | Case-insensitive string Starts with |
| `==*` | Case-insensitive string Equals |
| `!=*` | Case-insensitive string Not equals |
| `!@=*` | Case-insensitive string does not Contains |
| `!_=*` | Case-insensitive string does not Starts with |
### Handle Sieve's exceptions
Sieve will silently fail unless `ThrowExceptions` in the configuration is set to true. 3 kinds of custom exceptions can be thrown:
* `SieveMethodNotFoundException` with a `MethodName`
* `SieveIncompatibleMethodException` with a `MethodName`, an `ExpectedType` and an `ActualType`
* `SieveException` which encapsulates any other exception types in its `InnerException`
It is recommended that you write exception-handling middleware to globally handle Sieve's exceptions when using it with ASP.NET Core.
### Example project
You can find an example project incorporating most Sieve concepts in [SieveTests](https://github.com/Biarity/Sieve/tree/master/SieveTests).
## Fluent API
To use the Fluent API instead of attributes in marking properties, setup an alternative `SieveProcessor` that overrides `MapProperties`. For example:
```C#
public class ApplicationSieveProcessor : SieveProcessor
{
public ApplicationSieveProcessor(
IOptions<SieveOptions> options,
ISieveCustomSortMethods customSortMethods,
ISieveCustomFilterMethods customFilterMethods)
: base(options, customSortMethods, customFilterMethods)
{
}
protected override SievePropertyMapper MapProperties(SievePropertyMapper mapper)
{
mapper.Property<Post>(p => p.Title)
.CanFilter()
.HasName("a_different_query_name_here");
mapper.Property<Post>(p => p.CommentCount)
.CanSort();
mapper.Property<Post>(p => p.DateCreated)
.CanSort()
.CanFilter()
.HasName("created_on");
return mapper;
}
}
```
Now you should inject the new class instead:
```C#
services.AddScoped<ISieveProcessor, ApplicationSieveProcessor>();
```
Find More on Sieve's Fluent API [here](https://github.com/Biarity/Sieve/issues/4#issuecomment-364629048).
## Upgrading to v2.2.0
2.2.0 introduced OR logic for filter values. This means your custom filters will need to accept multiple values rather than just the one.
* In all your custom filter methods, change the last argument to be a `string[] values` instead of `string value`
* The first value can then be found to be `values[0]` rather than `value`
* Multiple values will be present if the client uses OR logic
## Upgrading from v1.* to v2.*
* Changes to the `SieveProcessor` API:
* `ApplyAll` is now `Apply`
* `ApplyFiltering`, `ApplySorting`, and `ApplyPagination` are now depricated - instead you can use optional arguments on `Apply` to achieve the same
* Instead of just removing commas from `{Value}`s, [you'll also need to remove brackets and pipes](#send-a-request)
## License & Contributing
Sieve is licensed under Apache 2.0. Any contributions highly appreciated!

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2027
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sieve", "Sieve\Sieve.csproj", "{B32B8B33-94B0-40E3-8FE5-D54602222717}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SieveTests", "SieveTests\SieveTests.csproj", "{8043D264-42A0-4275-97A1-46400C02E37E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SieveUnitTests", "SieveUnitTests\SieveUnitTests.csproj", "{21C3082D-F40E-457F-BE2E-AA099E19E199}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{904F25A9-5CBD-42AE-8422-ADAB98F4B4B7}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
README.md = README.md
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B32B8B33-94B0-40E3-8FE5-D54602222717}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B32B8B33-94B0-40E3-8FE5-D54602222717}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B32B8B33-94B0-40E3-8FE5-D54602222717}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B32B8B33-94B0-40E3-8FE5-D54602222717}.Release|Any CPU.Build.0 = Release|Any CPU
{8043D264-42A0-4275-97A1-46400C02E37E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8043D264-42A0-4275-97A1-46400C02E37E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8043D264-42A0-4275-97A1-46400C02E37E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8043D264-42A0-4275-97A1-46400C02E37E}.Release|Any CPU.Build.0 = Release|Any CPU
{21C3082D-F40E-457F-BE2E-AA099E19E199}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{21C3082D-F40E-457F-BE2E-AA099E19E199}.Debug|Any CPU.Build.0 = Debug|Any CPU
{21C3082D-F40E-457F-BE2E-AA099E19E199}.Release|Any CPU.ActiveCfg = Release|Any CPU
{21C3082D-F40E-457F-BE2E-AA099E19E199}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6D7C2175-439A-434B-94C1-C819129D948E}
EndGlobalSection
EndGlobal
using System;
using Sieve.Models;
namespace Sieve.Attributes
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SieveAttribute : Attribute, ISievePropertyMetadata
{
/// <summary>
/// Override name used
/// </summary>
public string Name { get; set; }
public string FullName => Name;
public bool CanSort { get; set; }
public bool CanFilter { get; set; }
}
}
using System;
namespace Sieve.Exceptions
{
public class SieveException : Exception
{
public SieveException(string message) : base(message)
{
}
public SieveException(string message, Exception innerException) : base(message, innerException)
{
}
public SieveException()
{
}
protected SieveException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)
{
}
}
}
using System;
namespace Sieve.Exceptions
{
public class SieveIncompatibleMethodException : SieveException
{
public string MethodName { get; protected set; }
public Type ExpectedType { get; protected set; }
public Type ActualType { get; protected set; }
public SieveIncompatibleMethodException(
string methodName,
Type expectedType,
Type actualType,
string message)
: base(message)
{
MethodName = methodName;
ExpectedType = expectedType;
ActualType = actualType;
}
public SieveIncompatibleMethodException(
string methodName,
Type expectedType,
Type actualType,
string message,
Exception innerException)
: base(message, innerException)
{
MethodName = methodName;
ExpectedType = expectedType;
ActualType = actualType;
}
public SieveIncompatibleMethodException(string message) : base(message)
{
}
public SieveIncompatibleMethodException(string message, Exception innerException) : base(message, innerException)
{
}
public SieveIncompatibleMethodException()
{
}
protected SieveIncompatibleMethodException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)
{
}
}
}
using System;
namespace Sieve.Exceptions
{
public class SieveMethodNotFoundException : SieveException
{
public string MethodName { get; protected set; }
public SieveMethodNotFoundException(string methodName, string message) : base(message)
{
MethodName = methodName;
}
public SieveMethodNotFoundException(string methodName, string message, Exception innerException) : base(message, innerException)
{
MethodName = methodName;
}
public SieveMethodNotFoundException(string message) : base(message)
{
}
public SieveMethodNotFoundException(string message, Exception innerException) : base(message, innerException)
{
}
public SieveMethodNotFoundException()
{
}
protected SieveMethodNotFoundException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)
{
}
}
}
using System;
using System.Reflection;
namespace Sieve.Extensions
{
// The default GetMethod doesn't allow for generic methods which means
// custom filters for different sources can't share the same name.
// https://stackoverflow.com/questions/4035719/getmethod-for-generic-method
public static partial class MethodInfoExtended
{
/// <summary>
/// Search for a method by name and parameter types.
/// Unlike GetMethod(), does 'loose' matching on generic
/// parameter types, and searches base interfaces.
/// </summary>
/// <exception cref="AmbiguousMatchException"/>
public static MethodInfo GetMethodExt(this Type thisType,
string name,
Type firstType)
{
return GetMethodExt(thisType,
name,
BindingFlags.Instance
| BindingFlags.Static
| BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.FlattenHierarchy,
firstType);
}
/// <summary>
/// Search for a method by name, parameter types, and binding flags.
/// Unlike GetMethod(), does 'loose' matching on generic
/// parameter types, and searches base interfaces.
/// </summary>
/// <exception cref="AmbiguousMatchException"/>
public static MethodInfo GetMethodExt(this Type thisType,
string name,
BindingFlags bindingFlags,
Type firstType)
{
MethodInfo matchingMethod = null;
// Check all methods with the specified name, including in base classes
GetMethodExt(ref matchingMethod, thisType, name, bindingFlags, firstType);
// If we're searching an interface, we have to manually search base interfaces
if (matchingMethod == null && thisType.IsInterface)
{
foreach (Type interfaceType in thisType.GetInterfaces())
GetMethodExt(ref matchingMethod,
interfaceType,
name,
bindingFlags,
firstType);
}
return matchingMethod;
}
private static void GetMethodExt(ref MethodInfo matchingMethod,
Type type,
string name,
BindingFlags bindingFlags,
Type firstType)
{
// Check all methods with the specified name, including in base classes
foreach (MethodInfo methodInfo in type.GetMember(name,
MemberTypes.Method,
bindingFlags))
{
// Check that the parameter counts and types match,
// with 'loose' matching on generic parameters
ParameterInfo[] parameterInfos = methodInfo.GetParameters();
if (parameterInfos[0].ParameterType.IsSimilarType(firstType))
{
if (matchingMethod == null)
matchingMethod = methodInfo;
else
throw new AmbiguousMatchException(
"More than one matching method found!");
}
}
}
/// <summary>
/// Special type used to match any generic parameter type in GetMethodExt().
/// </summary>
public class T
{ }
/// <summary>
/// Determines if the two types are either identical, or are both generic
/// parameters or generic types with generic parameters in the same
/// locations (generic parameters match any other generic paramter,
/// but NOT concrete types).
/// </summary>
private static bool IsSimilarType(this Type thisType, Type type)
{
// Ignore any 'ref' types
if (thisType.IsByRef)
thisType = thisType.GetElementType();
if (type.IsByRef)
type = type.GetElementType();
// Handle array types
if (thisType.IsArray && type.IsArray)
return thisType.GetElementType().IsSimilarType(type.GetElementType());
// If the types are identical, or they're both generic parameters
// or the special 'T' type, treat as a match
if (thisType == type || ((thisType.IsGenericParameter || thisType == typeof(T))
&& (type.IsGenericParameter || type == typeof(T))))
return true;
// Handle any generic arguments
if (thisType.IsGenericType && type.IsGenericType)
{
Type[] thisArguments = thisType.GetGenericArguments();
Type[] arguments = type.GetGenericArguments();
if (thisArguments.Length == arguments.Length)
{
for (int i = 0; i < thisArguments.Length; ++i)
{
if (!thisArguments[i].IsSimilarType(arguments[i]))
return false;
}
return true;
}
}
return false;
}
}
}
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Sieve.Extensions
{
public static partial class LinqExtentions
{
public static IQueryable<TEntity> OrderByDynamic<TEntity>(this IQueryable<TEntity> source, string fullPropertyName, PropertyInfo propertyInfo,
bool desc, bool useThenBy)
{
string command = desc ?
(useThenBy ? "ThenByDescending" : "OrderByDescending") :
(useThenBy ? "ThenBy" : "OrderBy");
var type = typeof(TEntity);
var parameter = Expression.Parameter(type, "p");
dynamic propertyValue = parameter;
if (fullPropertyName.Contains("."))
{
var parts = fullPropertyName.Split('.');
for (var i = 0; i < parts.Length - 1; i++)
{
propertyValue = Expression.PropertyOrField(propertyValue, parts[i]);
}
}
var propertyAccess = Expression.MakeMemberAccess(propertyValue, propertyInfo);
var orderByExpression = Expression.Lambda(propertyAccess, parameter);
var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, propertyInfo.PropertyType },
source.Expression, Expression.Quote(orderByExpression));
return source.Provider.CreateQuery<TEntity>(resultExpression);
}
}
}
namespace Sieve.Models
{
public enum FilterOperator
{
Equals,
NotEquals,
GreaterThan,
LessThan,
GreaterThanOrEqualTo,
LessThanOrEqualTo,
Contains,
StartsWith,
}
}
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace Sieve.Models
{
public class FilterTerm : IFilterTerm, IEquatable<FilterTerm>
{
public FilterTerm() { }
private const string EscapedPipePattern = @"(?<!($|[^\\])(\\\\)*?\\)\|";
private static readonly string[] Operators = new string[] {
"!@=*",
"!_=*",
"!=*",
"!@=",
"!_=",
"==*",
"@=*",
"_=*",
"==",
"!=",
">=",
"<=",
">",
"<",
"@=",
"_="
};
public string Filter
{
set
{
var filterSplits = value.Split(Operators, StringSplitOptions.RemoveEmptyEntries)
.Select(t => t.Trim()).ToArray();
Names = Regex.Split(filterSplits[0], EscapedPipePattern).Select(t => t.Trim()).ToArray();
Values = filterSplits.Length > 1 ? Regex.Split(filterSplits[1], EscapedPipePattern).Select(t => t.Trim()).ToArray() : null;
Operator = Array.Find(Operators, o => value.Contains(o)) ?? "==";
OperatorParsed = GetOperatorParsed(Operator);
OperatorIsCaseInsensitive = Operator.EndsWith("*");
OperatorIsNegated = OperatorParsed != FilterOperator.NotEquals && Operator.StartsWith("!");
}
}
public string[] Names { get; private set; }
public FilterOperator OperatorParsed { get; private set; }
public string[] Values { get; private set; }
public string Operator { get; private set; }
private FilterOperator GetOperatorParsed(string @operator)
{
switch (@operator.TrimEnd('*'))
{
case "==":
return FilterOperator.Equals;
case "!=":
return FilterOperator.NotEquals;
case "<":
return FilterOperator.LessThan;
case ">":
return FilterOperator.GreaterThan;
case ">=":
return FilterOperator.GreaterThanOrEqualTo;
case "<=":
return FilterOperator.LessThanOrEqualTo;
case "@=":
case "!@=":
return FilterOperator.Contains;
case "_=":
case "!_=":
return FilterOperator.StartsWith;
default:
return FilterOperator.Equals;
}
}
public bool OperatorIsCaseInsensitive { get; private set; }
public bool OperatorIsNegated { get; private set; }
public bool Equals(FilterTerm other)
{
return Names.SequenceEqual(other.Names)
&& Values.SequenceEqual(other.Values)
&& Operator == other.Operator;
}
}
}
namespace Sieve.Models
{
public interface IFilterTerm
{
string Filter { set; }
string[] Names { get; }
string Operator { get; }
bool OperatorIsCaseInsensitive { get; }
bool OperatorIsNegated { get; }
FilterOperator OperatorParsed { get; }
string[] Values { get; }
}
}
using System.Collections.Generic;
namespace Sieve.Models
{
public interface ISieveModel : ISieveModel<IFilterTerm, ISortTerm>
{
}
public interface ISieveModel<TFilterTerm, TSortTerm>
where TFilterTerm : IFilterTerm
where TSortTerm : ISortTerm
{
string Filters { get; set; }
string Sorts { get; set; }
int? Page { get; set; }
int? PageSize { get; set; }
List<TFilterTerm> GetFiltersParsed();
List<TSortTerm> GetSortsParsed();
}
}
namespace Sieve.Models
{
public interface ISievePropertyMetadata
{
string Name { get; set; }
string FullName { get; }
bool CanFilter { get; set; }
bool CanSort { get; set; }
}
}
namespace Sieve.Models
{
public interface ISortTerm
{
string Sort { set; }
bool Descending { get; }
string Name { get; }
}
}
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
namespace Sieve.Models
{
public class SieveModel : SieveModel<FilterTerm, SortTerm> { }
[DataContract]
public class SieveModel<TFilterTerm, TSortTerm> : ISieveModel<TFilterTerm, TSortTerm>
where TFilterTerm : IFilterTerm, new()
where TSortTerm : ISortTerm, new()
{
private const string EscapedCommaPattern = @"(?<!($|[^\\])(\\\\)*?\\),";
[DataMember]
public string Filters { get; set; }
[DataMember]
public string Sorts { get; set; }
[DataMember, Range(1, int.MaxValue)]
public int? Page { get; set; }
[DataMember, Range(1, int.MaxValue)]
public int? PageSize { get; set; }
public List<TFilterTerm> GetFiltersParsed()
{
if (Filters != null)
{
var value = new List<TFilterTerm>();
foreach (var filter in Regex.Split(Filters, EscapedCommaPattern))
{
if (string.IsNullOrWhiteSpace(filter)) continue;
if (filter.StartsWith("("))
{
var filterOpAndVal = filter.Substring(filter.LastIndexOf(")") + 1);
var subfilters = filter.Replace(filterOpAndVal, "").Replace("(", "").Replace(")", "");
var filterTerm = new TFilterTerm
{
Filter = subfilters + filterOpAndVal
};
if (!value.Any(f => f.Names.Any(n => filterTerm.Names.Any(n2 => n2 == n))))
{
value.Add(filterTerm);
}
}
else
{
var filterTerm = new TFilterTerm
{
Filter = filter
};
value.Add(filterTerm);
}
}
return value;
}
else
{
return null;
}
}
public List<TSortTerm> GetSortsParsed()
{
if (Sorts != null)
{
var value = new List<TSortTerm>();
foreach (var sort in Regex.Split(Sorts, EscapedCommaPattern))
{
if (string.IsNullOrWhiteSpace(sort)) continue;
var sortTerm = new TSortTerm()
{
Sort = sort
};
if (!value.Any(s => s.Name == sortTerm.Name))
{
value.Add(sortTerm);
}
}
return value;
}
else
{
return null;
}
}
}
}
namespace Sieve.Models
{
public class SieveOptions
{
public bool CaseSensitive { get; set; } = false;
public int DefaultPageSize { get; set; } = 0;
public int MaxPageSize { get; set; } = 0;
public bool ThrowExceptions { get; set; } = false;
}
}
\ No newline at end of file
namespace Sieve.Models
{
public class SievePropertyMetadata : ISievePropertyMetadata
{
public string Name { get; set; }
public string FullName { get; set; }
public bool CanFilter { get; set; }
public bool CanSort { get; set; }
}
}
using System;
namespace Sieve.Models
{
public class SortTerm : ISortTerm, IEquatable<SortTerm>
{
public SortTerm() { }
private string _sort;
public string Sort
{
set
{
_sort = value;
}
}
public string Name => (_sort.StartsWith("-")) ? _sort.Substring(1) : _sort;
public bool Descending => _sort.StartsWith("-");
public bool Equals(SortTerm other)
{
return Name == other.Name
&& Descending == other.Descending;
}
}
}
namespace Sieve.Services
{
public interface ISieveCustomFilterMethods
{
}
}
namespace Sieve.Services
{
public interface ISieveCustomSortMethods
{
}
}
using System.Linq;
using Sieve.Models;
namespace Sieve.Services
{
public interface ISieveProcessor : ISieveProcessor<SieveModel, FilterTerm, SortTerm>
{
}
public interface ISieveProcessor<TFilterTerm, TSortTerm> : ISieveProcessor<SieveModel<TFilterTerm, TSortTerm>, TFilterTerm, TSortTerm>
where TFilterTerm : IFilterTerm, new()
where TSortTerm : ISortTerm, new()
{
}
public interface ISieveProcessor<TSieveModel, TFilterTerm, TSortTerm>
where TSieveModel : class, ISieveModel<TFilterTerm, TSortTerm>
where TFilterTerm : IFilterTerm, new()
where TSortTerm : ISortTerm, new()
{
IQueryable<TEntity> Apply<TEntity>(
TSieveModel model,
IQueryable<TEntity> source,
object[] dataForCustomMethods = null,
bool applyFiltering = true,
bool applySorting = true,
bool applyPagination = true);
}
}
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;
}
}
}
private IQueryable<TEntity> ApplyFiltering<TEntity>(
TSieveModel model,
IQueryable<TEntity> result,
object[] dataForCustomMethods = null,
bool bCaseSensitive=false)
{
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;
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);
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);
}
}
}
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);
}
return outerExpression == null
? result
: result.Where(Expression.Lambda<Func<TEntity, bool>>(outerExpression, parameterExpression));
}
private static Expression GetExpression(TFilterTerm filterTerm, dynamic filterValue, dynamic propertyValue, bool bCaseSensitive)
{
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:
return Expression.Call(propertyValue,
typeof(string).GetMethods()
.First(m => m.Name == "Contains" && m.GetParameters().Length == 1),
filterValue);
case FilterOperator.StartsWith:
return Expression.Call(propertyValue,
typeof(string).GetMethods()
.First(m => m.Name == "StartsWith" && m.GetParameters().Length == 1),
filterValue);
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[]
{
result,
useThenBy,
sortTerm.Descending
}, dataForCustomMethods);
}
useThenBy = true;
}
return result;
}
private IQueryable<TEntity> ApplyPagination<TEntity>(
TSieveModel model,
IQueryable<TEntity> result)
{
var page = model?.Page ?? 1;
var pageSize = model?.PageSize ?? _options.Value.DefaultPageSize;
var maxPageSize = _options.Value.MaxPageSize > 0 ? _options.Value.MaxPageSize : pageSize;
if (pageSize > 0)
{
result = result.Skip((page - 1) * pageSize);
result = result.Take(Math.Min(pageSize, maxPageSize));
}
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;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Sieve.Models;
namespace Sieve.Services
{
public class SievePropertyMapper
{
private readonly Dictionary<Type, ICollection<KeyValuePair<PropertyInfo, ISievePropertyMetadata>>> _map
= new Dictionary<Type, ICollection<KeyValuePair<PropertyInfo, ISievePropertyMetadata>>>();
public PropertyFluentApi<TEntity> Property<TEntity>(Expression<Func<TEntity, object>> expression)
{
if (!_map.ContainsKey(typeof(TEntity)))
{
_map.Add(typeof(TEntity), new List<KeyValuePair<PropertyInfo, ISievePropertyMetadata>>());
}
return new PropertyFluentApi<TEntity>(this, expression);
}
public class PropertyFluentApi<TEntity>
{
private readonly SievePropertyMapper _sievePropertyMapper;
private readonly PropertyInfo _property;
public PropertyFluentApi(SievePropertyMapper sievePropertyMapper, Expression<Func<TEntity, object>> expression)
{
_sievePropertyMapper = sievePropertyMapper;
(_fullName, _property) = GetPropertyInfo(expression);
_name = _fullName;
_canFilter = false;
_canSort = false;
}
private string _name;
private readonly string _fullName;
private bool _canFilter;
private bool _canSort;
public PropertyFluentApi<TEntity> CanFilter()
{
_canFilter = true;
UpdateMap();
return this;
}
public PropertyFluentApi<TEntity> CanSort()
{
_canSort = true;
UpdateMap();
return this;
}
public PropertyFluentApi<TEntity> HasName(string name)
{
_name = name;
UpdateMap();
return this;
}
private void UpdateMap()
{
var metadata = new SievePropertyMetadata()
{
Name = _name,
FullName = _fullName,
CanFilter = _canFilter,
CanSort = _canSort
};
var pair = new KeyValuePair<PropertyInfo, ISievePropertyMetadata>(_property, metadata);
_sievePropertyMapper._map[typeof(TEntity)].Add(pair);
}
private static (string, PropertyInfo) GetPropertyInfo(Expression<Func<TEntity, object>> exp)
{
if (!(exp.Body is MemberExpression body))
{
var ubody = (UnaryExpression)exp.Body;
body = ubody.Operand as MemberExpression;
}
var member = body?.Member as PropertyInfo;
var stack = new Stack<string>();
while (body != null)
{
stack.Push(body.Member.Name);
body = body.Expression as MemberExpression;
}
return (string.Join(".", stack.ToArray()), member);
}
}
public (string, PropertyInfo) FindProperty<TEntity>(
bool canSortRequired,
bool canFilterRequired,
string name,
bool isCaseSensitive)
{
try
{
var result = _map[typeof(TEntity)]
.FirstOrDefault(kv =>
kv.Value.Name.Equals(name, isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)
&& (!canSortRequired || kv.Value.CanSort)
&& (!canFilterRequired || kv.Value.CanFilter));
return (result.Value?.FullName, result.Key);
}
catch (Exception ex) when (ex is KeyNotFoundException || ex is ArgumentNullException)
{
return (null, null);
}
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Version>2.3.3</Version>
<Description>Sieve is a simple, clean, and extensible framework for .NET Core that adds sorting, filtering, and pagination functionality out of the box. Most common use case would be for serving ASP.NET Core GET queries. Documentation available on GitHub: https://github.com/Biarity/Sieve/
</Description>
<Copyright>Copyright 2018</Copyright>
<PackageLicenseUrl>https://github.com/Biarity/Sieve/blob/master/LICENSE</PackageLicenseUrl>
<PackageProjectUrl>https://github.com/Biarity/Sieve</PackageProjectUrl>
<PackageIconUrl>https://emojipedia-us.s3.amazonaws.com/thumbs/240/twitter/120/alembic_2697.png</PackageIconUrl>
<RepositoryUrl></RepositoryUrl>
<PackageReleaseNotes>Only Skip when pageSize &gt; 0 (#63)
Added support for generic filter and sort methods (#60)
Don't process when filterTerm.Values is null (#59)
</PackageReleaseNotes>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<Authors>Biarity</Authors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CSharp" Version="4.4.1" />
<PackageReference Include="Microsoft.Extensions.Options" Version="2.0.0" />
<PackageReference Include="Microsoft.NetCore.Analyzers" Version="2.9.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="System.ComponentModel.Annotations" Version="4.4.1" />
</ItemGroup>
</Project>
File added
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Sieve.Models;
using Sieve.Services;
using SieveTests.Entities;
namespace SieveTests.Controllers
{
[Route("api/[controller]/[action]")]
public class PostsController : Controller
{
private readonly ISieveProcessor _sieveProcessor;
private readonly ApplicationDbContext _dbContext;
public PostsController(ISieveProcessor sieveProcessor,
ApplicationDbContext dbContext)
{
_sieveProcessor = sieveProcessor;
_dbContext = dbContext;
}
[HttpGet]
public JsonResult GetAllWithSieve(SieveModel sieveModel)
{
var result = _dbContext.Posts.AsNoTracking();
result = _sieveProcessor.Apply(sieveModel, result);
return Json(result.ToList());
}
[HttpGet]
public JsonResult Create(int number = 10)
{
for (int i = 0; i < number; i++)
{
_dbContext.Posts.Add(new Post());
}
_dbContext.SaveChanges();
return Json(_dbContext.Posts.ToList());
}
[HttpGet]
public JsonResult GetAll()
{
return Json(_dbContext.Posts.ToList());
}
}
}
using Microsoft.EntityFrameworkCore;
namespace SieveTests.Entities
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
public DbSet<Post> Posts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
}
using System;
using System.ComponentModel.DataAnnotations.Schema;
using Sieve.Attributes;
namespace SieveTests.Entities
{
public class Post
{
public int Id { get; set; }
[Sieve(CanFilter = true, CanSort = true)]
public string Title { get; set; } = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 8);
[Sieve(CanFilter = true, CanSort = true)]
public int LikeCount { get; set; } = new Random().Next(0, 1000);
[Sieve(CanFilter = true, CanSort = true)]
public int CommentCount { get; set; } = new Random().Next(0, 1000);
[Sieve(CanFilter = true, CanSort = true)]
public DateTimeOffset DateCreated { get; set; } = DateTimeOffset.UtcNow;
[Sieve(CanFilter = true, CanSort = true)]
[Column(TypeName = "datetime")]
public DateTime DateLastViewed { get; set; } = DateTime.UtcNow;
[Sieve(CanFilter = true, CanSort = true)]
public int? CategoryId { get; set; } = new Random().Next(0, 4);
}
}
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using SieveTests.Entities;
using System;
namespace SieveTests.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20180127005347_Init")]
partial class Init
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.0.1-rtm-125")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("SieveTests.Entities.Post", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CommentCount");
b.Property<DateTimeOffset>("DateCreated");
b.Property<int>("LikeCount");
b.Property<string>("Title");
b.HasKey("Id");
b.ToTable("Posts");
});
#pragma warning restore 612, 618
}
}
}
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace SieveTests.Migrations
{
public partial class Init : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Posts",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CommentCount = table.Column<int>(nullable: false),
DateCreated = table.Column<DateTimeOffset>(nullable: false),
LikeCount = table.Column<int>(nullable: false),
Title = table.Column<string>(nullable: true),
CategoryId = table.Column<int>(nullable: true)
},
constraints: table => table.PrimaryKey("PK_Posts", x => x.Id));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Posts");
}
}
}
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using SieveTests.Entities;
using System;
namespace SieveTests.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20180522013323_AddDateLastViewedColumn")]
partial class AddDateLastViewedColumn
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.0.1-rtm-125")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("SieveTests.Entities.Post", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CommentCount");
b.Property<DateTimeOffset>("DateCreated");
b.Property<DateTime>("DateLastViewed")
.HasColumnType("datetime");
b.Property<int>("LikeCount");
b.Property<string>("Title");
b.HasKey("Id");
b.ToTable("Posts");
});
#pragma warning restore 612, 618
}
}
}
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace SieveTests.Migrations
{
public partial class AddDateLastViewedColumn : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "DateLastViewed",
table: "Posts",
type: "datetime",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DateLastViewed",
table: "Posts");
}
}
}
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using SieveTests.Entities;
using System;
namespace SieveTests.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.0.1-rtm-125")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("SieveTests.Entities.Post", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CommentCount");
b.Property<DateTimeOffset>("DateCreated");
b.Property<DateTime>("DateLastViewed")
.HasColumnType("datetime");
b.Property<int>("LikeCount");
b.Property<int?>("CategoryId");
b.Property<string>("Title");
b.HasKey("Id");
b.ToTable("Posts");
});
#pragma warning restore 612, 618
}
}
}
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace SieveTests
{
public static class Program
{
public static void Main(string[] args)
{
var host = BuildWebHost(args);
host.Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:65136/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"SieveTests": {
"commandName": "Project",
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:6500/"
}
}
}
\ No newline at end of file
using Microsoft.Extensions.Options;
using Sieve.Models;
using Sieve.Services;
using SieveTests.Entities;
namespace SieveTests.Services
{
public class ApplicationSieveProcessor : SieveProcessor
{
public ApplicationSieveProcessor(IOptions<SieveOptions> options, ISieveCustomSortMethods customSortMethods, ISieveCustomFilterMethods customFilterMethods) : base(options, customSortMethods, customFilterMethods)
{
}
protected override SievePropertyMapper MapProperties(SievePropertyMapper mapper)
{
mapper.Property<Post>(p => p.Title)
.CanSort()
.CanFilter()
.HasName("CustomTitleName");
return mapper;
}
}
}
using System.Linq;
using Sieve.Services;
using SieveTests.Entities;
namespace SieveTests.Services
{
public class SieveCustomFilterMethods : ISieveCustomFilterMethods
{
public IQueryable<Post> IsNew(IQueryable<Post> source, string op, string[] values)
=> source.Where(p => p.LikeCount < 100 && p.CommentCount < 5);
}
}
using System.Linq;
using Sieve.Services;
using SieveTests.Entities;
namespace SieveTests.Services
{
public class SieveCustomSortMethods : ISieveCustomSortMethods
{
public IQueryable<Post> Popularity(IQueryable<Post> source, bool useThenBy) => useThenBy
? ((IOrderedQueryable<Post>)source).ThenBy(p => p.LikeCount)
: source.OrderBy(p => p.LikeCount)
.ThenBy(p => p.CommentCount)
.ThenBy(p => p.DateCreated);
}
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Migrations\20180127005211_Itit.cs" />
<Compile Remove="Migrations\20180127005211_Itit.Designer.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.9" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SieveUnitTests\SieveUnitTests.csproj" />
<ProjectReference Include="..\Sieve\Sieve.csproj" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Sieve.Models;
using Sieve.Services;
using SieveTests.Entities;
using SieveTests.Services;
namespace SieveTests
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TestSqlServer")));
services.Configure<SieveOptions>(Configuration.GetSection("Sieve"));
services.AddScoped<ISieveCustomSortMethods, SieveCustomSortMethods>();
services.AddScoped<ISieveCustomFilterMethods, SieveCustomFilterMethods>();
services.AddScoped<ISieveProcessor, ApplicationSieveProcessor>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// TIME MEASUREMENT
var times = new List<long>();
app.Use(async (context, next) =>
{
var sw = new Stopwatch();
sw.Start();
await next.Invoke();
sw.Stop();
times.Add(sw.ElapsedMilliseconds);
var text = $"AVG: {(int)times.Average()}ms; AT {sw.ElapsedMilliseconds}; COUNT: {times.Count()}";
Console.WriteLine(text);
await context.Response.WriteAsync($"<!-- {text} -->");
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
{
"ConnectionStrings": {
"TestSqlServer": "Server=(localdb)\\MSSQLLocalDB; Database=SieveTests;"
},
"Sieve": {
"CaseSensitive": false,
"DefaultPageSize": 10
},
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
}
}
import urllib.request
import time
for run in range(500):
contents = urllib.request.urlopen("http://localhost:6500/api/posts/getall").read()
print(contents[-50:])
#for run in range(50):
# contents = urllib.request.urlopen("http://localhost:6500/api/posts/getallWithSieve?filters=IsNew&sorts=popularity").read()
# print(contents[-50:])
# time.sleep(1)
print("done baseline")
input()
using System;
using Sieve.Attributes;
namespace SieveUnitTests.Entities
{
public class BaseEntity
{
public int Id { get; set; }
[Sieve(CanFilter = true, CanSort = true)]
public DateTimeOffset DateCreated { get; set; } = DateTimeOffset.UtcNow;
}
}
using Sieve.Attributes;
namespace SieveUnitTests.Entities
{
public class Comment : BaseEntity
{
[Sieve(CanFilter = true)]
public string Text { get; set; }
}
}
using System;
using Sieve.Attributes;
namespace SieveUnitTests.Entities
{
public class Post : BaseEntity
{
[Sieve(CanFilter = true, CanSort = true)]
public string Title { get; set; } = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 8);
[Sieve(CanFilter = true, CanSort = true)]
public int LikeCount { get; set; } = new Random().Next(0, 1000);
[Sieve(CanFilter = true, CanSort = true)]
public int CommentCount { get; set; } = new Random().Next(0, 1000);
[Sieve(CanFilter = true, CanSort = true)]
public int? CategoryId { get; set; } = new Random().Next(0, 4);
[Sieve(CanFilter = true, CanSort = true)]
public bool IsDraft { get; set; }
public string ThisHasNoAttribute { get; set; }
public string ThisHasNoAttributeButIsAccessible { get; set; }
public int OnlySortableViaFluentApi { get; set; }
public Comment TopComment { get; set; }
public Comment FeaturedComment { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Sieve.Exceptions;
using Sieve.Models;
using Sieve.Services;
using SieveUnitTests.Entities;
using SieveUnitTests.Services;
namespace SieveUnitTests
{
[TestClass]
public class General
{
private readonly SieveProcessor _processor;
private readonly IQueryable<Post> _posts;
private readonly IQueryable<Comment> _comments;
public General()
{
_processor = new ApplicationSieveProcessor(new SieveOptionsAccessor(),
new SieveCustomSortMethods(),
new SieveCustomFilterMethods());
_posts = new List<Post>
{
new Post() {
Id = 0,
Title = "A",
LikeCount = 100,
IsDraft = true,
CategoryId = null,
TopComment = new Comment { Id = 0, Text = "A1" },
FeaturedComment = new Comment { Id = 4, Text = "A2" }
},
new Post() {
Id = 1,
Title = "B",
LikeCount = 50,
IsDraft = false,
CategoryId = 1,
TopComment = new Comment { Id = 3, Text = "B1" },
FeaturedComment = new Comment { Id = 5, Text = "B2" }
},
new Post() {
Id = 2,
Title = "C",
LikeCount = 0,
CategoryId = 1,
TopComment = new Comment { Id = 2, Text = "C1" },
FeaturedComment = new Comment { Id = 6, Text = "C2" }
},
new Post() {
Id = 3,
Title = "D",
LikeCount = 3,
IsDraft = true,
CategoryId = 2,
TopComment = new Comment { Id = 1, Text = "D1" },
FeaturedComment = new Comment { Id = 7, Text = "D2" }
},
}.AsQueryable();
_comments = new List<Comment>
{
new Comment() {
Id = 0,
DateCreated = DateTimeOffset.UtcNow.AddDays(-20),
Text = "This is an old comment."
},
new Comment() {
Id = 1,
DateCreated = DateTimeOffset.UtcNow.AddDays(-1),
Text = "This is a fairly new comment."
},
new Comment() {
Id = 2,
DateCreated = DateTimeOffset.UtcNow,
Text = "This is a brand new comment. (Text in braces)"
},
}.AsQueryable();
}
[TestMethod]
public void ContainsCanBeCaseInsensitive()
{
var model = new SieveModel()
{
Filters = "Title@=*a"
};
var result = _processor.Apply(model, _posts);
Assert.AreEqual(result.First().Id, 0);
Assert.IsTrue(result.Count() == 1);
}
[TestMethod]
public void NotEqualsCanBeCaseInsensitive()
{
var model = new SieveModel()
{
Filters = "Title!=*a"
};
var result = _processor.Apply(model, _posts);
Assert.AreEqual(result.First().Id, 1);
Assert.IsTrue(result.Count() == 3);
}
[TestMethod]
public void ContainsIsCaseSensitive()
{
var model = new SieveModel()
{
Filters = "Title@=a",
};
var result = _processor.Apply(model, _posts);
Assert.IsTrue(result.Count() == 0);
}
[TestMethod]
public void NotContainsWorks()
{
var model = new SieveModel()
{
Filters = "Title!@=D",
};
var result = _processor.Apply(model, _posts);
Assert.IsTrue(result.Count() == 3);
}
[TestMethod]
public void CanFilterBools()
{
var model = new SieveModel()
{
Filters = "IsDraft==false"
};
var result = _processor.Apply(model, _posts);
Assert.IsTrue(result.Count() == 2);
}
[TestMethod]
public void CanSortBools()
{
var model = new SieveModel()
{
Sorts = "-IsDraft"
};
var result = _processor.Apply(model, _posts);
Assert.AreEqual(result.First().Id, 0);
}
[TestMethod]
public void CanFilterNullableInts()
{
var model = new SieveModel()
{
Filters = "CategoryId==1"
};
var result = _processor.Apply(model, _posts);
Assert.IsTrue(result.Count() == 2);
}
[TestMethod]
public void EqualsDoesntFailWithNonStringTypes()
{
var model = new SieveModel()
{
Filters = "LikeCount==50",
};
Console.WriteLine(model.GetFiltersParsed()[0].Values);
Console.WriteLine(model.GetFiltersParsed()[0].Operator);
Console.WriteLine(model.GetFiltersParsed()[0].OperatorParsed);
var result = _processor.Apply(model, _posts);
Assert.AreEqual(result.First().Id, 1);
Assert.IsTrue(result.Count() == 1);
}
[TestMethod]
public void CustomFiltersWork()
{
var model = new SieveModel()
{
Filters = "Isnew",
};
var result = _processor.Apply(model, _posts);
Assert.IsFalse(result.Any(p => p.Id == 0));
Assert.IsTrue(result.Count() == 3);
}
[TestMethod]
public void CustomGenericFiltersWork()
{
var model = new SieveModel()
{
Filters = "Latest",
};
var result = _processor.Apply(model, _comments);
Assert.IsFalse(result.Any(p => p.Id == 0));
Assert.IsTrue(result.Count() == 2);
}
[TestMethod]
public void CustomFiltersWithOperatorsWork()
{
var model = new SieveModel()
{
Filters = "HasInTitle==A",
};
var result = _processor.Apply(model, _posts);
Assert.IsTrue(result.Any(p => p.Id == 0));
Assert.IsTrue(result.Count() == 1);
}
[TestMethod]
public void CustomFiltersMixedWithUsualWork1()
{
var model = new SieveModel()
{
Filters = "Isnew,CategoryId==2",
};
var result = _processor.Apply(model, _posts);
Assert.IsTrue(result.Any(p => p.Id == 3));
Assert.IsTrue(result.Count() == 1);
}
[TestMethod]
public void CustomFiltersMixedWithUsualWork2()
{
var model = new SieveModel()
{
Filters = "CategoryId==2,Isnew",
};
var result = _processor.Apply(model, _posts);
Assert.IsTrue(result.Any(p => p.Id == 3));
Assert.IsTrue(result.Count() == 1);
}
[TestMethod]
public void CustomFiltersOnDifferentSourcesCanShareName()
{
var postModel = new SieveModel()
{
Filters = "CategoryId==2,Isnew",
};
var postResult = _processor.Apply(postModel, _posts);
Assert.IsTrue(postResult.Any(p => p.Id == 3));
Assert.AreEqual(1, postResult.Count());
var commentModel = new SieveModel()
{
Filters = "Isnew",
};
var commentResult = _processor.Apply(commentModel, _comments);
Assert.IsTrue(commentResult.Any(c => c.Id == 2));
Assert.AreEqual(2, commentResult.Count());
}
[TestMethod]
public void CustomSortsWork()
{
var model = new SieveModel()
{
Sorts = "Popularity",
};
var result = _processor.Apply(model, _posts);
Assert.IsFalse(result.First().Id == 0);
}
[TestMethod]
public void CustomGenericSortsWork()
{
var model = new SieveModel()
{
Sorts = "Oldest",
};
var result = _processor.Apply(model, _posts);
Assert.IsTrue(result.Last().Id == 0);
}
[TestMethod]
public void MethodNotFoundExceptionWork()
{
var model = new SieveModel()
{
Filters = "does not exist",
};
Assert.ThrowsException<SieveMethodNotFoundException>(() => _processor.Apply(model, _posts));
}
[TestMethod]
public void IncompatibleMethodExceptionsWork()
{
var model = new SieveModel()
{
Filters = "TestComment",
};
Assert.ThrowsException<SieveIncompatibleMethodException>(() => _processor.Apply(model, _posts));
}
[TestMethod]
public void OrNameFilteringWorks()
{
var model = new SieveModel()
{
Filters = "(Title|LikeCount)==3",
};
var result = _processor.Apply(model, _posts);
var entry = result.FirstOrDefault();
var resultCount = result.Count();
Assert.IsNotNull(entry);
Assert.AreEqual(1, resultCount);
Assert.AreEqual(3, entry.Id);
}
[TestMethod]
public void OrValueFilteringWorks()
{
var model = new SieveModel()
{
Filters = "Title==C|D",
};
var result = _processor.Apply(model, _posts);
Assert.AreEqual(2, result.Count());
Assert.IsTrue(result.Any(p => p.Id == 2));
Assert.IsTrue(result.Any(p => p.Id == 3));
}
[TestMethod]
public void OrValueFilteringWorks2()
{
var model = new SieveModel()
{
Filters = "Text@=(|)",
};
var result = _processor.Apply(model, _comments);
Assert.AreEqual(1, result.Count());
Assert.AreEqual(2, result.FirstOrDefault().Id);
}
[TestMethod]
public void NestedFilteringWorks()
{
var model = new SieveModel()
{
Filters = "TopComment.Text!@=A",
};
var result = _processor.Apply(model, _posts);
Assert.AreEqual(3, result.Count());
var posts = result.ToList();
Assert.IsTrue(posts[0].TopComment.Text.Contains("B"));
Assert.IsTrue(posts[1].TopComment.Text.Contains("C"));
Assert.IsTrue(posts[2].TopComment.Text.Contains("D"));
}
[TestMethod]
public void NestedSortingWorks()
{
var model = new SieveModel()
{
Sorts = "TopComment.Id",
};
var result = _processor.Apply(model, _posts);
Assert.AreEqual(4, result.Count());
var posts = result.ToList();
Assert.AreEqual(posts[0].Id, 0);
Assert.AreEqual(posts[1].Id, 3);
Assert.AreEqual(posts[2].Id, 2);
Assert.AreEqual(posts[3].Id, 1);
}
[TestMethod]
public void NestedFilteringWithIdenticTypesWorks()
{
var model = new SieveModel()
{
Filters = "(topc|featc)@=*2",
};
var result = _processor.Apply(model, _posts);
Assert.AreEqual(4, result.Count());
model = new SieveModel()
{
Filters = "(topc|featc)@=*B",
};
result = _processor.Apply(model, _posts);
Assert.AreEqual(1, result.Count());
}
}
}
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Sieve.Exceptions;
using Sieve.Models;
using SieveUnitTests.Entities;
using SieveUnitTests.Services;
namespace SieveUnitTests
{
[TestClass]
public class Mapper
{
private readonly ApplicationSieveProcessor _processor;
private readonly IQueryable<Post> _posts;
public Mapper()
{
_processor = new ApplicationSieveProcessor(new SieveOptionsAccessor(),
new SieveCustomSortMethods(),
new SieveCustomFilterMethods());
_posts = new List<Post>
{
new Post() {
Id = 1,
ThisHasNoAttributeButIsAccessible = "A",
ThisHasNoAttribute = "A",
OnlySortableViaFluentApi = 100
},
new Post() {
Id = 2,
ThisHasNoAttributeButIsAccessible = "B",
ThisHasNoAttribute = "B",
OnlySortableViaFluentApi = 50
},
new Post() {
Id = 3,
ThisHasNoAttributeButIsAccessible = "C",
ThisHasNoAttribute = "C",
OnlySortableViaFluentApi = 0
},
}.AsQueryable();
}
[TestMethod]
public void MapperWorks()
{
var model = new SieveModel()
{
Filters = "shortname@=A",
};
var result = _processor.Apply(model, _posts);
Assert.AreEqual(result.First().ThisHasNoAttributeButIsAccessible, "A");
Assert.IsTrue(result.Count() == 1);
}
[TestMethod]
public void MapperSortOnlyWorks()
{
var model = new SieveModel()
{
Filters = "OnlySortableViaFluentApi@=50",
Sorts = "OnlySortableViaFluentApi"
};
var result = _processor.Apply(model, _posts, applyFiltering: false, applyPagination: false);
Assert.ThrowsException<SieveMethodNotFoundException>(() => _processor.Apply(model, _posts));
Assert.AreEqual(result.First().Id, 3);
Assert.IsTrue(result.Count() == 3);
}
}
}
//
//Sorts = "LikeCount",
//Page = 1,
//PageSize = 10
//
\ No newline at end of file
using Microsoft.Extensions.Options;
using Sieve.Models;
using Sieve.Services;
using SieveUnitTests.Entities;
namespace SieveUnitTests.Services
{
public class ApplicationSieveProcessor : SieveProcessor
{
public ApplicationSieveProcessor(
IOptions<SieveOptions> options,
ISieveCustomSortMethods customSortMethods,
ISieveCustomFilterMethods customFilterMethods)
: base(options, customSortMethods, customFilterMethods)
{
}
protected override SievePropertyMapper MapProperties(SievePropertyMapper mapper)
{
mapper.Property<Post>(p => p.ThisHasNoAttributeButIsAccessible)
.CanSort()
.CanFilter()
.HasName("shortname");
mapper.Property<Post>(p => p.TopComment.Text)
.CanFilter();
mapper.Property<Post>(p => p.TopComment.Id)
.CanSort();
mapper.Property<Post>(p => p.OnlySortableViaFluentApi)
.CanSort();
mapper.Property<Post>(p => p.TopComment.Text)
.CanFilter()
.HasName("topc");
mapper.Property<Post>(p => p.FeaturedComment.Text)
.CanFilter()
.HasName("featc");
return mapper;
}
}
}
using System;
using System.Linq;
using Sieve.Services;
using SieveUnitTests.Entities;
namespace SieveUnitTests.Services
{
public class SieveCustomFilterMethods : ISieveCustomFilterMethods
{
public IQueryable<Post> IsNew(IQueryable<Post> source, string op, string[] values)
{
var result = source.Where(p => p.LikeCount < 100);
return result;
}
public IQueryable<Post> HasInTitle(IQueryable<Post> source, string op, string[] values)
{
var result = source.Where(p => p.Title.Contains(values[0]));
return result;
}
public IQueryable<Comment> IsNew(IQueryable<Comment> source, string op, string[] values)
{
var result = source.Where(c => c.DateCreated > DateTimeOffset.UtcNow.AddDays(-2));
return result;
}
public IQueryable<Comment> TestComment(IQueryable<Comment> source, string op, string[] values)
{
return source;
}
public IQueryable<T> Latest<T>(IQueryable<T> source, string op, string[] values) where T : BaseEntity
{
var result = source.Where(c => c.DateCreated > DateTimeOffset.UtcNow.AddDays(-14));
return result;
}
}
}
using System.Linq;
using Sieve.Services;
using SieveUnitTests.Entities;
namespace SieveUnitTests.Services
{
public class SieveCustomSortMethods : ISieveCustomSortMethods
{
public IQueryable<Post> Popularity(IQueryable<Post> source, bool useThenBy, bool desc)
{
var result = useThenBy ?
((IOrderedQueryable<Post>)source).ThenBy(p => p.LikeCount) :
source.OrderBy(p => p.LikeCount)
.ThenBy(p => p.CommentCount)
.ThenBy(p => p.DateCreated);
return result;
}
public IQueryable<T> Oldest<T>(IQueryable<T> source, bool useThenBy, bool desc) where T : BaseEntity
{
var result = useThenBy ?
((IOrderedQueryable<T>)source).ThenByDescending(p => p.DateCreated) :
source.OrderByDescending(p => p.DateCreated);
return result;
}
}
}
using Microsoft.Extensions.Options;
using Sieve.Models;
namespace SieveUnitTests
{
public class SieveOptionsAccessor : IOptions<SieveOptions>
{
public SieveOptions Value { get; }
public SieveOptionsAccessor()
{
Value = new SieveOptions()
{
ThrowExceptions = true
};
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" />
<PackageReference Include="MSTest.TestAdapter" Version="1.2.0" />
<PackageReference Include="MSTest.TestFramework" Version="1.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Sieve\Sieve.csproj" />
</ItemGroup>
</Project>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment