public static BlockDrawingObject Create(Database target, string blockName)
        {
            Transaction trans = target.TransactionManager.TopTransaction;
            BlockTable  bt    = (BlockTable)trans.GetObject(target.BlockTableId, OpenMode.ForRead);

            SymbolUtilityServices.ValidateSymbolName(blockName, false);
            if (bt.Has(blockName))
            {
                throw  new InvalidOperationException("Block name exists");
            }

            BlockTableRecord btr = new BlockTableRecord();

            btr.Name = blockName;

            bt.UpgradeOpen();
            ObjectId btrId = bt.Add(btr);

            trans.AddNewlyCreatedDBObject(btr, true);

            BlockDrawingObject blockDrawingObject = new BlockDrawingObject(target);

            blockDrawingObject.BaseObject = btrId;
            return(blockDrawingObject);
        }
Example #2
0
 /// <summary>
 /// 通过块Id来克隆块
 /// </summary>
 /// <param name="BlockId"></param>
 /// <param name="name"></param>
 /// <returns></returns>
 public ObjectId CreateBlockByClone(ObjectId BlockId)
 {
     try
     {
         using (Transaction tran = database.TransactionManager.StartTransaction())
         {
             BlockTableRecord SourceBtr = BlockId.GetObject(OpenMode.ForRead) as BlockTableRecord;
             BlockTbl.UpgradeOpen();//提升权限
             BlockTableRecord newBlock = new BlockTableRecord();
             newBlock.Name = SourceBtr.Name;
             ObjectId NewBlockId = BlockTbl.Add(newBlock);
             tran.AddNewlyCreatedDBObject(newBlock, true);
             BlockTbl.DowngradeOpen();//降低权限
             BlockHelper blockHelper = new BlockHelper(dwgHelper, newBlock);
             blockHelper.CloneEntitiesFromBlock(BlockId);
             tran.Commit();
             return(NewBlockId);
         }
     }
     catch (Exception ex)
     {
         Logger.log("CreateBlockByClone", ex.Message);
     }
     return(ObjectId.Null);
 }
Example #3
0
        /// <summary>
        /// Realizá la carga del bloque
        /// </summary>
        /// <param name="tr">La transacción activa.</param>
        /// <param name="localDwg">La base de datos local.</param>
        /// <param name="file">La ruta del bloque a cargar.</param>
        /// <param name="blockName">El nombre del bloque.</param>
        public static void LoadBlock(this Transaction tr, Database localDwg, string file, string blockName)
        {
            BlockTable blkTab = (BlockTable)localDwg.BlockTableId.GetObject(OpenMode.ForRead);

            if (!blkTab.Has(blockName) && File.Exists(file))
            {
                blkTab.UpgradeOpen();
                BlockTableRecord newRecord = new BlockTableRecord();
                newRecord.Name = blockName;
                blkTab.Add(newRecord);
                tr.AddNewlyCreatedDBObject(newRecord, true);
                //3: Se abre la base de datos externa
                Database externalDB = new Database();
                externalDB.ReadDwgFile(file, FileShare.Read, true, null);
                //4: Con una subtransacción se clonán los elementos que esten contenidos en el espcio de modelo de la
                //base de datos externa
                ObjectIdCollection ids;
                using (Transaction subTr = externalDB.TransactionManager.StartTransaction())
                {
                    //4.1: Abrir el espacio de modelo de la base de datos externa
                    ObjectId         modelId = SymbolUtilityServices.GetBlockModelSpaceId(externalDB);
                    BlockTableRecord model   = subTr.GetObject(modelId, OpenMode.ForRead) as BlockTableRecord;
                    //4.2: Se extraen y clonan los elementos mediante la clase IdMapping
                    ids = new ObjectIdCollection(model.OfType <ObjectId>().ToArray());
                    using (IdMapping iMap = new IdMapping())
                        localDwg.WblockCloneObjects(ids, newRecord.Id, iMap, DuplicateRecordCloning.Replace, false);
                }
            }
        }
Example #4
0
 public Drawer(Transaction tr, String blockTableRecord = null)
 {
     this.Ids = new ObjectIdCollection();
     if (blockTableRecord == null)
     {
         //CurrentSpaceId Devuelve el espacio de modelo activo, ya
         //sea el modelspace o el paperspace
         this.Block = (BlockTableRecord)
                      Application.DocumentManager.MdiActiveDocument.Database.CurrentSpaceId.GetObject(OpenMode.ForWrite);
     }
     else
     {
         Database   dwg    = Application.DocumentManager.MdiActiveDocument.Database;
         BlockTable blkTab = (BlockTable)dwg.BlockTableId.GetObject(OpenMode.ForRead);
         if (blkTab.Has(blockTableRecord))
         {
             this.Block = (BlockTableRecord)blkTab[blockTableRecord].GetObject(OpenMode.ForWrite);
         }
         else
         {
             //Se crea un nuevo registro si no existe
             BlockTableRecord newRecord = new BlockTableRecord();
             newRecord.Name = blockTableRecord;
             //Cambia un objeto abierto de modo lectura a modo escritura
             blkTab.UpgradeOpen();
             blkTab.Add(newRecord);
             tr.AddNewlyCreatedDBObject(newRecord, true);
             this.Block = newRecord;
             this.Block.UpgradeOpen();
         }
     }
     this.ActiveTransaction = tr;
 }
Example #5
0
        public static ObjectId GetBlock(this BlockTable blockTable, string blockName)
        {
            string   str;
            ObjectId @null;
            Database database = blockTable.Database;
            string   fileNameWithoutExtension = Path.GetFileNameWithoutExtension(blockName);

            if (blockTable.Has(fileNameWithoutExtension))
            {
                return(blockTable[fileNameWithoutExtension]);
            }
            try
            {
                if (Path.GetExtension(blockName) == "")
                {
                    blockName = string.Concat(blockName, ".dwg");
                }
                str = (!File.Exists(blockName) ? HostApplicationServices.Current.FindFile(blockName, database, FindFileHint.Default) : blockName);
                blockTable.UpgradeOpen();
                using (Database database1 = new Database(false, true))
                {
                    database1.ReadDwgFile(str, FileShare.Read, true, null);
                    @null = blockTable.Database.Insert(Path.GetFileNameWithoutExtension(blockName), database1, true);
                }
            }
            catch
            {
                @null = ObjectId.Null;
            }
            return(@null);
        }
Example #6
0
        public void CreateBlock()
        {
            using (Transaction tr = AcadFuncs.GetActiveDb().TransactionManager.StartTransaction())
            {
                // Get the block table from the drawing
                BlockTable blk_tbl = (BlockTable)tr.GetObject(
                    AcadFuncs.GetActiveDb().BlockTableId,
                    OpenMode.ForRead);

                PromptStringOptions pso = new PromptStringOptions("\nEnter new block name: ");
                pso.AllowSpaces = true;
                string blk_name = "";
                do
                {
                    PromptResult pr = AcadFuncs.GetEditor().GetString(pso);
                    if (PromptStatus.OK != pr.Status)
                    {
                        return;
                    }

                    try
                    {
                        SymbolUtilityServices.ValidateSymbolName(pr.StringResult, false);
                        if (blk_tbl.Has(pr.StringResult))
                        {
                            AcadFuncs.GetEditor().WriteMessage("\nA block with this name already exists.");
                        }
                        else
                        {
                            blk_name = pr.StringResult;
                        }
                    }
                    catch
                    {
                        AcadFuncs.GetEditor().WriteMessage("\nInvalid block name.");
                    }
                } while ("" == blk_name);

                BlockTableRecord btr = new BlockTableRecord();
                btr.Name = blk_name;

                blk_tbl.UpgradeOpen();
                ObjectId btrId = blk_tbl.Add(btr);
                tr.AddNewlyCreatedDBObject(btr, true);

                DBObjectCollection ents = SquareOfLines(5);
                foreach (Entity ent in ents)
                {
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                }

                BlockTableRecord ms = (BlockTableRecord)tr.GetObject(blk_tbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                BlockReference   br = new BlockReference(AcadGeo.Point3d.Origin, btrId);
                ms.AppendEntity(br);
                tr.AddNewlyCreatedDBObject(br, true);
                tr.Commit();
            }
        }
Example #7
0
        public static void CreateHandleBlock()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable       bt  = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = null;

                if (bt.Has("Handle"))
                {
                    btr = tr.GetObject(bt["Handle"], OpenMode.ForWrite) as BlockTableRecord;
                }
                else
                {
                    btr      = new BlockTableRecord();
                    btr.Name = "Handle";
                    bt.UpgradeOpen();
                    bt.Add(btr);
                    tr.AddNewlyCreatedDBObject(btr, true);
                }

                using (Autodesk.AutoCAD.DatabaseServices.Polyline outline = new Autodesk.AutoCAD.DatabaseServices.Polyline())
                {
                    outline.SetDatabaseDefaults();
                    outline.Normal = Vector3d.XAxis;

                    outline.AddVertexAt(0, new Point2d(0.0, 0.0), 0, 0, 0);
                    outline.AddVertexAt(1, new Point2d(0.0, 0.5 * t), 0, 0, 0);
                    outline.AddVertexAt(2, new Point2d(-t, 0.5 * t), 0, 0, 0);
                    outline.AddVertexAt(3, new Point2d(-t, 0.75 * t), 0, 0, 0);
                    outline.AddVertexAt(4, new Point2d(-1.25 * t, t), 0, 0, 0);
                    outline.AddVertexAt(5, new Point2d(-1.75 * t, t), 0, 0, 0);
                    outline.AddVertexAt(6, new Point2d(-2.0 * t, 0.75 * t), 0, 0, 0);
                    outline.AddVertexAt(7, new Point2d(-2.0 * t, 0.0), 0, 0, 0);
                    outline.Closed = true;

                    RevolveOptions        opts = new RevolveOptions();
                    RevolveOptionsBuilder rob  = new RevolveOptionsBuilder(opts);
                    rob.CloseToAxis = true;
                    rob.DraftAngle  = 0;
                    rob.TwistAngle  = 0;

                    Solid3d handle = new Solid3d();;
                    handle.CreateRevolvedSolid(outline, new Point3d(0, 0, 0), Vector3d.YAxis, 2.0 * Math.PI, 0, rob.ToRevolveOptions());
                    handle.ColorIndex = 0;

                    btr.AppendEntity(handle);
                    tr.AddNewlyCreatedDBObject(handle, true);

                    tr.Commit();
                }
            }
        }
