0

My site has a bunch of widgets and i'm trying to filter them based on the url which is passed in. Say a Widget has the following structure:

public class Widget {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Urls { get; set; }
}

Where Urls is a comma separated list for the urls where the widget should be displayed, e.g.:

/, /Blog/, /Blog/123, /News/*

The asterisk after News indicates the Widget will be selected whenever the passed in url starts with /News/.

How could i modify the following method to filter the widgets based on my conditions above?

public IList<Widget> GetWidgets(string url) {
    return _session
        .Where(w => w.Urls.Contains(url))
        .ToList();
}

Ideally i'd like to use a linq query and it must only hit the database once. I'd appreciate the help. Thanks

nfplee
  • 7,643
  • 12
  • 63
  • 124

2 Answers2

1

I managed to solve this by adding my own wild card match generator. See http://sentinel101.wordpress.com/2010/12/30/extend-nhibernate-linq-for-regex-matching/ for example of how to register the generator. Here's the generator incase anyone is interested:

public class WildCardMatchGenerator : BaseHqlGeneratorForMethod {
    public WildCardMatchGenerator() {
        var methodDefinition = ReflectionHelper.GetMethodDefinition(() => WildCardMatchExtensions.WildCardMatch(null, null, ','));
        SupportedMethods = new[] { methodDefinition };
    }

    public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) {
        return treeBuilder.Equality(treeBuilder.MethodCall("[dbo].[WildCardMatch]", new[] {
            visitor.Visit(arguments[0]).AsExpression(),
            visitor.Visit(arguments[1]).AsExpression(),
            visitor.Visit(arguments[2]).AsExpression()
        }), treeBuilder.Constant(1));
    }
}

And here is the WildCardMatch UDF:

CREATE FUNCTION [dbo].[WildCardMatch] (
    @Pattern NVARCHAR(MAX),
    @Input NVARCHAR(MAX),
    @Separator NVARCHAR(5)
)
RETURNS BIT
AS
BEGIN
    SET @Pattern = REPLACE(@Pattern, '*', '%')

    DECLARE @RtnValue BIT
    SELECT @RtnValue = CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END FROM [dbo].[Split](@Pattern, @Separator) WHERE @Input LIKE [Data]

    RETURN @RtnValue
END

And the Split function it calls (from http://blogs.microsoft.co.il/blogs/itai/archive/2009/02/01/t-sql-split-function.aspx):

CREATE FUNCTION [dbo].[Split]
(    
    @RowData NVARCHAR(MAX),
    @Separator NVARCHAR(MAX)
)
RETURNS @RtnValue TABLE 
(
    [Id] INT IDENTITY(1,1),
    [Data] NVARCHAR(MAX)
) 
AS
BEGIN 
    DECLARE @Iterator INT
    SET @Iterator = 1

    DECLARE @FoundIndex INT
    SET @FoundIndex = CHARINDEX(@Separator, @RowData)

    WHILE (@FoundIndex > 0)
    BEGIN
        INSERT INTO @RtnValue ([Data])
        SELECT Data = LTRIM(RTRIM(SUBSTRING(@RowData, 1, @FoundIndex - 1)))

        SET @RowData = SUBSTRING(@RowData, @FoundIndex + DATALENGTH(@Separator) / 2, LEN(@RowData))
        SET @Iterator = @Iterator + 1
        SET @FoundIndex = CHARINDEX(@Separator, @RowData)
    END

    INSERT INTO @RtnValue ([Data])
    SELECT Data = LTRIM(RTRIM(@RowData))

    RETURN
END

Lastly you'll need the C# implementation of the above UDF:

public static class WildCardMatchExtensions {
    public static bool WildCardMatch(this string pattern, string input, char separator = ',') {
        foreach (var str in pattern.Split(new char[] { separator }, StringSplitOptions.RemoveEmptyEntries)) {
            if (Regex.IsMatch(input, Regex.Escape(str.Trim()).Replace("\\*", ".*")))
                return true;
        }

        return false;
    }
}

Hope this helps.

nfplee
  • 7,643
  • 12
  • 63
  • 124
0

I don't think SQL server allows you to use IN for comma delimited field values. You need LIKE (SQL example below):

Urls LIKE '%_your_url_%'

Linq, Expressions, NHibernate and Like comparison may help you with translation LIKE to Linq to NHibernate

Community
  • 1
  • 1
the_joric
  • 11,986
  • 6
  • 36
  • 57