0

This is my datatables serverside implementation. FilterInput contains 5 variables:

  1. Level <- string
  2. Message <- string
  3. Exception <-string
  4. StartDate <- DateTime
  5. EndDate <- DateTime

For some reason when I run this code as it is, I will always get this error:

{System.NullReferenceException: Object reference not set to an instance of an object.

This is referring to this line:

data = data.Where(
                        u => u.Level.ToString().ToLower().Contains(FilterInput.Level.ToLower()) &&
                        u.Message.ToString().ToLower().Contains(FilterInput.Message.ToLower()) &&
                        u.Exception.ToString().ToLower().Contains(FilterInput.Exception.ToLower())
                    ).ToList();

However, if I remove the search for FilterInput.Exception, everything runs fine again. I have tested it with input ("abc") or without input ("") and the results are the same. The other FilterInputs don't have the same error.

public JsonResult Search(SearchViewModels Input, EventLogsSearchViewModel FilterInput)
{
    JsonResult result = new JsonResult(null);
    try
    {

        var data = dbContext.EventLogs.ToList();
        int totalRecords = data.Count;

        var modelStructure = new Dictionary<int, string>();
        modelStructure.Add(1, "Level");
        modelStructure.Add(2, "TimeStamp");
        modelStructure.Add(3, "LogEvent");
        modelStructure.Add(4, "Message");
        modelStructure.Add(5, "MessageTemplate");
        modelStructure.Add(6, "Exception");
        modelStructure.Add(7, "Properties");
        var StartDate = FilterInput.StartDate != default(DateTime);
        var EndDate = FilterInput.EndDate != default(DateTime);
        if ((!string.IsNullOrEmpty(FilterInput.Level) && !string.IsNullOrWhiteSpace(FilterInput.Level)) ||
            (!string.IsNullOrEmpty(FilterInput.Message) && !string.IsNullOrWhiteSpace(FilterInput.Message)) ||
            (!string.IsNullOrEmpty(FilterInput.Exception) && !string.IsNullOrWhiteSpace(FilterInput.Exception)) ||
            (StartDate && EndDate))
        {
            data = data.Where(
                u => u.Level.ToString().ToLower().Contains(FilterInput.Level.ToLower()) &&
                u.Message.ToString().ToLower().Contains(FilterInput.Message.ToLower()) &&
                u.Exception.ToString().ToLower().Contains(FilterInput.Exception.ToLower())
            ).ToList();

            data = data.Where(u => u.TimeStamp >= FilterInput.StartDate && u.TimeStamp <= FilterInput.EndDate).ToList();
        }
        if (!(string.IsNullOrEmpty(Input.Order) && string.IsNullOrEmpty(Input.OrderDir)))
        {
            var columnName = modelStructure.FirstOrDefault(f => f.Key == Convert.ToInt32(Input.Order));
            data = data.AsQueryable().OrderBy(columnName.Value + " " + Input.OrderDir).ToList();
        }

        int recFilter = data.Count;
        data = data.Skip(Input.StartRec).Take(Input.PageSize).ToList();
        var modifiedData = data.Select(u => new EventLogsListViewModel
        {
            Id = u.Id,
            Message = u.Message,
            MessageTemplate = u.MessageTemplate,
            Level = u.Level,
            TimeStamp = u.TimeStamp,
            Exception = u.Exception,
            Properties = u.Properties,
            LogEvent = u.LogEvent
        });
        result = this.Json(new
        {
            draw = Convert.ToInt32(Input.Draw),
            recordsTotal = totalRecords,
            recordsFiltered = recFilter,
            data = modifiedData,
            order = Input.Order,
            orderdir = Input.OrderDir
        });
    }
    catch (Exception e)
    {
        logger.LogError(e, LoggingGlobals.LoadingException);
    }
    return result;
}

EDIT: The exception still happens even when FilterInput.Exception is not null

JianYA
  • 2,750
  • 8
  • 60
  • 136
  • `if I remove the search for FilterInput.Exception, everything runs fine again` <= So `FilterInput.Exception` is null. I think you came to that conclusion yourself.... – Igor Oct 30 '18 at 20:48
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Igor Oct 30 '18 at 20:48
  • But even if its not null the exception still happens? Also, FilterInput.Exception is a string. – JianYA Oct 30 '18 at 20:53
  • I saw it is a string and if you call `ToLower()` on a null string reference you still get an NRE. – Igor Oct 30 '18 at 20:55
  • But wouldn't it fail the initial checks for if the string is null or whitespace and is null of empty? – JianYA Oct 30 '18 at 20:59
  • No, you have it as an optional condition along with the others. `||` = **OR**. If you were looking for **AND** you need to use `&&` – Igor Oct 30 '18 at 21:00
  • I see, but why does it fail for this string only? It doesn't fail for the other strings that come through – JianYA Oct 30 '18 at 21:01
  • It should. If you set `FilterInput.Level = null;` that should also through an NRE assuming that at least one other condition evals to `true` so it enters the `if` body. – Igor Oct 30 '18 at 21:03
  • What value can I replace null with so that the ToLower won't call an exception? – JianYA Oct 30 '18 at 21:16
  • Honestly your whole approach is inadequate. `dbContext.EventLogs.ToList();` gets every item in your DB (not good) and then you start filtering. You should filter the items in the db query. What if your DB grows and you have 1.000.000 records? That means every time this method runs you load every one into memory before you start filtering and return a result, that is a huge performance killer and you could start running into OutOfMemoryExceptions – Igor Oct 30 '18 at 21:20
  • I understand. I'm currently making a change to that as well. However I can't get past the part where I need to use tolower – JianYA Oct 30 '18 at 21:22
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/182822/discussion-between-igor-and-jianya). – Igor Oct 30 '18 at 21:25

0 Answers0