Example #8
0
        public static ObjectId InsertBlock(Database db, string loName, string blkName, Point3d insPt)
        {
            ObjectId RtnObjId = ObjectId.Null;

            using (Transaction Trans = db.TransactionManager.StartTransaction())
            {
                DBDictionary LoDict = Trans.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;
                foreach (DictionaryEntry de in LoDict)
                {
                    if (string.Compare((string)de.Key, loName, true).Equals(0))
                    {
                        Layout           Lo          = Trans.GetObject((ObjectId)de.Value, OpenMode.ForWrite) as Layout;
                        BlockTable       BlkTbl      = Trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                        BlockTableRecord LoRec       = Trans.GetObject(Lo.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord;
                        ObjectId         BlkTblRecId = GetNonErasedTableRecordId(BlkTbl.Id, blkName);
                        if (BlkTblRecId.IsNull)
                        {
                            string BlkPath = HostApplicationServices.Current.FindFile(blkName + ".dwg", db, FindFileHint.Default);
                            if (string.IsNullOrEmpty(BlkPath))
                            {
                                return(RtnObjId);
                            }
                            BlkTbl.UpgradeOpen();
                            using (Database tempDb = new Database(false, true))
                            {
                                tempDb.ReadDwgFile(BlkPath, FileShare.Read, true, null);
                                db.Insert(blkName, tempDb, false);
                            }
                            BlkTblRecId = GetNonErasedTableRecordId(BlkTbl.Id, blkName);
                        }
                        LoRec.UpgradeOpen();
                        BlockReference BlkRef = new BlockReference(insPt, BlkTblRecId);
                        LoRec.AppendEntity(BlkRef);
                        Trans.AddNewlyCreatedDBObject(BlkRef, true);
                        BlockTableRecord BlkTblRec = Trans.GetObject(BlkTblRecId, OpenMode.ForRead) as BlockTableRecord;
                        if (BlkTblRec.HasAttributeDefinitions)
                        {
                            foreach (ObjectId objId in BlkTblRec)
                            {
                                AttributeDefinition AttDef = Trans.GetObject(objId, OpenMode.ForRead) as AttributeDefinition;
                                if (AttDef != null)
                                {
                                    AttributeReference AttRef = new AttributeReference();
                                    AttRef.SetAttributeFromBlock(AttDef, BlkRef.BlockTransform);
                                    BlkRef.AttributeCollection.AppendAttribute(AttRef);
                                    Trans.AddNewlyCreatedDBObject(AttRef, true);
                                }
                            }
                        }
                        Trans.Commit();
                    }
                }
            }
            return(RtnObjId);
        }
Example #9
0
        private ObjectId GetBlkTblRcd(Transaction tr)
        {
            BlockTable       blk_tbl = AcadFuncs.GetBlkTbl(tr);
            BlockTableRecord blk_ref = new BlockTableRecord();

            blk_ref.Name = "TestBlkRef";
            blk_tbl.UpgradeOpen();
            blk_tbl.Add(blk_ref);
            tr.AddNewlyCreatedDBObject(blk_ref, true);
            return(blk_ref.Id);
        }
Example #10
0
        protected void CreateOutlineRecord(Transaction tr, BlockTable blockTable)
        {
            using (var record = new OutlineBlockTableRecord(CurrentPart))
            {
                blockTable.UpgradeOpen();
                blockTable.Add(record);
                tr.AddNewlyCreatedDBObject(record, true);

                record.BuildObject(tr, Properties.Algorythim.Options.OutlineDistance);
            }
        }
Example #11
0
        /// <summary>
        /// Создание определения блока панели по описанию из базы XML от конструкторов.
        /// Должна быть открыта транзакция.
        /// </summary>
        /// <exception cref="Autodesk.AutoCAD.Runtime.Exception">DuplicateBlockName</exception>
        /// <returns>ObjectId созданного определения блока в текущей базе.</returns>
        public void CreateBlock()
        {
            // Имя для блока панели АКР
            BlNameAkr = defineBlockPanelAkrName();

            Openings = new List <Extents3d>();

            Database db = Service.Db;

            //Transaction t = db.TransactionManager.TopTransaction;
            using (var t = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable;
                // Ошибка если блок с таким именем уже есть
                if (bt.Has(BlNameAkr))
                {
                    IdBtrPanel = bt[BlNameAkr];
                    Inspector.AddError($"Блок панели с именем {BlNameAkr} уже определен в чертеже.", icon: System.Drawing.SystemIcons.Error);
                    return;
                }
                BlockTableRecord btrPanel = new BlockTableRecord();
                btrPanel.Name = BlNameAkr;
                bt.UpgradeOpen();
                IdBtrPanel = bt.Add(btrPanel);
                bt.DowngradeOpen();
                t.AddNewlyCreatedDBObject(btrPanel, true);

                //корректировка точки отсчета панели
                correctStartPointCoordinatesPanel();

                // Добавление полилинии контура
                createContour(btrPanel, t);

                // Добавление окон
                addWindows(btrPanel, t);

                // заполнение плиткой
                addTiles(btrPanel, t);

                // Добавление торцов (Cheek)
                addCheek(btrPanel, t);

                // Образмеривание (на Фасаде)
                DimensionFacade dimFacade = new DimensionFacade(btrPanel, t, this);
                dimFacade.Create();

                // Образмеривание (в Форме)
                DimensionForm dimForm = new DimensionForm(btrPanel, t, this);
                dimForm.Create();

                t.Commit();
            }
        }
Example #12
0
        public static ObjectId criarDefiniçãoDeBloco(ObjectId[] objIds)
        {
            string   nomeBloco = "Teste1";
            Database db        = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                try
                {
                    Autodesk.AutoCAD.ApplicationServices.Document Doc = null;
                    Doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                    using (DocumentLock dl = Doc.LockDocument())
                    {
                        //abrir tabela de blocos
                        BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;

                        //verificar se o bloco já existe
                        if (bt.Has(nomeBloco))
                        {
                            return(bt[nomeBloco]);
                        }
                        BlockTableRecord novoBloco = new BlockTableRecord();
                        novoBloco.Name = nomeBloco;

                        bt.UpgradeOpen();
                        bt.Add(novoBloco);

                        trans.AddNewlyCreatedDBObject(novoBloco, true);

                        foreach (ObjectId objId in objIds)
                        {
                            DBObject obj      = trans.GetObject(objId, OpenMode.ForRead);
                            Entity   ent      = (Entity)obj;
                            Entity   entClone = ent.Clone() as Entity;
                            novoBloco.AppendEntity(entClone);
                            trans.AddNewlyCreatedDBObject(entClone, true);
                        }

                        trans.Commit();

                        return(novoBloco.ObjectId);
                    }
                }
                catch (System.Exception ex)
                {
                    trans.Abort();

                    return(ObjectId.Null);
                }
            }
        }
