Friday, January 16, 2015

X++ types Date and UtcDateTime are not implicitly converted to System.DateTime in .NET CIL, in AX 2012

Consider the following code sample:
System.Web.HttpCookie   cookie  = new System.Web.HttpCookie('test');
date                    dateVar = today() + 1;
cookie.set_Expires(dateVar);
It's just a .NET class object with a property of System.DateTime type initialized by a value of X++ date type. This code works perfectly in X++, but in .NET CIL it raises System.NotSupportedException with a message DateTimeConverter cannot convert from Microsoft.Dynamics.Ax.Xpp.AxShared.Date (or DateTimeConverter cannot convert from Microsoft.Dynamics.Ax.Xpp.AxShared.utcdatetime in case of X++ utcDateTime type).
According to MSDN article How to: Marshal Between X++ and CLR Primitive Types [AX 2012]
in Microsoft Dynamics AX, the X++ language does implicit conversion or marshaling between several X++ primitive types and their counterpart types managed by the common language runtime (CLR).
such as dateSystem.DateTime conversion. Well, in fact it does utcDateTimeSystem.DateTime conversion, too! But when X++ code runs in .NET CIL you have to explicitly convert values between date/utcDateTime types and System.DateTime. And actually you should do that anyway ‐ just in case your code happens to run in .NET CIL, otherwise you'll get System.NotSupportedException when you least expect it...