public class JsonXRecordCommands
{
[CommandMethod("StoreJsonInXRecord")]
public void StoreJsonInXRecord()
{
string jsonFilePath = @"G:\DevProjects\a62488f5-29fe-4525-b6e2-eb8ac404e237.json";
try
{
// Чтение JSON-файла и преобразование в байты
string jsonString = File.ReadAllText(jsonFilePath);
byte[] fullData = Encoding.UTF8.GetBytes(jsonString);
int chunkSize = 100 * 1024; // 100 КБ
// Создание списка для хранения частей данных
List<TypedValue> typedValues = new List<TypedValue>();
for (int i = 0; i < fullData.Length; i += chunkSize)
{
int length = Math.Min(chunkSize, fullData.Length - i);
byte[] chunk = new byte[length];
Array.Copy(fullData, i, chunk, 0, length);
typedValues.Add(new TypedValue((int) DxfCode.BinaryChunk, chunk));
}
// Создание ResultBuffer из списка частей
ResultBuffer rb = new ResultBuffer(typedValues.ToArray());
Database db = Application.DocumentManager.MdiActiveDocument.Database;
// Сохранение в XRecord
using (Transaction tr = db.TransactionManager.StartTransaction())
{
DBDictionary nod = (DBDictionary) tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite);
string key = "MyJsonData";
ObjectId xrecId;
if (nod.Contains(key))
{
xrecId = nod.GetAt(key);
}
else
{
Xrecord xrec = new Xrecord();
nod.SetAt(key, xrec);
tr.AddNewlyCreatedDBObject(xrec, true);
xrecId = xrec.ObjectId;
}
Xrecord xrec1 = (Xrecord) tr.GetObject(xrecId, OpenMode.ForWrite);
xrec1.Data = rb;
tr.Commit();
}
}
catch (Exception ex)
{
Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage($"Ошибка: {ex.Message}\n");
}
}
[CommandMethod("RetrieveJsonFromXRecord")]
public void RetrieveJsonFromXRecord()
{
Database db = Application.DocumentManager.MdiActiveDocument.Database;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
DBDictionary nod = (DBDictionary) tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead);
string key = "MyJsonData";
if (nod.Contains(key))
{
ObjectId xrecId = nod.GetAt(key);
Xrecord xrec = (Xrecord) tr.GetObject(xrecId, OpenMode.ForRead);
ResultBuffer rb = xrec.Data;
// Сбор всех частей данных
List<byte> fullData = new List<byte>();
foreach (TypedValue tv in rb.AsArray())
{
if (tv.TypeCode == (int) DxfCode.BinaryChunk)
{
byte[] chunk = (byte[]) tv.Value;
fullData.AddRange(chunk);
}
}
// Преобразование в строку JSON
string jsonString = Encoding.UTF8.GetString(fullData.ToArray());
Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage($"JSON: {jsonString}\n");
}
else
{
Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("XRecord не найден.\n");
}
}
}
}