Example #13
0
        /// <summary>
        /// Loads a block table record from an external database to the current database.
        /// If the blockname exists on the table record, the block table record id is taken from the curren database block table.
        /// </summary>
        /// <param name="blockname">The block table record name.</param>
        /// <param name="filePath">The dwg block file path.</param>
        /// <param name="tr">The active transaction.</param>
        /// <returns>The object id of the block table record</returns>
        public static ObjectId _LoadBlock(this String blockname, String filePath, Transaction tr)
        {
            ObjectId id  = new ObjectId();
            Database dwg = Application.DocumentManager.MdiActiveDocument.Database;

            try
            {
                BlockTable blkTab = (BlockTable)dwg.BlockTableId.GetObject(OpenMode.ForRead);
                if (!blkTab.Has(blockname))
                {
                    //1: Se crea un registro de bloque
                    blkTab.UpgradeOpen();
                    BlockTableRecord newRecord = new BlockTableRecord();
                    newRecord.Name = blockname;
                    //2: Se agregá el registro a la tabla
                    blkTab.Add(newRecord);
                    tr.AddNewlyCreatedDBObject(newRecord, true);
                    //3: Se abre la base de datos externa
                    Database externalDB = new Database(false, true);
                    externalDB.ReadDwgFile(filePath, FileShare.Read, true, "");
                    //4: Con una subtransacción se clonán los elementos que esten contenidos en el espcio de modelo de la
                    //base de datos externa
                    ObjectIdCollection ids;
                    using (Transaction subTr = externalDB.TransactionManager.StartTransaction())
                    {
                        //4.1: Abrir el espacio de modelo de la base de datos externa
                        ObjectId         modelId = SymbolUtilityServices.GetBlockModelSpaceId(externalDB);
                        BlockTableRecord model   = subTr.GetObject(modelId, OpenMode.ForRead) as BlockTableRecord;
                        //4.2: Se extraen y clonan los elementos mediante la clase IdMapping
                        ids = new ObjectIdCollection(model.OfType <ObjectId>().ToArray());
                        //IEnumerable<DBObject> objs = ids.OfType<ObjectId>().Select(x => x.GetObject(OpenMode.ForRead));
                        int erased = ids.OfType <ObjectId>().Count(x => x.IsValid);
                        using (IdMapping iMap = new IdMapping())
                            dwg.WblockCloneObjects(ids, newRecord.Id, iMap, DuplicateRecordCloning.Replace, false);
                    }
                    id = newRecord.Id;
                }
                else
                {
                    id = blkTab[blockname];
                }
            }
            catch (Exception exc)
            {
                throw exc;
            }
            return(id);
        }
Example #14
0
        private ObjectId GetOrCreateBlock(Database db, string blockName, ObjectId textLayerId, ObjectId lineLayerId, ObjectId textStyleId)
        {
            ObjectId id = ObjectId.Null;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable table = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                if (table.Has(blockName))
                {
                    id = table[blockName];
                }
                else
                {
                    BlockTableRecord blockDef = new BlockTableRecord();
                    blockDef.Name = blockName;

                    table.UpgradeOpen();
                    id = table.Add(blockDef);
                    tr.AddNewlyCreatedDBObject(blockDef, true);

                    double crossSize = 1;
                    double spacing   = 0.5;
                    double th        = 1;

                    Point3d pt = new Point3d(0, 0, 0);

                    Line line1 = AcadUtility.AcadEntity.CreateLine(db, pt - new Vector3d(crossSize, 0, 0), pt + new Vector3d(crossSize, 0, 0), lineLayerId);
                    Line line2 = AcadUtility.AcadEntity.CreateLine(db, pt - new Vector3d(0, crossSize, 0), pt + new Vector3d(0, crossSize, 0), lineLayerId);

                    AttributeDefinition text1 = AcadUtility.AcadEntity.CreateAttribute(db, pt + new Vector3d(crossSize + spacing, 0, 0), "Y", "Y", "0 000 000", th, 0, 1, TextHorizontalMode.TextLeft, TextVerticalMode.TextVerticalMid, textStyleId, textLayerId);
                    text1.LockPositionInBlock = true;
                    AttributeDefinition text2 = AcadUtility.AcadEntity.CreateAttribute(db, pt + new Vector3d(0, crossSize + spacing, 0), "X", "X", "0 000 000", th, Math.PI / 2, 1, TextHorizontalMode.TextLeft, TextVerticalMode.TextVerticalMid, textStyleId, textLayerId);
                    text2.LockPositionInBlock = true;

                    foreach (Entity ent in new Entity[] { line1, line2, text1, text2 })
                    {
                        blockDef.AppendEntity(ent);
                        tr.AddNewlyCreatedDBObject(ent, true);
                    }
                }

                tr.Commit();
            }

            return(id);
        }
Example #15
0
        /// <summary>
        /// 创建一个块表记录并添加到数据库中
        /// </summary>
        /// <param name="db">数据库对象</param>
        /// <param name="blockName">块名</param>
        /// <param name="ents">加入块中的实体列表</param>
        /// <returns>返回块表记录的Id</returns>
        public static ObjectId AddBlockTableRecord(this Database db, string blockName, List <Entity> ents)
        {
            //打开块表
            BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead);

            if (!bt.Has(blockName)) //判断是否存在名为blockName的块
            {
                //创建一个BlockTableRecord类的对象,表示所要创建的块
                BlockTableRecord btr = new BlockTableRecord();
                btr.Name = blockName;//设置块名
                //将列表中的实体加入到新建的BlockTableRecord对象
                ents.ForEach(ent => btr.AppendEntity(ent));
                bt.UpgradeOpen();                                         //切换块表为写的状态
                bt.Add(btr);                                              //在块表中加入blockName块
                db.TransactionManager.AddNewlyCreatedDBObject(btr, true); //通知事务处理
                bt.DowngradeOpen();                                       //为了安全,将块表状态改为读
            }
            return(bt[blockName]);                                        //返回块表记录的Id
        }
 public static Boolean LoadBlock(String path, String blockname, Document doc, Transaction tr)
 {
     if (File.Exists(path))
     {
         //Buscamos que no exista el registro
         BlockTable blkTab = (BlockTable)
                             doc.Database.BlockTableId.GetObject(OpenMode.ForRead);
         //Si no existe el registro debe cargarse del archivo
         if (!blkTab.Has(blockname))
         {
             //1: Creación de espacio de bloque
             blkTab.UpgradeOpen();//A modo escritura para escribir el bloque
             BlockTableRecord newRecord = new BlockTableRecord();
             newRecord.Name = blockname;
             blkTab.Add(newRecord);
             tr.AddNewlyCreatedDBObject(newRecord, true);
             //2: Abrir base de datos externas
             Database external = new Database();
             external.ReadDwgFile(path, FileShare.Read, true, null);
             ObjectIdCollection ids;
             //3: Agregarles las entidades mediante un mapeo
             using (Transaction extTr = external.TransactionManager.StartTransaction())
             {
                 BlockTableRecord extModelSpace = (BlockTableRecord)
                                                  SymbolUtilityServices.GetBlockModelSpaceId(external).GetObject(OpenMode.ForRead);
                 ids = new ObjectIdCollection(extModelSpace.OfType <ObjectId>().ToArray());
                 using (IdMapping iMap = new IdMapping())
                 {
                     doc.Database.WblockCloneObjects(ids, newRecord.Id, iMap,
                                                     DuplicateRecordCloning.Replace, false);
                 }
             }
         }
         return(true);
     }
     else
     {
         BlockTable blkTab = (BlockTable)doc.Database.BlockTableId.GetObject(OpenMode.ForRead);
         //Si no existe el registro debe cargarse del archivo
         return(blkTab.Has(blockname));
     }
 }
Example #17
0
        public void CreateBlockFrom()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction())
            {
                DBObjectCollection objs = new DBObjectCollection();
                BlockTable         bt   = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                //EntProxy.Explode(objs);

                string blkName = "Getname";

                if (bt.Has(blkName) == false)
                {
                    BlockTableRecord btr = new BlockTableRecord();
                    btr.Name = blkName;

                    bt.UpgradeOpen();
                    ObjectId btrId = bt.Add(btr);
                    tr.AddNewlyCreatedDBObject(btr, true);

                    foreach (DBObject obj in objs)
                    {
                        Entity ent = (Entity)obj;
                        btr.AppendEntity(ent);
                        tr.AddNewlyCreatedDBObject(ent, true);
                    }

                    BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                    BlockReference br =
                        new BlockReference(Point3d.Origin, btrId);

                    ms.AppendEntity(br);
                    tr.AddNewlyCreatedDBObject(br, true);
                }
                tr.Commit();
            }
        }
Example #18
0
        public static ObjectId GetBlock(this BlockTable blockTable, string blockName)
        {
            if (blockTable == null)
            {
                throw new ArgumentNullException("blockTable");
            }
            Database db = blockTable.Database;

            if (blockTable.Has(blockName))
            {
                return(blockTable[blockName]);
            }
            try
            {
                string ext = Path.GetExtension(blockName);
                if (ext == "")
                {
                    blockName += ".dwg";
                }
                string blockPath;
                if (File.Exists(blockName))
                {
                    blockPath = blockName;
                }
                else
                {
                    blockPath = HostApplicationServices.Current.FindFile(blockName, db, FindFileHint.Default);
                }
                blockTable.UpgradeOpen();
                using (Database tmpDb = new Database(false, true))
                {
                    tmpDb.ReadDwgFile(blockPath, FileShare.Read, true, null);
                    return(blockTable.Database.Insert(Path.GetFileNameWithoutExtension(blockName), tmpDb, true));
                }
            }
            catch
            {
                return(ObjectId.Null);
            }
        }
Example #19
0
        public static void CreateBlock(string _name, DBObjectCollection ents)
        {
            Document mdiActiveDocument = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database database          = mdiActiveDocument.Database;

            using (mdiActiveDocument.LockDocument())
            {
                using (Transaction transaction = database.TransactionManager.StartTransaction())
                {
                    BlockTable       blockTable       = (BlockTable)transaction.GetObject(database.BlockTableId, OpenMode.ForRead);
                    BlockTableRecord blockTableRecord = new BlockTableRecord();
                    if (blockTable.Has(_name))
                    {
                        blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[_name], OpenMode.ForWrite, false, true);
                        foreach (ObjectId id in blockTableRecord)
                        {
                            Entity entity = (Entity)transaction.GetObject(id, OpenMode.ForWrite);
                            entity.Erase();
                        }
                        ObjectId objectId = blockTableRecord.ObjectId;
                    }
                    else
                    {
                        blockTableRecord.Name = _name;
                        blockTable.UpgradeOpen();
                        ObjectId objectId = blockTable.Add(blockTableRecord);
                        transaction.AddNewlyCreatedDBObject(blockTableRecord, true);
                    }
                    foreach (object obj2 in ents)
                    {
                        Entity entity = (Entity)obj2;
                        blockTableRecord.AppendEntity(entity);
                        transaction.AddNewlyCreatedDBObject(entity, true);
                    }
                    blockTableRecord.Units = UnitsValue.Millimeters;
                    transaction.Commit();
                }
            }
        }
