我正在尝试在 X++ 中对 .NET GZIPStream 进行放气,但遇到了一个错误。创建字符串的 .NET 代码非常简单:
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;
}
AX 端将通过一些 Web 服务调用获取压缩字符串。我目前拥有的 X++ 代码如下,但在创建 StreamWriter 时出现错误“无法创建对象 'CLRObject'”。
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);
}
编辑:基于@robert-allen 下面的答案,在 AX 中完成此操作的正确代码是:
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);
}