/// <summary> /// Adds the block attributes. /// </summary> /// <param name="blockRef">The block ref.</param> /// <param name="blockDefinition">The block definition.</param> /// <param name="attributeTagValue">The attribute tag value.</param> /// <param name="tm">The tm.</param> private static void AddBlockAttributes(BlockReference blockRef, BlockTableRecord blockDefinition, Hashtable attributeTagValue, TransactionManager tm) { PGA.MessengerManager.MessengerManager.AddLog("Start AddBlockAttributes"); var m = blockRef.BlockTransform; IEnumerator i; i = blockDefinition.GetEnumerator(); while (i.MoveNext()) { var obj = tm.GetObject((ObjectId)i.Current, OpenMode.ForRead, false); if (typeof(AttributeDefinition) == obj.GetType()) { var attDef = (AttributeDefinition)obj; if (!attDef.Constant) { var attRef = new AttributeReference(); attRef.SetAttributeFromBlock(attDef, blockRef.BlockTransform); if (attributeTagValue.ContainsKey(attRef.Tag)) { attRef.TextString = (string)attributeTagValue[attRef.Tag]; } attRef.Position = attDef.Position.TransformBy(m); blockRef.AttributeCollection.AppendAttribute(attRef); tm.AddNewlyCreatedDBObject(attRef, true); } } } PGA.MessengerManager.MessengerManager.AddLog("End AddBlockAttributes"); }
public AcBlockRef AddBlockRef(Point3d pos, AcTransaction trans) { //Create the block reference... var blockRef = new BlockReference(pos, this.ObjectId); blockRef.SetDatabaseDefaults(); // Default/Active layer, color, ... trans.AddEntity(blockRef); // Do it before blockRef.AttributeCollection.AppendAttribute(attRef); var attrRefs = new List <AttributeReference>(); foreach (var attrDef in this.Attributes) { // this BlockDef could be initialized throught other (closed) Transaction, the same with this.Attributes var attDefObj = attrDef.GetAcObject(trans); // trans.GetObject<AttributeDefinition>(attrDef.ObjectId); // attrDef.AcObject; var attRef = new AttributeReference(); attRef.SetAttributeFromBlock(attDefObj, blockRef.BlockTransform); attRef.SetDatabaseDefaults(); if (!attDefObj.Constant) { attRef.TextString = attDefObj.TextString; } blockRef.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); attrRefs.Add(attRef); } return(new AcBlockRef(blockRef, trans, attrRefs)); }
public static ObjectId Insert(ObjectId blkDefId, Matrix3d transform, Database db = null, string space = null) { db = (db ?? Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Database); ObjectId id = ObjectId.Null; using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTable blkTbl = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord mdlSpc = trans.GetObject(blkTbl[space ?? BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; BlockReference blkRef = new BlockReference(Point3d.Origin, blkDefId); blkRef.BlockTransform = transform; id = mdlSpc.AppendEntity(blkRef); trans.AddNewlyCreatedDBObject(blkRef, true); BlockTableRecord blkDef = trans.GetObject(blkDefId, OpenMode.ForRead) as BlockTableRecord; if (blkDef.HasAttributeDefinitions) { foreach (ObjectId subId in blkDef) { if (subId.ObjectClass.Equals(RXObject.GetClass(typeof(AttributeDefinition)))) { AttributeDefinition attrDef = trans.GetObject(subId, OpenMode.ForRead) as AttributeDefinition; AttributeReference attrRef = new AttributeReference(); attrRef.SetAttributeFromBlock(attrDef, transform); blkRef.AttributeCollection.AppendAttribute(attrRef); } } } trans.Commit(); } return(id); }
/// <summary> /// Inserts all attributreferences /// </summary> /// <param name="blkRef">Blockreference to append the attributes</param> /// <param name="strAttributeTag">The tag to insert the <paramref name="strAttributeText"/></param> /// <param name="strAttributeText">The textstring for <paramref name="strAttributeTag"/></param> public static void InsertBlockAttibuteRef(this BlockReference blkRef, string strAttributeTag, string strAttributeText) { Database dbCurrent = HostApplicationServices.WorkingDatabase; Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = dbCurrent.TransactionManager; using (Transaction tr = tm.StartTransaction()) { BlockTableRecord btAttRec = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead); foreach (ObjectId idAtt in btAttRec) { Entity ent = (Entity)tr.GetObject(idAtt, OpenMode.ForRead); if (ent is AttributeDefinition) { AttributeDefinition attDef = (AttributeDefinition)ent; AttributeReference attRef = new AttributeReference(); attRef.SetAttributeFromBlock(attDef, blkRef.BlockTransform); if (attRef.Tag == strAttributeTag) { attRef.TextString = strAttributeText; } ObjectId idTemp = blkRef.AttributeCollection.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); } } tr.Commit(); } }
private static void ResetAttributes(this BlockReference br, List <AttributeDefinition> attDefs, Transaction tr) { Dictionary <string, string> attValues = new Dictionary <string, string>(); foreach (ObjectId id in br.AttributeCollection) { if (!id.IsErased) { AttributeReference attRef = (AttributeReference)tr.GetObject(id, OpenMode.ForWrite); attValues.Add(attRef.Tag, attRef.IsMTextAttribute ? attRef.MTextAttribute.Contents : attRef.TextString); attRef.Erase(); } } foreach (AttributeDefinition attDef in attDefs) { AttributeReference attRef = new AttributeReference(); attRef.SetAttributeFromBlock(attDef, br.BlockTransform); if (attDef.Constant) { attRef.TextString = attDef.IsMTextAttributeDefinition ? attDef.MTextAttributeDefinition.Contents : attDef.TextString; } else if (attValues.ContainsKey(attRef.Tag)) { attRef.TextString = attValues[attRef.Tag]; } br.AttributeCollection.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); } }
/// <summary> /// 创建属性参照 /// </summary> /// <param name="ad"></param> /// <returns></returns> public static AttributeReference CreateAttributeReference(AttributeDefinition ad) { AttributeReference ar = new AttributeReference(); ar.SetAttributeFromBlock(ad, new Matrix3d()); return(ar); }
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 static void CopyAttributeDefinition(this BlockTableRecord tableRecord, BlockReference reference, Dictionary <string, string> values) { var tr = tableRecord.Database.TransactionManager.TopTransaction; if (tableRecord.HasAttributeDefinitions) { foreach (var objectId in tableRecord) { using (var dbObject = objectId.GetObject(OpenMode.ForRead)) { var attrDef = dbObject as AttributeDefinition; if (attrDef != null && !attrDef.Constant) { using (var attrRef = new AttributeReference()) { attrRef.SetAttributeFromBlock(attrDef, reference.BlockTransform); attrRef.Position = attrDef.Position.TransformBy(reference.BlockTransform); if (values.ContainsKey(attrDef.Tag)) { attrRef.TextString = values[attrDef.Tag]; } reference.AttributeCollection.AppendAttribute(attrRef); tr.AddNewlyCreatedDBObject(attrRef, true); } } } } } }
public static AttributeReference AddAttributeReferences(this BlockReference br, int index, string value) { BlockTableRecord obj = br.BlockTableRecord.GetObject <BlockTableRecord>(); Transaction topTransaction = br.Database.TransactionManager.TopTransaction; AttributeReference attributeReference = null; AttributeDefinition[] array = obj.GetObjects <AttributeDefinition>().ToArray <AttributeDefinition>(); for (int i = 0; i < (int)array.Length; i++) { AttributeDefinition attributeDefinition = array[i]; AttributeReference attributeReference1 = new AttributeReference(); attributeReference1.SetAttributeFromBlock(attributeDefinition, br.BlockTransform); Point3d position = attributeDefinition.Position; attributeReference1.Position = position.TransformBy(br.BlockTransform); if (attributeDefinition.Justify != AttachmentPoint.BaseLeft) { position = attributeDefinition.AlignmentPoint; attributeReference1.AlignmentPoint = position.TransformBy(br.BlockTransform); attributeReference1.AdjustAlignment(br.Database); } if (attributeReference1.IsMTextAttribute) { attributeReference1.UpdateMTextAttribute(); } if (i == index) { attributeReference1.TextString = value; attributeReference = attributeReference1; } br.AttributeCollection.AppendAttribute(attributeReference1); topTransaction.AddNewlyCreatedDBObject(attributeReference1, true); } return(attributeReference); }
/// <summary> /// Utility method to set block attributes /// </summary> /// <param name="acBlkRef"></param> /// <param name="blkRecId"></param> /// <param name="acTrans"></param> public static void AppendAttributes(this BlockReference acBlkRef, BlockTableRecord acBlkTblRec, Transaction acTrans) { // Verify block table record has attribute definitions associated with it if (acBlkTblRec != null && acBlkTblRec.HasAttributeDefinitions) { foreach (var objId in acBlkTblRec) { var dbObj = acTrans.GetObject(objId, OpenMode.ForRead); if (!(dbObj is AttributeDefinition acAtt)) { continue; } if (acAtt.Constant) { continue; } using (var acAttRef = new AttributeReference()) { acAttRef.SetAttributeFromBlock(acAtt, acBlkRef.BlockTransform); if (!acBlkRef.ContainsAttributeDef(acAtt.Tag, acTrans)) { acAttRef.TextString = acAtt.TextString; acBlkRef.AttributeCollection.AppendAttribute(acAttRef); acTrans.AddNewlyCreatedDBObject(acAttRef, true); } } } } }
//returns a blockreference public static BlockReference InsertBlockRef(Point3d dblInsert, string strSourceBlockPath, string layerName, short colorindex, string lineType) { string strSourceBlockName = Path.GetFileName(strSourceBlockPath); BlockTable bt; BlockTableRecord btr; BlockReference br; //ObjectId id; Document doc = Acad.DocumentManager.MdiActiveDocument; Database db = doc.Database; using (Transaction trans = db.TransactionManager.StartTransaction()) { //insert block bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite, true, true); //if block already exists in drawing retrieve it, if not create it from external drawing if (bt.Has(strSourceBlockName)) { ObjectId id = bt[strSourceBlockName]; btr = (BlockTableRecord)trans.GetObject(id, OpenMode.ForRead, true, true); } else { BlockTableRecord btrSource = GetBlock(strSourceBlockName, strSourceBlockPath); btr = (BlockTableRecord)trans.GetObject(btrSource.ObjectId, OpenMode.ForRead, true, true); } //Get the current space var btrSpace = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); //Get the Attributes from the block source and add references to them in the blockref's attribute collection Entity ent; br = new BlockReference(dblInsert, btr.ObjectId); CreateLayer(layerName, colorindex, lineType, false); br.Layer = layerName; btrSpace.AppendEntity(br); trans.AddNewlyCreatedDBObject(br, true); var attColl = br.AttributeCollection; foreach (ObjectId oid in btr) { ent = (Entity)trans.GetObject(oid, OpenMode.ForRead, true, true); if (ent.GetType() == typeof(AttributeDefinition)) { AttributeDefinition attdef = (AttributeDefinition)ent; AttributeReference attref = new AttributeReference(); attref.SetAttributeFromBlock(attdef, br.BlockTransform); attref.TextString = attdef.TextString; attColl.AppendAttribute(attref); trans.AddNewlyCreatedDBObject(attref, true); } } trans.Commit(); return(br); } }
/// <summary> /// 绘制标高符号 /// </summary> /// <param name="bgdata">标高数据</param> /// <param name="refpt">标高点</param> /// <param name="ms"></param> /// <param name="tr"></param> /// <param name="blockTbl"></param> /// <param name="s"></param> public static void BiaoGao(double bgdata, Point3d refpt, BlockTableRecord ms, Transaction tr, BlockTable blockTbl, double s = 100) { ObjectId blkRecId = blockTbl["BG"]; double factor = s / 100; using (BlockReference acBlkRef = new BlockReference(refpt, blkRecId)) { //acBlkRef.SetAttributes(); acBlkRef.ScaleFactors = new Scale3d(factor); acBlkRef.Layer = "标注"; ms.AppendEntity(acBlkRef); tr.AddNewlyCreatedDBObject(acBlkRef, true); BlockTableRecord zheshiyuankuai; zheshiyuankuai = tr.GetObject(blkRecId, OpenMode.ForRead) as BlockTableRecord; foreach (ObjectId gezhongshuxingID in zheshiyuankuai) { DBObject gezhongshuxing = tr.GetObject(gezhongshuxingID, OpenMode.ForRead) as DBObject; if (gezhongshuxing is AttributeDefinition) { AttributeDefinition acAtt = gezhongshuxing as AttributeDefinition; using (AttributeReference acAttRef = new AttributeReference()) { acAttRef.SetAttributeFromBlock(acAtt, acBlkRef.BlockTransform); acAttRef.Position = acAtt.Position.TransformBy(acBlkRef.BlockTransform); acAttRef.TextString = String.Format("{0:f2}", bgdata); //acAttRef.Height = acAttRef.Height * factor; acBlkRef.AttributeCollection.AppendAttribute(acAttRef); tr.AddNewlyCreatedDBObject(acAttRef, true); } } } } }
public void InsertAt(Point3d position, string model, bool sideWall = false, double angle = 0.0) { BlockTableRecord record = Define(sideWall); var blockRef = new BlockReference(position, Define(sideWall).Id) { Layer = Layer, ColorIndex = ColorIndices.ByLayer, Rotation = angle, }; ModelSpace.From(transaction).AppendEntity(blockRef); transaction.AddNewlyCreatedDBObject(blockRef, true); foreach (ObjectId id in record) { using (var def = id.GetObject(OpenMode.ForRead) as AttributeDefinition) { if ((def != null) && (!def.Constant) && def.Tag.ToUpper() == "MODEL") { using (var ar = new AttributeReference()) { ar.SetAttributeFromBlock(def, blockRef.BlockTransform); ar.TextString = $"{model}-{coverage}"; ar.Rotation = 0; blockRef.AttributeCollection.AppendAttribute(ar); transaction.AddNewlyCreatedDBObject(ar, true); } } } } }
//******************* wstaw atrybut do bloku public static void InsertAttibuteInBlockRef( BlockReference blkRef, string attributeTag, string attributeText, double atangle, Transaction tr) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead); foreach (ObjectId id in btr) { AttributeDefinition aDef = tr.GetObject(id, OpenMode.ForRead) as AttributeDefinition; if (aDef != null) { AttributeReference aRef = new AttributeReference(); aRef.SetAttributeFromBlock(aDef, blkRef.BlockTransform); if (aRef.Tag == attributeTag) { aRef.TextString = attributeText; } aRef.Rotation = atangle; blkRef.AttributeCollection.AppendAttribute(aRef); tr.AddNewlyCreatedDBObject(aRef, true); } } }
/// <summary> /// Utility method to set block attributes /// </summary> /// <param name="acBlkRef"></param> /// <param name="acBlkTblRec"></param> /// <param name="acTrans"></param> public static void AppendAttributes(this BlockReference acBlkRef, ObjectId blkRecId, Transaction acTrans) { BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(blkRecId, OpenMode.ForRead) as BlockTableRecord; // Verify block table record has attribute definitions associated with it if (acBlkTblRec.HasAttributeDefinitions) { // Add attributes from the block table record foreach (var objID in acBlkTblRec) { var dbObj = acTrans.GetObject(objID, OpenMode.ForRead); if (dbObj is AttributeDefinition) { var acAtt = dbObj as AttributeDefinition; if (!acAtt.Constant) { using (var acAttRef = new AttributeReference()) { acAttRef.SetAttributeFromBlock(acAtt, acBlkRef.BlockTransform); acAttRef.TextString = acAtt.TextString; acBlkRef.AttributeCollection.AppendAttribute(acAttRef); acTrans.AddNewlyCreatedDBObject(acAttRef, true); } } } } } }
public static void ApplyAttributes(Database db, QuickTransaction tr, BlockReference bref) { if (bref == null) { return; } var _brec = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead); var btrec = _brec as BlockTableRecord; if (btrec == null) { return; } if (btrec.HasAttributeDefinitions) { var atcoll = bref.AttributeCollection; foreach (var subid in btrec) { var ent = (Entity)subid.GetObject(OpenMode.ForRead); var attDef = ent as AttributeDefinition; if (attDef != null) { var attRef = new AttributeReference(); attRef.SetDatabaseDefaults(); //optional attRef.SetAttributeFromBlock(attDef, bref.BlockTransform); attRef.Position = attDef.Position.TransformBy(bref.BlockTransform); attRef.Tag = attDef.Tag; attRef.AdjustAlignment(db); atcoll.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); } } } }
public static void AddAttributeReferences(this BlockReference target, Dictionary <string, string> attValues) { if (target == null) { throw new ArgumentNullException("target"); } Transaction tr = target.Database.TransactionManager.TopTransaction; if (tr == null) { throw new AcRx.Exception(ErrorStatus.NoActiveTransactions); } BlockTableRecord btr = (BlockTableRecord)tr.GetObject(target.BlockTableRecord, OpenMode.ForRead); RXClass attDefClass = RXClass.GetClass(typeof(AttributeDefinition)); foreach (ObjectId id in btr) { if (id.ObjectClass != attDefClass) { continue; } AttributeDefinition attDef = (AttributeDefinition)tr.GetObject(id, OpenMode.ForRead); AttributeReference attRef = new AttributeReference(); attRef.SetAttributeFromBlock(attDef, target.BlockTransform); if (attValues != null && attValues.ContainsKey(attDef.Tag.ToUpper())) { attRef.TextString = attValues[attDef.Tag.ToUpper()]; } target.AttributeCollection.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); } }
private static void ApplyAttibutes(Database db, Transaction tr, BlockReference bref, List<string> listTags, List<string> listValues) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead); foreach (ObjectId attId in btr) { Entity ent = (Entity)tr.GetObject(attId, OpenMode.ForRead); if (ent is AttributeDefinition) { AttributeDefinition attDef = (AttributeDefinition)ent; AttributeReference attRef = new AttributeReference(); attRef.SetAttributeFromBlock(attDef, bref.BlockTransform); bref.AttributeCollection.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); if (listTags.Contains(attDef.Tag.ToUpper())) { ListStringComparer lsc = new ListStringComparer(); int found = listTags.BinarySearch(attDef.Tag.ToUpper(), lsc); int index = listTags.FindIndex(s => s.Contains(attDef.Tag.ToUpper())); string strtemp = listValues[index]; if (index >= 0) { attRef.TextString = listValues[index]; attRef.AdjustAlignment(db); } } } } }
public static List <Entity> CloneAttribute(ObjectId blk_ref_id, ObjectId btr_id) { List <Entity> ents = new List <Entity>(); //return ents; using (Transaction tran = AcadFuncs.GetActiveDb().TransactionManager.StartTransaction()) { BlockReference blk_ref = tran.GetObject(blk_ref_id, OpenMode.ForWrite) as BlockReference; BlockTableRecord btr = tran.GetObject(btr_id, OpenMode.ForRead) as BlockTableRecord; foreach (var obj_id in btr) { AttributeDefinition att_def = obj_id.GetObject(OpenMode.ForRead) as AttributeDefinition; if (null != att_def && !att_def.Constant) { AttributeReference att_ref = new AttributeReference(); att_ref.SetAttributeFromBlock(att_def, blk_ref.BlockTransform); att_ref.Position = att_def.Position.TransformBy(blk_ref.BlockTransform); att_ref.AlignmentPoint = att_def.AlignmentPoint.TransformBy(blk_ref.BlockTransform); blk_ref.AttributeCollection.AppendAttribute(att_ref); tran.AddNewlyCreatedDBObject(att_ref, true); } } blk_ref.RecordGraphicsModified(true); tran.Commit(); } return(ents); }
public static ObjectId AppendBlockItem(Point3d insertPoint, ObjectId blockTableRecordId, List <string> attrTextValues, Matrix3d toWcsTransform) { ObjectId resBlockId = ObjectId.Null; Tools.StartTransaction(() => { Transaction trans = Tools.GetTopTransaction(); // Add a block reference to the model space BlockTableRecord ms = Tools.GetAcadBlockTableRecordModelSpace(OpenMode.ForWrite); BlockTableRecord btr = blockTableRecordId.GetObjectForRead <BlockTableRecord>(); BlockReference br = new BlockReference(insertPoint, blockTableRecordId); br.SetDatabaseDefaults(); br.TransformBy(toWcsTransform); ObjectContextManager ocm = btr.Database.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (btr.Annotative == AnnotativeStates.True) { br.AddContext(occ.CurrentContext); } resBlockId = ms.AppendEntity(br); trans.AddNewlyCreatedDBObject(br, true); // Add attributes from the block table record List <AttributeDefinition> attributes = GetAttributes(btr, trans); int i = 0; foreach (AttributeDefinition acAtt in attributes) { if (!acAtt.Constant) { using (AttributeReference acAttRef = new AttributeReference()) { acAttRef.SetAttributeFromBlock(acAtt, br.BlockTransform); if (attrTextValues != null) { acAttRef.TextString = attrTextValues[i++]; } else { acAttRef.TextString = acAtt.TextString; } br.AttributeCollection.AppendAttribute(acAttRef); trans.AddNewlyCreatedDBObject(acAttRef, true); } } } br.RecordGraphicsModified(true); }); return(resBlockId); }
public static ObjectId InsertBlock(Point3d anchorPoint, double Rotation, ObjectId BlockID) { // Get the current document and database Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; ObjectContextCollection occ = acCurDb.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); Transaction acTrans = acDoc.TransactionManager.TopTransaction; // Open the Block table for read BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord blockDef = BlockID.GetObject(OpenMode.ForRead) as BlockTableRecord; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // Insert the block into the current space using (BlockReference acBlkRef = new BlockReference(anchorPoint, BlockID)) { Matrix3d curUCSMatrix = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem; CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d; acBlkRef.TransformBy(Matrix3d.Rotation(Rotation, curUCS.Zaxis, anchorPoint)); //For some unknown reason this is needed in Civil3D //TODO: Find reason below line is needed and fix it acBlkRef.TransformBy(Matrix3d.Scaling(1000, anchorPoint)); acBlkRef.AddContext(occ.GetContext("1:1")); acBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; acBlkTblRec.AppendEntity(acBlkRef); acTrans.AddNewlyCreatedDBObject(acBlkRef, true); // AttributeDefinitions foreach (ObjectId id in blockDef) { DBObject obj = id.GetObject(OpenMode.ForRead); AttributeDefinition attDef = obj as AttributeDefinition; if ((attDef != null) && (!attDef.Constant)) { //This is a non-constant AttributeDefinition //Create a new AttributeReference using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attDef, acBlkRef.BlockTransform); attRef.TextString = "0"; //Add the AttributeReference to the BlockReference acBlkRef.AttributeCollection.AppendAttribute(attRef); acTrans.AddNewlyCreatedDBObject(attRef, true); } } } return(acBlkRef.ObjectId); } }
/// <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, Dictionary <string, string> attNameValues) { 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); ObjectId btrId = bt[blockName];//获取块表记录的Id //打开块表记录 BlockTableRecord record = (BlockTableRecord)btrId.GetObject(OpenMode.ForRead); //创建一个块参照并设置插入点 BlockReference br = new BlockReference(position, bt[blockName]); br.ScaleFactors = scale; //设置块参照的缩放比例 br.Layer = layer; //设置块参照的层名 br.Rotation = rotateAngle; //设置块参照的旋转角度 space.AppendEntity(br); //为了安全,将块表状态改为读 //判断块表记录是否包含属性定义 if (record.HasAttributeDefinitions) { //若包含属性定义,则遍历属性定义 foreach (ObjectId id in record) { //检查是否是属性定义 AttributeDefinition attDef = id.GetObject(OpenMode.ForRead) as AttributeDefinition; if (attDef != null) { //创建一个新的属性对象 AttributeReference attribute = new AttributeReference(); //从属性定义获得属性对象的对象特性 attribute.SetAttributeFromBlock(attDef, br.BlockTransform); //设置属性对象的其它特性 attribute.Position = attDef.Position.TransformBy(br.BlockTransform); attribute.Rotation = attDef.Rotation; attribute.AdjustAlignment(db); //判断是否包含指定的属性名称 if (attNameValues.ContainsKey(attDef.Tag.ToUpper())) { //设置属性值 attribute.TextString = attNameValues[attDef.Tag.ToUpper()].ToString(); } //向块参照添加属性对象 br.AttributeCollection.AppendAttribute(attribute); db.TransactionManager.AddNewlyCreatedDBObject(attribute, true); } } } db.TransactionManager.AddNewlyCreatedDBObject(br, true); return(br.ObjectId);//返回添加的块参照的Id }
public static ObjectId InsertBlock(Database db, string loName, string blkName, Point3d insPt) { ObjectId RtnObjId = ObjectId.Null; using (Transaction Trans = db.TransactionManager.StartTransaction()) { DBDictionary LoDict = Trans.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary; foreach (DictionaryEntry de in LoDict) { if (string.Compare((string)de.Key, loName, true).Equals(0)) { Layout Lo = Trans.GetObject((ObjectId)de.Value, OpenMode.ForWrite) as Layout; BlockTable BlkTbl = Trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord LoRec = Trans.GetObject(Lo.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord; ObjectId BlkTblRecId = GetNonErasedTableRecordId(BlkTbl.Id, blkName); if (BlkTblRecId.IsNull) { string BlkPath = HostApplicationServices.Current.FindFile(blkName + ".dwg", db, FindFileHint.Default); if (string.IsNullOrEmpty(BlkPath)) { return(RtnObjId); } BlkTbl.UpgradeOpen(); using (Database tempDb = new Database(false, true)) { tempDb.ReadDwgFile(BlkPath, FileShare.Read, true, null); db.Insert(blkName, tempDb, false); } BlkTblRecId = GetNonErasedTableRecordId(BlkTbl.Id, blkName); } LoRec.UpgradeOpen(); BlockReference BlkRef = new BlockReference(insPt, BlkTblRecId); LoRec.AppendEntity(BlkRef); Trans.AddNewlyCreatedDBObject(BlkRef, true); BlockTableRecord BlkTblRec = Trans.GetObject(BlkTblRecId, OpenMode.ForRead) as BlockTableRecord; if (BlkTblRec.HasAttributeDefinitions) { foreach (ObjectId objId in BlkTblRec) { AttributeDefinition AttDef = Trans.GetObject(objId, OpenMode.ForRead) as AttributeDefinition; if (AttDef != null) { AttributeReference AttRef = new AttributeReference(); AttRef.SetAttributeFromBlock(AttDef, BlkRef.BlockTransform); BlkRef.AttributeCollection.AppendAttribute(AttRef); Trans.AddNewlyCreatedDBObject(AttRef, true); } } } Trans.Commit(); } } } return(RtnObjId); }
public static ObjectId Insert(string blockPath, string blockName, Point3d position, bool scaleBlock = false, Scale3d scaleFactor = default(Scale3d)) { ObjectId id = new ObjectId(); using (World.Docu.LockDocument()) { using (Database db = World.Docu.Database) { using (Transaction tr = db.TransactionManager.StartTransaction()) { using (BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead)) { if (AcadIO.Insert.DB.AddBlock(blockPath + "\\" + blockName) == false) { return(id); } using (BlockReference br = new BlockReference(position, bt[blockPath])) { using (BlockTableRecord drawingSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite)) { if (scaleBlock == true) { br.ScaleFactors = scaleFactor; } drawingSpace.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); if (AcadIO.Layers.IsObjectLayerLocked(br.ObjectId)) { World.Docu.Editor.WriteMessage(Environment.NewLine + "BCAD: Cannot insert on locked layer" + Environment.NewLine); return(id); } using (BlockTableRecord attributeBlockTableRecord = (BlockTableRecord)tr.GetObject(br.BlockTableRecord, OpenMode.ForWrite)) { foreach (ObjectId attributeId in attributeBlockTableRecord) { if (attributeId.ObjectClass.Name == "AcDbAttributeDefinition") { using (AttributeDefinition attributedef = (AttributeDefinition)tr.GetObject(attributeId, OpenMode.ForWrite)) { AttributeReference attributeref = new AttributeReference(); attributeref.SetAttributeFromBlock(attributedef, br.BlockTransform); br.AttributeCollection.AppendAttribute(attributeref); tr.AddNewlyCreatedDBObject(attributeref, true); } } } } id = br.ObjectId; } } } tr.Commit(); } } } return(id); }
private void DrawAxisBlock(Point3d point, Vector3d direction, double chainage) { var doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; var db = doc.Database; using (Transaction tr = db.TransactionManager.StartTransaction()) using (BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead)) using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite)) { // Draw block ObjectId blockId = ObjectId.Null; if (bt.Has(BlockName)) { blockId = bt[BlockName]; } // Chainage string string chainageString = ChPrefix + AcadText.ChainageToString(chainage, ChPrecision); // Insert block BlockReference bref = new BlockReference(point, blockId); bref.Rotation = Vector3d.YAxis.GetAngleTo(direction, Vector3d.ZAxis); bref.ScaleFactors = new Scale3d(1); btr.AppendEntity(bref); tr.AddNewlyCreatedDBObject(bref, true); BlockTableRecord blockDef = tr.GetObject(blockId, OpenMode.ForRead) as BlockTableRecord; foreach (ObjectId id in blockDef) { AttributeDefinition attDef = tr.GetObject(id, OpenMode.ForRead) as AttributeDefinition; if ((attDef != null) && (!attDef.Constant)) { // Create a new AttributeReference AttributeReference attRef = new AttributeReference(); attRef.SetAttributeFromBlock(attDef, bref.BlockTransform); if (string.Compare(attDef.Tag, AxisAttribute, true) == 0) { attRef.TextString = AxisName; } else if (string.Compare(attDef.Tag, ChAttribute, true) == 0) { attRef.TextString = chainageString; } bref.AttributeCollection.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); } } tr.Commit(); } }
protected AttributeReference AddAttrToBlockRef(BlockReference blRef, ObjectId idAttrDef, string textString) { using (var attrDef = idAttrDef.GetObject(OpenMode.ForRead, false, true) as AttributeDefinition) { var attrRef = new AttributeReference(); attrRef.SetAttributeFromBlock(attrDef, blRef.BlockTransform); attrRef.TextString = textString; blRef.AttributeCollection.AppendAttribute(attrRef); t.AddNewlyCreatedDBObject(attrRef, true); return attrRef; } }
protected AttributeReference AddAttrToBlockRef(BlockReference blRef, ObjectId idAttrDef, string textString) { using (var attrDef = idAttrDef.GetObject(OpenMode.ForRead, false, true) as AttributeDefinition) { var attrRef = new AttributeReference(); attrRef.SetAttributeFromBlock(attrDef, blRef.BlockTransform); attrRef.TextString = textString; blRef.AttributeCollection.AppendAttribute(attrRef); t.AddNewlyCreatedDBObject(attrRef, true); return(attrRef); } }
private static void addAttrTypeFlat(Apartment apart, string typeFlatValue) { var btrApart = apart.IdBtr.GetObject(OpenMode.ForRead) as BlockTableRecord; var atrDeftypeFlat = defineAtrDefTypeFlat(btrApart, typeFlatValue); if (atrDeftypeFlat.Constant) { return; } var idsBlRef = btrApart.GetBlockReferenceIds(true, true); foreach (ObjectId idBlRef in idsBlRef) { using (var blRef = idBlRef.GetObject(OpenMode.ForRead, false, true) as BlockReference) { bool isFind = false; if (blRef.AttributeCollection != null) { foreach (ObjectId idAtr in blRef.AttributeCollection) { using (var atr = idAtr.GetObject(OpenMode.ForRead, false, true) as AttributeReference) { if (atr == null || !atr.Tag.Equals(Options.Instance.ApartmentTypeFlatParameter, StringComparison.OrdinalIgnoreCase)) { continue; } atr.UpgradeOpen(); atr.TextString = typeFlatValue; atr.Invisible = true; atr.LockPositionInBlock = true; isFind = true; break; } } } if (!isFind) { // Добавление атрибута к вхождению блока AttributeReference atrRef = new AttributeReference(); atrRef.SetAttributeFromBlock(atrDeftypeFlat, blRef.BlockTransform); atrRef.TextString = typeFlatValue; blRef.UpgradeOpen(); blRef.AttributeCollection.AppendAttribute(atrRef); blRef.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(atrRef, true); } } } }
/// <summary> /// Добавление атрибутов к вставке блока /// </summary> public static void AddAttributes(BlockReference blRef, [NotNull] BlockTableRecord btrBl, Transaction t) { foreach (var atrDef in btrBl.GetObjects <AttributeDefinition>()) { if (atrDef.Constant) { continue; } using var atrRef = new AttributeReference(); atrRef.SetAttributeFromBlock(atrDef, blRef.BlockTransform); blRef.AttributeCollection.AppendAttribute(atrRef); t.AddNewlyCreatedDBObject(atrRef, true); } }
//private bool checkBlockRefs(BlockTableRecord btrFrame, Transaction t) //{ // bool res = false; // var ms = t.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(_db), OpenMode.ForRead) as BlockTableRecord; // foreach (ObjectId idEnt in ms) // { // if (idEnt.ObjectClass.Name == "AcDbBlockReference") // { // var blRef = t.GetObject(idEnt, OpenMode.ForRead, false, true) as BlockReference; // if (blRef.GetEffectiveName().Equals(_blFrameName, StringComparison.OrdinalIgnoreCase)) // { // // считывание атрибутов // var atrCol = blRef.AttributeCollection; // _attrs = new Dictionary<string, string>(); // foreach (ObjectId idAtrRef in atrCol) // { // var atrRef = t.GetObject(idAtrRef, OpenMode.ForRead, false, true) as AttributeReference; // string key = atrRef.Tag.ToUpper(); // if (!_attrs.ContainsKey(key)) // { // _attrs.Add(key, atrRef.TextString); // } // } // res = true; // } // } // } // return res; //} //private bool checkBtrFrame(BlockTableRecord btrFrame, Transaction t) //{ // bool res = false; // if (btrFrame.HasAttributeDefinitions) // { // Dictionary<string, string> attrsChecks = new Dictionary<string, string>(); // foreach (ObjectId idEnt in btrFrame) // { // if (idEnt.ObjectClass.Name == "AcDbAttributeDefinition") // { // var atrDef = t.GetObject(idEnt, OpenMode.ForRead, false, true) as AttributeDefinition; // switch (atrDef.Tag.ToUpper()) // { // case "ВИД": // attrsChecks.Add("ВИД", atrDef.TextString); // break; // case "НАИМЕНОВАНИЕ": // attrsChecks.Add("НАИМЕНОВАНИЕ", atrDef.TextString); // break; // case "ЛИСТ": // attrsChecks.Add("ЛИСТ", atrDef.TextString); // break; // default: // break; // } // } // } // if (attrsChecks.Count == 3) // { // res = true; // } // } // return res; //} private void updateBlRefFrame(BlockReference blRef, BlockTableRecord btrFrame, Transaction t, bool insertDescription) { // Обновление вхождения блока рамки if (!IsOk) { return; } // Удаление атрибутов foreach (ObjectId idAtrRef in blRef.AttributeCollection) { if (!idAtrRef.IsValidEx()) { continue; } var atrRef = t.GetObject(idAtrRef, OpenMode.ForWrite, false, true) as AttributeReference; atrRef.Erase(true); } blRef.UpgradeOpen(); foreach (ObjectId idEnt in btrFrame) { if (idEnt.IsValidEx() && idEnt.ObjectClass.Name == "AcDbAttributeDefinition") { var atrDef = t.GetObject(idEnt, OpenMode.ForRead, false, true) as AttributeDefinition; if (!atrDef.Constant) { if (!insertDescription && atrDef.Tag.Equals("ПРИМЕЧАНИЕ", StringComparison.OrdinalIgnoreCase)) { continue; } using (var atrRef = new AttributeReference()) { atrRef.SetAttributeFromBlock(atrDef, blRef.BlockTransform); string key = atrDef.Tag.ToUpper(); if (_attrs.ContainsKey(key)) { atrRef.TextString = _attrs[key]; } else { atrRef.TextString = atrDef.TextString; } blRef.AttributeCollection.AppendAttribute(atrRef); t.AddNewlyCreatedDBObject(atrRef, true); } } } } }
public override void SetAttributeValue(BlockReference blockReference) { using (var blockTableRecord = blockReference.BlockTableRecord.GetObject(OpenMode.ForRead) as BlockTableRecord) { var attDef = blockTableRecord.GetAttribDefinition("Value"); if (!attDef.Constant) { var attRef = new AttributeReference(); attRef.SetAttributeFromBlock(attDef, blockReference.BlockTransform); attRef.TextString = value.Sign + value.Value; blockReference.AttributeCollection.AppendAttribute(attRef); } } }
public Handle InsertBlock(Transaction trans, string blockName, Point3d origin, double scale, double rotationDegrees, string layerName) { BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; LayerTable lt = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; if (!bt.Has(blockName)) { BlockDefinitionCreator bdc = new BlockDefinitionCreator(); bdc.CreateBlock(blockName); } if (!lt.Has(layerName)) { throw new ArgumentException("Layer doesn't exists."); } ObjectId btObjectId = bt[blockName]; if (btObjectId != ObjectId.Null) { BlockReference blockRef = new BlockReference(origin, btObjectId); blockRef.Rotation = rotationDegrees * Math.PI / 180; blockRef.TransformBy(Matrix3d.Scaling(scale, origin)); blockRef.Layer = layerName; BlockTableRecord currentSpaceId = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; currentSpaceId.AppendEntity(blockRef); trans.AddNewlyCreatedDBObject(blockRef, true); BlockTableRecord btr = trans.GetObject(btObjectId, OpenMode.ForRead) as BlockTableRecord; if (btr.HasAttributeDefinitions) { foreach (ObjectId atId in btr) { Entity ent = trans.GetObject(atId, OpenMode.ForRead) as Entity; if (ent is AttributeDefinition) { AttributeDefinition atd = ent as AttributeDefinition; AttributeReference atr = new AttributeReference(); atr.SetAttributeFromBlock(atd, blockRef.BlockTransform); blockRef.AttributeCollection.AppendAttribute(atr); trans.AddNewlyCreatedDBObject(atr, true); } } } return blockRef.ObjectId.Handle; } else { return new Handle(); } }
/// <summary> /// Добавление атрибутов к вставке блока /// </summary> public static void AddAttributes(BlockReference blRef, BlockTableRecord btrBl, Transaction t) { foreach (ObjectId idEnt in btrBl) { if (idEnt.ObjectClass.Name == "AcDbAttributeDefinition") { var atrDef = t.GetObject(idEnt, OpenMode.ForRead) as AttributeDefinition; if (!atrDef.Constant) { using (var atrRef = new AttributeReference()) { atrRef.SetAttributeFromBlock(atrDef, blRef.BlockTransform); //atrRef.TextString = atrDef.TextString; blRef.AttributeCollection.AppendAttribute(atrRef); t.AddNewlyCreatedDBObject(atrRef, true); } } } } }
private AttributeReference addAttrToBlockCross(BlockReference blRefCross, string num) { if (blRefCross == null) { return null; } AttributeReference attrRefCross = null; if (!panelBase.Service.Env.IdAttrDefCross.IsNull) { using (var attrDefCross = panelBase.Service.Env.IdAttrDefCross.GetObject(OpenMode.ForRead, false, true) as AttributeDefinition) { attrRefCross = new AttributeReference(); attrRefCross.SetAttributeFromBlock(attrDefCross, blRefCross.BlockTransform); attrRefCross.TextString = num; blRefCross.AttributeCollection.AppendAttribute(attrRefCross); t.AddNewlyCreatedDBObject(attrRefCross, true); } } return attrRefCross; }
public void RunCommand() { NumberFormatInfo provider = new NumberFormatInfo(); provider.NumberDecimalSeparator = "."; provider.NumberGroupSeparator = ","; provider.NumberGroupSizes = new int[] { 3 }; Document adoc = Application.DocumentManager.MdiActiveDocument; if (adoc == null) { return; } Database db = adoc.Database; Editor ed = adoc.Editor; PromptFileNameResult sourceFileName; sourceFileName = ed.GetFileNameForOpen("\nEnter the name of the coordinates file to be imported:"); string[] lines = File.ReadAllLines(sourceFileName.StringResult); using (db) { using (Transaction tr = db.TransactionManager.StartTransaction()) { //BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); string blockName = "piket"; BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); BlockTableRecord blockDef = (BlockTableRecord)bt[blockName].GetObject(OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)bt[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForWrite); string[] coord; foreach (string s in lines) { coord = s.Split(','); double coordX = Convert.ToDouble(coord[0], provider); double coordY = Convert.ToDouble(coord[1], provider); double coordZ = 0.0; string prim = coord[2]; Point3d point = new Point3d(coordX, coordY, coordZ); using (BlockReference blockRef = new BlockReference(point, blockDef.ObjectId)) { ms.AppendEntity(blockRef); tr.AddNewlyCreatedDBObject(blockRef, true); foreach (ObjectId id in blockDef) { DBObject obj = id.GetObject(OpenMode.ForRead); AttributeDefinition attDef = obj as AttributeDefinition; if ((attDef != null) && (!attDef.Constant)) { using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attDef, blockRef.BlockTransform); attRef.TextString = prim; blockRef.AttributeCollection.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); } } } } //DBPoint point = new DBPoint(new Point3d(coordX, coordY, coordZ)); //btr.AppendEntity(point); //tr.AddNewlyCreatedDBObject(point, true); //ed.WriteMessage("\n" + coordX); //ed.WriteMessage("\n" + coordY); //ed.WriteMessage("\n" + coordZ); //ed.WriteMessage("\n" + prim); } //btr.Dispose(); tr.Commit(); } } //Database db = adoc.Database; }
public void DrawGroupLeader() { Editor ed = dwg.Editor; PromptEntityOptions prmtEntityOpts = new PromptEntityOptions("Укажите линию"); prmtEntityOpts.AllowNone = false; prmtEntityOpts.SetRejectMessage("Должна быть линия или полилиния!"); prmtEntityOpts.AddAllowedClass(typeof(Line), true); prmtEntityOpts.AddAllowedClass(typeof(Polyline), true); PromptEntityResult entRes = ed.GetEntity(prmtEntityOpts); if (entRes.Status!= PromptStatus.OK) { return; } using (Transaction tr = CurrentDatabase.TransactionManager.StartTransaction()) { GroupsInformation groupEntities = new GroupsInformation(tr, CurrentDatabase); List<string> groupList = groupEntities.GetGroupsOfObject(entRes.ObjectId); if (groupList == null) { ed.WriteMessage("За указанным объектом не значится никаких групп!"); return; } PromptPointOptions pointOpts = new PromptPointOptions("\nУкажите точку вставки блока: "); PromptPointResult pointRes = ed.GetPoint(pointOpts); if (pointRes.Status!= PromptStatus.OK) { return; } BlockTable bt = (BlockTable)CurrentDatabase.BlockTableId.GetObject(OpenMode.ForRead); BlockTableRecord btrSpace = (BlockTableRecord)CurrentDatabase.CurrentSpaceId .GetObject(OpenMode.ForWrite); if (!bt.Has("group_vinoska")) { ed.WriteMessage("\nВ файле не определён блок выноски!!"); return; } BlockTableRecord gleaderBtr = (BlockTableRecord)bt["group_vinoska"].GetObject(OpenMode.ForRead); BlockReference gleader = new BlockReference(pointRes.Value, gleaderBtr.ObjectId); btrSpace.AppendEntity(gleader); tr.AddNewlyCreatedDBObject(gleader, true); //Если блок аннотативный - добавляем в таблицу аннотативных масштабов блока текущий масштаб ObjectContextManager ocm = CurrentDatabase.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (gleaderBtr.Annotative == AnnotativeStates.True) { ObjectContexts.AddContext(gleader, occ.CurrentContext); } gleader.SetDatabaseDefaults(); if (gleaderBtr.HasAttributeDefinitions) { var attDefs = gleaderBtr.Cast<ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => (AttributeDefinition)n.GetObject(OpenMode.ForRead)); foreach (AttributeDefinition attdef in attDefs) { AttributeReference attref = new AttributeReference(); attref.SetAttributeFromBlock(attdef, gleader.BlockTransform); gleader.AttributeCollection.AppendAttribute(attref); tr.AddNewlyCreatedDBObject(attref, true); if (gleaderBtr.Annotative == AnnotativeStates.True) { ObjectContexts.AddContext(attref, occ.CurrentContext); } int attCount = int.Parse(attref.Tag.Remove(0,10)); if (attCount<=groupList.Count) { attref.TextString = groupList[attCount-1]; } } } if (gleaderBtr.IsDynamicBlock) { DynamicBlockReferencePropertyCollection dynBRefColl = gleader.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in dynBRefColl) { if (prop.PropertyName == "Lookup1") { prop.Value = prop.GetAllowedValues()[groupList.Count-1]; } } } tr.Commit(); } }
private void addCheekViewBlock(bool doTrans, Matrix3d trans, double xPosView, bool isLeft) { // Добавление блока вида. // Если блока нет, то выход. if (panelBase.Service.Env.IdBtrView.IsNull) { return; } Point3d ptBlView = new Point3d(xPosView, 860, 0); if (doTrans) { ptBlView = ptBlView.TransformBy(trans); } BlockReference blRefView = CreateBlRefInBtrDim(ptBlView, panelBase.Service.Env.IdBtrView, Settings.Default.SheetScale); if (blRefView == null) { return; } // атрибут Вида if (!panelBase.Service.Env.IdAttrDefView.IsNull) { using (var attrDefView = panelBase.Service.Env.IdAttrDefView.GetObject(OpenMode.ForRead, false, true) as AttributeDefinition) { var attrRefView = new AttributeReference(); attrRefView.SetAttributeFromBlock(attrDefView, blRefView.BlockTransform); attrRefView.TextString = "А"; blRefView.AttributeCollection.AppendAttribute(attrRefView); t.AddNewlyCreatedDBObject(attrRefView, true); if ((!isLeft || doTrans) && !(!isLeft && doTrans)) { attrRefView.TransformBy(Matrix3d.Mirroring( new Line3d(attrRefView.AlignmentPoint, new Point3d(attrRefView.AlignmentPoint.X, 0, 0)))); } } } if ((!isLeft || doTrans) && !(!isLeft && doTrans)) { blRefView.TransformBy(Matrix3d.Mirroring(new Line3d(ptBlView, new Point3d(ptBlView.X, 0, 0)))); } }
public static void DrawVolumesTableInBlock(decimal[] decVolumesArray/*, Point3d tablePosition */) { if (decVolumesArray == null) { AcVolShowForm(); return; } string tableLayerName = "acVlm_Таблицы объемов"; CreateLayer(tableLayerName, true, false); string tableAttributeLayerName = "acVlm_Invisible Layers"; CreateLayer(tableAttributeLayerName, false, true); Document acDoc = Application.DocumentManager.MdiActiveDocument; //Текущий документ. //Editor acDocEd = acDoc.Editor; // Editor текущего документа. Database acDocDb = acDoc.Database; // Database текущего документа. using (acDoc.LockDocument()) // блокировка документа { // начинаем транзакцию using (Transaction acTrans = acDocDb.TransactionManager.StartTransaction()) { //*** // ШАГ 0 - запрос ПК поперечника и его распознание //*** double doublePk = ParcePk(SelectPk("Укажите ПК поперечного профиля:")); if (doublePk < 0) { MessageBox.Show("Пикет не распознан или выбор пикета отменен!\nТаблица объемов не будет привязана к пикету и не будет учитываться при экспорте объемов в Excel.", myCommands.msgBoxCaption_acVolume, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } //*** //ШАГ 1 - создаем таблицу и заполняем ее //*** Table objTable = new Table(); int tableColNumber = 3; int tableRowNumber = _form.listBoxLayers.Items.Count + 1;// количество слоев +1 строка на заголовок таблицы objTable.SetSize(tableRowNumber, tableColNumber); Point3d tablePosition = GetUserPoint("Укажите точку вставки таблицы:"); if (tablePosition == new Point3d(2147483647, 2147483647, 2147483647)) { acTrans.Abort(); AcVolShowForm(); return; } objTable.Position = tablePosition; //создаем массив значений для таблицы включая заголовки. string[,] strTableArray = new string[tableRowNumber, tableColNumber]; //Записываем в массив заголовки strTableArray[0, 0] = "Наименование"; strTableArray[0, 1] = "Ед.Изм."; strTableArray[0, 2] = "Значение"; //Записываем в массив Имя объема, Ед.Изм и значение объема и так для каждого объема из лист бокса for (int rowNumber = 1; rowNumber < tableRowNumber; rowNumber++) { strTableArray[rowNumber, 0] = (string)_form.listBoxLayers.Items[rowNumber - 1]; strTableArray[rowNumber, 1] = (string)_form.listBoxLayersUnits.Items[rowNumber - 1]; strTableArray[rowNumber, 2] = Convert.ToString(Math.Round(decVolumesArray[rowNumber - 1], 2), CultureInfo.InvariantCulture); } // Заполняем таблицу значениями из массива String[,] strTableArray for (int rowNumber = 0; rowNumber < tableRowNumber; rowNumber++) { for (int colNumber = 0; colNumber < tableColNumber; colNumber++) { objTable.Cells[rowNumber, colNumber].TextHeight = 2.5; switch (colNumber) { case 0: objTable.Columns[colNumber].Width = 60; break; case 1: objTable.Columns[colNumber].Width = 15; break; case 2: objTable.Columns[colNumber].Width = 20; break; } objTable.Rows[rowNumber].Height = 8; if (colNumber == 0 & rowNumber > 0) { objTable.Cells[rowNumber, colNumber].Alignment = CellAlignment.MiddleLeft; } else { objTable.Cells[rowNumber, colNumber].Alignment = CellAlignment.MiddleCenter; } objTable.Cells[rowNumber, colNumber].SetValue(strTableArray[rowNumber, colNumber], ParseOption.ParseOptionNone); } } // задаем слой таблице objTable.Layer = tableLayerName; //*** // если ПК распознан, то создаем блок, помещаем таблицу в блок и присваиваем атрибут "ПК" //*** if (doublePk >= 0) { string pk = Convert.ToString(doublePk, CultureInfo.InvariantCulture); // имя создаваемого блока string objTableBlockName = "acVlm_" + Convert.ToString((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds, CultureInfo.InvariantCulture); // открываем таблицу блоков на чтение BlockTable blockTable = (BlockTable)acTrans.GetObject(acDocDb.BlockTableId, OpenMode.ForRead); // вначале проверяем, нет ли в таблице блока с таким именем // если есть - выводим сообщение об ошибке и заканчиваем выполнение команды if (blockTable.Has(objTableBlockName)) { MessageBox.Show("A block with the name \"" + objTableBlockName + "\" already exists.", myCommands.msgBoxCaption_acVolume, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // создаем новое определение блока, задаем ему имя BlockTableRecord objBtr = new BlockTableRecord { Name = objTableBlockName }; blockTable.UpgradeOpen(); //переоткрываем blockTable на запись. // добавляем созданное определение блока в таблицу блоков и в транзакцию, // запоминаем ID созданного определения блока (оно пригодится чуть позже) ObjectId objBtrId = blockTable.Add(objBtr); acTrans.AddNewlyCreatedDBObject(objBtr, true); //добавляем таблицу в блок и в транзацию objBtr.AppendEntity(objTable); acTrans.AddNewlyCreatedDBObject(objTable, true); // создаем определение аттрибута AttributeDefinition objAttribute = new AttributeDefinition { Position = new Point3d(0, 0, 0), Tag = "ПК", Layer = tableAttributeLayerName }; // добавляем атрибут в блок и в транзакцию objBtr.AppendEntity(objAttribute); acTrans.AddNewlyCreatedDBObject(objAttribute, true); //*** // добавляем вхождение созданного блока на чертеж //*** var acBtr = acTrans.GetObject(acDocDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; // создаем новое вхождение блока, используя ранее сохраненный ID определения блока BlockReference objBlockReference = new BlockReference(Point3d.Origin, objBtrId) { Layer = tableLayerName }; // добавляем созданное вхождение блока на пространство чертежа и в транзакцию if (acBtr != null) acBtr.AppendEntity(objBlockReference); acTrans.AddNewlyCreatedDBObject(objBlockReference, true); // задаем значение аттрибута AttributeReference objAttributeReference = new AttributeReference(); objAttributeReference.SetAttributeFromBlock(objAttribute, objBlockReference.BlockTransform); objAttributeReference.TextString = pk; objAttributeReference.Layer = tableAttributeLayerName; objBlockReference.AttributeCollection.AppendAttribute(objAttributeReference); acTrans.AddNewlyCreatedDBObject(objAttributeReference, true); } //*** // если ПК _НЕ_распознан, то помещаем таблицу на чертеж без создания блока с выводом предупреждения //*** else { var acBtr = acTrans.GetObject(acDocDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; if (acBtr != null) acBtr.AppendEntity(objTable); acTrans.AddNewlyCreatedDBObject(objTable, true); } // фиксируем транзакцию acTrans.Commit(); AcVolShowForm(); } } }
//private bool checkBlockRefs(BlockTableRecord btrFrame, Transaction t) //{ // bool res = false; // var ms = t.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(_db), OpenMode.ForRead) as BlockTableRecord; // foreach (ObjectId idEnt in ms) // { // if (idEnt.ObjectClass.Name == "AcDbBlockReference") // { // var blRef = t.GetObject(idEnt, OpenMode.ForRead, false, true) as BlockReference; // if (blRef.GetEffectiveName().Equals(_blFrameName, StringComparison.OrdinalIgnoreCase)) // { // // считывание атрибутов // var atrCol = blRef.AttributeCollection; // _attrs = new Dictionary<string, string>(); // foreach (ObjectId idAtrRef in atrCol) // { // var atrRef = t.GetObject(idAtrRef, OpenMode.ForRead, false, true) as AttributeReference; // string key = atrRef.Tag.ToUpper(); // if (!_attrs.ContainsKey(key)) // { // _attrs.Add(key, atrRef.TextString); // } // } // res = true; // } // } // } // return res; //} //private bool checkBtrFrame(BlockTableRecord btrFrame, Transaction t) //{ // bool res = false; // if (btrFrame.HasAttributeDefinitions) // { // Dictionary<string, string> attrsChecks = new Dictionary<string, string>(); // foreach (ObjectId idEnt in btrFrame) // { // if (idEnt.ObjectClass.Name == "AcDbAttributeDefinition") // { // var atrDef = t.GetObject(idEnt, OpenMode.ForRead, false, true) as AttributeDefinition; // switch (atrDef.Tag.ToUpper()) // { // case "ВИД": // attrsChecks.Add("ВИД", atrDef.TextString); // break; // case "НАИМЕНОВАНИЕ": // attrsChecks.Add("НАИМЕНОВАНИЕ", atrDef.TextString); // break; // case "ЛИСТ": // attrsChecks.Add("ЛИСТ", atrDef.TextString); // break; // default: // break; // } // } // } // if (attrsChecks.Count == 3) // { // res = true; // } // } // return res; //} private void updateBlRefFrame(BlockReference blRef, BlockTableRecord btrFrame, Transaction t, bool insertDescription) { // Обновление вхождения блока рамки if (!IsOk) return; // Удаление атрибутов foreach (ObjectId idAtrRef in blRef.AttributeCollection) { var atrRef = t.GetObject(idAtrRef, OpenMode.ForWrite, false, true) as AttributeReference; atrRef.Erase(true); } blRef.UpgradeOpen(); foreach (ObjectId idEnt in btrFrame) { if (idEnt.ObjectClass.Name == "AcDbAttributeDefinition") { var atrDef = t.GetObject(idEnt, OpenMode.ForRead, false, true) as AttributeDefinition; if (!atrDef.Constant) { if (!insertDescription && atrDef.Tag.Equals("ПРИМЕЧАНИЕ", StringComparison.OrdinalIgnoreCase)) { continue; } using (var atrRef = new AttributeReference()) { atrRef.SetAttributeFromBlock(atrDef, blRef.BlockTransform); string key = atrDef.Tag.ToUpper(); if (_attrs.ContainsKey(key)) { atrRef.TextString = _attrs[key]; } else { atrRef.TextString = atrDef.TextString; } blRef.AttributeCollection.AppendAttribute(atrRef); t.AddNewlyCreatedDBObject(atrRef, true); } } } } }
//[CommandMethod("BJ")] public static void BlockJigCmd(Double finalCalcText) { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; //Set the block Name to use. string pr = "TagHgr"; Transaction tr = doc.TransactionManager.StartTransaction(); using (tr) { BlockTable bt = (BlockTable)tr.GetObject( db.BlockTableId, OpenMode.ForRead ); if (!bt.Has(pr)) { ed.WriteMessage( "\nBlock \"" + pr + "\" not found."); return; } BlockTableRecord space = (BlockTableRecord)tr.GetObject( db.CurrentSpaceId, OpenMode.ForWrite ); BlockTableRecord btr = (BlockTableRecord)tr.GetObject( bt[pr], OpenMode.ForRead); // Block needs to be inserted to current space before // being able to append attribute to it BlockReference br = new BlockReference(new Point3d(), btr.ObjectId); space.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); Dictionary<ObjectId, AttInfo> attInfo = new Dictionary<ObjectId, AttInfo>(); if (btr.HasAttributeDefinitions) { foreach (ObjectId id in btr) { DBObject obj = tr.GetObject(id, OpenMode.ForRead); AttributeDefinition ad = obj as AttributeDefinition; if (ad != null && !ad.Constant) { AttributeReference ar = new AttributeReference(); ar.SetAttributeFromBlock(ad, br.BlockTransform); ar.Position = ad.Position.TransformBy(br.BlockTransform); if (ad.Justify != AttachmentPoint.BaseLeft) { ar.AlignmentPoint = ad.AlignmentPoint.TransformBy(br.BlockTransform); } if (ar.IsMTextAttribute) { ar.UpdateMTextAttribute(); } //ar.TextString = ad.TextString; ar.TextString = PopulateAttributes(ad.Tag, finalCalcText.ToString()); ObjectId arId = br.AttributeCollection.AppendAttribute(ar); tr.AddNewlyCreatedDBObject(ar, true); // Initialize our dictionary with the ObjectId of // the attribute reference + attribute definition info attInfo.Add( arId, new AttInfo( ad.Position, ad.AlignmentPoint, ad.Justify != AttachmentPoint.BaseLeft ) ); } } } // Run the jig BlockJig myJig = new BlockJig(tr, br, attInfo); if (myJig.Run() != PromptStatus.OK) return; // Commit changes if user accepted, otherwise discard tr.Commit(); } }