Morten Lehrmann's Dynamics AX Blog

Morten Lehrmann's Dynamics AX Blog

About the Blog

The Blog gathers issues I have found useful during my work with Dynamics AX

Base64 decoding a string in Dynamics AX 3.0

TipsPosted by Morten Lehrmann 2009-04-07 16:43:25
// Transforms the base64 encoded string _encoded to it's binary representation.
// Throws an error on errors.
static Binary base64decode(str _encoded)
// The size in bytes of the binary representation is found by trying
// to convert until it fits
#define.minTIFSz(30000) // Minimum try
#define.maxTIFSz(900000) // Maximum try
#define.TIFSzInc(10000) // Increments during trying
DLL DLL = new DLL('crypt32.dll');
DLLFunction decode = new DLLFunction(DLL, 'CryptStringToBinaryA');
int retval; // BOOL
int encodedlen;
int lasterr;
Binary decoded;
Binary junk1 = new Binary(#SizeOfInt);
Binary junk2 = new Binary(#SizeOfInt);
Binary size = new Binary(#SizeOfInt);
int TIFsz;


BOOL WINAPI CryptStringToBinary(
__in LPCTSTR pszString,
__in DWORD cchString,
__in DWORD dwFlags,
__in BYTE *pbBinary,
__inout DWORD *pcbBinary,
__out DWORD *pdwSkip,
__out DWORD *pdwFlags
decode.returns(ExtTypes::DWord); // BOOL
Exttypes::String, // __in LPCTSTR pszString,
Exttypes::DWord, // __in DWORD cchString,
Exttypes::DWord, // __in DWORD dwFlags,
Exttypes::Pointer, // __in BYTE *pbBinary,
Exttypes::Pointer, // __inout DWORD *pcbBinary,
Exttypes::Pointer, // __out DWORD *pdwSkip,
Exttypes::Pointer // __out DWORD *pdwFlags

encodedlen = strlen(_encoded);
TIFSz = #minTIFSz;
lasterr = #moredata;
while (lasterr == #moredata) // As long as the image is too large
if (TIFSz > #maxTIFSz)
throw error(strfmt("The eInvoice image is larger than %1 bytes - cannot handle this",#maxTIFSz)); //TODO:Label
decoded = new Binary(TIFSz);
retval =
1, // Base64, without headers
lasterr = DLL::lastDLLError();
TifSz += #TIFSzInc;
if (!retval)
throw error(strfmt("%1 (%2)",WINAPI::formatMessage(lasterr),lasterr));
return decoded;