Example #20
0
        private static void ImportMBlock(string path, BlockTable blockTable)
        {
            using (Database mBlocksDb = new Database(false, true))
            {
                ObjectIdCollection oidc;

                mBlocksDb.ReadDwgFile(path, FileShare.Read, false, null);
                mBlocksDb.CloseInput(true);

                using (Transaction trans = mBlocksDb.TransactionManager.StartTransaction())
                {
                    BlockTable       bt         = (BlockTable)mBlocksDb.BlockTableId.GetObject(OpenMode.ForRead);
                    BlockTableRecord modelSpace = (BlockTableRecord)bt[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForRead);

                    using (BlockTableRecord btr = new BlockTableRecord())
                    {
                        bt.UpgradeOpen();
                        bt.Add(btr);
                        btr.Name = Regex.Match(path, @"M\d{4}").Value;

                        oidc = new ObjectIdCollection();
                        foreach (ObjectId oid in modelSpace)
                        {
                            oidc.Add(oid);
                        }

                        btr.AssumeOwnershipOf(oidc);
                        trans.AddNewlyCreatedDBObject(btr, true);

                        oidc = new ObjectIdCollection(new ObjectId[] { btr.ObjectId });
                    }

                    trans.Commit();
                }

                mBlocksDb.WblockCloneObjects(oidc, blockTable.ObjectId, new IdMapping(), DuplicateRecordCloning.Ignore, false);
            }
        }
Example #21
0
        /// <summary> 创建块定义 </summary>
        public static ObjectId CreateBTR(Database db, string blockName, IEnumerable <Entity> ents)
        {
            BlockTable blockTable = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead);

            if (!blockTable.Has(blockName))
            {
                var btr = new BlockTableRecord
                {
                    Name = blockName
                };
                //将列表中的实体加入到新建的BlockTableRecord
                foreach (var ent in ents)
                {
                    btr.AppendEntity(ent);
                }

                blockTable.UpgradeOpen(); //切换块为写的状态
                blockTable.Add(btr);
                db.TransactionManager.AddNewlyCreatedDBObject(btr, true);
                blockTable.DowngradeOpen(); //切换块为读的状态
            }
            return(blockTable[blockName]);
        }
Example #22
0
        private ObjectId getIdBtrEnd(BlockTable bt)
        {
            ObjectId idBtrEnd;

            if (bt.Has(BlNameEnd))
            {
                // отредактировать существующий блок торца - удалтить все старые объекты
                idBtrEnd = bt[BlNameEnd];
                eraseEntInBlock(idBtrEnd);
                IsExistsBlockEnd = true;
            }
            else
            {
                using (var btr = new BlockTableRecord())
                {
                    btr.Name = BlNameEnd;
                    bt.UpgradeOpen();
                    idBtrEnd = bt.Add(btr);
                    bt.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(btr, true);
                }
            }
            return(idBtrEnd);
        }
Example #23
0
        public static void CreatePlotType()
        {
            Document acDoc    = Application.DocumentManager.MdiActiveDocument;
            Editor   acEditor = acDoc.Editor;
            Database acCurDb  = acDoc.Database;

            if (CurrentOpen == null)
            {
                PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter plot type name: ")
                {
                    AllowSpaces = true
                };
                PromptResult pStrRes = acDoc.Editor.GetString(pStrOpts);

                //Verify input
                if (pStrRes.Status == PromptStatus.OK)
                {
                    //Check the block does not already exist
                    bool exists = false;
                    using (Transaction tr = acCurDb.TransactionManager.StartTransaction())
                    {
                        //Create all plot specific layers
                        LayerTable acLayerTable = tr.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite) as LayerTable;
                        Core.Utilities.CreateLayer(tr, acLayerTable, Constants.JPP_HS_PlotPerimiter, Constants.JPP_HS_PlotPerimiterColor);

                        //Create the background block
                        BlockTable bt = (BlockTable)tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);
                        if (bt.Has(pStrRes.StringResult))
                        {
                            exists = true;
                        }
                    }

                    if (!exists)
                    {
                        // Prompt for the start point
                        PromptPointOptions pPtOpts = new PromptPointOptions("")
                        {
                            Message = "\nEnter the base point. Basepoint to be located at bottom left corner of the plot: "
                        };
                        PromptPointResult pPtRes = acDoc.Editor.GetPoint(pPtOpts);

                        if (pPtRes.Status == PromptStatus.OK)
                        {
                            CurrentOpen = new PlotType()
                            {
                                PlotTypeName = pStrRes.StringResult,
                                BasePoint    = pPtRes.Value
                            };

                            using (Transaction tr = acCurDb.TransactionManager.StartTransaction())
                            {
                                Main.AddRegAppTableRecord();

                                //Create all plot specific layers
                                LayerTable acLayerTable = tr.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite) as LayerTable;
                                Core.Utilities.CreateLayer(tr, acLayerTable, Constants.JPP_HS_PlotPerimiter, Constants.JPP_HS_PlotPerimiterColor);

                                //Create the background block
                                BlockTable bt = (BlockTable)tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);
                                bt.UpgradeOpen();

                                BlockTableRecord backgroundBlockRecord = new BlockTableRecord
                                {
                                    Name   = CurrentOpen.PlotTypeName + "Background",
                                    Origin = CurrentOpen.BasePoint
                                };
                                ObjectId objRef = bt.Add(backgroundBlockRecord);
                                tr.AddNewlyCreatedDBObject(backgroundBlockRecord, true);

                                //Prep the block for finalising
                                BlockTableRecord plotTypeBlockRecord = new BlockTableRecord
                                {
                                    Name   = CurrentOpen.PlotTypeName,
                                    Origin = CurrentOpen.BasePoint
                                };
                                ObjectId blockRef = bt.Add(plotTypeBlockRecord);
                                tr.AddNewlyCreatedDBObject(plotTypeBlockRecord, true);

                                //Insert the background block
                                CurrentOpen.BackgroundBlockID = Core.Utilities.InsertBlock(CurrentOpen.BasePoint, 0, objRef);
                                CurrentOpen.BlockID           = blockRef;

                                //Create and add basepoint
                                Circle bp = new Circle
                                {
                                    Center = CurrentOpen.BasePoint,
                                    Radius = 0.5f
                                };
                                BlockTableRecord acBlkTblRec = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                                if (acBlkTblRec != null)
                                {
                                    CurrentOpen.BasepointID = acBlkTblRec.AppendEntity(bp);
                                }
                                else
                                {
                                    //This should never, ever come up but best to handle it
                                    throw new NullReferenceException("Model space not found", null);
                                }

                                tr.AddNewlyCreatedDBObject(bp, true);

                                tr.Commit();
                            }

                            //Inform all event handlers the current plot type has changed
                            OnCurrentOpenChanged?.Invoke();
                        }
                        else
                        {
                            acEditor.WriteMessage("Point selection cancelled\n");
                        }
                    }
                    else
                    {
                        acEditor.WriteMessage("Plot Type Name already exists as block. Please choose a different name or rename exisitng block\n");
                    }
                }
                else
                {
                    acEditor.WriteMessage("No plot type name entered\n");
                }
            }
            else
            {
                acEditor.WriteMessage("Plot Type already open for editing. Please finalise before attempting to create a new plot type.\n");
            }
        }
Example #24
0
        //loads the block into the blocktable if it isnt there
        //then uses a jig to find extents of print area
        public static Extents3d BlockInserter(Database db, Editor ed, Document doc)
        {
            //create a window to show the plot area
            Polyline polyPlot = new Polyline();

            polyPlot.AddVertexAt(0, new Point2d(-4.25, 5.5), 0, 0, 0);
            polyPlot.AddVertexAt(1, new Point2d(4.25, 5.5), 0, 0, 0);
            polyPlot.AddVertexAt(2, new Point2d(4.25, -5.5), 0, 0, 0);
            polyPlot.AddVertexAt(3, new Point2d(-4.25, -5.5), 0, 0, 0);
            polyPlot.Closed = true;

            using (Transaction trCurrent = db.TransactionManager.StartTransaction())
            {
                //open block table for read
                BlockTable btCurrent = trCurrent.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                //check if spec is already loaded into drawing
                ObjectId blkRecId = ObjectId.Null;
                if (!btCurrent.Has("PlotGuide"))
                {
                    using (BlockTableRecord newRec = new BlockTableRecord())
                    {
                        newRec.Name   = "PlotGuide";
                        newRec.Origin = new Point3d(0, 0, 0);
                        //add the polyline to the block
                        newRec.AppendEntity(polyPlot);
                        //from read to write
                        btCurrent.UpgradeOpen();
                        btCurrent.Add(newRec);
                        trCurrent.AddNewlyCreatedDBObject(newRec, true);

                        blkRecId = newRec.Id;
                    }
                }
                else
                {
                    blkRecId = btCurrent["PlotGuide"];
                }

                //now insert block into current space using our jig
                Point3d        stPnt  = new Point3d(0, 0, 0);
                BlockReference br     = new BlockReference(stPnt, blkRecId);
                BlockJig       entJig = new BlockJig(br);

                //use jig
                Extents3d printWindow = new Extents3d();
                //loop as jig is running, to get keywords/key strokes for rotation
                PromptStatus stat = PromptStatus.Keyword;
                while (stat == PromptStatus.Keyword)
                {
                    //use iMsg filter
                    var filt = new TxtRotMsgFilter(doc);

                    WinForms.Application.AddMessageFilter(filt);
                    PromptResult pr = ed.Drag(entJig);
                    WinForms.Application.RemoveMessageFilter(filt);

                    stat = pr.Status;
                    if (stat == PromptStatus.OK)
                    {
                        printWindow = entJig.GetEntity().GeometricExtents;
                    }

                    //commit changes
                }
                trCurrent.Commit();

                return(printWindow);
            }
        }
