TimeSpan Calculated Element struggles

New to Dundas and .NET/C# coding so struggling to even get my syntax right

I’m attempting to create a calculated element in a data cube to get the interval in hours between two datetimes.

What I’ve tried:
DateTime date1 = $Date1$;
DateTime date2 = $Date2$;
TimeSpan interval = (date1 - date2);
return interval.TotalHours;

The thing is, if I filter my input data and limit it to one row, this code works.

However, if I unfilter it and include all data, it will not run and I get the “Data retrieval failed, as it was not possible to generate a valid query for the specified metric set” error.

Can anyone please help me figure out how to return this interval of hours between two datetimes for each record in my datacube?

1 Like

Hey Molly,

Do you have any rows in your data where either of your date columns are nulls? That would be the most likely cause of this kind of error (NullReferenceException). You can insert an if statement to account for potential null values like this:

DateTime date1 = $Date1$;
DateTime date2 = $Date2$;

TimeSpan interval;

if (date1 != null && date2 != null) {
  interval = (date2 - date1);
  return interval.TotalHours;
}
return null;
1 Like

Thank you so much, this worked! Strangely, I hadn’t run into null-handling issues before this, so it didn’t cross my mind.