//something plobrem //文件的名称必须和块的名称一致 //不一致将会发生错误 //将图块写入到当前文档中 private bool WBlockBetweenDataBase(string BlockName) { Database SourceDB = new Database(false, true); ErrorStatus Stats = this.GetInsertDwgFile(ref SourceDB); Document Doc = AcadApp.DocumentManager.MdiActiveDocument; Database TargetDB = Doc.Database; ObjectIdCollection SourceIds = new ObjectIdCollection(); using (Transaction Tr = SourceDB.TransactionManager.StartTransaction()) { using (Transaction Tr2 = TargetDB.TransactionManager.StartTransaction()) { BlockTable SourceBt = (BlockTable)Tr.GetObject(SourceDB.BlockTableId, OpenMode.ForRead); if (SourceBt.Has(BlockName)) { SourceIds.Add(SourceBt[BlockName]); } Tr.Commit(); } } if (SourceIds.Count != 0) { IdMapping IdMap = new IdMapping(); TargetDB.WblockCloneObjects(SourceIds, TargetDB.BlockTableId, IdMap, DuplicateRecordCloning.Ignore, false); SourceDB.Dispose(); return(true); } else { SourceDB.Dispose(); return(false); } }
//INSERT BLOCK INTO TABLE CELL; public static void InsertDynamicBlockToTableCell(Cell tCell, Database db, string BlockName, FixtureDetails df) { using (Transaction tr = db.TransactionManager.StartTransaction()) { //tCell.DeleteContent(); BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite); if (bt.Has(BlockName)) { tCell.BlockTableRecordId = bt[BlockName]; BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockName], OpenMode.ForRead); if (btr.HasAttributeDefinitions) { foreach (ObjectId id in btr) { DBObject dbObj = tr.GetObject(id, OpenMode.ForRead); if (dbObj is AttributeDefinition) { AttributeDefinition attDef = (AttributeDefinition)dbObj; if (attDef.Tag == HexNoteName.ID) { tCell.SetBlockAttributeValue(id, df.model.TAG); } else if (attDef.Tag == HexNoteName.NUM) { tCell.SetBlockAttributeValue(id, df.model.NUMBER); } } } } } tr.Commit(); } }
protected IEnumerable <ObjectId> Query() { try { var db = HostApplicationServices.WorkingDatabase; var result = new List <ObjectId>(); using (var tr = db.TransactionManager.StartOpenCloseTransaction()) { using (BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false, true)) { if (bt.Has(BlockTableRecord)) { using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord], OpenMode.ForRead, false, true)) { foreach (var oid in btr) { if (HitTypeFilter(oid) && HitLayerFilter(oid, tr) && HitDataFilter(oid, tr)) { result.Add(oid); } } } } } return(result); } } catch (Exception ex) { Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage($"执行失败,{ex.Message}{Environment.NewLine}"); } return(null); }
public override void Draw() { using (var l = Application.DocumentManager.MdiActiveDocument.LockDocument()) { var db = HostApplicationServices.WorkingDatabase; using (var tr = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); if (!bt.Has(BlockName)) { return; } using (var ent = new BlockReference(Point3d.Origin, bt[BlockName])) { if (LayerName != null) { LayerManager.SetLayer(db, ent, LayerName, true); } var space = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); space.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); var jig = new Jig.BlockReferenceJig(ent as BlockReference); if (jig.Run()) { tr.Commit(); DataManager.WriteDictionary(ent.ObjectId, Data); } } } } }
private void AddToDB() { using (Database DB = new Database(false, true)) { DB.ReadDwgFile(path, FileShare.Read, false, ""); ObjectIdCollection ids = new ObjectIdCollection(); using (Transaction tr = DB.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(DB.BlockTableId, OpenMode.ForRead); if (bt.Has(BlockReplacement)) { ids.Add(bt[BlockReplacement]); } tr.Commit(); } if (ids.Count != 0) { foreach (DWG dwg in DWGs) { Database destdb = new Database(false, true); using (destdb) { destdb.ReadDwgFile(dwg.Path, FileShare.ReadWrite, false, ""); IdMapping iMap = new IdMapping(); destdb.WblockCloneObjects(ids, destdb.BlockTableId, iMap, DuplicateRecordCloning.Ignore, false); destdb.SaveAs(dwg.Path, DwgVersion.Current); } } } } }
public string[,] GetAttributeDefinitionNameAllCollection(DocumentCollection acDocMgr, DBObjectCollection acBlkTblRecCol) { string[,] acAttDefNamAllCol = new string[acBlkTblRecCol.Count, 50]; for (int i = 0; i < acBlkTblRecCol.Count; i++) { foreach (Document acDoc in acDocMgr) { Database acCurDb = acDoc.Database; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { BlockTable acBlkTbl = (BlockTable)acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead); if (acBlkTbl.Has(((BlockTableRecord)acBlkTblRecCol[i]).Name)) { //BlockTableRecord acBlkTblRec = (BlockTableRecord) acTrans.GetObject(acBlkTbl[((BlockTableRecord)acBlkTblRecCol[i]).Name], OpenMode.ForRead); string[] acAttDefNam = GetAttributeDefinitionNameCollection(acDoc, acTrans, (BlockTableRecord)acBlkTblRecCol[i]); for (int j = 0; j < acAttDefNam.Length; j++) { acAttDefNamAllCol[i, j] = acAttDefNam[j]; } } } } } return(acAttDefNamAllCol); }
public DBObjectCollection GetAttributeDefinitionCollection(Document acDoc, Transaction acTrans, BlockTableRecord acBlkTblRec) { Database acCurDb = acDoc.Database; DBObjectCollection acAttDefCol = new DBObjectCollection(); string acStrAtt = string.Empty; //if (Application.DocumentManager.MdiActiveDocument != acDoc) Application.DocumentManager.MdiActiveDocument = acDoc; //HostApplicationServices.WorkingDatabase = acDoc.Database; //using (DocumentLock acDocLck = acDoc.LockDocument()) //{ //using (Transaction acTrans = acDoc.Database.TransactionManager.StartTransaction()) //{ BlockTable acBlkTbl = (BlockTable)acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead); if (acBlkTbl.Has(acBlkTblRec.Name)) { BlockTableRecord acBlkTblRec2 = (BlockTableRecord)acTrans.GetObject(acBlkTbl[acBlkTblRec.Name], OpenMode.ForRead); foreach (ObjectId acObjId in acBlkTblRec2) { DBObject acDbObj = acTrans.GetObject(acObjId, OpenMode.ForRead); if (acDbObj is AttributeDefinition) { acAttDefCol.Add(acDbObj); } } //} //} } return(acAttDefCol); }
public static void CopyBlockFromDwg(string blockName, string filePath, Database destinationDatabase) { using (Database sourceDatabase = new Database(false, true)) { sourceDatabase.ReadDwgFile(filePath, FileShare.ReadWrite, true, string.Empty); ObjectIdCollection ids = new ObjectIdCollection(); using (Transaction sourceTransaction = sourceDatabase.TransactionManager.StartTransaction()) { BlockTable blockTable = (BlockTable)sourceTransaction.GetObject(sourceDatabase.BlockTableId, OpenMode.ForRead); if (blockTable.Has(blockName)) { ids.Add(blockTable[blockName]); } sourceTransaction.Commit(); } if (ids.Count != 0) { IdMapping mapping = new IdMapping(); destinationDatabase.WblockCloneObjects(ids, destinationDatabase.BlockTableId, mapping, DuplicateRecordCloning.Ignore, false); } } }
private void CloneModelSpaceDataFromSourceToTarget(Database SourceDB, Database TargetDB) { using (Transaction SourceTran = SourceDB.TransactionManager.StartTransaction()) { BlockTableRecord SourceModelSpace = (BlockTableRecord)SymbolUtilityServices.GetBlockModelSpaceId(SourceDB).GetObject(OpenMode.ForRead); BlockTable SourceBlockTable = SourceTran.GetObject(SourceDB.BlockTableId, OpenMode.ForRead) as BlockTable; using (Transaction TargetTran = TargetDB.TransactionManager.StartTransaction()) { BlockTable TargetBlockTable = TargetTran.GetObject(TargetDB.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord TargetModelSpace = (BlockTableRecord)SymbolUtilityServices.GetBlockModelSpaceId(TargetDB).GetObject(OpenMode.ForRead); foreach (ObjectId item in SourceModelSpace) { DBObject Rec = SourceTran.GetObject(item, OpenMode.ForRead); System.Diagnostics.Debug.WriteLine(Rec.GetType()); Entity Ent = Rec as Entity; if (Ent != null) { if (!TargetBlockTable.Has(Ent.BlockName)) { TargetModelSpace.AppendEntity(Ent); TargetTran.AddNewlyCreatedDBObject(Rec, true); } } } TargetTran.Commit(); } } }
public void AddDwg(Database db, string dwgPathname) { ObjectId dwgBlkId = ObjectId.Null; using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); string blockName = Path.GetFileNameWithoutExtension(dwgPathname); if (bt.Has(blockName)) { dwgBlkId = bt[blockName]; } else { if (!File.Exists(dwgPathname)) { return; } using (Database dwgDb = new Database(false, true)) { dwgDb.ReadDwgFile(dwgPathname, FileShare.Read, true, null); dwgDb.CloseInput(true); dwgBlkId = db.Insert(blockName, dwgDb, true); if (dwgBlkId == ObjectId.Null) { return; } } } tr.Commit(); } }
public static bool AddBlock(string blockPath) { //if (blockPath.Contains(".dwg") == false) { blockPath = blockPath + ".dwg"; } blockPath = blockPath + ".dwg"; if (System.IO.File.Exists(blockPath)) { using (World.Docu.LockDocument()) { using (Database db = World.Docu.Database) { using (Transaction tr = db.TransactionManager.StartTransaction()) { using (BlockTable bt = (BlockTable)tr.GetObject(World.Docu.Database.BlockTableId, OpenMode.ForRead)) { if (bt.Has(blockPath) == false) { using (Database tempDB = new Database(false, true)) { tempDB.ReadDwgFile(blockPath, System.IO.FileShare.Read, true, ""); World.Docu.Database.Insert(blockPath, tempDB, false); } tr.Commit(); } return(true); } } } } } return(false); }
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); }
/// <summary> /// 在AutoCAD图形中插入块参照 /// </summary> /// <param name="spaceId">块参照要加入的模型空间或图纸空间的Id</param> /// <param name="layer">块参照要加入的图层名</param> /// <param name="blockName">块参照所属的块名</param> /// <param name="position">插入点</param> /// <param name="scale">缩放比例</param> /// <param name="rotateAngle">旋转角度</param> /// <returns>返回块参照的Id</returns> public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle) { ObjectId blockRefId; //存储要插入的块参照的Id Database db = spaceId.Database; //获取数据库对象 //以读的方式打开块表 BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); //如果没有blockName表示的块,则程序返回 if (!bt.Has(blockName)) { return(ObjectId.Null); } //以写的方式打开空间(模型空间或图纸空间) BlockTableRecord space = (BlockTableRecord)spaceId.GetObject(OpenMode.ForWrite); //创建一个块参照并设置插入点 BlockReference br = new BlockReference(position, bt[blockName]); br.ScaleFactors = scale; //设置块参照的缩放比例 br.Layer = layer; //设置块参照的层名 br.Rotation = rotateAngle; //设置块参照的旋转角度 ObjectId btrId = bt[blockName]; //获取块表记录的Id //打开块表记录 BlockTableRecord record = (BlockTableRecord)btrId.GetObject(OpenMode.ForRead); //添加可缩放性支持 if (record.Annotative == AnnotativeStates.True) { ObjectContextCollection contextCollection = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); ObjectContexts.AddContext(br, contextCollection.GetContext("1:1")); } blockRefId = space.AppendEntity(br); //在空间中加入创建的块参照 db.TransactionManager.AddNewlyCreatedDBObject(br, true); //通知事务处理加入创建的块参照 space.DowngradeOpen(); //为了安全,将块表状态改为读 return(blockRefId); //返回添加的块参照的Id }
/// <summary> /// Insert block into layout /// </summary> /// <param name="db"></param> /// <param name="layoutName"></param> /// <param name="blockName"></param> /// <param name="insPnt"></param> /// <returns></returns> public static bool InsertBlock(Database db, string layoutName, string blockName, Point3d insPnt) { LayoutManager lm = LayoutManager.Current; using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; if (!bt.Has(blockName)) { return(false); ////// need to load the block } //get the block id ObjectId blkId = bt[blockName]; BlockTableRecord btr = null; if (string.IsNullOrEmpty(layoutName)) { btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord; } else { ObjectId layoutId = lm.GetLayoutId(layoutName); Layout layout = tr.GetObject(layoutId, OpenMode.ForRead) as Layout; btr = tr.GetObject(layout.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord; } //insert the block BlockReference blkRef = new BlockReference(insPnt, blkId); btr.UpgradeOpen(); btr.AppendEntity(blkRef); tr.AddNewlyCreatedDBObject(blkRef, true); tr.Commit(); } return(true); }
/// <summary> /// 在AutoCAD图形中插入块参照 /// </summary> /// <param name="spaceId">块参照要加入的模型空间或图纸空间的Id</param> /// <param name="layer">块参照要加入的图层名</param> /// <param name="blockName">块参照所属的块名</param> /// <param name="position">插入点</param> /// <param name="scale">缩放比例</param> /// <param name="rotateAngle">旋转角度</param> /// <param name="attNameValues">属性的名称与取值</param> /// <returns>返回块参照的Id</returns> public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle) { DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument(); ObjectId blockRefId; Database db = spaceId.Database; BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); if (!bt.Has(blockName)) { return(ObjectId.Null); } BlockTableRecord space = (BlockTableRecord)spaceId.GetObject(OpenMode.ForWrite); BlockReference br = new BlockReference(position, bt[blockName]); br.ScaleFactors = scale; br.Layer = layer; br.Rotation = rotateAngle; ObjectId btrId = bt[blockName]; BlockTableRecord record = (BlockTableRecord)btrId.GetObject(OpenMode.ForRead); if (record.Annotative == AnnotativeStates.True) { ObjectContextCollection contextCollection = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); ObjectContexts.AddContext(br, contextCollection.GetContext("1:1")); } blockRefId = space.AppendEntity(br); db.TransactionManager.AddNewlyCreatedDBObject(br, true); space.DowngradeOpen(); docLock.Dispose(); return(blockRefId); }
/// <summary> /// Inserts this instance block as a BlockReference. /// </summary> /// <param name="doc">The active document.</param> /// <param name="tr">The active transaction.</param> /// <param name="insPt">The insertion point.</param> /// <param name="angle">The block rotation.</param> /// <param name="scale">The block scale.</param> /// <returns> /// The Block Reference /// </returns> /// <exception cref="RivieraException">Si existe un error al insertar el bloque</exception> public BlockReference Insert(Document doc, Transaction tr, LBlockType blockDir, Point3d insPt, double angle = 0, double scale = 1) { BlockTable blockTable = doc.Database.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; AutoCADBlock instance; Boolean is2DBlock = !App.Riviera.Is3DEnabled; String instanceName = this.GetInstanceName(blockDir); if (!blockTable.Has(instanceName)) { instance = this.SetContent(blockDir, is2DBlock, doc, tr); } else { Dictionary <LBlockType, AutoCADBlock> blocks2d, blocks3d; this.LoadBlocks(doc, tr, out blocks2d, out blocks3d); instance = new AutoCADBlock(instanceName, tr); } //Se realizá la inserción de la instancia if (instance != null) { BlockReference blkRef = instance.CreateReference(insPt, angle, scale); BlockTableRecord modelSpace = tr.GetModelSpace(); blkRef.Draw(modelSpace, tr); AutoCADLayer lay = new AutoCADLayer(LAYER_RIVIERA_GEOMETRY, tr); lay.SetStatus(LayerStatus.EnableStatus, tr); blkRef.UpgradeOpen(); blkRef.Layer = lay.Layername; return(blkRef); } else { throw new RivieraException(String.Format(ERR_LOADING_BLOCK, this.BlockName)); } }
/// <summary> /// 从外部DWG文件中插入图块 /// </summary> /// <param name="db">图形数据库</param> /// <param name="dwgFileName">外部DWG文件名全称</param> /// <param name="blkname">块名</param> public static void ImportBlocksFromDWG(this Database db, string dwgFileName, string blkname) { Database tempDB = new Database(false, true);//新建一个临时图形数据库<1> try { tempDB.ReadDwgFile(dwgFileName, System.IO.FileShare.Read, true, null); //读取外部DWG到临时数据库<2> ObjectIdCollection ids = new ObjectIdCollection(); //存放块OjbectId的集合 using (Transaction trans = tempDB.TransactionManager.StartTransaction()) { BlockTable bt = trans.GetObject(tempDB.BlockTableId, OpenMode.ForRead) as BlockTable; if (bt.Has(blkname)) { BlockTableRecord btr = trans.GetObject(bt[blkname], OpenMode.ForRead) as BlockTableRecord; ids.Add(bt[blkname]); } } tempDB.WblockCloneObjects(ids, db.BlockTableId, new IdMapping(), DuplicateRecordCloning.Replace, false); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { Application.ShowAlertDialog("\n错误:" + ex.Message); } tempDB.Dispose(); }
public ObjectId CreateBlock() { Database db = HostApplicationServices.WorkingDatabase; ObjectId blockId = ObjectId.Null; //用于返回所创建的块的对象Id BlockTableRecord record = new BlockTableRecord(); //创建一个BlockTableRecord类的对象,表示所要创建的块 record.Name = "Room"; //设置块名 using (Transaction trans = db.TransactionManager.StartTransaction()) { Point3dCollection points = new Point3dCollection();//用于表示组成块的多段线的顶点 points.Add(new Point3d(-18.0, -6.0, 0.0)); points.Add(new Point3d(18.0, -6.0, 0.0)); points.Add(new Point3d(18.0, 6.0, 0.0)); points.Add(new Point3d(-18.0, 6.0, 0.0)); Polyline2d pline = new Polyline2d(Poly2dType.SimplePoly, points, 0.0, true, 0.0, 0.0, null); //创建组成块的多段线 record.Origin = points[3]; //设置块的基点 record.AppendEntity(pline); //将多段线加入到新建的BlockTableRecord对象 BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite); //以写的方式打开块表 if (!bt.Has("Room")) //判断是否存在名为"Room"的块 { blockId = bt.Add(record); //在块表中加入"Room"块 trans.AddNewlyCreatedDBObject(record, true); //通知事务处理 trans.Commit(); //提交事务 } } return(blockId);//返回创建的块的对象Id }
/// <summary> 插入一个块参照到CAD图形中 </summary> /// <param name="spaceId">模型空间Id</param> /// <param name="layer">要插入的图层名</param> /// <param name="insertedBlockName">块名</param> /// <param name="postion">插入点</param> /// <param name="scale">缩放比例</param> /// <param name="rotateAngle">旋转角度</param> /// <returns> 返回添加的块参照的ID </returns> public static ObjectId InsertBlockRef(ObjectId spaceId, string layer, string insertedBlockName, Point3d postion, Scale3d scale, double rotateAngle) { ObjectId blockRefId; //存储要插入的块参照的Id Database db = spaceId.Database; //获取数据库对象 BlockTable bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; if (!bt.Has(insertedBlockName)) { return(ObjectId.Null); //如果没有blockName的块,程序返回 } //以写的方式打开空间 BlockTableRecord btr = spaceId.GetObject(OpenMode.ForWrite) as BlockTableRecord; //创建块参照的插入点 BlockReference br = new BlockReference(postion, bt[insertedBlockName]); br.ScaleFactors = scale; br.Layer = layer; br.Rotation = rotateAngle; blockRefId = btr.AppendEntity(br); db.TransactionManager.AddNewlyCreatedDBObject(br, true); btr.DowngradeOpen(); return(blockRefId); //返回添加的块参照的ID }
/// <summary> /// Inserts this instance block as a BlockReference. /// </summary> /// <param name="doc">The active document.</param> /// <param name="tr">The active transaction.</param> /// <param name="insPt">The insertion point.</param> /// <param name="angle">The block rotation.</param> /// <param name="scale">The block scale.</param> /// <returns>The Block Reference</returns> public BlockReference Insert(Document doc, Transaction tr, Point3d insPt, Double angle = 0, Double scale = 1) { BlockTable blockTable = doc.Database.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; AutoCADBlock instance = null, content; BlockReference blockContent; Boolean is2DBlock = !App.Riviera.Is3DEnabled; if (!blockTable.Has(this.InstanceBlockName) && this.LoadBlocks(doc, tr, out instance, out content, is2DBlock)) { this.SetContent(is2DBlock, out blockContent, doc, tr); } else { this.LoadBlocks(doc, tr, out instance, out content, is2DBlock); instance = new AutoCADBlock(this.InstanceBlockName, tr); } if (instance != null) { BlockReference blkRef = instance.CreateReference(insPt, angle, scale); BlockTableRecord modelSpace = tr.GetModelSpace(); blkRef.Draw(modelSpace, tr); AutoCADLayer lay = new AutoCADLayer(LAYER_RIVIERA_GEOMETRY, tr); lay.SetStatus(LayerStatus.EnableStatus, tr); blkRef.UpgradeOpen(); blkRef.Layer = lay.Layername; return(blkRef); } else { throw new RivieraException(String.Format(ERR_LOADING_BLOCK, this.BlockName)); } }
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); }
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; }
/// <summary> /// Actualizamos la ruta de las imagenes del tablero /// </summary> /// <param name="tr">La transacción activa.</param> /// <param name="doc">El documento a cargar.</param> /// <param name="tablero">El nombre del bloque.</param> public static void UpdatePath(this Transaction tr, Document doc, string tablero) { BlockTable blk = doc.Database.BlockTableId.GetObject(OpenMode.ForWrite) as BlockTable; if (blk.Has(tablero)) { BlockTableRecord tabRec = blk[tablero].GetObject(OpenMode.ForRead) as BlockTableRecord; DBObject obj; foreach (ObjectId objId in tabRec) { obj = objId.GetObject(OpenMode.ForRead); if (obj is RasterImage) { obj.UpgradeOpen(); RasterImage img = obj as RasterImage; String appData = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); String imgFile = Path.Combine(appData, "Autodesk", "ApplicationPlugins", "Tabalim.bundle", "contents", "img", "tableros", String.Format("{0}.BMP", tablero)); DBDictionary imgDic = RasterImageDef.GetImageDictionary(doc.Database).GetObject(OpenMode.ForRead) as DBDictionary; if (File.Exists(imgFile) && imgDic.Contains(tablero)) { RasterImageDef imgDef = imgDic.GetAt(tablero).GetObject(OpenMode.ForWrite) as RasterImageDef; if (imgDef.SourceFileName != imgFile) { imgDef.SourceFileName = imgFile; imgDef.Load(); //img.UpgradeOpen(); //img.ImageDefId = imgDef.Id; //img.AssociateRasterDef(imgDef); } } } } } }
/// <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); } } }
public void InsertBlockRefWithAtt(string blockName, Point3d point, Scale3d scale, double rotateAngle, string roomnumber) { Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; if (!bt.Has(blockName)) { return; } BlockTableRecord blockwithatt = (BlockTableRecord)trans.GetObject(bt[blockName], OpenMode.ForRead); BlockReference blockRef = new BlockReference(point, bt[blockName]); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); blockRef.ScaleFactors = scale; blockRef.Rotation = rotateAngle; btr.AppendEntity(blockRef); trans.AddNewlyCreatedDBObject(blockRef, true); //获取blockName块的遍历器,以实现对块中对象的访问 BlockTableRecordEnumerator iterator = blockwithatt.GetEnumerator(); //如果blockName块包含属性 if (blockwithatt.HasAttributeDefinitions) { //利用块遍历器对块中的对象进行遍历 while (iterator.MoveNext()) { //获取块遍历器当前指向的块中的对象 AttributeDefinition attdef = trans.GetObject(iterator.Current, OpenMode.ForRead) as AttributeDefinition; //定义一个新的属性参照对象 AttributeReference att = new AttributeReference(); //判断块遍历器当前指向的块中的对象是否为属性定义 if (attdef != null) { //从属性定义对象中继承相关的属性到属性参照对象中 att.SetAttributeFromBlock(attdef, blockRef.BlockTransform); //设置属性参照对象的位置为属性定义的位置+块参照的位置 att.Position = attdef.Position + blockRef.Position.GetAsVector(); //判断属性定义的名称 switch (attdef.Tag) { //如果为"NUMBER",则设置块参照的属性值 case "NUMBER": att.TextString = roomnumber; break; } //判断块参照是否可写,如不可写,则切换为可写状态 if (!blockRef.IsWriteEnabled) { blockRef.UpgradeOpen(); } //添加新创建的属性参照 blockRef.AttributeCollection.AppendAttribute(att); //通知事务处理添加新创建的属性参照 trans.AddNewlyCreatedDBObject(att, true); } } } trans.Commit();//提交事务处理 } }
public void InsertBlockRef(string blockName, Point3d point, Scale3d scale, double rotateAngle) { Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { //以读的方式打开块表 BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; //如果没有blockName表示的块,则程序返回 if (!bt.Has(blockName)) { return; } //以读的方式打开blockName表示的块 BlockTableRecord block = (BlockTableRecord)trans.GetObject(bt[blockName], OpenMode.ForRead); //创建一个块参照并设置插入点 BlockReference blockRef = new BlockReference(point, bt[blockName]); blockRef.ScaleFactors = scale; //设置块参照的缩放比例 blockRef.Rotation = rotateAngle; //设置块参照的旋转角度 //以写的方式打开当前空间(模型空间或图纸空间) BlockTableRecord btr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); btr.AppendEntity(blockRef);//在当前空间加入创建的块参照 //通知事务处理加入创建的块参照 trans.AddNewlyCreatedDBObject(blockRef, true); trans.Commit();//提交事务处理以实现块参照的真实加入 } }
public static ObjectId GetBlkId(Database db, string blkName) { ObjectId blkId = ObjectId.Null; if (db == null) { return(ObjectId.Null); } if (string.IsNullOrWhiteSpace(blkName)) { return(ObjectId.Null); } using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); if (bt.Has(blkName)) { blkId = bt[blkName]; } tr.Commit(); } return(blkId); }
/// <summary> /// 用于在AutoCAD图形中插入块参照 /// </summary> /// <param name="spaceId">块参照要加入的模型空间或图纸空间的Id</param> /// <param name="layer">块参照要加入的图层名</param> /// <param name="blockName">块参照所属的块名</param> /// <param name="position">块参照的插入点</param> /// <param name="scale">块参照的缩放比例</param> /// <param name="rotateAngle">块参照的旋转角度</param> /// <returns></returns> public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle) { ObjectId blockRefId; Database db = spaceId.Database; //打开块表 BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); if (!bt.Has(blockName)) { return(ObjectId.Null); } //以写的方式打开空间(模型空间或图纸空间) BlockTableRecord space = (BlockTableRecord)spaceId.GetObject(OpenMode.ForWrite); //创建一个块参照并设置插入点 BlockReference br = new BlockReference(position, bt[blockName]) { //设置块参照的缩放比例 ScaleFactors = scale, //设置块参照的层名 Layer = layer, //设置块参照的旋转角度 Rotation = rotateAngle }; //在空间中加入创建的块参照 blockRefId = space.AppendEntity(br); //通知事务处理加入创建的块参照 db.TransactionManager.AddNewlyCreatedDBObject(br, true); space.DowngradeOpen(); return(blockRefId); }
public static void AddBlockToActiveDrawing(string blockDrawingFile, string blockName) { Database dbDest = Application.DocumentManager.MdiActiveDocument.Database; if (HasBlockDefinition(blockName, dbDest)) { return; } using (Database db = new Database(false, true)) { db.ReadDwgFile(blockDrawingFile, FileOpenMode.OpenForReadAndAllShare, false, null); ObjectIdCollection ids = new ObjectIdCollection(); using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); //BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead); if (bt.Has(blockName)) { ObjectId id = bt[blockName]; BlockTableRecord btr = (BlockTableRecord)tr.GetObject(id, OpenMode.ForRead); ObjectIdCollection IdsCol = new ObjectIdCollection(); IdsCol.Add(id); IdMapping iMap = new IdMapping(); dbDest.WblockCloneObjects(IdsCol, dbDest.BlockTableId, iMap, DuplicateRecordCloning.Ignore, false); } tr.Commit(); } } }
public static void GetPropsToSave(string blName, BlockTable bt, ref List<SaveDynProp> propsToSave) { if (bt.Has(blName)) { var btr = bt[blName].GetObject(OpenMode.ForRead) as BlockTableRecord; var idsBlRef = btr.GetBlockReferenceIds(true, false); IterateIdsBlRef(idsBlRef, blName, ref propsToSave); var idsBtrAnonyms = btr.GetAnonymousBlockIds(); foreach (ObjectId idBtrAnonym in idsBtrAnonyms) { var btrAnonym = idBtrAnonym.GetObject(OpenMode.ForRead) as BlockTableRecord; var idsBlRefAnonym = btrAnonym.GetBlockReferenceIds(true, false); IterateIdsBlRef(idsBlRefAnonym, blName, ref propsToSave); } } }
// // Vérification de la non-utilisation du nom des blocks // private string checkName(BoxCollection boxArray, BlockTable bt, int x, Editor ed) { string blkName = ""; do try { blkName = boxArray.ArrayBox[x].BlckName + _id.ToString(CultureInfo.InvariantCulture); while (bt.Has(blkName)) { _id++; blkName = boxArray.ArrayBox[x].BlckName + _id.ToString(CultureInfo.InvariantCulture); } } catch { ed.WriteMessage("\nInvalid block name."); } while (blkName == ""); return blkName; }
private ObjectId getBtr(string name, BlockTable bt) { if (bt.Has(name)) { return bt[name]; } else { doc.Editor.WriteMessage("Не найден блок оформления {0}", name); return ObjectId.Null; } }
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; }
/// <summary> /// COPY A BLOCK (WITH BLOCK NAME) from ONE FILE TO ANOTHER. /// </summary> /// <param name="blockDrawingFile"></param> /// <param name="blockDestinationFile"></param> /// <param name="blockName"></param> public static void AddBlockToDrawing(string blockDrawingFile, string blockDestinationFile, string blockName) { if (!GoodiesPath.IsFileLocked(blockDestinationFile) && !GoodiesPath.IsFileReadOnly(blockDestinationFile)) { using (Database db = new Database()) { db.ReadDwgFile(blockDrawingFile, System.IO.FileShare.Read, true, ""); ObjectIdCollection ids = new ObjectIdCollection(); using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); //BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead); if (bt.Has(blockName)) { ObjectId id = bt[blockName]; BlockTableRecord btr = (BlockTableRecord)tr.GetObject(id, OpenMode.ForRead); ObjectIdCollection IdsCol = new ObjectIdCollection(); using (Database dbDest = new Database()) { dbDest.ReadDwgFile(blockDestinationFile, System.IO.FileShare.Write, true, ""); IdsCol.Add(id); IdMapping iMap = new IdMapping(); dbDest.WblockCloneObjects(IdsCol, dbDest.BlockTableId, iMap, DuplicateRecordCloning.Ignore, false); dbDest.Save(); dbDest.Dispose(); } } tr.Commit(); } } } }