Files
mxaccessgw/src/ZB.MOM.WW.MxGateway.Worker/Conversion/VariantConverter.cs
T
Joseph Doherty 9adea04b37 fix(worker): report worker-side validation and STA shutdown without an MXAccess HRESULT (WIP-005, #255)
Per D9: a request the worker rejects before calling MXAccess (write value
with no kind, raw payload, empty MxArray) throws the new
WorkerRequestValidationException and replies INVALID_REQUEST with no
HRESULT. A plain ArgumentException stays MXACCESS_FAILURE with its HRESULT,
because the interop raises MXAccess E_INVALIDARG that way. The dispatcher
now converts executor exceptions on the STA, so anything the InvokeAsync
await throws is the runtime refusing the work item (shutdown, disposal,
dead loop, canceled at shutdown) and replies WORKER_UNAVAILABLE. No .proto
change. Status mapping documented in docs/WorkerConversion.md.
2026-12-03 09:45:14 -05:00

871 lines
30 KiB
C#

using System;
using System.Globalization;
using System.Linq;
using Google.Protobuf;
using Google.Protobuf.Collections;
using Google.Protobuf.WellKnownTypes;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.MxGateway.Worker.MxAccess;
namespace ZB.MOM.WW.MxGateway.Worker.Conversion;
public sealed class VariantConverter
{
private const string FileTimeOutOfRangeDiagnostic =
"Value is outside the FILETIME range; projected as an integer.";
private readonly TimeZoneInfo? mxAccessLocalTimeZone;
/// <summary>
/// Initializes a converter that renders timestamped-write time arguments in
/// the worker box's local zone (<see cref="TimeZoneInfo.Local"/>).
/// </summary>
public VariantConverter()
: this(mxAccessLocalTimeZone: null)
{
}
/// <summary>
/// Initializes a converter with an explicit zone for the timestamped-write
/// time argument. Tests inject a fixed zone so they do not depend on the
/// zone of the machine that runs them.
/// </summary>
/// <param name="mxAccessLocalTimeZone">
/// Zone MXAccess reads the <c>Write2</c>/<c>WriteSecured2</c> time argument in,
/// or <see langword="null"/> for <see cref="TimeZoneInfo.Local"/> resolved per call.
/// </param>
public VariantConverter(TimeZoneInfo? mxAccessLocalTimeZone)
{
this.mxAccessLocalTimeZone = mxAccessLocalTimeZone;
}
/// <summary>
/// Converts an object value to an MxValue without a specified data type.
/// </summary>
/// <param name="value">Value to convert.</param>
/// <returns>Converted MxValue.</returns>
public MxValue Convert(object? value)
{
return Convert(value, MxDataType.Unspecified);
}
/// <summary>
/// Converts an object value to an MxValue with an expected data type.
/// </summary>
/// <param name="value">Value to convert.</param>
/// <param name="expectedDataType">Expected MXAccess data type.</param>
/// <returns>Converted MxValue.</returns>
public MxValue Convert(
object? value,
MxDataType expectedDataType)
{
if (value is null || value is DBNull)
{
return CreateNullValue(value, expectedDataType);
}
if (value is Array array)
{
return new MxValue
{
DataType = MxDataType.Unspecified,
VariantType = CreateArrayVariantType(array),
ArrayValue = ConvertArray(array, expectedDataType),
};
}
return ConvertScalar(value, expectedDataType);
}
/// <summary>
/// Converts a .NET array to an MxArray.
/// </summary>
/// <param name="array">Array to convert.</param>
/// <param name="expectedElementDataType">Expected data type for array elements.</param>
/// <returns>Converted MxArray.</returns>
public MxArray ConvertArray(
Array array,
MxDataType expectedElementDataType = MxDataType.Unspecified)
{
if (array is null)
{
throw new ArgumentNullException(nameof(array));
}
MxArray mxArray = new()
{
VariantType = CreateArrayVariantType(array),
};
for (int dimension = 0; dimension < array.Rank; dimension++)
{
mxArray.Dimensions.Add((uint)array.GetLength(dimension));
}
System.Type? elementType = array.GetType().GetElementType();
MxDataType elementDataType = ResolveArrayElementDataType(elementType, expectedElementDataType);
if (TryProjectTypedArray(mxArray, array, elementDataType, elementType, out string? failure))
{
return mxArray;
}
// A typed projection failed on one element (an expected-type hint the
// element does not fit, a FILETIME out of range, an integer too wide).
// Conversion must stay total: it runs on the MXAccess event path, where
// a throw faults the whole session (WIP-003). Fall back to the
// projection the array's own CLR element type gives, and failing that
// to the raw projection with a diagnostic naming the element.
MxDataType actualDataType = ResolveArrayElementDataType(elementType, MxDataType.Unspecified);
if (failure is not null
&& actualDataType != elementDataType
&& actualDataType != MxDataType.Unknown
&& TryProjectTypedArray(mxArray, array, actualDataType, elementType, out _))
{
mxArray.RawDiagnostic = $"{failure} Projected as {actualDataType} from the array's element type.";
return mxArray;
}
mxArray.ElementDataType = MxDataType.Unknown;
mxArray.RawElementDataType = (int)expectedElementDataType;
mxArray.RawDiagnostic = failure ?? CreateRawDiagnostic(array);
mxArray.RawValues = ConvertRawArray(array);
return mxArray;
}
/// <summary>
/// Projects <paramref name="array"/> into the typed value list for
/// <paramref name="elementDataType"/>. Nothing is written to
/// <paramref name="mxArray"/> unless every element converts.
/// </summary>
/// <param name="mxArray">Array message to fill on success.</param>
/// <param name="array">Source array.</param>
/// <param name="elementDataType">Element type to project to.</param>
/// <param name="elementType">CLR element type of the source array.</param>
/// <param name="failure">
/// Why an element did not convert, or <see langword="null"/> when the data
/// type has no typed projection at all.
/// </param>
/// <returns><see langword="true"/> when the typed projection was applied.</returns>
private static bool TryProjectTypedArray(
MxArray mxArray,
Array array,
MxDataType elementDataType,
System.Type? elementType,
out string? failure)
{
switch (elementDataType)
{
case MxDataType.Boolean:
{
BoolArray values = new();
if (!TryConvertElements(array, values.Values, ConvertBoolElement, elementDataType, out failure))
{
return false;
}
mxArray.ElementDataType = elementDataType;
mxArray.BoolValues = values;
return true;
}
case MxDataType.Integer:
{
// Widen the same way the scalar path does (WIP-004): uint, long
// and ulong never fit an int, and an object[] (SAFEARRAY of
// VARIANT) may hold any of them, so a narrow projection that
// overflows retries as 64-bit. A ulong above long.MaxValue
// fails both and lands on the raw projection, as the scalar does.
if (!UsesInt64Projection(elementType))
{
Int32Array narrow = new();
if (TryConvertElements(array, narrow.Values, ConvertInt32Element, elementDataType, out failure))
{
mxArray.ElementDataType = elementDataType;
mxArray.Int32Values = narrow;
return true;
}
}
Int64Array wide = new();
if (!TryConvertElements(array, wide.Values, ConvertInt64Element, elementDataType, out failure))
{
return false;
}
mxArray.ElementDataType = elementDataType;
mxArray.Int64Values = wide;
return true;
}
case MxDataType.Float:
{
FloatArray values = new();
if (!TryConvertElements(array, values.Values, ConvertFloatElement, elementDataType, out failure))
{
return false;
}
mxArray.ElementDataType = elementDataType;
mxArray.FloatValues = values;
return true;
}
case MxDataType.Double:
{
DoubleArray values = new();
if (!TryConvertElements(array, values.Values, ConvertDoubleElement, elementDataType, out failure))
{
return false;
}
mxArray.ElementDataType = elementDataType;
mxArray.DoubleValues = values;
return true;
}
case MxDataType.String:
{
StringArray values = new();
if (!TryConvertElements(array, values.Values, ConvertStringElement, elementDataType, out failure))
{
return false;
}
mxArray.ElementDataType = elementDataType;
mxArray.StringValues = values;
return true;
}
case MxDataType.Time:
{
TimestampArray values = new();
if (!TryConvertElements(array, values.Values, ConvertTimestampElement, elementDataType, out failure))
{
return false;
}
mxArray.ElementDataType = elementDataType;
mxArray.TimestampValues = values;
return true;
}
default:
failure = null;
return false;
}
}
/// <summary>
/// Converts an <see cref="MxValue"/> into a CLR object suitable for an
/// MXAccess COM write. The COM marshaler boxes the returned value into the
/// matching VARIANT, so this is the inverse of <see cref="Convert(object?)"/>.
/// </summary>
/// <param name="value">Protobuf value to convert.</param>
/// <returns>A COM-marshalable value, or <see langword="null"/> for an MXAccess null.</returns>
public object? ConvertToComValue(MxValue value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.IsNull)
{
return null;
}
return value.KindCase switch
{
MxValue.KindOneofCase.BoolValue => value.BoolValue,
MxValue.KindOneofCase.Int32Value => value.Int32Value,
MxValue.KindOneofCase.Int64Value => value.Int64Value,
MxValue.KindOneofCase.FloatValue => value.FloatValue,
MxValue.KindOneofCase.DoubleValue => value.DoubleValue,
MxValue.KindOneofCase.StringValue => value.StringValue,
// The COM marshaler renders a DateTime as VT_DATE; MXAccess accepts
// it as the timestamped-write time argument.
MxValue.KindOneofCase.TimestampValue => value.TimestampValue.ToDateTime(),
MxValue.KindOneofCase.ArrayValue => ConvertToComArray(value.ArrayValue),
MxValue.KindOneofCase.RawValue => throw new WorkerRequestValidationException(
"MxValue raw payloads cannot be written to MXAccess.", nameof(value)),
_ => throw new WorkerRequestValidationException(
"MxValue has no value kind set; nothing to write.", nameof(value)),
};
}
/// <summary>
/// Converts the time argument of a timestamped write (<c>Write2</c>,
/// <c>WriteSecured2</c> and their bulk forms) into the CLR object MXAccess
/// expects. Unlike <see cref="ConvertToComValue(MxValue)"/>, a
/// <c>timestamp_value</c> instant is rendered as box-local wall-clock time.
/// </summary>
/// <remarks>
/// <para>
/// MXAccess reads the <c>VT_DATE</c> time argument as local time on the worker
/// box and converts it to UTC itself, while a <c>VT_DATE</c> carries no
/// offset and the COM marshaler ignores <see cref="DateTime.Kind"/>. Passing
/// the UTC clock fields therefore stored the source timestamp shifted by the
/// box's UTC offset (+5 h on a UTC-5 box, #228). The read direction is the
/// opposite and stays as it is: MXAccess hands OnDataChange timestamps over
/// as UTC, and <c>ToTimestamp</c> treats them as UTC.
/// </para>
/// <para>
/// The UTC-to-local step uses <see cref="TimeZoneInfo.ConvertTimeFromUtc(DateTime, TimeZoneInfo)"/>
/// with the zone's DST rules, so it is exact and never yields an invalid
/// local time. The one residual loss is on the MXAccess side: in the hour
/// that repeats when DST ends, two UTC instants share one local wall-clock
/// time, and the offset-less <c>VT_DATE</c> cannot say which one is meant,
/// so MXAccess may store an instant from that hour 1 h off. Clients that
/// need exact timestamps across the fall-back hour should run the worker
/// box on UTC.
/// </para>
/// <para>
/// Only the <c>timestamp_value</c> kind is converted. Any other kind (a
/// string or a number) carries no zone, so it is passed through unchanged
/// as before and its meaning is the caller's.
/// </para>
/// </remarks>
/// <param name="timestamp">Protobuf time argument of a timestamped write.</param>
/// <returns>A COM-marshalable value for the MXAccess time argument.</returns>
public object? ConvertToComTimestamp(MxValue timestamp)
{
if (timestamp is null)
{
throw new ArgumentNullException(nameof(timestamp));
}
if (!timestamp.IsNull && timestamp.KindCase == MxValue.KindOneofCase.TimestampValue)
{
return ToMxAccessLocalTime(timestamp.TimestampValue.ToDateTime());
}
return ConvertToComValue(timestamp);
}
/// <summary>
/// Converts a UTC instant to the wall-clock time MXAccess expects for a
/// timestamped-write time argument. See <see cref="ConvertToComTimestamp(MxValue)"/>.
/// </summary>
/// <param name="utcDateTime">UTC instant (<see cref="DateTimeKind.Utc"/> or unspecified).</param>
/// <returns>The same instant as wall-clock time in the MXAccess zone.</returns>
public DateTime ToMxAccessLocalTime(DateTime utcDateTime)
{
DateTime utc = utcDateTime.Kind == DateTimeKind.Local
? utcDateTime.ToUniversalTime()
: DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);
return TimeZoneInfo.ConvertTimeFromUtc(utc, mxAccessLocalTimeZone ?? TimeZoneInfo.Local);
}
private static Array ConvertToComArray(MxArray array)
{
return array.ValuesCase switch
{
MxArray.ValuesOneofCase.BoolValues => array.BoolValues.Values.ToArray(),
MxArray.ValuesOneofCase.Int32Values => array.Int32Values.Values.ToArray(),
MxArray.ValuesOneofCase.Int64Values => array.Int64Values.Values.ToArray(),
MxArray.ValuesOneofCase.FloatValues => array.FloatValues.Values.ToArray(),
MxArray.ValuesOneofCase.DoubleValues => array.DoubleValues.Values.ToArray(),
MxArray.ValuesOneofCase.StringValues => array.StringValues.Values.ToArray(),
MxArray.ValuesOneofCase.TimestampValues =>
array.TimestampValues.Values.Select(timestamp => timestamp.ToDateTime()).ToArray(),
MxArray.ValuesOneofCase.RawValues => throw new WorkerRequestValidationException(
"MxArray raw payloads cannot be written to MXAccess.", nameof(array)),
_ => throw new WorkerRequestValidationException(
"MxArray has no element values set; nothing to write.", nameof(array)),
};
}
private static MxValue ConvertScalar(
object value,
MxDataType expectedDataType)
{
System.Type valueType = value.GetType();
string variantType = GetVariantTypeName(valueType);
switch (System.Type.GetTypeCode(valueType))
{
case TypeCode.Boolean:
return new MxValue
{
DataType = MxDataType.Boolean,
VariantType = variantType,
BoolValue = (bool)value,
};
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
return new MxValue
{
DataType = MxDataType.Integer,
VariantType = variantType,
Int32Value = System.Convert.ToInt32(value, CultureInfo.InvariantCulture),
};
case TypeCode.UInt32:
case TypeCode.Int64:
return ConvertInt64Scalar(value, variantType, expectedDataType);
case TypeCode.UInt64:
return ConvertUInt64Scalar((ulong)value, variantType, expectedDataType);
case TypeCode.Single:
return new MxValue
{
DataType = MxDataType.Float,
VariantType = variantType,
FloatValue = (float)value,
};
case TypeCode.Double:
return new MxValue
{
DataType = MxDataType.Double,
VariantType = variantType,
DoubleValue = (double)value,
};
case TypeCode.Decimal:
return new MxValue
{
DataType = MxDataType.Double,
VariantType = variantType,
DoubleValue = System.Convert.ToDouble(value, CultureInfo.InvariantCulture),
RawDiagnostic = "Decimal value projected to double.",
};
case TypeCode.String:
case TypeCode.Char:
return new MxValue
{
DataType = MxDataType.String,
VariantType = variantType,
StringValue = System.Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty,
};
case TypeCode.DateTime:
return new MxValue
{
DataType = MxDataType.Time,
VariantType = variantType,
TimestampValue = ToTimestamp((DateTime)value),
};
default:
return CreateRawValue(value, expectedDataType);
}
}
private static MxValue ConvertInt64Scalar(
object value,
string variantType,
MxDataType expectedDataType)
{
long longValue = System.Convert.ToInt64(value, CultureInfo.InvariantCulture);
// The MxDataType.Time projection treats the source as a Windows FILETIME
// (a 64-bit 100-ns tick count since 1601). Only a genuine 64-bit source
// (long) can carry a valid full FILETIME; a uint can only hold the low
// 32 bits, which DateTime.FromFileTimeUtc would silently render as a
// timestamp near the 1601 epoch. For uint sources fall through to the integer
// projection rather than producing a bogus timestamp.
string? diagnostic = null;
if (expectedDataType == MxDataType.Time && value is long)
{
Timestamp? timestamp = TryFromFileTimeUtc(longValue);
if (timestamp is not null)
{
return new MxValue
{
DataType = MxDataType.Time,
VariantType = variantType,
TimestampValue = timestamp,
};
}
diagnostic = FileTimeOutOfRangeDiagnostic;
}
MxValue converted = new()
{
DataType = MxDataType.Integer,
VariantType = variantType,
Int64Value = longValue,
};
if (diagnostic is not null)
{
converted.RawDiagnostic = diagnostic;
}
return converted;
}
private static MxValue ConvertUInt64Scalar(
ulong value,
string variantType,
MxDataType expectedDataType)
{
string? diagnostic = null;
if (expectedDataType == MxDataType.Time && value <= long.MaxValue)
{
Timestamp? timestamp = TryFromFileTimeUtc((long)value);
if (timestamp is not null)
{
return new MxValue
{
DataType = MxDataType.Time,
VariantType = variantType,
TimestampValue = timestamp,
};
}
diagnostic = FileTimeOutOfRangeDiagnostic;
}
if (value <= long.MaxValue)
{
MxValue converted = new()
{
DataType = MxDataType.Integer,
VariantType = variantType,
Int64Value = (long)value,
};
if (diagnostic is not null)
{
converted.RawDiagnostic = diagnostic;
}
return converted;
}
return CreateRawValue(value, expectedDataType, "UInt64 value exceeds Int64 range.");
}
private static MxValue CreateNullValue(
object? value,
MxDataType expectedDataType)
{
return new MxValue
{
DataType = expectedDataType == MxDataType.Unspecified ? MxDataType.NoData : expectedDataType,
VariantType = value is DBNull ? "VT_NULL" : "VT_EMPTY",
IsNull = true,
};
}
private static MxValue CreateRawValue(
object value,
MxDataType expectedDataType,
string? diagnosticPrefix = null)
{
string diagnostic = CreateRawDiagnostic(value);
if (!string.IsNullOrWhiteSpace(diagnosticPrefix))
{
diagnostic = $"{diagnosticPrefix} {diagnostic}";
}
return new MxValue
{
DataType = MxDataType.Unknown,
VariantType = GetVariantTypeName(value.GetType()),
RawDataType = (int)expectedDataType,
RawDiagnostic = diagnostic,
RawValue = ByteString.CopyFromUtf8(System.Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty),
};
}
private static bool TryConvertElements<T>(
Array array,
RepeatedField<T> target,
Func<object?, T> convert,
MxDataType elementDataType,
out string? failure)
{
int index = 0;
foreach (object? item in array)
{
try
{
target.Add(convert(item));
}
catch (Exception exception) when (IsElementConversionFailure(exception))
{
// Name the element and its CLR type, never its value: values
// are not logged by default and this text reaches the client.
failure = $"Array element {index} ({item?.GetType().FullName ?? "null"}) "
+ $"could not be projected to {elementDataType}: {exception.GetType().Name}.";
return false;
}
index++;
}
failure = null;
return true;
}
private static bool IsElementConversionFailure(Exception exception)
{
return exception is FormatException
|| exception is InvalidCastException
|| exception is OverflowException
|| exception is ArgumentException;
}
private static bool UsesInt64Projection(System.Type? elementType)
{
return elementType == typeof(uint)
|| elementType == typeof(long)
|| elementType == typeof(ulong);
}
// Null elements keep their historical default projection until a live
// capture shows how MXAccess represents a missing array element (WIP-008,
// decision D8: no invented null encoding).
private static bool ConvertBoolElement(object? item)
{
return item is not null && System.Convert.ToBoolean(item, CultureInfo.InvariantCulture);
}
private static int ConvertInt32Element(object? item)
{
return item is null ? 0 : System.Convert.ToInt32(item, CultureInfo.InvariantCulture);
}
private static long ConvertInt64Element(object? item)
{
return item is null ? 0 : System.Convert.ToInt64(item, CultureInfo.InvariantCulture);
}
private static float ConvertFloatElement(object? item)
{
return item is null ? 0 : System.Convert.ToSingle(item, CultureInfo.InvariantCulture);
}
private static double ConvertDoubleElement(object? item)
{
return item is null ? 0 : System.Convert.ToDouble(item, CultureInfo.InvariantCulture);
}
private static string ConvertStringElement(object? item)
{
return item is null ? string.Empty : System.Convert.ToString(item, CultureInfo.InvariantCulture) ?? string.Empty;
}
/// <summary>
/// Converts one element of a Time-typed array. A <c>VT_DATE</c> element is
/// a <see cref="DateTime"/>; a 64-bit integer is a FILETIME; a string is
/// the culture-formatted local time MXAccess uses for the
/// <c>OnDataChange</c> timestamp. Anything else (a 32-bit integer, which
/// can only hold the low half of a FILETIME, or a double) is rejected so the
/// caller falls back instead of emitting a timestamp near 1601.
/// </summary>
private static Timestamp ConvertTimestampElement(object? item)
{
switch (item)
{
case null:
return Timestamp.FromDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
case DateTime dateTime:
return ToTimestamp(dateTime);
case string text:
if (MxAccessEventMapper.TryParseSourceTimestamp(text, out DateTime parsedUtc))
{
return Timestamp.FromDateTime(parsedUtc);
}
throw new FormatException("Timestamp string did not parse.");
case long fileTime:
return Timestamp.FromDateTime(DateTime.FromFileTimeUtc(fileTime));
case ulong fileTime when fileTime <= long.MaxValue:
return Timestamp.FromDateTime(DateTime.FromFileTimeUtc((long)fileTime));
default:
throw new InvalidCastException("Element type has no timestamp projection.");
}
}
private static Timestamp? TryFromFileTimeUtc(long fileTime)
{
// DateTime.FromFileTimeUtc rejects negative values and values past
// DateTime.MaxValue; on the event path that throw would fault the
// session (WIP-003), so an out-of-range FILETIME stays an integer.
try
{
return Timestamp.FromDateTime(DateTime.FromFileTimeUtc(fileTime));
}
catch (ArgumentOutOfRangeException)
{
return null;
}
}
private static RawArray ConvertRawArray(Array array)
{
RawArray values = new();
foreach (object? item in array)
{
string rawValue = item is null
? string.Empty
: System.Convert.ToString(item, CultureInfo.InvariantCulture) ?? string.Empty;
values.Values.Add(ByteString.CopyFromUtf8(rawValue));
}
return values;
}
private static MxDataType ResolveArrayElementDataType(
System.Type? elementType,
MxDataType expectedElementDataType)
{
if (expectedElementDataType != MxDataType.Unspecified)
{
return expectedElementDataType;
}
if (elementType == typeof(bool))
{
return MxDataType.Boolean;
}
if (elementType == typeof(byte)
|| elementType == typeof(sbyte)
|| elementType == typeof(short)
|| elementType == typeof(ushort)
|| elementType == typeof(int)
|| elementType == typeof(uint)
|| elementType == typeof(long)
|| elementType == typeof(ulong))
{
return MxDataType.Integer;
}
if (elementType == typeof(float))
{
return MxDataType.Float;
}
if (elementType == typeof(double) || elementType == typeof(decimal))
{
return MxDataType.Double;
}
if (elementType == typeof(string) || elementType == typeof(char))
{
return MxDataType.String;
}
if (elementType == typeof(DateTime))
{
return MxDataType.Time;
}
return MxDataType.Unknown;
}
private static Timestamp ToTimestamp(DateTime dateTime)
{
DateTime utcDateTime = dateTime.Kind switch
{
DateTimeKind.Utc => dateTime,
DateTimeKind.Local => dateTime.ToUniversalTime(),
_ => DateTime.SpecifyKind(dateTime, DateTimeKind.Utc),
};
return Timestamp.FromDateTime(utcDateTime);
}
private static string CreateArrayVariantType(Array array)
{
System.Type? elementType = array.GetType().GetElementType();
return $"SAFEARRAY({GetVariantTypeName(elementType)})";
}
private static string GetVariantTypeName(System.Type? type)
{
if (type is null)
{
return "VT_EMPTY";
}
System.Type nonNullableType = Nullable.GetUnderlyingType(type) ?? type;
if (nonNullableType == typeof(bool))
{
return "VT_BOOL";
}
if (nonNullableType == typeof(byte))
{
return "VT_UI1";
}
if (nonNullableType == typeof(sbyte))
{
return "VT_I1";
}
if (nonNullableType == typeof(short))
{
return "VT_I2";
}
if (nonNullableType == typeof(ushort))
{
return "VT_UI2";
}
if (nonNullableType == typeof(int))
{
return "VT_I4";
}
if (nonNullableType == typeof(uint))
{
return "VT_UI4";
}
if (nonNullableType == typeof(long))
{
return "VT_I8";
}
if (nonNullableType == typeof(ulong))
{
return "VT_UI8";
}
if (nonNullableType == typeof(float))
{
return "VT_R4";
}
if (nonNullableType == typeof(double) || nonNullableType == typeof(decimal))
{
return "VT_R8";
}
if (nonNullableType == typeof(string) || nonNullableType == typeof(char))
{
return "VT_BSTR";
}
if (nonNullableType == typeof(DateTime))
{
return "VT_DATE";
}
return $"CLR:{nonNullableType.FullName}";
}
private static string CreateRawDiagnostic(object value)
{
return $"Unsupported variant projection for CLR type '{value.GetType().FullName}'.";
}
}