XSLT FAQ

How do I filter on optional Date fields?

I have created a Data Type containing a field of type "optional Date". In the XSLT Function designer, when I call the "Get[data type name]Xml()" function and try to add a filter for the optional Date field, I am not given any options - i.e. I can't filter on this field. Am I forced to make this a required field or is there a workaround?

Answer:

The ".NET technical" type of the field is Nullable<DateTime> and in Composite C1 1.2 and earlier versions no build-in functions provide predicate filters for the Nullable<DateTime> type. What is required are functions that return the following type:

Expression<Func<Nullable<DateTime>, bool>>

You can introduce such functions by creating one or more C# Functions which build them. Here is how to do so:

Create a file /App_Code/NullableDateTimePredicates.cs containing the following code:

using System;
using System.Linq.Expressions;


namespace Sample
{
    public class NullableDateTimePredicates
    {
        public static Expression<Func<Nullable<DateTime>, bool>> HasDateValue()
        {
            return f => f.HasValue;
        }

        public static Expression<Func<Nullable<DateTime>, bool>> GreaterThan( DateTime dateToCompareWith )
        {
            return f => f.HasValue && f.Value > dateToCompareWith;
        }

        public static Expression<Func<Nullable<DateTime>, bool>> LessThan(DateTime dateToCompareWith)
        {
            return f => f.HasValue && f.Value < dateToCompareWith;
        }

        public static Expression<Func<Nullable<DateTime>, bool>> Equals(DateTime dateToCompareWith)
        {
            return f => f.HasValue && f.Value == dateToCompareWith;
        }
    }
}

Download the source

Once this file has been added to the /App_Code directory, ASP.NET will compile it and make it available. At this point you can go to the "C# Functions" folder in the Functions perspective and register the functions you need. Select 'Add' on the "C# Functions" node and specify "Sample.NullableDateTimePredicates" as the Type Name and follow the wizard from there.