Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bug? not execute Custom Expression #65

Open
neozhu opened this issue Mar 16, 2023 · 9 comments
Open

bug? not execute Custom Expression #65

neozhu opened this issue Mar 16, 2023 · 9 comments
Labels
autofilterer enhancement New feature or request

Comments

@neozhu
Copy link

neozhu commented Mar 16, 2023

there is my code:
image

image

@enisn
Copy link
Owner

enisn commented Mar 16, 2023

As I understand you say the breakpoint never be hit inside your custom attribute. Right?

Let me check it

@neozhu
Copy link
Author

neozhu commented Mar 16, 2023

As I understand you say the breakpoint never be hit inside your custom attribute. Right?

Let me check it

yes, right

@enisn
Copy link
Owner

enisn commented Mar 16, 2023

It should be working and tests are passed.
But can you try to pass it as a parameter of [CompareTo] attribute like the following:

[CompareTo(typeof([SearchProductsWithListViewAttribute), "ListView")]
public ProductListView ListView { get; set; }

@enisn
Copy link
Owner

enisn commented Mar 16, 2023

Here my Test class:

public class CustomAttributesTests
{
    public enum MyEnum
    {
        ValueA, ValueB, ValueC, ValueD, ValueE,
    }

    public class MyEnumFilterAttribute : FilteringOptionsBaseAttribute
    {
        public static bool IsExecuted { get; set; }
        public override Expression BuildExpression(Expression expressionBody, PropertyInfo targetProperty, PropertyInfo filterProperty, object value)
        {
            IsExecuted = true;

            return expressionBody;
        }
    }

    public class FooFilter : FilterBase
    {
        [MyEnumFilter]
        public MyEnum Value { get; set; }
    }

    public class FooEntity
    {
        public MyEnum Value { get; set; }
    }

    [Theory, AutoMoqData(count: 64)]
    public void CustomMethodShouldBeCalled(List<FooEntity> entities)
    {
        var filter = new FooFilter();
        MyEnumFilterAttribute.IsExecuted = false;

        var query = entities.AsQueryable().ApplyFilter(filter);

        MyEnumFilterAttribute.IsExecuted.Should().BeTrue();
    }
}

As I get it, you don't have the property with the same name in your entity, so FilterBase ignores that property since there no matched property in the entity.
This is a tough situation, maybe there might be some changes required in the AutoFilterer. The library shouldn't assume that there is always matching properties in the entity.

@enisn enisn added the enhancement New feature or request label Mar 16, 2023
@neozhu
Copy link
Author

neozhu commented Mar 16, 2023

thank you for your information. Yes, It's working.

[CompareTo(typeof(SearchProductsWithListView), "Name")]
public ProductListView ListView { get; set; } = ProductListView.All;

The property name “Name” must be the same as the property name of the Entity Object.

Now I have a requirement that when the value of ProductListView is "My Products", I need to query records where CreatedBy equals the current user ID. I would like to pass the current user ID as a parameter. If I declare the property using [CompareTo(typeof(SearchProductsWithListView), "Name")], how can I pass the parameter?

image

@neozhu
Copy link
Author

neozhu commented Apr 10, 2023

I want to use Dependency Injection with SearchProductsWithListView to pass the current user. but not working

services.AddScoped<SearchProductsWithListView>();

public enum ProductListView
{
    [Description("All")]
    All,
    [Description("My Products")]
    My,
    [Description("Created Toady")]
    CreatedToday,
    [Description("Created within the last 30 days")]
    Created30Days
}

public class SearchProductsWithListView : FilteringOptionsBaseAttribute
{
    private readonly ICurrentUserService _currentUserService;

    public SearchProductsWithListView(ICurrentUserService currentUserService)
    {
        _currentUserService = currentUserService;
    }
    public override Expression BuildExpression(Expression expressionBody, PropertyInfo targetProperty, PropertyInfo filterProperty, object value)
    {
        var today = DateTime.Now.Date;
        var start = Convert.ToDateTime(today.ToString("yyyy-MM-dd", CultureInfo.CurrentCulture) + " 00:00:00", CultureInfo.CurrentCulture);
        var end = Convert.ToDateTime(today.ToString("yyyy-MM-dd", CultureInfo.CurrentCulture) + " 23:59:59", CultureInfo.CurrentCulture);
        var end30 = Convert.ToDateTime(today.AddDays(30).ToString("yyyy-MM-dd", CultureInfo.CurrentCulture) + " 23:59:59", CultureInfo.CurrentCulture);
        var userId = _currentUserService.UserId;
        var listview = (ProductListView)value;
        return listview switch
        {
            ProductListView.All => expressionBody,
           ProductListView.My=>  Expression.Equal(Expression.Property(expressionBody, "CreatedBy"),  Expression.Constant(userId)),
            ProductListView.CreatedToday => Expression.GreaterThanOrEqual(Expression.Property(expressionBody, "Created"),
                                                                          Expression.Constant(start, typeof(DateTime?)))
                                            .Combine(Expression.LessThanOrEqual(Expression.Property(expressionBody, "Created"),
                                                     Expression.Constant(end, typeof(DateTime?))),
                                                     CombineType.And),
            ProductListView.Created30Days => Expression.GreaterThanOrEqual(Expression.Property(expressionBody, "Created"),
                                             Expression.Constant(start, typeof(DateTime?)))
                                             .Combine(Expression.LessThanOrEqual(Expression.Property(expressionBody, "Created"),
                                                     Expression.Constant(end30, typeof(DateTime?))),
                                                     CombineType.And),
            _ => expressionBody
        };
    }
}

@enisn
Copy link
Owner

enisn commented Apr 10, 2023

I want to use Dependency Injection with SearchProductsWithListView to pass the current user. but not working

Unfortunately, it's just a C# attribute and it doesn't support dependency injection. I have a plan for dependency injection compatibility ( #52 ) But I see there is a performance gap between regular one that uses DI.

This kind of dynamic parameters are not the main focus of AutoFilterer at the moment. But after #52 is implemented, it'll be quite possible to filter.

@neozhu
Copy link
Author

neozhu commented Apr 10, 2023

thank you for your information,
You know IActionFilter support DI inject IHttpContextAccessor

@enisn
Copy link
Owner

enisn commented Apr 10, 2023

Yeah, you're right, but AutoFilterer is an independent library and it doesn't have any reference to AspNetCore. Maybe an alternative attribute can be developed which extends IActionFilter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
autofilterer enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants