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
This diff is collapsed.
This diff is collapsed.

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);
}
}
This diff is collapsed.
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; }
}
}
This diff is collapsed.
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