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

Автор Тема: Ошибка вставки блоков  (Прочитано 323 раз)

0 Пользователей и 2 Гостей просматривают эту тему.

Оффлайн AtomohodАвтор темы

  • ADN OPEN
  • ****
  • Сообщений: 461
  • Карма: 1
Ошибка вставки блоков
« : 22-06-2025, 16:41:28 »
Здравствуйте!
Не могу понять причину поведения кода. Если запускаю его отдельно по команде 111ImportAndInsertBlocks, все в порядке метод работает. Если же вызываю его из кода см. метод ниже, то по окончании работы метода кад чуть зависает и аварийно закрывается без всяких сообщений. Если вызов ImportAndInsertBlocksFromDwg закоммитить то второй метод прекрасно работает без проблем. Что не так с методом вставки блоков?

Код - C# [Выбрать]
  1. [CommandMethod("111ImportAndInsertBlocks")]
  2. public static void ImportAndInsertBlocksFromDwg()
  3. {
  4.     Document doc = Application.DocumentManager.MdiActiveDocument;
  5.     Database destDb = doc.Database;
  6.     Editor ed = doc.Editor;
  7.     string sourceFilePath = @"G:\Blocks\Iso3DBlocks.dwg";
  8.     if (!File.Exists(sourceFilePath))
  9.     {
  10.         ed.WriteMessage("\nФайл не найден.");
  11.         return;
  12.     }
  13.  
  14.     using (Database sourceDb = new Database(false, true))
  15.     {
  16.         try
  17.         {
  18.             sourceDb.ReadDwgFile(sourceFilePath, FileShare.Read, true, "");
  19.             sourceDb.CloseInput(true);
  20.  
  21.             // Собираем все блоки
  22.             ObjectIdCollection blockIds = new ObjectIdCollection();
  23.             List<string> blockNames = new List<string>();
  24.  
  25.             using (Transaction trSrc = sourceDb.TransactionManager.StartTransaction())
  26.             {
  27.                 BlockTable btSrc = (BlockTable) trSrc.GetObject(sourceDb.BlockTableId, OpenMode.ForRead);
  28.  
  29.                 foreach (ObjectId id in btSrc)
  30.                 {
  31.                     BlockTableRecord btr = (BlockTableRecord) trSrc.GetObject(id, OpenMode.ForRead);
  32.                     if (!btr.IsAnonymous && !btr.IsLayout)
  33.                     {
  34.                         blockIds.Add(id);
  35.                         blockNames.Add(btr.Name);
  36.                     }
  37.                 }
  38.  
  39.                 trSrc.Commit();
  40.             }
  41.  
  42.             if (blockIds.Count == 0)
  43.             {
  44.                 ed.WriteMessage("\nВ исходном файле не найдено подходящих блоков.");
  45.                 return;
  46.             }
  47.  
  48.             // Копируем блоки
  49.             IdMapping idMap = new IdMapping();
  50.             sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, idMap, DuplicateRecordCloning.Replace, false);
  51.  
  52.             // Вставка блоков
  53.             using (Transaction tr = destDb.TransactionManager.StartTransaction())
  54.             {
  55.                 BlockTable bt = (BlockTable) tr.GetObject(destDb.BlockTableId, OpenMode.ForRead);
  56.                 BlockTableRecord ms = (BlockTableRecord) tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
  57.  
  58.                 foreach (string name in blockNames)
  59.                 {
  60.                     if (bt.Has(name))
  61.                     {
  62.                         ObjectId btrId = bt[name];
  63.                         BlockReference br = new BlockReference(Point3d.Origin, btrId);
  64.                         ms.AppendEntity(br);
  65.                         tr.AddNewlyCreatedDBObject(br, true);
  66.                     }
  67.                 }
  68.  
  69.                 tr.Commit();
  70.             }
  71.  
  72.             ed.WriteMessage($"\nУспешно импортировано и вставлено блоков: {blockNames.Count}");
  73.         }
  74.         catch (System.Exception ex)
  75.         {
  76.             ed.WriteMessage($"\nОшибка: {ex.Message}");
  77.         }
  78.     }
  79. }