Example #25
0
        public static void BlocksDef()
        {
            //Document doc =curdoc;
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                //-------------------------------------------------------------------------------------------
                // 自定义块
                //-------------------------------------------------------------------------------------------
                BlockTable       bt  = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = new BlockTableRecord();
                TextStyleTable   st  = tr.GetObject(db.TextStyleTableId, OpenMode.ForWrite) as TextStyleTable;

                if (!bt.Has("HDB60-1"))
                {
                    btr.Name = "HDB60-1";
                    bt.UpgradeOpen();
                    bt.Add(btr);
                    tr.AddNewlyCreatedDBObject(btr, true);


                    // 轴线
                    Polyline AxisTri = new Polyline()
                    {
                        Layer  = "中心线",
                        Closed = true,
                    };
                    AxisTri.AddVertexAt(0, new Point2d(-1524, 0), 0, 0, 0);
                    AxisTri.AddVertexAt(1, new Point2d(0, 2250), 0, 0, 0);
                    AxisTri.AddVertexAt(2, new Point2d(1524, 0), 0, 0, 0);
                    btr.AppendEntity(AxisTri);
                    tr.AddNewlyCreatedDBObject(AxisTri, true);

                    // 工字钢
                    List <Line> H0, H1, H2, H3;
                    H0 = HShapePlot(AxisTri.GetLine(0), 150, 8, btr, db);
                    H1 = HShapePlot(AxisTri.GetLine(1), 150, 8, btr, db);
                    H2 = HShapePlot(AxisTri.GetLine(2), 200, 8, btr, db);
                    Line AxY = new Line(new Point3d(0, -150, 0), new Point3d(0, 2250 + 150, 0));
                    H3 = HShapePlot(AxY, 150, 8, btr, db);

                    // 修剪
                    Polyline cuter = new Polyline();
                    cuter.AddVertexAt(0, new Point2d(-1524, 5000), 0, 0, 0);
                    cuter.AddVertexAt(1, new Point2d(-1524, 100), 0, 0, 0);
                    cuter.AddVertexAt(2, new Point2d(5000, 100), 0, 0, 0);
                    //LinesCut(ref H0, ref cuter, true);
                    //cuter.TransformBy(Matrix3d.Mirroring(AxY.Convert3D()));
                    //LinesCut(ref H0, ref cuter, true);
                }


                tr.Commit();
            }



            ed.WriteMessage("\n HBD60 Block Defination Success..");
        }
Example #26
0
        public void AddAnEnt()
        {
            // get the editor object so we can carry out some input
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            // first decide what type of entity we want to create
            PromptKeywordOptions getWhichEntityOptions = new PromptKeywordOptions("Which entity do you want to create? [Circle/Block] : ", "Circle Block");

            // now input it
            PromptResult getWhichEntityResult = ed.GetKeywords(getWhichEntityOptions);

            // if ok
            if ((getWhichEntityResult.Status == PromptStatus.OK))
            {
                // test which one is required
                switch (getWhichEntityResult.StringResult)
                {
                case "Circle":
                    // pick the center point of the circle
                    PromptPointOptions getPointOptions = new PromptPointOptions("Pick Center Point : ");
                    PromptPointResult  getPointResult  = ed.GetPoint(getPointOptions);

                    // if ok
                    if ((getPointResult.Status == PromptStatus.OK))
                    {
                        // the get the radius
                        PromptDistanceOptions getRadiusOptions = new PromptDistanceOptions("Pick Radius : ");

                        // set the start point to the center (the point we just picked)
                        getRadiusOptions.BasePoint = getPointResult.Value;

                        // now tell the input mechanism to actually use the basepoint!
                        getRadiusOptions.UseBasePoint = true;

                        // now get the radius
                        PromptDoubleResult getRadiusResult = ed.GetDistance(getRadiusOptions);

                        // if all is ok
                        if ((getRadiusResult.Status == PromptStatus.OK))
                        {
                            // need to add the circle to the current space
                            //get the current working database
                            Database dwg = ed.Document.Database;

                            // now start a transaction
                            Transaction trans = dwg.TransactionManager.StartTransaction();
                            try
                            {
                                //create a new circle
                                Circle circle = new Circle(getPointResult.Value, Vector3d.ZAxis, getRadiusResult.Value);

                                // open the current space (block table record) for write
                                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite);

                                // now the circle to the current space, model space more than likely
                                btr.AppendEntity(circle);

                                // tell the transaction about the new circle so that it can autoclose it
                                trans.AddNewlyCreatedDBObject(circle, true);

                                // now commit the transaction
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                // ok so we have an exception
                                ed.WriteMessage("problem due to " + ex.Message);
                            }
                            finally
                            {
                                // all done, whether an error on not - dispose the transaction.
                                trans.Dispose();
                            }
                        }
                    }
                    break;

                case "Block":

                    // enter the name of the block
                    PromptStringOptions blockNameOptions = new PromptStringOptions("Enter name of the Block to create : ");
                    // no spaces are allowed in a blockname so disable it
                    blockNameOptions.AllowSpaces = false;
                    // get the name
                    PromptResult blockNameResult = ed.GetString(blockNameOptions);
                    // if ok
                    if ((blockNameResult.Status == PromptStatus.OK))
                    {
                        // lets create the block definition
                        // get the current drawing
                        Database dwg = ed.Document.Database;

                        // now start a transaction
                        Transaction trans = (Transaction)dwg.TransactionManager.StartTransaction();
                        try
                        {
                            // create the new block definition
                            BlockTableRecord newBlockDef = new BlockTableRecord();

                            // name the block definition
                            newBlockDef.Name = blockNameResult.StringResult;

                            // now add the new block defintion to the block table
                            // open the blok table for read so we can check to see if the name already exists
                            BlockTable blockTable = (BlockTable)trans.GetObject(dwg.BlockTableId, OpenMode.ForRead);

                            // check to see if the block already exists
                            if ((blockTable.Has(blockNameResult.StringResult) == false))
                            {
                                // if it's not there, then we are ok to add it
                                // but first we need to upgrade the open to write
                                blockTable.UpgradeOpen();

                                // Add the BlockTableRecord to the blockTable
                                blockTable.Add(newBlockDef);

                                // tell the transaction manager about the new object so that the transaction will autoclose it
                                trans.AddNewlyCreatedDBObject(newBlockDef, true);

                                // now add some objects to the block definition
                                Circle circle1 = new Circle(new Point3d(0, 0, 0), Vector3d.ZAxis, 10);
                                newBlockDef.AppendEntity(circle1);

                                Circle circle2 = new Circle(new Point3d(20, 10, 0), Vector3d.ZAxis, 10);
                                newBlockDef.AppendEntity(circle2);

                                // tell the transaction manager about the new objects
                                //so that the transaction will autoclose it
                                trans.AddNewlyCreatedDBObject(circle1, true);
                                trans.AddNewlyCreatedDBObject(circle2, true);

                                // now set where it should appear in the current space
                                PromptPointOptions blockRefPointOptions = new PromptPointOptions("Pick insertion point of BlockRef : ");
                                PromptPointResult  blockRefPointResult  = ed.GetPoint(blockRefPointOptions);

                                // check to see if everything was ok - if not
                                if ((blockRefPointResult.Status != PromptStatus.OK))
                                {
                                    //dispose of everything that we have done so far and return
                                    trans.Dispose();
                                    return;
                                }

                                // now we have the block defintion in place and the position we need to create the reference to it
                                BlockReference blockRef = new BlockReference(blockRefPointResult.Value, newBlockDef.ObjectId);

                                // otherwise add it to the current space, first open the current space for write
                                BlockTableRecord curSpace = (BlockTableRecord)trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite);

                                // now add the block reference to it
                                curSpace.AppendEntity(blockRef);

                                // remember to tell the transaction about the new block reference so that the transaction can autoclose it
                                trans.AddNewlyCreatedDBObject(blockRef, true);

                                // all ok, commit it
                                trans.Commit();
                            }
                        }
                        catch (Exception ex)
                        {
                            // a problem occured, lets print it
                            ed.WriteMessage("a problem occured because " + ex.Message);
                        }
                        finally
                        {
                            // whatever happens we must dispose the transaction
                            trans.Dispose();
                        }
                    }
                    break;
                }
            }
        }
