I'm having trouble reading from some field types using DI API. I'm reading data both from the SAP database and another database, and the particular fields in question were not created by SAP, so it's understandable the DI API isn't guaranteed to work perfectly.
It seems the DI API can read field data into a Recordset: the data comes from the underlying SQL query properly and gets loaded into the Recordset, but the DI API's Field object doesn't always know what to do with it. In particular, IsNull() can't be trusted.
Here's my code that attempts to work around these issues. I'm curious if other developers have taken this further and could maybe suggest known-to-work improvements that might make it more reliable.
static public class SAPbobsCOM_Field_Extensions {
static public T FieldValue<T>( this SAPbobsCOM.Fields fields, object fieldIndex, T defaultValue ) {
return fields.Item( fieldIndex ).FieldValue<T>( defaultValue );
}
static public T FieldValue<T>( this SAPbobsCOM.Field fd, T defaultValue ) {
// NOTE: We don't check fd.IsNull() because it will sometimes return SAPbobsCOM.BoYesNoEnum.tYES
// despite having data. Since we can't trust it, we ignore it and try a cast instead. The latest
// version of DI API tested for this bug is 9.0.0.0
if ( typeof( T ).IsValueType ) {
try {
var obj = fd.Value;
if ( typeof( T ).Name == m_dateTimeTypeName ) {
// DI API always returns a date, even for fields that are null in the database, so since
// we can't trust IsNull(), we have to assume all pre-1900 dates are actually null
DateTime dt = ( DateTime ) obj;
if ( dt.Year < 1900 ) {
return defaultValue;
}
}
var val = ( T ) obj;
return val;
}
catch ( InvalidCastException ) {
return defaultValue;
}
} else {
return fd.Value ?? defaultValue;
}
}
static private string m_dateTimeTypeName = typeof( DateTime ).Name;
}