ADN Club > AutoCAD .NET API

Ошибка вставки блоков

(1/1)

Atomohod:
Здравствуйте!
Не могу понять причину поведения кода. Если запускаю его отдельно по команде 111ImportAndInsertBlocks, все в порядке метод работает. Если же вызываю его из кода см. метод ниже, то по окончании работы метода кад чуть зависает и аварийно закрывается без всяких сообщений. Если вызов ImportAndInsertBlocksFromDwg закоммитить то второй метод прекрасно работает без проблем. Что не так с методом вставки блоков?


--- Код - C# [Выбрать] ---[CommandMethod("111ImportAndInsertBlocks")]public static void ImportAndInsertBlocksFromDwg(){    Document doc = Application.DocumentManager.MdiActiveDocument;    Database destDb = doc.Database;    Editor ed = doc.Editor;    string sourceFilePath = @"G:\Blocks\Iso3DBlocks.dwg";    if (!File.Exists(sourceFilePath))    {        ed.WriteMessage("\nФайл не найден.");        return;    }     using (Database sourceDb = new Database(false, true))    {        try        {            sourceDb.ReadDwgFile(sourceFilePath, FileShare.Read, true, "");            sourceDb.CloseInput(true);             // Собираем все блоки            ObjectIdCollection blockIds = new ObjectIdCollection();            List<string> blockNames = new List<string>();             using (Transaction trSrc = sourceDb.TransactionManager.StartTransaction())            {                BlockTable btSrc = (BlockTable) trSrc.GetObject(sourceDb.BlockTableId, OpenMode.ForRead);                 foreach (ObjectId id in btSrc)                {                    BlockTableRecord btr = (BlockTableRecord) trSrc.GetObject(id, OpenMode.ForRead);                    if (!btr.IsAnonymous && !btr.IsLayout)                    {                        blockIds.Add(id);                        blockNames.Add(btr.Name);                    }                }                 trSrc.Commit();            }             if (blockIds.Count == 0)            {                ed.WriteMessage("\nВ исходном файле не найдено подходящих блоков.");                return;            }             // Копируем блоки            IdMapping idMap = new IdMapping();            sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, idMap, DuplicateRecordCloning.Replace, false);             // Вставка блоков            using (Transaction tr = destDb.TransactionManager.StartTransaction())            {                BlockTable bt = (BlockTable) tr.GetObject(destDb.BlockTableId, OpenMode.ForRead);                BlockTableRecord ms = (BlockTableRecord) tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);                 foreach (string name in blockNames)                {                    if (bt.Has(name))                    {                        ObjectId btrId = bt[name];                        BlockReference br = new BlockReference(Point3d.Origin, btrId);                        ms.AppendEntity(br);                        tr.AddNewlyCreatedDBObject(br, true);                    }                }                 tr.Commit();            }             ed.WriteMessage($"\nУспешно импортировано и вставлено блоков: {blockNames.Count}");        }        catch (System.Exception ex)        {            ed.WriteMessage($"\nОшибка: {ex.Message}");        }    }}

--- Код - C# [Выбрать] --- public static void FindLinePairs() {     Root z = GetIsometryFromJson(@"G:\DevProjects\Iso3DRepo\a62488f5-29fe-4525-b6e2-eb8ac404e237.json");          Document doc = Application.DocumentManager.MdiActiveDocument;     Database db = doc.Database;     Editor ed = doc.Editor;        PolylineBlockAligner.ImportAndInsertBlocksFromDwg();     if (z.Pipes.Count > 0)     {         List<List<ObjectId>> vpList = new List<List<ObjectId>>();         using (Transaction trans = db.TransactionManager.StartTransaction())         {             BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;             BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;             int color = 10;             foreach (Pipe pipe in z.Pipes)             {                 foreach (Branch branch in pipe.Branches)                 {                     List<ObjectId> ids = new List<ObjectId>();                      Point3dCollection points = new Point3dCollection();                     foreach (BranchObject item in branch.BranchObjects)                     {                         ObjectId layer = Debugger.CreateLayer(branch.Name.Replace('/', '-') + " " + item.ElementType + " --- " + item.Name.Replace('/', '-').Replace('=', ' '));                          Point3d arrive = new Point3d(item.ArriveXPosition, item.ArriveYPosition, item.ArriveZPosition);                         Point3d leave = new Point3d(item.LeaveXPosition, item.LeaveYPosition, item.LeaveZPosition);                          Point3d pointA = new Point3d(item.ElementXPosition, item.ElementYPosition, item.ElementZPosition);                          points.Add(arrive);                         points.Add(pointA);                         points.Add(leave);                                                using (MText mtext = new MText())                         {                             mtext.TextHeight = 5;                             mtext.Attachment = AttachmentPoint.MiddleLeft;                             mtext.Contents = item.ToString();                           //  mtext.Contents = item.ElementType;                             mtext.ColorIndex = color;                             mtext.Location = pointA;                             mtext.Normal = new Vector3d(-0.5774, -0.5774, 0.5774);                             mtext.Direction = new Vector3d(0.7071, -0.7071, 0);                             btr.AppendEntity(mtext);                             trans.AddNewlyCreatedDBObject(mtext, true);                             mtext.LayerId = layer;                         }                                                  Polyline3d polyline3D;                         if (item.ElementType.Contains("BEND"))                         {                             polyline3D = new Polyline3d(Poly3dType.QuadSplinePoly, points, false);                         }                         else if (item.ElementType.Contains("ELBOW"))                         {                             polyline3D = new Polyline3d(Poly3dType.CubicSplinePoly, points, false);                         }                         else                         {                             polyline3D = new Polyline3d(Poly3dType.SimplePoly, points, false);                         }                         polyline3D.LineWeight = LineWeight.LineWeight080;                         polyline3D.ColorIndex = color;                          polyline3D.LayerId = layer;                         btr.AppendEntity(polyline3D);                         trans.AddNewlyCreatedDBObject(polyline3D, true);                         XDataUtilities.AddJsonXDataToObject(polyline3D.ObjectId, item);                         ids.Add(polyline3D.ObjectId);                         points.Clear();                         if (item.ElementType.Contains("VALVE"))                         {                             BlockUtilities.InsertAndAlignValveBlock(pointA, polyline3D.ObjectId);                         }                         if (item.ElementType.Contains("FLANGE"))                         {                             BlockUtilities.InsertAndAlignFlangeBlock(pointA, polyline3D.ObjectId);                         }                     }                      // Создаем 3D полилинию                     color += 5;                     vpList.Add(ids);                     //ids.Clear();                 }             }             trans.Commit();         }            }     else     {         ed.WriteMessage("\nПары линий с общей точкой не найдены.");     }      ViewSetter viewSetter = new ViewSetter();     viewSetter.SetSouthWestIsometricViewInModelSpace();     ed.Regen(); }

Привалов Дмитрий:

--- Цитата: Atomohod от 22-06-2025, 16:41:28 ---Что не так с методом вставки блоков?
--- Конец цитаты ---
1. Нет блокировки текущего документа.
2. IdMapping idMap = new IdMapping(); Нужно вызвать Dispose(), после клонирования.

Atomohod:

--- Цитата: Привалов Дмитрий от 23-06-2025, 07:25:06 --- Нужно вызвать Dispose(), после клонирования.
--- Конец цитаты ---
это помогло, спасибо!

Навигация

[0] Главная страница сообщений

Перейти к полной версии