I'm attempting to deflate a .NET GZIPStream in X++ but I'm running into a bug. The .NET code to create the string is pretty simple:
private string CompressString()
{
string stringToCompress = "Some data here";
string result = string.Empty;
using (MemoryStream output = new MemoryStream())
using (GZipStream gzip = new GZipStream(output, CompressionMode.Compress, true))
using (StreamWriter writer = new StreamWriter(gzip))
{
writer.Write(stringToCompress);
writer.Close();
result = Convert.ToBase64String(output.ToArray());
}
return result;
}
The AX side will get the compressed string via some web service call. The X++ code I have currently is below, but I'm getting the error "Object 'CLRObject' could not be created" when creating the StreamWriter.
static void Job2(Args _args)
{
System.String decodedString;
System.Byte[] buffer;
System.IO.Compression.GZipStream gzip;
System.IO.StreamWriter writer;
System.IO.MemoryStream output;
InteropPermission permission;
CLRObject ex;
str compressedString ="Compressed data here";
;
ttsBegin;
permission = new InteropPermission(InteropKind::ClrInterop);
permission.assert();
buffer = System.Convert::FromBase64String(compressedString);
output = new System.IO.MemoryStream(buffer);
gzip = new System.IO.Compression.GZipStream(output, System.IO.Compression.CompressionMode::Decompress);
try {
//Error here: "Object 'CLRObject' could not be created"
writer = new System.IO.StreamWriter(gzip);
writer.Write(decodedString);
writer.Close();
CodeAccessPermission::revertAssert();
}
catch (Exception::CLRError) {
//Code never executes past this point
ex = CLRInterop::getLastException();
while(ex != null) {
error(ex.ToString());
ex = ex.get_InnerException();
}
}
ttsCommit;
info(decodedString);
}
Edit: building on @robert-allen 's answer below, the correct code to accomplish this in AX is:
static void Job2(Args _args)
{
System.String decodedString;
System.Byte[] buffer;
System.IO.Compression.GZipStream gzip;
System.IO.StreamReader reader; //<-- Reader instead of writer
System.IO.MemoryStream output;
InteropPermission permission;
CLRObject ex;
str compressedString ="Compressed data here";
;
ttsBegin;
permission = new InteropPermission(InteropKind::ClrInterop);
permission.assert();
buffer = System.Convert::FromBase64String(compressedString);
output = new System.IO.MemoryStream(buffer);
gzip = new System.IO.Compression.GZipStream(output, System.IO.Compression.CompressionMode::Decompress);
try {
//Reader code changes
reader = new System.IO.StreamReader(gzip);
decodedString = reader.ReadToEnd();
reader.Close();
//End reader code changes
CodeAccessPermission::revertAssert();
}
catch (Exception::CLRError) {
//Code never executes past this point
ex = CLRInterop::getLastException();
while(ex != null) {
error(ex.ToString());
ex = ex.get_InnerException();
}
}
ttsCommit;
info(decodedString);
}