String Search parsing and filtering

Sometimes I overlook some pretty important things.  I realised recently that I had missed an interesting behaviour of the TrimMainObjectSearch string searching.

A valid search with filtering

The search below will search for all records where the Additional Field 'Alcohol Level' is greater than zero and filter on Record Type == "Infringement".

TrimMainObjectSearch recordSearch = new TrimMainObjectSearch(db, BaseObjectTypes.Record);
recordSearch.SetSearchString("AlcoholLevel>0");
recordSearch.SetFilterString("recType:Infringement");

foreach (Record record in recordSearch)
{
    Console.WriteLine(record.Title);
}

An invalid search without filtering

This search is invalid because 'Alcohol Level' is a number field, so no results are returned, everything is good so far.

TrimMainObjectSearch recordSearch = new TrimMainObjectSearch(db, BaseObjectTypes.Record);
recordSearch.SetSearchString("AlcoholLevel>abc");

foreach (Record record in recordSearch)
{
    Console.WriteLine(record.Title);
}

An invalid search with filtering

You might expect that the search below would behave just as the search above and return no results, given the invalid search string, this is not the case.  The invalid search string is discarded and the filter is applied, the result is all Records where Record Type == 'Infringement'. 

TrimMainObjectSearch recordSearch = new TrimMainObjectSearch(db, BaseObjectTypes.Record);
recordSearch.SetSearchString("AlcoholLevel>abc");
recordSearch.SetFilterString("recType:Infringement");

foreach (Record record in recordSearch)
{
    Console.WriteLine(record.Title);
}

The solution

To avoid this problem always check the return value of SetSearchString().

TrimMainObjectSearch recordSearch = new TrimMainObjectSearch(db, BaseObjectTypes.Record);
TrimParserException parserException = recordSearch.SetSearchString("AlcoholLevel>abc");

if (parserException.Bad)
{
    Console.WriteLine(parserException.Message);
}
else
{
    recordSearch.SetFilterString("recType:Infringement");

    foreach (Record record in recordSearch)
    {
        Console.WriteLine(record.Title);
    }
}
Written on September 13, 2017