Код - C# [Выбрать]
  1.  public static void FindLinePairs()
  2.  {
  3.      Root z = GetIsometryFromJson(@"G:\DevProjects\Iso3DRepo\a62488f5-29fe-4525-b6e2-eb8ac404e237.json");
  4.    
  5.  
  6.      Document doc = Application.DocumentManager.MdiActiveDocument;
  7.      Database db = doc.Database;
  8.      Editor ed = doc.Editor;
  9.    
  10.      PolylineBlockAligner.ImportAndInsertBlocksFromDwg();
  11.      if (z.Pipes.Count > 0)
  12.      {
  13.          List<List<ObjectId>> vpList = new List<List<ObjectId>>();
  14.          using (Transaction trans = db.TransactionManager.StartTransaction())
  15.          {
  16.              BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
  17.              BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
  18.              int color = 10;
  19.              foreach (Pipe pipe in z.Pipes)
  20.              {
  21.                  foreach (Branch branch in pipe.Branches)
  22.                  {
  23.                      List<ObjectId> ids = new List<ObjectId>();
  24.  
  25.                      Point3dCollection points = new Point3dCollection();
  26.                      foreach (BranchObject item in branch.BranchObjects)
  27.                      {
  28.                          ObjectId layer = Debugger.CreateLayer(branch.Name.Replace('/', '-') + " " + item.ElementType + " --- " + item.Name.Replace('/', '-').Replace('=', ' '));
  29.  
  30.                          Point3d arrive = new Point3d(item.ArriveXPosition, item.ArriveYPosition, item.ArriveZPosition);
  31.                          Point3d leave = new Point3d(item.LeaveXPosition, item.LeaveYPosition, item.LeaveZPosition);
  32.  
  33.                          Point3d pointA = new Point3d(item.ElementXPosition, item.ElementYPosition, item.ElementZPosition);
  34.  
  35.                          points.Add(arrive);
  36.                          points.Add(pointA);
  37.                          points.Add(leave);
  38.                        
  39.                          using (MText mtext = new MText())
  40.                          {
  41.                              mtext.TextHeight = 5;
  42.                              mtext.Attachment = AttachmentPoint.MiddleLeft;
  43.                              mtext.Contents = item.ToString();
  44.                            //  mtext.Contents = item.ElementType;
  45.                              mtext.ColorIndex = color;
  46.                              mtext.Location = pointA;
  47.                              mtext.Normal = new Vector3d(-0.5774, -0.5774, 0.5774);
  48.                              mtext.Direction = new Vector3d(0.7071, -0.7071, 0);
  49.                              btr.AppendEntity(mtext);
  50.                              trans.AddNewlyCreatedDBObject(mtext, true);
  51.                              mtext.LayerId = layer;
  52.                          }
  53.                          
  54.                          Polyline3d polyline3D;
  55.                          if (item.ElementType.Contains("BEND"))
  56.                          {
  57.                              polyline3D = new Polyline3d(Poly3dType.QuadSplinePoly, points, false);
  58.                          }
  59.                          else if (item.ElementType.Contains("ELBOW"))
  60.                          {
  61.                              polyline3D = new Polyline3d(Poly3dType.CubicSplinePoly, points, false);
  62.                          }
  63.                          else
  64.                          {
  65.                              polyline3D = new Polyline3d(Poly3dType.SimplePoly, points, false);
  66.                          }
  67.                          polyline3D.LineWeight = LineWeight.LineWeight080;
  68.                          polyline3D.ColorIndex = color;
  69.  
  70.                          polyline3D.LayerId = layer;
  71.                          btr.AppendEntity(polyline3D);
  72.                          trans.AddNewlyCreatedDBObject(polyline3D, true);
  73.                          XDataUtilities.AddJsonXDataToObject(polyline3D.ObjectId, item);
  74.                          ids.Add(polyline3D.ObjectId);
  75.                          points.Clear();
  76.                          if (item.ElementType.Contains("VALVE"))
  77.                          {
  78.                              BlockUtilities.InsertAndAlignValveBlock(pointA, polyline3D.ObjectId);
  79.                          }
  80.                          if (item.ElementType.Contains("FLANGE"))
  81.                          {
  82.                              BlockUtilities.InsertAndAlignFlangeBlock(pointA, polyline3D.ObjectId);
  83.                          }
  84.                      }
  85.  
  86.                      // Создаем 3D полилинию
  87.                      color += 5;
  88.                      vpList.Add(ids);
  89.                      //ids.Clear();
  90.                  }
  91.              }
  92.              trans.Commit();
  93.          }
  94.        
  95.      }
  96.      else
  97.      {
  98.          ed.WriteMessage("\nПары линий с общей точкой не найдены.");
  99.      }
  100.  
  101.      ViewSetter viewSetter = new ViewSetter();
  102.      viewSetter.SetSouthWestIsometricViewInModelSpace();
  103.      ed.Regen();
  104.  }

Оффлайн Привалов Дмитрий

  • ADN Club
  • *****
  • Сообщений: 562
  • Карма: 121
Re: Ошибка вставки блоков
« Ответ #1 : 23-06-2025, 07:25:06 »
Что не так с методом вставки блоков?
1. Нет блокировки текущего документа.
2. IdMapping idMap = new IdMapping(); Нужно вызвать Dispose(), после клонирования.