Example #27
0
        // Thêm 1 block chứa bản vẽ của 1 file dwg vào bản vẽ hiện tại (có scale riêng)
        public static bool InsertDrawing(string partDwg, Scale3d scale, Point3d ipt, double angle, out ObjectId objectId)
        {
            Document doc       = AcAp.DocumentManager.MdiActiveDocument;
            Database curdb     = doc.Database; // Biến database của bản vẽ hện tại
            Editor   ed        = doc.Editor;
            string   blockname = Path.GetFileNameWithoutExtension(partDwg);
            bool     result    = false;

            objectId = ObjectId.Null;

            using (DocumentLock loc = doc.LockDocument())
            {
                ObjectId blkid = ObjectId.Null; // Biến lấy ID của file đọc vào
                try
                {
                    using (Database db = new Database(false, true))                  // Biến lấy database của file nạp vào
                    {
                        db.ReadDwgFile(partDwg, System.IO.FileShare.Read, true, ""); // Lấy database
                        blkid = curdb.Insert(partDwg, db, true);                     // Lấy ID
                    }
                }
                catch (IOException)
                {
                    return(false);
                }

                using (Transaction tr = doc.TransactionManager.StartTransaction())
                {
                    BlockTable bt = (BlockTable)tr.GetObject(curdb.BlockTableId, OpenMode.ForRead);
                    if (!bt.Has(blockname))
                    {
                        bt.UpgradeOpen();
                        BlockTableRecord btrec = blkid.GetObject(OpenMode.ForRead) as BlockTableRecord;
                        btrec.UpgradeOpen();    //nâng cấp để ghi
                        btrec.Name = blockname; //thêm tên
                        btrec.DowngradeOpen();  //hạ cấp, không cho ghi nữa
                        bt.DowngradeOpen();
                    }
                    blkid = bt[blockname];

                    //Thêm các hình vẽ ở bản vẽ cũ vào
                    using (BlockTableRecord btr = (BlockTableRecord)curdb.CurrentSpaceId.GetObject(OpenMode.ForWrite))
                    {
                        //Insert vật thể
                        using (BlockReference bref = new BlockReference(ipt, blkid))
                        {
                            Matrix3d mat = Matrix3d.Identity;
                            bref.TransformBy(mat);
                            bref.ScaleFactors = scale;
                            bref.Rotation     = angle;
                            btr.AppendEntity(bref);
                            tr.AddNewlyCreatedDBObject(bref, true);
                            bref.DowngradeOpen();
                            objectId = bref.ObjectId;
                        }
                    }

                    //Tạo lại bản vẽ???
                    ed.Regen();
                    tr.Commit();
                    result = true;
                }
            }

            return(result);
        }
 private ObjectId getIdBtrEnd(BlockTable bt)
 {
     ObjectId idBtrEnd;
     if (bt.Has(BlNameEnd))
     {
         // отредактировать существующий блок торца - удалтить все старые объекты
         idBtrEnd = bt[BlNameEnd];
         eraseEntInBlock(idBtrEnd);
         IsExistsBlockEnd = true;
     }
     else
     {
         using (var btr = new BlockTableRecord())
         {
             btr.Name = BlNameEnd;
             bt.UpgradeOpen();
             idBtrEnd = bt.Add(btr);
             bt.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(btr, true);
         }
     }
     return idBtrEnd;
 }
        public static void CADini()
        {
            // Get the current document and database
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            Editor   ed      = acDoc.Editor;

            // Start a transaction
            using (Transaction tr = acCurDb.TransactionManager.StartTransaction())
            {
                Dictionary <string, short> ldic = new Dictionary <string, short>()
                {
                    ["粗线"]  = 4,
                    ["细线"]  = 2,
                    ["标注"]  = 7,
                    ["中心线"] = 1,
                    ["虚线"]  = 3,
                    ["填充"]  = 8,
                    ["图框"]  = 8,
                    ["地质"]  = 8,
                };
                List <string> Lname = new List <string>()
                {
                    "CENTER", "DASHED"
                };
                LayerTable acLyrTbl;
                acLyrTbl = tr.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
                LinetypeTable acLinTbl;
                acLinTbl = tr.GetObject(acCurDb.LinetypeTableId, OpenMode.ForRead) as LinetypeTable;
                foreach (string ltname in Lname)
                {
                    if (!acLinTbl.Has(ltname))
                    {
                        acCurDb.LoadLineTypeFile(ltname, "acad.lin");
                    }
                }
                LayerTableRecord acLyrTblRec = new LayerTableRecord();
                foreach (string key in ldic.Keys)
                {
                    short cid = ldic[key];
                    acLyrTblRec = new LayerTableRecord();
                    if (!acLyrTbl.Has(key))
                    {
                        acLyrTblRec.Color = Color.FromColorIndex(ColorMethod.ByAci, cid);
                        if (cid != 4)
                        {
                            acLyrTblRec.LineWeight = LineWeight.LineWeight013;
                        }
                        else
                        {
                            acLyrTblRec.LineWeight = LineWeight.LineWeight030;
                        }
                        if (cid == 1)
                        {
                            acLyrTblRec.LinetypeObjectId = acLinTbl["CENTER"];
                        }
                        if (cid == 3)
                        {
                            acLyrTblRec.LinetypeObjectId = acLinTbl["DASHED"];
                        }
                        if (key == "图框")
                        {
                            acLyrTblRec.IsPlottable = false;
                        }
                        if (key == "地质")
                        {
                            acLyrTblRec.IsPlottable = false;
                        }
                        acLyrTblRec.Name = key;
                        if (acLyrTbl.IsWriteEnabled == false)
                        {
                            acLyrTbl.UpgradeOpen();
                        }
                        acLyrTbl.Add(acLyrTblRec);
                        tr.AddNewlyCreatedDBObject(acLyrTblRec, true);
                    }
                    else
                    {
                        acLyrTblRec       = tr.GetObject(acLyrTbl[key], OpenMode.ForWrite) as LayerTableRecord;
                        acLyrTblRec.Color = Color.FromColorIndex(ColorMethod.ByAci, cid);
                        if (cid != 4)
                        {
                            acLyrTblRec.LineWeight = LineWeight.LineWeight013;
                        }
                        else
                        {
                            acLyrTblRec.LineWeight = LineWeight.LineWeight030;
                        }
                        if (cid == 1)
                        {
                            acLyrTblRec.LinetypeObjectId = acLinTbl["CENTER"];
                        }
                        if (cid == 3)
                        {
                            acLyrTblRec.LinetypeObjectId = acLinTbl["DASHED"];
                        }
                        if (key == "图框")
                        {
                            acLyrTblRec.IsPlottable = false;
                        }
                        if (key == "地质")
                        {
                            acLyrTblRec.IsPlottable = false;
                        }
                    }
                }
                if (!acLyrTbl.Has("sjx"))
                {
                    acLyrTblRec            = new LayerTableRecord();
                    acLyrTblRec.Color      = Color.FromColorIndex(ColorMethod.ByAci, 1);
                    acLyrTblRec.Name       = "sjx";
                    acLyrTblRec.LineWeight = LineWeight.LineWeight015;
                    if (acLyrTbl.IsWriteEnabled == false)
                    {
                        acLyrTbl.UpgradeOpen();
                    }
                    acLyrTbl.Add(acLyrTblRec);
                    tr.AddNewlyCreatedDBObject(acLyrTblRec, true);
                }
                if (!acLyrTbl.Has("dmx"))
                {
                    acLyrTblRec            = new LayerTableRecord();
                    acLyrTblRec.Color      = Color.FromColorIndex(ColorMethod.ByAci, 8);
                    acLyrTblRec.Name       = "dmx";
                    acLyrTblRec.LineWeight = LineWeight.LineWeight015;
                    if (acLyrTbl.IsWriteEnabled == false)
                    {
                        acLyrTbl.UpgradeOpen();
                    }
                    acLyrTbl.Add(acLyrTblRec);
                    tr.AddNewlyCreatedDBObject(acLyrTblRec, true);
                }


                //-------------------------------------------------------------------------------------------
                TextStyleTable st = tr.GetObject(acCurDb.TextStyleTableId, OpenMode.ForWrite) as TextStyleTable;
                if (!st.Has("EN"))
                {
                    TextStyleTableRecord str = new TextStyleTableRecord()
                    {
                        Name     = "En",
                        FileName = "times.ttf",
                        XScale   = 0.85,
                    };
                    st.Add(str);
                    tr.AddNewlyCreatedDBObject(str, true);
                }
                else
                {
                    TextStyleTableRecord str = tr.GetObject(st["En"], OpenMode.ForWrite) as TextStyleTableRecord;
                    str.FileName = "times.ttf";
                    str.XScale   = 0.85;
                }
                if (!st.Has("fsdb"))
                {
                    TextStyleTableRecord str2 = new TextStyleTableRecord()
                    {
                        Name            = "fsdb",
                        FileName        = "fsdb_e.shx",
                        BigFontFileName = "fsdb.shx",
                        XScale          = 0.75,
                    };
                    ObjectId textstyleid = st.Add(str2);
                    tr.AddNewlyCreatedDBObject(str2, true);
                }
                else
                {
                    TextStyleTableRecord str = tr.GetObject(st["fsdb"], OpenMode.ForWrite) as TextStyleTableRecord;
                    str.FileName        = "fsdb_e.shx";
                    str.BigFontFileName = "fsdb.shx";
                    str.XScale          = 0.75;
                }
                if (!st.Has("仿宋"))
                {
                    TextStyleTableRecord str2 = new TextStyleTableRecord()
                    {
                        Name     = "仿宋",
                        FileName = "仿宋_GB2312.ttf",
                        XScale   = 0.8,
                    };
                    ObjectId textstyleid = st.Add(str2);
                    tr.AddNewlyCreatedDBObject(str2, true);
                }
                else
                {
                    TextStyleTableRecord str = tr.GetObject(st["仿宋"], OpenMode.ForWrite) as TextStyleTableRecord;
                    str.FileName = "仿宋_GB2312.ttf";
                    str.XScale   = 0.8;
                }
                if (!st.Has("钢筋"))
                {
                    TextStyleTableRecord str2 = new TextStyleTableRecord()
                    {
                        Name     = "钢筋",
                        FileName = "FS-GB2312-Rebar.ttf",
                        XScale   = 0.8,
                    };
                    ObjectId textstyleid = st.Add(str2);
                    tr.AddNewlyCreatedDBObject(str2, true);
                }
                else
                {
                    TextStyleTableRecord str = tr.GetObject(st["钢筋"], OpenMode.ForWrite) as TextStyleTableRecord;
                    str.FileName = "FS-GB2312-Rebar.ttf";
                    str.XScale   = 0.8;
                }



                //-------------------------------------------------------------------------------------------
                DimStyleTable dst = (DimStyleTable)tr.GetObject(acCurDb.DimStyleTableId, OpenMode.ForWrite);
                foreach (int thescale in new int[] { 50, 75, 100, 125, 150, 200 })
                {
                    string scname            = "1-" + thescale.ToString();
                    DimStyleTableRecord dstr = new DimStyleTableRecord();
                    if (!dst.Has(scname))
                    {
                        dstr.Name       = "1-" + thescale.ToString();
                        dstr.Dimscale   = thescale;
                        dstr.Dimtxsty   = st["仿宋"];
                        dstr.Dimclrd    = Color.FromColorIndex(ColorMethod.ByAci, 6);
                        dstr.Dimclre    = Color.FromColorIndex(ColorMethod.ByAci, 6);
                        dstr.Dimdli     = 5.0;
                        dstr.Dimexe     = 1.0;
                        dstr.Dimexo     = 1.0;
                        dstr.DimfxlenOn = true;
                        dstr.Dimfxlen   = 4;
                        dstr.Dimtxt     = 2.5;
                        dstr.Dimasz     = 1.5;
                        dstr.Dimtix     = true;
                        dstr.Dimtmove   = 1;
                        dstr.Dimtad     = 1;
                        dstr.Dimgap     = 0.8;
                        dstr.Dimdec     = 0;
                        dstr.Dimtih     = false;
                        dstr.Dimtoh     = false;
                        dstr.Dimdsep    = '.';
                        //dstr.Dimlfac = 0.1;
                        dst.Add(dstr);
                        tr.AddNewlyCreatedDBObject(dstr, true);
                    }
                    else
                    {
                        dstr            = tr.GetObject(dst[scname], OpenMode.ForWrite) as DimStyleTableRecord;
                        dstr.Name       = "1-" + thescale.ToString();
                        dstr.Dimscale   = thescale;
                        dstr.Dimtxsty   = st["fsdb"];
                        dstr.Dimclrd    = Color.FromColorIndex(ColorMethod.ByAci, 6);
                        dstr.Dimclre    = Color.FromColorIndex(ColorMethod.ByAci, 6);
                        dstr.Dimdli     = 5.0;
                        dstr.Dimexe     = 1.0;
                        dstr.Dimexo     = 1.0;
                        dstr.DimfxlenOn = true;
                        dstr.Dimfxlen   = 4;
                        dstr.Dimtxt     = 2.5;
                        dstr.Dimasz     = 1.5;
                        dstr.Dimtix     = true;
                        dstr.Dimtmove   = 1;
                        dstr.Dimtad     = 1;
                        dstr.Dimgap     = 0.8;
                        dstr.Dimdec     = 0;
                        dstr.Dimtih     = false;
                        dstr.Dimtoh     = false;
                        dstr.Dimdsep    = '.';
                        dstr.Dimlfac    = 0.1;
                    }
                }
                //-------------------------------------------------------------------------------------------
                // 自定义块
                //-------------------------------------------------------------------------------------------
                BlockTable       bt  = (BlockTable)tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = new BlockTableRecord();

                //-------------------------------------------------------------------------------------------
                if (!bt.Has("BG"))
                {
                    btr.Name = "BG";
                    bt.UpgradeOpen();
                    bt.Add(btr);
                    tr.AddNewlyCreatedDBObject(btr, true);
                    Polyline Paa = new Polyline()
                    {
                        //Color = Color.FromColorIndex(ColorMethod.ByAci, 9),
                        //Layer = "标注",
                    };
                    Paa.AddVertexAt(0, new Point2d(0, 0), 0, 0, 200);
                    Paa.AddVertexAt(1, new Point2d(0, 200), 0, 0, 0);
                    btr.AppendEntity(Paa);
                    tr.AddNewlyCreatedDBObject(Paa, true);
                    AttributeDefinition curbg = new AttributeDefinition();
                    curbg.Position    = new Point3d(120, 200, 0);
                    curbg.Height      = 250;
                    curbg.WidthFactor = 0.75;
                    curbg.Tag         = "标高";
                    //curbg.Layer = "标注";
                    curbg.TextStyleId = st["fsdb"];
                    btr.AppendEntity(curbg);
                    tr.AddNewlyCreatedDBObject(curbg, true);
                }
                //-------------------------------------------------------------------------------------------
                if (!bt.Has("ZP"))
                {
                    BlockTableRecord btr2 = new BlockTableRecord();
                    btr2.Name = "ZP";
                    bt.UpgradeOpen();
                    bt.Add(btr2);
                    tr.AddNewlyCreatedDBObject(btr2, true);
                    Polyline Paa2 = new Polyline()
                    {
                        Color = Color.FromColorIndex(ColorMethod.ByAci, 9),
                    };
                    Paa2.AddVertexAt(0, new Point2d(0 - 350, 0), 0, 0, 80);
                    Paa2.AddVertexAt(1, new Point2d(200 - 350, 0), 0, 0, 0);
                    Paa2.AddVertexAt(2, new Point2d(900 - 350, 0), 0, 0, 0);
                    btr2.AppendEntity(Paa2);
                    tr.AddNewlyCreatedDBObject(Paa2, true);
                    AttributeDefinition curzp = new AttributeDefinition();
                    curzp.Position    = new Point3d(220 - 350, 0, 0);
                    curzp.Height      = 250;
                    curzp.WidthFactor = 0.75;
                    curzp.Tag         = "左坡";
                    curzp.TextStyleId = st["fsdb"];
                    btr2.AppendEntity(curzp);
                    tr.AddNewlyCreatedDBObject(curzp, true);
                }

                //-------------------------------------------------------------------------------------------
                if (!bt.Has("YP"))
                {
                    BlockTableRecord btr3 = new BlockTableRecord();
                    btr3.Name = "YP";
                    bt.UpgradeOpen();
                    bt.Add(btr3);
                    tr.AddNewlyCreatedDBObject(btr3, true);
                    Polyline Paa3 = new Polyline()
                    {
                        Color = Color.FromColorIndex(ColorMethod.ByAci, 9),
                    };
                    Paa3.AddVertexAt(0, new Point2d(0 + 350, 0), 0, 0, 80);
                    Paa3.AddVertexAt(1, new Point2d(-200 + 350, 0), 0, 0, 0);
                    Paa3.AddVertexAt(2, new Point2d(-900 + 350, 0), 0, 0, 0);
                    btr3.AppendEntity(Paa3);
                    tr.AddNewlyCreatedDBObject(Paa3, true);
                    AttributeDefinition curyp = new AttributeDefinition();
                    curyp.Position       = new Point3d(-220 + 350, 0, 0);
                    curyp.HorizontalMode = TextHorizontalMode.TextRight;
                    curyp.AlignmentPoint = curyp.Position;
                    curyp.Height         = 250;
                    curyp.WidthFactor    = 0.75;
                    curyp.Tag            = "右坡";
                    curyp.TextStyleId    = st["fsdb"];
                    btr3.AppendEntity(curyp);
                    tr.AddNewlyCreatedDBObject(curyp, true);
                }
                //-------------------------------------------------------------------------------------------

                //-------------------------------------------------------------------------------------------
                tr.Commit();
            }
        }
