private static string[] getBlockAttributes(Transaction tr, ObjectId blkId, Editor ed) { string[] point = null; BlockReference blkRef = (BlockReference)tr.GetObject(blkId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead); ed.WriteMessage("\nBlock: " + btr.Name); BlockTable bt = (BlockTable)tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead); ObjectId ModelSpaceID = bt[BlockTableRecord.ModelSpace]; btr.Dispose(); AttributeCollection attCol = blkRef.AttributeCollection; foreach (ObjectId attId in attCol) { AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForRead); string str = ("\n Attribute Tag: " + attRef.Tag + "\n Attribute String: " + attRef.TextString); ed.WriteMessage(str); if (attRef.Tag == "POINT") { point = new string[] { Math.Round(blkRef.Position.X, 1, MidpointRounding.AwayFromZero).ToString(), Math.Round(blkRef.Position.Y, 1, MidpointRounding.AwayFromZero).ToString(), attRef.TextString }; } } return(point); }
public static List <string> ImportBlocks(Database db, Database sourceDb, List <string> blockNames) { List <string> output = new List <string>(); try { //create a variable to store the list of block identifiers ObjectIdCollection blockIds = new ObjectIdCollection(); Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager; using (Transaction tr = tm.StartTransaction()) { //open the block table BlockTable bt = tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false) as BlockTable; //check each block in the block table foreach (ObjectId btrId in bt) { BlockTableRecord btr = tm.GetObject(btrId, OpenMode.ForRead, false) as BlockTableRecord; //only add named & non-layout blocks to the copy list if (blockNames.Contains(btr.Name)) { blockIds.Add(btrId); output.Add(btr.Name); } btr.Dispose(); } } //copy blocks from source to destination database IdMapping mapping = new IdMapping(); sourceDb.WblockCloneObjects(blockIds, db.BlockTableId, mapping, DuplicateRecordCloning.Ignore, false); } catch { } return(output); }
public static DBObject Create(this Grevit.Types.Arc a, Transaction tr) { try { LayerTable lt = (LayerTable)tr.GetObject(Command.Database.LayerTableId, OpenMode.ForRead); Arc arc = new Arc(a.center.ToPoint3d(), a.radius, a.start, a.end); arc.SetDatabaseDefaults(Command.Database); if (lt.Has(a.TypeOrLayer)) { arc.LayerId = lt[a.TypeOrLayer]; } BlockTable bt = (BlockTable)tr.GetObject(Command.Database.BlockTableId, OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); ms.AppendEntity(arc); tr.AddNewlyCreatedDBObject(arc, true); ms.Dispose(); return(arc); } catch (Autodesk.AutoCAD.Runtime.Exception e) { } return(null); }
public static List <Sheet> GetSheetsFromBlocks(Editor ed, List <Sheet> dict, Transaction tr, ObjectIdCollection idArray) { // Build a filter list so that only // block references are selected string sheetNumber = "", docNumber = "", objectNameEng = "", docTitleEng = "", objectNameRu = "", docTitleRu = ""; foreach (ObjectId blkId in idArray) { //TODO Check this point if (blkId != ObjectId.Null) { BlockReference blkRef = (BlockReference)tr.GetObject(blkId, OpenMode.ForRead); string stampViewValue = GetBlockAttributeValueByAttrName(blkRef); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead); ed.WriteMessage("\nBlock: " + btr.Name); btr.Dispose(); AttributeCollection attCol = blkRef.AttributeCollection; foreach (ObjectId attId in attCol) { AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForRead); bool vis = attRef.Visible; //ed.WriteMessage("\n{0} значение {1} видимость {2}", attRef.Tag, attRef.TextString, vis.ToString()); switch (attRef.Tag) { case "НОМЕР_ЛИСТА": docNumber = attRef.TextString; break; case "НАЗВАНИЕEN": objectNameEng = attRef.TextString; break; case "ЛИСТEN": docTitleEng = attRef.TextString; break; case "НАЗВАНИЕRU": objectNameRu = attRef.TextString; break; case "НАЗВАНИЕ_ЛИСТАRU": docTitleRu = attRef.TextString; break; case "ЛИСТ": sheetNumber = attRef.TextString; break; } } dict.Add(new Sheet(sheetNumber, docNumber, objectNameEng, docTitleEng, objectNameRu, docTitleRu, stampViewValue)); } } return(dict); }
/// <summary> /// get dict from attributes of block /// </summary> /// <param name="tr"></param> /// <param name="attrList"></param> /// <returns></returns> public static (string, Dictionary <string, string>) GetAttrList(Transaction tr, Dictionary <string, string> attrList) { string blockName = ""; try { // Build a filter list so that only // block references are selected TypedValue[] filList = new TypedValue[1] { new TypedValue((int)DxfCode.Start, "INSERT") }; SelectionFilter filter = new SelectionFilter(filList); PromptSelectionOptions opts = new PromptSelectionOptions(); opts.SingleOnly = true; opts.SinglePickInSpace = true; opts.MessageForAdding = "Select block references: "; PromptSelectionResult res = Active.Editor.GetSelection(opts, filter); // Do nothing if selection is unsuccessful if (res.Status != PromptStatus.OK) { throw new InvalidOperationException("block not selected"); } if (res.Value.Count > 1) { throw new InvalidOperationException("For selecting block attributes, please select only one block"); } SelectionSet selSet = res.Value; ObjectId[] idArray = selSet.GetObjectIds(); foreach (ObjectId blkId in idArray) { BlockReference blkRef = (BlockReference)tr.GetObject(blkId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.DynamicBlockTableRecord, OpenMode.ForRead); blockName = btr.Name; Active.Editor.WriteMessage("\nBlock: " + blockName); btr.Dispose(); AttributeCollection attCol = blkRef.AttributeCollection; foreach (ObjectId attId in attCol) { AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForRead); string str = ("\n Attribute Tag: " + attRef.Tag + "\n Attribute String: " + attRef.TextString); attrList.Add(attRef.Tag, attRef.TextString); Active.Editor.WriteMessage(str); } } tr.Commit(); } catch (Exception ex) { Active.Editor.WriteMessage(("Exception: " + ex.Message)); } finally { tr.Dispose(); } return(blockName, attrList); }
public void DisplayBlockAttributesSample() { Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("===================================================="); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\nDisplay Block Attributes:\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("====================================================\n"); Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; Database db = HostApplicationServices.WorkingDatabase; Transaction tr = db.TransactionManager.StartTransaction(); // Start the transaction try { // Build a filter list so that only // block references are selected TypedValue[] filList = new TypedValue[1] { new TypedValue((int)DxfCode.Start, "INSERT") }; SelectionFilter filter = new SelectionFilter(filList); PromptSelectionOptions opts = new PromptSelectionOptions(); opts.MessageForAdding = "Select block references: "; PromptSelectionResult res = ed.GetSelection(opts, filter); if (res.Status != PromptStatus.OK) { return; } SelectionSet selSet = res.Value; ObjectId[] idArray = selSet.GetObjectIds(); foreach (ObjectId blkId in idArray) { BlockReference blkRef = (BlockReference)tr.GetObject(blkId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead); btr.Dispose(); AttributeCollection attCol = blkRef.AttributeCollection; foreach (ObjectId attId in attCol) { AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForRead); } } tr.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage(("Exception: " + ex.Message)); } finally { tr.Dispose(); } }
public static DBObject Create(this Grevit.Types.Door door, Transaction tr, Wall wall) { BlockTable bt = (BlockTable)tr.GetObject(Command.Database.BlockTableId, OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); Door d = new Door(); DictionaryDoorStyle dds = new DictionaryDoorStyle(Command.Database); bool newEnt = false; if (Command.existing_objects.ContainsKey(door.GID)) { d = (Door)tr.GetObject(Command.existing_objects[door.GID], OpenMode.ForWrite); } else { d.SetDatabaseDefaults(Command.Database); d.SetToStandard(Command.Database); AnchorOpeningBaseToWall w = new AnchorOpeningBaseToWall(); w.SetToStandard(Command.Database); w.SubSetDatabaseDefaults(Command.Database); d.SetAnchor(w); newEnt = true; w.SetSingleReference(wall.Id, Autodesk.Aec.DatabaseServices.RelationType.OwnedBy); } Point3d pkt = new Point3d(door.locationPoint.x, door.locationPoint.y + (wall.Width / 2), door.locationPoint.z); d.Location = pkt; LayerTable lt = (LayerTable)tr.GetObject(Command.Database.LayerTableId, OpenMode.ForRead); if (door.TypeOrLayer != "") { if (lt.Has(door.TypeOrLayer)) { d.LayerId = lt[door.TypeOrLayer]; } } if (dds.Has(door.FamilyOrStyle, tr)) { d.StyleId = dds.GetAt(door.FamilyOrStyle); } if (newEnt) { ms.AppendEntity(d); tr.AddNewlyCreatedDBObject(d, true); ms.Dispose(); } return(d); }
static public void SetDynamicBlkProperty() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; PromptEntityOptions prEntOptions = new PromptEntityOptions("Выберите вставку динамического блока..."); PromptEntityResult prEntResult = ed.GetEntity(prEntOptions); if (prEntResult.Status != PromptStatus.OK) { ed.WriteMessage("Ошибка..."); return; } using (Transaction Tx = db.TransactionManager.StartTransaction()) { BlockReference bref = Tx.GetObject(prEntResult.ObjectId, OpenMode.ForWrite) as BlockReference; double blockWidth = 0; if (bref.IsDynamicBlock) { DynamicBlockReferencePropertyCollection props = bref.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in props) { object[] values = prop.GetAllowedValues(); if (prop.PropertyName == "Штамп") { BlockTableRecord btr = (BlockTableRecord)Tx.GetObject(bref.BlockTableRecord, OpenMode.ForRead); btr.Dispose(); AttributeCollection attCol = bref.AttributeCollection; var attrDict = AttributeExtensions.GetAttributesValues(bref); if (prop.Value.ToString() == "Форма 3 ГОСТ Р 21.1101 - 2009") { blockWidth = double.Parse(prop.Value.ToString(), CultureInfo.InvariantCulture); } ed.WriteMessage(blockWidth.ToString()); } //if (prop.PropertyName == "Высота") //{ // blockHeidht = double.Parse(prop.Value.ToString(), System.Globalization.CultureInfo.InvariantCulture); // ed.WriteMessage("\n{0}", blockHeidht.ToString()); //} } } Tx.Commit(); } }
public void BrowseBlock() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; Database db = HostApplicationServices.WorkingDatabase; //只选择块参照对象 TypedValue[] filterValues = { new TypedValue((int)DxfCode.Start, "INSERT") }; SelectionFilter filter = new SelectionFilter(filterValues); PromptSelectionOptions opts = new PromptSelectionOptions(); //提示用户进行选择 opts.MessageForAdding = "请选择图形中的块对象"; //根据选择过滤器选择对象,本例中为块参照对象 PromptSelectionResult res = ed.GetSelection(opts, filter); //如果选择失败,则返回 if (res.Status != PromptStatus.OK) { return; } //获取选择集对象,表示所选择的对象集合 SelectionSet ss = res.Value; //获取选择集中包含的对象ID,用于访问选择集中的对象 ObjectId[] ids = ss.GetObjectIds(); using (Transaction trans = db.TransactionManager.StartTransaction()) { //循环遍历选择集中的对象 foreach (ObjectId blockId in ids) { //获取选择集中当前的对象,由于是只选择块参照对象,所以直接赋值为块对象 BlockReference blockRef = (BlockReference)trans.GetObject(blockId, OpenMode.ForRead); //获取当前块参照对象所属的块表记录对象 BlockTableRecord btr = (BlockTableRecord)trans.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead); //在命令行上显示块名 ed.WriteMessage("\n块:" + btr.Name); //销毁块表记录对象 btr.Dispose(); //获取块参照的属性集合对象 AttributeCollection atts = blockRef.AttributeCollection; //循环遍历属性集合对象 foreach (ObjectId attId in atts) { //获取当前的块参照属性 AttributeReference attRef = (AttributeReference)trans.GetObject(attId, OpenMode.ForRead); //获取块参照属性的属性名和属性值 string attString = " 属性名:" + attRef.Tag + " 属性值:" + attRef.TextString; //在命令行上显示块的属性名和属性值 ed.WriteMessage(attString); } } } }
//[CommandMethod("IB")] public static void ImportBlocks() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database destDb = doc.Database; Database sourceDb = new Database(false, true); String sourceFileName; try { //Get name of DWG from which to copy blocks sourceFileName = "C:\\Program Files\\AutoCAD MEP 2010\\DynaPrograms\\TagHgr.dwg"; //Read the DWG file into the database sourceDb.ReadDwgFile(sourceFileName.ToString(), System.IO.FileShare.Read, true, ""); //Create a variable to store the list of block Identifiers ObjectIdCollection blockIds = new ObjectIdCollection(); Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager; using (Transaction myTm = tm.StartTransaction()) { //Open the block table BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false); //Check each block in the table foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId, OpenMode.ForRead, false); //Only add named and non-layout blocks to the copy file if the don't already exist. if (!btr.IsAnonymous && !btr.IsLayout) { blockIds.Add(btrId); } btr.Dispose(); } } //Copy blocks from source to dest database IdMapping mapping = new IdMapping(); sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, false); //Writes the number of blocks copied to cmd line. //ed.WriteMessage("\nCopied: " + blockIds.Count.ToString() + " block definitions from " + sourceFileName + " to the current drawing."); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage(ex.Message); } sourceDb.Dispose(); } //end ImportBlocks()
public void ImportBlocks() { DocumentCollection dm = Application.DocumentManager; Editor ed = dm.MdiActiveDocument.Editor; Database destDb = dm.MdiActiveDocument.Database; Database sourceDb = new Database(false, true); PromptResult sourceFileName; try { // Get name of DWG from which to copy blocks sourceFileName = ed.GetString("\nEnter the name of the source drawing: "); // Read the DWG into a side database sourceDb.ReadDwgFile(sourceFileName.StringResult, System.IO.FileShare.Read, true, ""); // Create a variable to store the list of block identifiers ObjectIdCollection blockIds = new ObjectIdCollection(); Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager; using (Transaction myT = tm.StartTransaction()) { // Open the block table BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false); // Check each block in the block table foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId, OpenMode.ForRead, false); // Only add named & non-layout blocks to the copy list if (!btr.IsAnonymous && !btr.IsLayout) { blockIds.Add(btrId); } btr.Dispose(); } } // Copy blocks from source to destination database IdMapping mapping = new IdMapping(); sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, false); ed.WriteMessage("\nCopied " + blockIds.Count.ToString() + " block definitions from " + sourceFileName.StringResult + " to the current drawing."); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage("\nError during copy: " + ex.Message); } sourceDb.Dispose(); }
public static PrintModel GetPrintModelByBlockId(Transaction tr, string selAttrName, ObjectId blkId) { BlockReference blkRef = (BlockReference)tr.GetObject(blkId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead); string docNumber = GetBlockAttributeValue(blkRef, selAttrName); //formatValue = attrDict.FirstOrDefault(x => x.Key == "ФОРМАТ").Value; //ed.WriteMessage("\nBlock:{0} - {1} габариты {2} -{3}", btr.Name, docNumber, posPoint2d.ToString(), formatValue); btr.Dispose(); return(new PrintModel(docNumber, blkId)); }
public void ImportBlocks() { AcadApp.DocumentCollection dm = AcadApp.Application.DocumentManager; Editor ed = dm.MdiActiveDocument.Editor; Database destDb = dm.MdiActiveDocument.Database; Database sourceDb = new Database(false, true); PromptResult sourceFileName; try { //从命令行要求用户输入以得到要导入的块所在的源DWG文件的名字 sourceFileName = ed.GetString("\nEnter the name of the source drawing: "); //把源DWG读入辅助数据库 sourceDb.ReadDwgFile(sourceFileName.StringResult, System.IO.FileShare.Write, true, ""); //用集合变量来存储块ID的列表 ObjectIdCollection blockIds = new ObjectIdCollection(); Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager; using (Transaction myT = tm.StartTransaction()) { //打开块表 BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false); //在块表中检查每个块 foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId, OpenMode.ForRead, false); //只添加有名块和非layout块(layout块是非MS和非PS的块) if (!btr.IsAnonymous && !btr.IsLayout) { blockIds.Add(btrId); } btr.Dispose(); //释放块表记录引用变量所占用的资源 } bt.Dispose(); //释放块表引用变量所占用的资源 //没有作改变,不需要提交事务 myT.Dispose(); } IdMapping mapping = new IdMapping(); mapping = sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, DuplicateRecordCloning.Replace, false); ed.WriteMessage("\nCopied " + blockIds.Count.ToString() + " block definitions from " + sourceFileName.StringResult + " to the current drawing."); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage("\nError during copy: " + ex.Message); } sourceDb.Dispose(); }
public static void ImportBlocks() { using (DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument()) { DocumentCollection dm = Application.DocumentManager; Editor ed = dm.MdiActiveDocument.Editor; Database destDb = dm.MdiActiveDocument.Database; Database sourceDb = new Database(false, true); try { // Read the DWG into a side database #if DEBUG sourceDb.ReadDwgFile("../../88.dwg", System.IO.FileShare.Read, true, ""); #else sourceDb.ReadDwgFile("./Resource/88.dwg", System.IO.FileShare.Read, true, ""); #endif // Create a variable to store the list of block identifiers ObjectIdCollection blockIds = new ObjectIdCollection(); Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager; using (Transaction myT = tm.StartTransaction()) { // Open the block table BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false); // Check each block in the block table foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId, OpenMode.ForRead, false); // Only add named & non-layout blocks to the copy list if (!btr.IsAnonymous && !btr.IsLayout) { blockIds.Add(btrId); } btr.Dispose(); } } // Copy blocks from source to destination database IdMapping mapping = new IdMapping(); sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, false); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage("\nError during copy: " + ex.Message); } sourceDb.Dispose(); } }
public void ImportBlocksFromDwg(string sourceFileName) { DocumentCollection dm = Application.DocumentManager; Editor ed = dm.MdiActiveDocument.Editor; //获取当前数据库作为目标数据库 Database destDb = dm.MdiActiveDocument.Database; //创建一个新的数据库对象,作为源数据库,以读入外部文件中的对象 Database sourceDb = new Database(false, true); try { //把DWG文件读入到一个临时的数据库中 sourceDb.ReadDwgFile(sourceFileName, System.IO.FileShare.Read, true, null); //创建一个变量用来存储块的ObjectId列表 ObjectIdCollection blockIds = new ObjectIdCollection(); //获取源数据库的事务处理管理器 Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager; //在源数据库中开始事务处理 using (Transaction myT = tm.StartTransaction()) { //打开源数据库中的块表 BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false); //遍历每个块 foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId, OpenMode.ForRead, false); //只加入命名块和非布局块到复制列表中 if (!btr.IsAnonymous && !btr.IsLayout) { blockIds.Add(btrId); } btr.Dispose(); } bt.Dispose(); } //定义一个IdMapping对象 IdMapping mapping = new IdMapping(); //从源数据库向目标数据库复制块表记录 sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, false); //'复制完成后,命令行显示复制了多少个块的信息 ed.WriteMessage("复制了 " + blockIds.Count.ToString() + " 个块,从 " + sourceFileName + " 到当前图形"); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage("\nError during copy: " + ex.Message); } //操作完成,销毁源数据库 sourceDb.Dispose(); }
public static DBObject Create(this Grevit.Types.Spline s, Transaction tr) { LayerTable lt = (LayerTable)tr.GetObject(Command.Database.LayerTableId, OpenMode.ForRead); try { Point3dCollection points = new Point3dCollection(); foreach (Grevit.Types.Point p in s.controlPoints) { points.Add(p.ToPoint3d()); } DoubleCollection dc = new DoubleCollection(); foreach (double dbl in s.weights) { dc.Add(dbl); } DoubleCollection dcc = new DoubleCollection(); foreach (double dbl in s.knots) { dcc.Add(dbl); } Spline sp = new Spline(s.degree, s.isRational, s.isClosed, s.isPeriodic, points, dcc, dc, 0, 0); sp.SetDatabaseDefaults(Command.Database); BlockTable bt = (BlockTable)tr.GetObject(Command.Database.BlockTableId, OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); if (lt.Has(s.TypeOrLayer)) { sp.LayerId = lt[s.TypeOrLayer]; } ms.AppendEntity(sp); tr.AddNewlyCreatedDBObject(sp, true); ms.Dispose(); return(sp); } catch (Autodesk.AutoCAD.Runtime.Exception e) { } return(null); }
/// <summary> /// 导入外部文件中的块 /// </summary> /// <param name="destDb">目标数据库</param> /// <param name="sourceFileName">包含完整路径的外部文件名</param> public static void ImportBlocksFromDwg(this Database destDb, string sourceFileName) { //创建一个新的数据库对象,作为源数据库,以读入外部文件中的对象 Database sourceDb = new Database(false, true); try { //把DWG文件读入到一个临时的数据库中 sourceDb.ReadDwgFile(sourceFileName, System.IO.FileShare.Read, true, null); //创建一个变量用来存储块的ObjectId列表 ObjectIdCollection blockIds = new ObjectIdCollection(); //获取源数据库的事务处理管理器 Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager; //在源数据库中开始事务处理 using (Transaction myT = tm.StartTransaction()) { //打开源数据库中的块表 BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false); //遍历每个块 foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId, OpenMode.ForRead, false); //只加入命名块和非布局块到复制列表中 if (!btr.IsAnonymous && !btr.IsLayout) { blockIds.Add(btrId); } btr.Dispose(); } bt.Dispose(); } //定义一个IdMapping对象 IdMapping mapping = new IdMapping(); //从源数据库向目标数据库复制块表记录 sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, false); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { Application.ShowAlertDialog("复制错误: " + ex.Message); } //操作完成,销毁源数据库 sourceDb.Dispose(); }
/// <summary> /// создает колекцию листов из блоков штампа /// </summary> /// <param name="ed">editor</param> /// <param name="dict"> коллекция листов</param> /// <param name="tr"> транзакция </param> /// <returns>коллекция листов </returns> public static List <Sheet> GetSheetsFromBlocks(Editor ed, List <Sheet> dict, Transaction tr, ObjectIdCollection objectIdCollection, AttributModel attributModel) { string objectNameEn = attributModel.ObjectNameEn; string objectNameRu = attributModel.ObjectNameRu; string listNumber = attributModel.Position; string nomination = attributModel.Nomination; string commentAttr = attributModel.Comment; string trDocTitleEn = attributModel.TrDocTitleEn; string trDocTitleRu = attributModel.TrDocTitleRu; string sheetNumber = "", docNumber = "", comment = "", objectNameEng = "", docTitleEng = "", objectNameRus = "", docTitleRu = ""; foreach (ObjectId blkId in objectIdCollection) { BlockReference blkRef = (BlockReference)tr.GetObject(blkId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead); Extents3d extents3d = blkRef.GeometricExtents; ed.WriteMessage("\nBlock:{0} габариты {1} ", btr.Name, extents3d.MinPoint.ToString(), extents3d.MaxPoint.ToString()); btr.Dispose(); AttributeCollection attCol = blkRef.AttributeCollection; var attrDict = AttributeExtensions.GetAttributesValues(blkRef); docTitleEng = attrDict.FirstOrDefault(x => x.Key == objectNameEn).Value; docTitleRu = attrDict.FirstOrDefault(x => x.Key == objectNameRu).Value; sheetNumber = attrDict.FirstOrDefault(x => x.Key == listNumber).Value; docNumber = attrDict.FirstOrDefault(x => x.Key == nomination).Value; comment = attrDict.FirstOrDefault(x => x.Key == commentAttr).Value; //transItem = attrDict.FirstOrDefault(x => x.Key == trItem).Value; objectNameEng = attrDict.FirstOrDefault(x => x.Key == trDocTitleEn).Value; objectNameRus = attrDict.FirstOrDefault(x => x.Key == trDocTitleRu).Value; } return(dict); }
public static void load(string dwgFilePath) { DocumentCollection dm = Application.DocumentManager; Editor ed = dm.MdiActiveDocument.Editor; Database destDb = dm.MdiActiveDocument.Database; Database sourceDb = new Database(false, true); try { sourceDb.ReadDwgFile(dwgFilePath, System.IO.FileShare.Read, true, ""); ObjectIdCollection blockIds = new ObjectIdCollection(); Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager; using (Transaction myT = tm.StartTransaction()) { BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false); foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId, OpenMode.ForRead, false); if (!btr.IsAnonymous && !btr.IsLayout) { blockIds.Add(btrId); } btr.Dispose(); } } IdMapping mapping = new IdMapping(); sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, false); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage("\nError during loading blocks dwg file: " + ex.Message); } }
private void file_open_handler(object sender, EventArgs e) { if (DialogResult.OK == openFileDialog.ShowDialog(this)) { if (lm != null) { lm.LayoutSwitched -= new Teigha.DatabaseServices.LayoutEventHandler(reinitGraphDevice); HostApplicationServices.WorkingDatabase = null; lm = null; } bool bLoaded = true; database = new Database(false, false); if (openFileDialog.FilterIndex == 1) { try { database.ReadDwgFile(openFileDialog.FileName, FileOpenMode.OpenForReadAndAllShare, false, ""); //现在进入数据库并获得数据库的块表引用 Transaction trans = database.TransactionManager.StartTransaction(); BlockTable bt = (BlockTable)trans.GetObject(database.BlockTableId, OpenMode.ForRead, false, true); //从块表的模型空间特性中获得块表记录,块表记录对象包含DWG文件数据库实体 BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead, false, true); foreach (ObjectId btrId in btr) { DBObject entBlock = (DBObject)trans.GetObject(btrId, OpenMode.ForRead, false, true); String dxfName = entBlock.GetRXClass().DxfName; if (entBlock.GetRXClass().DxfName.ToUpper() == "INSERT") { BlockReference bRef = (BlockReference)entBlock; if (bRef.AttributeCollection.Count != 0) { System.Collections.IEnumerator bRefEnum = bRef.AttributeCollection.GetEnumerator(); while (bRefEnum.MoveNext()) { ObjectId aId = (ObjectId)bRefEnum.Current;//这一句极其关键 AttributeReference aRef = (AttributeReference)trans.GetObject(aId, OpenMode.ForRead, false, true); string sss = aRef.TextString; //this.textBox1.Text = aRef.TextString;//此语句即获得属性单行文本,请自行在此语句前添加 属性单行文本 赋于的变量 } } } if (entBlock.GetRXClass().DxfName.ToUpper() == "MTEXT") { MText bRef = (MText)entBlock; string sd = bRef.Text; } if (entBlock.GetRXClass().DxfName.ToUpper() == "LINE") { Line bRef = (Line)entBlock; ObjectId oid = bRef.Id; } } trans.Commit(); //提交事务处理 btr.Dispose(); bt.Dispose(); } catch (System.Exception ex) { MessageBox.Show(ex.Message); bLoaded = false; } } else if (openFileDialog.FilterIndex == 2) { try { database.DxfIn(openFileDialog.FileName, ""); } catch (System.Exception ex) { MessageBox.Show(ex.Message); bLoaded = false; } } if (bLoaded) { HostApplicationServices.WorkingDatabase = database; lm = LayoutManager.Current; lm.LayoutSwitched += new Teigha.DatabaseServices.LayoutEventHandler(reinitGraphDevice); String str = HostApplicationServices.Current.FontMapFileName; //menuStrip. exportToolStripMenuItem.Enabled = true; zoomToExtentsToolStripMenuItem.Enabled = true; zoomWindowToolStripMenuItem.Enabled = true; setAvtiveLayoutToolStripMenuItem.Enabled = true; fileDependencyToolStripMenuItem.Enabled = true; panel1.Enabled = true; pageSetupToolStripMenuItem.Enabled = true; printPreviewToolStripMenuItem.Enabled = true; printToolStripMenuItem.Enabled = true; this.Text = String.Format("OdViewExMgd - [{0}]", openFileDialog.SafeFileName); initializeGraphics(); Invalidate(); } } }
private static void LibraryAction(Editor ed) { if (MessageHandler.LibraryToAppActions.Count > 0) { string action = MessageHandler.LibraryToAppActions.Dequeue(); //MessageBox.Show(action); Dictionary <string, string> actionD = JsonConvert.DeserializeObject <Dictionary <string, string> >(action); if (actionD["option"] == "OPEN") { List <string> files = Directory.GetFiles(actionD["hyperlink"]).ToList(); string dwg = ""; foreach (string file in files) { if (file.Contains(".dwg")) { dwg = file; } } if (dwg != "") { DocumentCollection docMgr = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager; DocumentCollectionExtension.Open(docMgr, dwg, false); } } else if (actionD["option"] == "LOAD") { List <string> files = Directory.GetFiles(actionD["hyperlink"]).ToList(); string dwg = ""; foreach (string file in files) { if (file.Contains(".dwg")) { dwg = file; } } if (dwg != "") { Database sourceDb = new Database(false, true); Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database cDB = doc.Database; sourceDb.ReadDwgFile(dwg, FileOpenMode.OpenForReadAndAllShare, true, ""); //Read the DWG into a side database String fileName = Path.GetFileNameWithoutExtension(dwg); cDB.Insert(fileName, sourceDb, false); Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = cDB.TransactionManager; try { ObjectIdCollection blockIds = new ObjectIdCollection(); using (Transaction myT = tm.StartTransaction()) { // Open the block table BlockTable bt = (BlockTable)tm.GetObject(cDB.BlockTableId, OpenMode.ForRead, false); BlockTableRecord btr = myT.GetObject(bt[fileName], OpenMode.ForRead) as BlockTableRecord; BlockReference br = new BlockReference(Point3d.Origin, btr.ObjectId); if (BlockMovingRotating.Jig(br)) { BlockTableRecord modelspace = myT.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; modelspace.AppendEntity(br); myT.AddNewlyCreatedDBObject(br, true); myT.Commit(); } else { myT.Abort(); } btr.Dispose(); } } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } } else if (actionD["option"] == "VIEW") { MessageBox.Show("VIEW"); } // do your AutoCAD tasks here //MessageBox.Show("Text received from the Library window: " + actionD); // reply something back //MessageHandler.AppToLibraryActions.Enqueue("A message from the AutoCAD plugin - " + DateTime.Now.ToString()); } }
static public void InsertBlocksByExcel() { Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; string excelFile = "D:\\dwgBlock_list.xlsx"; Dictionary <string, List <string> > data = Excel.getDwgBlockList(excelFile); string blockTemplate = @"D:\_PROJECTs\60614740-MascotTunnel\_blocks\CADtemplate.dwg"; List <string> blockRequired = new List <string>() { "RMS_TfNSW_DESIGN-BLK-00-0000-GE-ADM_A1", "RMS_TfNSW_DESIGN-BLK-00-0000-GE-ATT_A1" }; //load block template file database Database sourceDb = new Database(false, true); if (File.Exists(blockTemplate)) { //open block template file to read sourceDb.ReadDwgFile(blockTemplate, System.IO.FileShare.Read, true, null); foreach (KeyValuePair <string, List <string> > d in data) { string file = d.Key; List <string> blocks = d.Value; if (File.Exists(file)) { ed.WriteMessage($"Open {file} to insert blocks.....\n"); try { Database db = new Database(false, true); using (db) { //open drawing database db.ReadDwgFile(file, System.IO.FileShare.ReadWrite, true, null); #region load blocks into drawings, make sure the block is available to be inserted List <string> loadedBlock = new List <string>(); try { //create a variable to store the list of block identifiers ObjectIdCollection blockIdsToCopied = new ObjectIdCollection(); Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager; using (Transaction tr = tm.StartTransaction()) { ed.WriteMessage($"start transaction to copy blocks.....\n"); BlockTable bt = tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false) as BlockTable;//open the block table //check each block in the block table foreach (ObjectId btrId in bt) { BlockTableRecord btr = tm.GetObject(btrId, OpenMode.ForRead, false) as BlockTableRecord; if (!btr.IsAnonymous && !btr.IsLayout) { blockIdsToCopied.Add(btrId); loadedBlock.Add(btr.Name); ed.WriteMessage($"Block: {btr.Name}, will be loaded in {file}.\n"); } btr.Dispose(); } } //copy blocks from source to destination database if (blockIdsToCopied.Count > 0) { IdMapping mapping = new IdMapping(); sourceDb.WblockCloneObjects(blockIdsToCopied, db.BlockTableId, mapping, DuplicateRecordCloning.Replace, false); ed.WriteMessage($"copied blocks into {file}.....\n"); } } catch { } #endregion #region determine what blocks needs to be added //create the list of blocks that will be added List <string> blocksTobeAdded = new List <string>(); foreach (string b in blockRequired) { if (!blocks.Contains(b)) { blocksTobeAdded.Add(b); } } #endregion #region insert blocks into paper space Point3d insPoint = new Point3d(0, 0, 0); //string layoutName = "Layout1";//get all layout name LayoutManager lm = LayoutManager.Current; using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; DBDictionary layoutDic = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead, false) as DBDictionary;//get layout dictionary from current drawings foreach (DBDictionaryEntry entry in layoutDic) { ObjectId layoutId = entry.Value; //layout id Layout layout = tr.GetObject(layoutId, OpenMode.ForRead) as Layout; //get layout if (layout.LayoutName == "Model") { continue; } BlockTableRecord btr = tr.GetObject(layout.BlockTableRecordId, OpenMode.ForWrite) as BlockTableRecord; foreach (string blockName in blocksTobeAdded) { ObjectId blkId = bt[blockName]; ed.WriteMessage($"ObjectId {blkId} in {layout.LayoutName}\n"); //insert the block BlockReference blkRef = new BlockReference(insPoint, blkId); btr.UpgradeOpen(); btr.AppendEntity(blkRef); tr.AddNewlyCreatedDBObject(blkRef, true); ed.WriteMessage($"Insert {blockName} in {layout.LayoutName}\n"); } } tr.Commit(); } //foreach (string blockName in blocksTobeAdded) //{ // try // { // CADops.InsertBlock(db, layoutName, blockName, insPoint); // ed.WriteMessage($"Insert {blockName} in {file}\n"); // } // catch { } //} #endregion db.SaveAs(file, DwgVersion.Current);//save changes } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage(ex.ToString() + Environment.NewLine); } } else { ed.WriteMessage("File " + file + " does not exist.\n"); } } sourceDb.Dispose(); } ed.WriteMessage($"Done."); }
public static DBObject Create(this Grevit.Types.Room r, Transaction tr) { DictionarySpaceStyle ss = new DictionarySpaceStyle(Command.Database); try { BlockTable bt = (BlockTable)tr.GetObject(Command.Database.BlockTableId, OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); Polyline acPoly = new Polyline(); acPoly.SetDatabaseDefaults(); int i = 0; foreach (Grevit.Types.Point p in r.points) { acPoly.AddVertexAt(i, new Point2d(p.x, p.y), 0, 0, 0); i++; } acPoly.Closed = true; ms.AppendEntity(acPoly); tr.AddNewlyCreatedDBObject(acPoly, true); Autodesk.Aec.Geometry.Profile myProfile = Autodesk.Aec.Geometry.Profile.CreateFromEntity(acPoly, Command.Editor.CurrentUserCoordinateSystem); Space space; bool newEnt = false; if (Command.existing_objects.ContainsKey(r.GID)) { space = (Space)tr.GetObject(Command.existing_objects[r.GID], OpenMode.ForWrite); } else { newEnt = true; space = new Space(); space.SetDatabaseDefaults(Command.Database); space.SetToStandard(Command.Database); } space.Associative = r.associative; space.Name = r.name; space.GeometryType = SpaceGeometryType.TwoD; space.Location = new Point3d(0, 0, 0); space.SetBaseProfile(myProfile, Matrix3d.Identity); LayerTable lt = (LayerTable)tr.GetObject(Command.Database.LayerTableId, OpenMode.ForRead); if (r.TypeOrLayer != "") { if (lt.Has(r.TypeOrLayer)) { space.LayerId = lt[r.TypeOrLayer]; } } if (ss.Has(r.FamilyOrStyle, tr)) { space.StyleId = ss.GetAt(r.FamilyOrStyle); } if (newEnt) { ms.AppendEntity(space); tr.AddNewlyCreatedDBObject(space, true); ms.Dispose(); } return(space); } catch (Autodesk.AutoCAD.Runtime.Exception e) { } return(null); }
/// <summary> /// /// </summary> /// <param name="isLocalTest">true: simulate an signature image to a json string. the example image is testsig.png</param> void GenerateTBJson(bool isLocalTest = false) { Editor ed = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor; Database db = HostApplicationServices.WorkingDatabase; Transaction tr = db.TransactionManager.StartTransaction(); try { ed.WriteMessage("\nbegin att checking"); // Build a filter list so that only block references are selected TypedValue[] filList = new TypedValue[1] { new TypedValue((int)DxfCode.Start, "INSERT") }; SelectionFilter filter = new SelectionFilter(filList); PromptSelectionResult res = ed.SelectAll(filter); // Do nothing if selection is unsuccessful if (res.Status != PromptStatus.OK) { return; } SelectionSet selSet = res.Value; ObjectId[] idArray = selSet.GetObjectIds(); List <jsonAttribute> jsonDataArray = new List <jsonAttribute>(); ed.WriteMessage("\nbegin each checking"); foreach (ObjectId blkId in idArray) { BlockReference blkRef = (BlockReference)tr.GetObject(blkId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead); ed.WriteMessage("\nBlock: " + btr.Name); btr.Dispose(); AttributeCollection attCol = blkRef.AttributeCollection; //attribute index int index = 0; foreach (ObjectId attId in attCol) { AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForRead); if (attRef.Layer == "AM_BOR") { ed.WriteMessage("\nbegin: " + attRef.Tag); string _height = attRef.Height.ToString(); string _tag = attRef.Tag; int pFrom = _tag.IndexOf("{") + 1; int pTo = _tag.LastIndexOf("}"); string _width_radio = _tag.Substring(pFrom, pTo - pFrom); string _pos = attRef.Position.X.ToString() + "," + attRef.Position.Y.ToString() + "," + attRef.Position.Z.ToString(); string _cont = attRef.TextString; var jsonData = new jsonAttribute() { tag = _tag, height = _height, width_ratio = _width_radio, position = _pos, content = _cont, isImage = false, imgbase64 = "" }; //if this is to test an image locally //only simulate the attribute in even index will be an image if (isLocalTest && (index % 2 == 1)) { jsonData.isImage = true; jsonData.imgbase64 = imageToBase64(); } jsonDataArray.Add(jsonData); ed.WriteMessage("end: " + attRef.Tag); index++; } //tag: {12.3} is the\ ratio of the defined width for the text to the text height. For example, if the text height is 5 units, and the width of the available space is 100 units, the value between the curly brackets is 20. //http://knowledge.autodesk.com/support/autocad-mechanical/getting-started/caas/CloudHelp/cloudhelp/2015/ENU/AutoCAD-Mechanical/files/GUID-ADFE83F7-CE92-4996-8231-D3C5FD5A1A92-htm.html } } tr.Commit(); var jsonDrawingInstance = new jsonDrawing() { tbjson = jsonDataArray.ToArray <jsonAttribute>() }; // this is the Newtonsoft API method string json_data = JsonConvert.SerializeObject(jsonDrawingInstance); var jsonOut = Path.Combine(Helper.jsonfilename); FileStream fs = new FileStream(jsonOut, FileMode.Create); StreamWriter sw = new StreamWriter(fs); try { sw.Write(json_data); sw.Flush(); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message.ToString()); } finally { sw.Close(); fs.Close(); } ed.WriteMessage("\nend att checking"); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage(("\nException: " + ex.Message)); return; } finally { tr.Dispose(); } }
public void Main() { //-------------------------------------------------------------------------------------- // 基本句柄 //-------------------------------------------------------------------------------------- Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; ObjectId paperSpace = db.CreatPaperSpace(); MOExcel.Application app = new MOExcel.Application(); MOExcel.Workbook wbook = app.Workbooks.Add(Type.Missing); MOExcel.Worksheet wsheet = (MOExcel.Worksheet)wbook.Worksheets[1]; //-------------------------------------------------------------------------------------- // 初始化桥梁列表 //-------------------------------------------------------------------------------------- Bridge TheBridge; System.Data.DataTable Parameters = new System.Data.DataTable(); string aa = BPublicFunctions.GetXPath("选择设计表", "参数表|*.xls"); if (aa == "") { return; } else { Parameters = BPublicFunctions.GetDataFromExcelByCom(true, aa); ed.WriteMessage("\n桥梁数据读取成功"); } var IDtoPolot = Parameters.AsEnumerable().Select(t => t.Field <int>("序号")).ToList(); //-------------------------------------------------------------------------------------- // 加载贝雷梁模型 //-------------------------------------------------------------------------------------- MyCommands.CADini(); string T321ModelFilePath = BPublicFunctions.GetCADPath("选择设计表", "模型|*.model"); Database sourceDb = new Database(false, true); try { sourceDb.ReadDwgFile(T321ModelFilePath, System.IO.FileShare.Read, true, ""); ObjectIdCollection blockIds = new ObjectIdCollection(); Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager; using (Transaction myT = tm.StartTransaction()) { // Open the block table BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false); // Check each block in the block table foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId, OpenMode.ForRead, false); // Only add named & non-layout blocks to the copy list if (!btr.IsAnonymous && !btr.IsLayout) { blockIds.Add(btrId); } btr.Dispose(); } } IdMapping mapping = new IdMapping(); sourceDb.WblockCloneObjects(blockIds, db.BlockTableId, mapping, DuplicateRecordCloning.Replace, false); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage("\nError during copy: " + ex.Message); } sourceDb.Dispose(); //-------------------------------------------------------------------------------------- // 初始化绘图空间 //-------------------------------------------------------------------------------------- ed.WriteMessage("\n 环境初始化成功.\n"); //-------------------------------------------------------------------------------------- // 绘图 //-------------------------------------------------------------------------------------- string fsd = Path.Combine(Path.GetDirectoryName(T321ModelFilePath), "TK.dwg"); int conter = 0; foreach (int ii in IDtoPolot) { TheBridge = new Bridge(Parameters, ii); double dymax; Point2d AP = Point2d.Origin.Convert2D(-0.5 * TheBridge.Pieces * 3000, conter * -30000); Point2d CC = Point2d.Origin.Convert2D(0, conter * -30000); Point2d PlotB_AP = CC.Convert2D(30000); dymax = TheBridge.PlotA(db, AP); TheBridge.PlotB(db, PlotB_AP); conter++; // 套图框 db.XrefAttachAndInsert(fsd, paperSpace, Point3d.Origin.Convert3D(0, (ii - 1) * (-297), 0)); db.XrefAttachAndInsert(fsd, paperSpace, Point3d.Origin.Convert3D(420, (ii - 1) * (-297), 0)); // 图名图号注释 TextPloter.PrintNumTitle(db, Point3d.Origin.Convert3D(0, (ii - 1) * (-297), 0), TheBridge); TextPloter.PrintNote(db, Point3d.Origin.Convert3D(360, (ii - 1) * (-297) + 40, 0)); TextPloter.PrintNote2(db, Point3d.Origin.Convert3D(250 + 420, (ii - 1) * (-297) + 62, 0)); TextPloter.PrintFName(db, Point3d.Origin.Convert3D(0, (ii - 1) * (-297), 0), TheBridge); // 视口 using (Transaction tr = db.TransactionManager.StartTransaction()) { Layout lay = (Layout)tr.GetObject(paperSpace, OpenMode.ForWrite); Viewport vpA, vpB; var btr = (BlockTableRecord)tr.GetObject(lay.BlockTableRecordId, OpenMode.ForWrite); vpA = new Viewport(); btr.AppendEntity(vpA); tr.AddNewlyCreatedDBObject(vpA, true); vpA.On = true; vpA.GridOn = false; vpA.DrawMyViewport(1, Point3d.Origin.Convert3D(0, (ii - 1) * (-297)), CC.Convert2D(0, dymax + (8 - 0.5 * 247) * TheBridge.GetScaleA()), TheBridge.GetScaleA()); vpB = new Viewport(); btr.AppendEntity(vpB); tr.AddNewlyCreatedDBObject(vpB, true); vpB.On = true; vpB.GridOn = false; vpB.DrawMyViewport(1, Point3d.Origin.Convert3D(420, (ii - 1) * (-297)), PlotB_AP.Convert2D(90 * 50, -35 * 50), 50); tr.Commit(); } // 表格 TheBridge.PlotNumTB(db, Point2d.Origin.Convert2D(420 + 310, (ii - 1) * (-297) + 240)); TheBridge.PlotMatTB(db, Point2d.Origin.Convert2D(420 + 620, (ii - 1) * (-297) + 240)); break; } Marshal.ReleaseComObject(wbook); wbook = null; app.Workbooks.Close(); app.KillExcelApp(); }
public void updateTBFromFile() { Database db = HostApplicationServices.WorkingDatabase; Editor ed = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor; //read external json PromptFileNameResult pfnr = ed.GetFileNameForOpen("\nSpecify json file"); if (pfnr.Status != PromptStatus.OK) { ed.WriteMessage("\nerror to read external json file " + pfnr.Status.ToString()); return; } string paramFile = pfnr.StringResult; string rawJsonContent = File.ReadAllText(paramFile); Transaction tr = db.TransactionManager.StartTransaction(); // Start the transaction try { //convert json to json class jsonDrawing jsonDrawingInstance = JsonConvert.DeserializeObject <jsonDrawing>(rawJsonContent); if (jsonDrawingInstance == null) { ed.WriteMessage("\nraw json file is bad!\n"); return; } //string tblayer = jsonDrawingInstance.tblayer; //create the layer for signature ObjectId lyId = createLayer("signature_layer"); if (lyId.IsNull) { ed.WriteMessage("\nlayer cannot be created"); return; } // Build a filter list so that only block references are selected TypedValue[] filList = new TypedValue[1] { new TypedValue((int)DxfCode.Start, "INSERT") }; SelectionFilter filter = new SelectionFilter(filList); PromptSelectionResult res = ed.SelectAll(filter); // Do nothing if selection is unsuccessful if (res.Status != PromptStatus.OK) { ed.WriteMessage("\nno any Insert in this drawing!"); return; } SelectionSet selSet = res.Value; ObjectId[] idArray = selSet.GetObjectIds(); foreach (ObjectId blkId in idArray) { BlockReference blkRef = (BlockReference)tr.GetObject(blkId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead); ed.WriteMessage("\nBlock: " + btr.Name); btr.Dispose(); AttributeCollection attCol = blkRef.AttributeCollection; foreach (ObjectId attId in attCol) { AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForWrite); //check the block ref of title block on the specific layer if (attRef.Layer == Helper.tblayer) { foreach (var eachAtt in jsonDrawingInstance.tbjson) { if (eachAtt.tag == attRef.Tag) { ed.WriteMessage("\nbegin: " + eachAtt.tag + " \n"); ed.WriteMessage("\nis image: " + eachAtt.isImage + " \n"); if (eachAtt.isImage) { attRef.TextString = ""; //create image for signature createImages(eachAtt, tr, lyId); } else { attRef.TextString = eachAtt.content; } break; ed.WriteMessage("\nend: " + eachAtt.tag + " \n"); } } } } } tr.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage(("\nException: " + ex.Message)); } finally { tr.Dispose(); } db.SaveAs("newTB.dwg", DwgVersion.Newest); }
public void ImportBlocks() { DocumentCollection dm = Application.DocumentManager; Editor ed = dm.MdiActiveDocument.Editor; Database destDb = dm.MdiActiveDocument.Database; Database sourceDb = new Database(false, true); try { const string filename = "psw.dwg"; string dwgFileFullPath = HostApplicationServices.Current.FindFile(filename, destDb, FindFileHint.Default); sourceDb.ReadDwgFile(dwgFileFullPath, System.IO.FileShare.Read, true, ""); // Create a variable to store the list of block identifiers ObjectIdCollection blockIds = new ObjectIdCollection(); var tm = sourceDb.TransactionManager; using (var myT = tm.StartOpenCloseTransaction()) { // Open the block table BlockTable bt = (BlockTable)myT.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false); // Check each block in the block table foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)myT.GetObject(btrId, OpenMode.ForRead, false); // Only add named & non-layout blocks to the copy list if (!btr.IsAnonymous && !btr.IsLayout) { blockIds.Add(btrId); } btr.Dispose(); } } // Copy blocks from source to destination database var mapping = new IdMapping(); sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, false); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage("\nError during copy: " + ex.Message); } sourceDb.Dispose(); //显示到界面上 using (Transaction trans = destDb.TransactionManager.StartTransaction()) { BlockTable bt = trans.GetObject(destDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; ObjectId refid = bt["psw"]; BlockReference br = new BlockReference(Point3d.Origin, refid); // 通过块定义创建块参照 btr.AppendEntity(br); //把块参照添加到块表记录 trans.AddNewlyCreatedDBObject(br, true); // 通过事务添加块参照到数据库 trans.Commit(); } }
//SELECIONAR UMA REGIÃO DO PROJETO PARA LEVANTAR O QUANTITATIVO public List <Elemento> SelecionarBlocos() { List <double> contagem = new List <double>(); Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; Editor acDocEd = acDoc.Editor; //COMEÇAR UMA TRANSAÇÃO using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //CRIAR UM ARRAY COM O(S) TIPO(S) DE OBJETO(S) A SER(EM) FILTRADO(S) TypedValue[] acTypValAr = new TypedValue[1]; //acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 0); acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "INSERT"), 0); //CRIAR O FILTRO COM O ARRAY DECLARADO ACIMA SelectionFilter acSelFtr = new SelectionFilter(acTypValAr); //É PEDIDO AO USUÁRIO SELECIONAR UMA REGIÃO DO DESENHO PromptSelectionResult acSSPrompt = acDocEd.GetSelection(acSelFtr); string tipo = ""; string id = ""; string nome = ""; string especificacao = ""; string quant = "0"; //CASO ELE SELECIONE UMA REGIÃO if (acSSPrompt.Status == PromptStatus.OK) { SelectionSet acSSet = acSSPrompt.Value; //PERCORRE OS OBJETOS DO CONJUNTO DE SELEÇÃO foreach (SelectedObject acSSObj in acSSet) { Elemento elemento = new Elemento(); //VERIFICAR SE O OBJETO SELECIONADO EXISTE if (acSSObj != null) { // Open the selected object for write Entity acEnt = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as Entity; contagem.Add(10); if (acEnt.GetType() == typeof(BlockReference)) { BlockReference blRef = acEnt as BlockReference; nome = blRef.Name; elemento.Nome = nome; tipo = RetornaTipoElemento(nome); elemento.Tipo = tipo; //MessageBox.Show("Nome do bloco: " + nome, "Contagem de blocos", MessageBoxButtons.OK, MessageBoxIcon.Information); //Now you can open BlockTableRecord: BlockTableRecord acBlkTblRec = acTrans.GetObject(blRef.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord; foreach (ObjectId eid in acBlkTblRec) { DBObject obj = (Entity)acTrans.GetObject(eid, OpenMode.ForRead); if (obj is AttributeDefinition) { AttributeDefinition atdef = obj as AttributeDefinition; if (atdef.Constant) { id = atdef.Tag; especificacao = atdef.TextString; elemento.ID = id; elemento.Especificacao = especificacao; elemento.Quantificacao = quant; //MessageBox.Show(atdef.Tag, "Contagem de blocos", MessageBoxButtons.OK, MessageBoxIcon.Information); //MessageBox.Show(atdef.TextString, "Contagem de blocos", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } acBlkTblRec.Dispose(); //AttributeCollection attCol = blRef.AttributeCollection; //foreach (ObjectId attId in attCol) //{ // AttributeReference attRef = (AttributeReference)acTrans.GetObject(attId, OpenMode.ForRead); // string str = ("\n Attribute Tag: " + attRef.Tag + "\n Attribute String: " + attRef.TextString); // MessageBox.Show(str, "Contagem de blocos", MessageBoxButtons.OK, MessageBoxIcon.Information); //} } } if (elemento.Nome != "") { listaElementos.Add(elemento); } } //SALVAR O OBJETO NO BANCO DE DADOS acTrans.Commit(); } //int qtd = contagem.Count(); //MessageBox.Show("Número de blocos selecionados: " + qtd.ToString(), "Contagem de blocos", MessageBoxButtons.OK, MessageBoxIcon.Information); // Dispose of the transaction } return(listaElementos); }
public void Dispose() { poly?.Dispose(); block?.Dispose(); }
public DiaSettings() { InitializeComponent(); //Init Configuration //Basislayer value = _config.GetAppSettingString("Basislayer"); if (value == String.Empty) { _config.SetAppSetting("Basislayer", "MP-P"); } //Header value = _config.GetAppSettingString("useHeader"); if (value == String.Empty) { _config.SetAppSetting("useHeader", "False"); } cB_Header.Checked = Convert.ToBoolean(value); value = _config.GetAppSettingString("Header"); if (value == String.Empty) { _config.SetAppSetting("Header", "PNr, X,Y,Z"); } tb_Header.Text = value; //3dImport value = _config.GetAppSettingString("3dImport"); if (value == String.Empty) { _config.SetAppSetting("3dImport", "False"); } cb_3dImport.Checked = Convert.ToBoolean(value); //Output File value = _config.GetAppSettingString("OutputFile"); if (File.Exists(value)) { tb_PunktExport.Text = value; cB_ExportFile.Enabled = File.Exists(value); value = _config.GetAppSettingString("useOutputFile"); if (value == String.Empty) { _config.SetAppSetting("useOutputFile", "False"); } cB_OutputFile.Checked = Convert.ToBoolean(value); } else { tb_PunktExport.Text = " "; } //Separator & Decimal value = _config.GetAppSettingString("Separator"); if (value == String.Empty) { _config.SetAppSetting("Separator", ";"); } tB_Separator.Text = value; value = _config.GetAppSettingString("Decimal"); if (value == String.Empty) { _config.SetAppSetting("Decimal", "."); } cb_Decimal.SelectedItem = value; cb_Decimal.Refresh(); value = _config.GetAppSettingString("decimals"); if (value == "") { value = "3"; _config.SetAppSetting("decimals", value); } numUD_Kommastellen.Value = Convert.ToInt32(value); //import Exportfile value = _config.GetAppSettingString("importExportfile"); if (value == String.Empty) { cB_ExportFile.Checked = false; } else { cB_ExportFile.Checked = Convert.ToBoolean(value); } //Treenode TreeNode root = treeView1.Nodes.Add("CAS 2019"); //root.Nodes.Add("general"); root.Nodes.Add("Import"); root.Nodes.Add("Export"); root.ExpandAll(); treeView1.SelectedNode = root.FirstNode; //Basislayer myCAD.MyLayer objLayer = myCAD.MyLayer.Instance; objLayer.Refresh(); try { foreach (_AcDb.LayerTableRecord ltr in objLayer.LsLayerTableRecord) { string layName = ltr.Name; if (layName.Length > 2) { if (layName.Substring(layName.Length - 2, 2) == "-P") { cbBasislayer.Items.Add(layName); } } } } catch { } cbBasislayer.SelectedIndex = cbBasislayer.FindStringExact(_config.GetAppSettingString("Basislayer")); if (cbBasislayer.SelectedIndex == -1) { if (cbBasislayer.Items.Count > 0) { DialogResult res = MessageBox.Show(_config.GetAppSettingString("Basislayer") + " nicht gefunden! Soll dieser Layer erstellt werden?", "", MessageBoxButtons.YesNo); if (res == DialogResult.Yes) { objLayer.Add(_config.GetAppSettingString("Basislayer")); } } else { string Basislayer = _config.GetAppSettingString("Basislayer"); CheckBasislayer(); cbBasislayer.Items.Add(Basislayer); cbBasislayer.SelectedItem = cbBasislayer.Items[0]; } } //Blöcke aus Protoypzeichnung lesen _AcAp.Document myDWG; _AcAp.DocumentLock myDWGlock; Database db = HostApplicationServices.WorkingDatabase; _AcDb.TransactionManager myTm = null; myTm = db.TransactionManager; Transaction myT = db.TransactionManager.StartTransaction(); string ProtoDWG = CAS.myUtilities.Global.Instance.PrototypFullPath; lb_Prototypzeichnung.Text = ProtoDWG; if (File.Exists(ProtoDWG)) { try { myDWG = _AcAp.Application.DocumentManager.MdiActiveDocument; myDWGlock = myDWG.LockDocument(); using (Database srcDb = new Database(false, false)) { srcDb.ReadDwgFile(ProtoDWG, FileShare.Read, true, ""); ObjectIdCollection blockIds = new ObjectIdCollection(); _AcDb.TransactionManager srcT = srcDb.TransactionManager; try { using (Transaction protoT = srcT.StartTransaction()) { BlockTable bt = (BlockTable)protoT.GetObject(srcDb.BlockTableId, OpenMode.ForRead, false); foreach (ObjectId btrid in bt) { BlockTableRecord btr = (BlockTableRecord)protoT.GetObject(btrid, OpenMode.ForRead, false); if (!btr.IsAnonymous && !btr.IsLayout) { blockIds.Add(btrid); cbBlock.Items.Add(btr.Name); } btr.Dispose(); } protoT.Commit(); protoT.Dispose(); } } catch { } finally { myT.Commit(); myT.Dispose(); } //Blöcke in aktuelle Zeichnung einfügen IdMapping mapping = new IdMapping(); srcDb.WblockCloneObjects(blockIds, db.BlockTableId, mapping, DuplicateRecordCloning.Replace, false); srcDb.Dispose(); myDWGlock.Dispose(); } } catch { } } else { MessageBox.Show("Achtung!!! Prototypzeichnung nicht gefunden!"); } if (cbBlock.Items.Count > 0) { try { cbBlock.SelectedIndex = cbBlock.FindStringExact(_config.GetAppSettingString("Block")); //Block aus settings.xml suchen } catch { cbBlock.SelectedItem = cbBlock.Items[0]; //sonst ersten Block wählen } } else { MessageBox.Show("Keine Blöcke gefunden!"); } //Header cB_Header.Checked = _config.GetAppSettingBool("useHeader"); tb_Header.Text = _config.GetAppSettingString("Header"); //Output File cB_OutputFile.Checked = _config.GetAppSettingBool("useOutputFile"); tb_PunktExport.Text = _config.GetAppSettingString("OutputFile"); }