using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using AcAp = Autodesk.AutoCAD.ApplicationServices.Application;
[assembly
: CommandClass
(typeof(BlockAttributeSample
.Commands))]
namespace BlockAttributeSample
{
public class Commands
{
// test command
[CommandMethod("Test")]
public void Test()
{
var doc = AcAp.DocumentManager.MdiActiveDocument;
var db = doc.Database;
var ed = doc.Editor;
using (var tr = db.TransactionManager.StartTransaction())
{
foreach (var br in db.GetBlockReferences("stamp"))
{
var owner = br.OwnerId.GetObject<BlockTableRecord>();
if (owner.IsLayout)
ed.WriteMessage("\n" + owner.LayoutId.GetObject<Layout>().LayoutName);
else
ed.WriteMessage("\n" + owner.Name);
foreach (var att in br.GetAttributes())
{
ed.WriteMessage($"\n\t{att.Tag}: {att.TextString}");
}
}
tr.Commit();
}
}
}
// extension methods
static class extension
{
// returns the object (opened in the specified mode)
public static T GetObject<T>(
this ObjectId id,
OpenMode mode = OpenMode.ForRead,
bool openErased = false,
bool forceOpenOnLockedLayer = false) where T : DBObject
{
if (id == ObjectId.Null)
throw new ArgumentNullException
(nameof
(id
));
var tr = id.Database.TransactionManager.TopTransaction;
if (tr == null)
throw new Autodesk
.AutoCAD.Runtime.Exception(ErrorStatus
.NoActiveTransactions);
return (T)tr.GetObject(id, mode, openErased, forceOpenOnLockedLayer);
}
// gets all references of the block (opened for read)
public static IEnumerable<BlockReference> GetBlockReferences(this Database db, string blockName)
{
if (db == null)
throw new ArgumentNullException
(nameof
(db
));
var tr = db.TransactionManager.TopTransaction;
if (tr == null)
throw new Autodesk
.AutoCAD.Runtime.Exception(ErrorStatus
.NoActiveTransactions);
var bt = db.BlockTableId.GetObject< BlockTable>();
if (bt.Has(blockName))
{
var btr = bt[blockName].GetObject<BlockTableRecord>();
foreach (ObjectId id in btr.GetBlockReferenceIds(true, false))
{
yield return id.GetObject<BlockReference>();
}
if (btr.IsDynamicBlock)
{
foreach (ObjectId btrId in btr.GetAnonymousBlockIds())
{
var anonBtr = btrId.GetObject<BlockTableRecord>();
foreach (ObjectId id in anonBtr.GetBlockReferenceIds(true, false))
{
yield return id.GetObject<BlockReference>();
}
}
}
}
}
// gets the attribute references (opened for read)
public static IEnumerable<AttributeReference> GetAttributes(this BlockReference source)
{
if (source == null)
throw new ArgumentNullException
(nameof
(source
));
var tr = source.Database.TransactionManager.TopTransaction;
if (tr == null)
throw new Autodesk
.AutoCAD.Runtime.Exception(ErrorStatus
.NoActiveTransactions);
foreach (ObjectId id in source.AttributeCollection)
{
yield return id.GetObject< AttributeReference>();
}
}
}
}