Example #30
0
        public void AddAnEnt()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor   ed  = doc.Editor;

            // Declare a PromptKeywordOptions variable and instantiate it by creating
            // a new PromptKeywordOptions. Use a string similar to the following for the
            // messageAndKeywords string.
            // "Which entity do you want to create? [Circle/Block] : ", "Circle Block"
            PromptKeywordOptions poEntity = new PromptKeywordOptions(
                "Which entity do you want to create? [Circle/Block] : ",
                "Circle Block");    // String with the options separated with a space

            // Instantiate the PromptResult by making it equal to the return value of the GetKeywords method.
            PromptResult prEntity = ed.GetKeywords(poEntity);

            if (prEntity.Status == PromptStatus.OK)
            {
                switch (prEntity.StringResult)
                {
                case "Circle":
                    // Ask for a point, which will be the center of the circle
                    PromptPointOptions poCenterPoint = new PromptPointOptions("Pick Center Point: ");

                    // Pass the prompt to the editor and get the resulting point
                    PromptPointResult prCenterPoint = ed.GetPoint(poCenterPoint);

                    if (prCenterPoint.Status == PromptStatus.OK)
                    {
                        // Ask for a distance (radius)
                        PromptDistanceOptions poRadius = new PromptDistanceOptions("Pick Radius: ");

                        // Make the point selected earlier the base point of the distance prompt
                        poRadius.BasePoint = prCenterPoint.Value;
                        // Tell the prompt to actually use the base point
                        poRadius.UseBasePoint = true;

                        // Get the distance
                        PromptDoubleResult prRadius = ed.GetDistance(poRadius);

                        if (prRadius.Status == PromptStatus.OK)
                        {
                            // Add the circle to the DWG
                            Database dwg = ed.Document.Database;

                            // Start a transaction (as you would with a database)
                            Transaction trans = dwg.TransactionManager.StartTransaction();

                            try
                            {
                                // Create the circle.
                                // The second parameter is the normal (perpendicular) vector.
                                Circle circle = new Circle(prCenterPoint.Value, Vector3d.ZAxis, prRadius.Value);

                                // Create a new block
                                // A BlockTableRecord is similar to using the "BLOCK" command on AutoCAD.
                                // When we add a record to the current space, we ARE NOT adding it to the "Blocks" utility.
                                BlockTableRecord curSpace = (BlockTableRecord)trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite);

                                // Add the circle to the new block
                                curSpace.AppendEntity(circle);

                                // Tell the transaction about the new object (entity)
                                trans.AddNewlyCreatedDBObject(circle, true);

                                // Commit
                                trans.Commit();
                            }
                            catch (Autodesk.AutoCAD.Runtime.Exception ex)
                            {
                                // Write exception on the AutoCAD command line
                                ed.WriteMessage("EXCEPTION: " + ex.Message);
                            }
                            finally
                            {
                                // Dispose of the transaction (whether an error has occurred or not)
                                trans.Dispose();
                            }
                        }
                    }
                    break;

                case "Block":
                    // Add a prompt to name the block
                    PromptStringOptions poBlockName = new PromptStringOptions("Enter the name of the Block to create: ");

                    // Don't allow spaces, as a block's name can't have spaces
                    poBlockName.AllowSpaces = false;

                    // Get the name
                    PromptResult prBlockName = ed.GetString(poBlockName);

                    if (prBlockName.Status == PromptStatus.OK)
                    {
                        // Add the block to the dwg
                        Database    dwg   = ed.Document.Database;
                        Transaction trans = dwg.TransactionManager.StartTransaction();

                        try
                        {
                            // Create new BTR from scratch
                            BlockTableRecord btr = new BlockTableRecord();

                            // Set name to the prompt result
                            btr.Name = prBlockName.StringResult;

                            // First verify if a block with the same name already exists in the Block Table
                            // We open the Block Table in read, because we won't be changing it right now
                            BlockTable blockTable = (BlockTable)trans.GetObject(dwg.BlockTableId, OpenMode.ForRead);

                            if (blockTable.Has(prBlockName.StringResult))
                            {
                                throw new Autodesk.AutoCAD.Runtime.Exception(
                                          ErrorStatus.InvalidInput,
                                          "Cannot create block. Block with same name already exists.");
                            }
                            else
                            {
                                // Update OpenMode to ForWrite
                                blockTable.UpgradeOpen();

                                // Add to the block table (this will make the block available for the user in the "Block" utility)
                                blockTable.Add(btr);

                                // Tell the transaction about the new object, so that it auto-closes it
                                trans.AddNewlyCreatedDBObject(btr, true);

                                // We defined that the block consists of two circles, so we'll add them
                                Circle circle1 = new Circle(new Point3d(0, 0, 0), Vector3d.ZAxis, 10);
                                Circle circle2 = new Circle(new Point3d(20, 10, 0), Vector3d.ZAxis, 10);

                                btr.AppendEntity(circle1);
                                btr.AppendEntity(circle2);

                                trans.AddNewlyCreatedDBObject(circle1, true);
                                trans.AddNewlyCreatedDBObject(circle2, true);

                                // Prompt for insertion point
                                PromptPointOptions poPoint = new PromptPointOptions("Pick insertion point of BlockRef : ");
                                PromptPointResult  prPoint = ed.GetPoint(poPoint);

                                if (prPoint.Status != PromptStatus.OK)
                                {
                                    // If point is not valid, return

                                    trans.Dispose();
                                    return;
                                }

                                // The BlockTableRecord is the BLOCK (i.e., a template)
                                // The BlockReference is the result of using INSERT (i.e., an instance of a block)
                                BlockReference blockRef = new BlockReference(prPoint.Value, btr.ObjectId);

                                // Add to the current space
                                BlockTableRecord curSpace = (BlockTableRecord)trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite);
                                curSpace.AppendEntity(blockRef);

                                // Finish transaction
                                trans.AddNewlyCreatedDBObject(blockRef, true);
                                trans.Commit();
                            }
                        }
                        catch (Autodesk.AutoCAD.Runtime.Exception ex)
                        {
                            ed.WriteMessage("EXCEPTION: " + ex.Message);
                        }
                        finally
                        {
                            trans.Dispose();
                        }
                    }
                    break;
                }
            }
        }
Example #31
0
        public static void CreateBlock()
        {
            string strBlockName = "Присоска квадратная";

            using (Document.LockDocument())
            {
                using (var trans = TransactionManager.StartTransaction())
                {
                    BlockTable blockTable = trans.GetObject(Database.BlockTableId, OpenMode.ForRead, false) as BlockTable;
                    //BlockTableRecord blockTableRecord = trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false) as BlockTableRecord;

                    try
                    {
                        // проверка на корректность символов в имени блока
                        SymbolUtilityServices.ValidateSymbolName(strBlockName, false);
                    }
                    catch
                    {
                        WriteMessage("nInvalid block name.");
                        return;
                    }
                    BlockTableRecord btrRecord;
                    ObjectId         btrId;
                    if (!blockTable.Has(strBlockName))
                    {
                        // создаем ОПРЕДЕЛЕНИЕ блока
                        // создаем примитивы, которые будет содержать блок
                        Polyline acPoly = new Polyline();
                        acPoly.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
                        acPoly.AddVertexAt(1, new Point2d(100, 0), 0, 0, 0);
                        acPoly.AddVertexAt(2, new Point2d(100, 100), 0, 0, 0);
                        acPoly.AddVertexAt(3, new Point2d(0, 100), 0, 0, 0);
                        acPoly.Closed     = true;
                        acPoly.ColorIndex = 3;

                        // создаем определение аттрибута
                        AttributeDefinition adAttr = new AttributeDefinition();

/*                        adAttr.Position = new Point3d(0, 0, 0);
 *                      adAttr.Tag = "ATTRDEF";
 *                      adAttr.TextString = "Присоска";*/

                        // создаем новое определение блока
                        btrRecord          = new BlockTableRecord();
                        btrRecord.Name     = strBlockName;
                        btrRecord.Comments = "Присоска для закрепления детали на станке";
                        blockTable.UpgradeOpen();

                        // добавляем его в таблицу блоков
                        btrId = blockTable.Add(btrRecord);
                        trans.AddNewlyCreatedDBObject(btrRecord, true);

                        // добавляем в определение блока примитивы
                        btrRecord.AppendEntity(acPoly);
                        trans.AddNewlyCreatedDBObject(acPoly, true);

                        // и аттрибут
//                        btrRecord.AppendEntity(adAttr);
//                        trans.AddNewlyCreatedDBObject(adAttr, true);
                    }
                    else
                    {
                        btrId     = blockTable[strBlockName];
                        btrRecord = (BlockTableRecord)trans.GetObject(blockTable[strBlockName], OpenMode.ForWrite);
                    }
                    // теперь создадим экземпляр блока на чертеже
                    // получаем пространство модели
                    BlockTableRecord btrModelSpace = (BlockTableRecord)trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                    // создаем новый экземпляр блока на основе его определения
                    BlockReference brRefBlock = new BlockReference(new Point3d(2000, 1500, 0), btrId);

                    // добавляем экземпляр блока в базу данных пространства модели
                    btrModelSpace.AppendEntity(brRefBlock);
                    trans.AddNewlyCreatedDBObject(brRefBlock, true);

                    // задаем значение аттрибуета
//                    AttributeReference arAttr = new AttributeReference();
//                    arAttr.SetAttributeFromBlock(adAttr, brRefBlock.BlockTransform);
//                    arAttr.TextString = "Атрибут!";
//                    brRefBlock.AttributeCollection.AppendAttribute(arAttr);
//                    trans.AddNewlyCreatedDBObject(arAttr, true);

                    // закрываем транзакцию
                    trans.Commit();
                }
            }
        }