A Case Study in Creating More Efficient APIs

I came across the following post, which seeks to add a block reference, with standard tags to the model space.

Consider the boiler plate required!

BlockReference bref = new BlockReference(ptm, acBlkTbl["TestBlock"]);
acBlkTblRec.AppendEntity(bref);
acTrans.AddNewlyCreatedDBObject(bref, true);

// Add the attribute references
var blockDef = (BlockTableRecord)acTrans.GetObject(acBlkTbl["TestBlock"], OpenMode.ForRead);
foreach (ObjectId id in blockDef)
{
    if (id.ObjectClass == RXObject.GetClass(typeof(AttributeDefinition)))
    {
        var attDef = (AttributeDefinition)acTrans.GetObject(id, OpenMode.ForRead);
        if (!attDef.Constant)
        {
            var attRef = new AttributeReference();
            attRef.SetAttributeFromBlock(attDef, bref.BlockTransform);
            bref.AttributeCollection.AppendAttribute(attRef);
            acTrans.AddNewlyCreatedDBObject(attRef, true);

            if (attRef.Tag.ToUpper() == "WTYPE")
            {
                attRef.TextString = "SR23";
            }
        }
    }
}
acTrans.Commit();

A simplification:

BlockReference blockReference = blockTableRecord.NewReference(point3d); 
												  // create block reference
 												  // adds all the attribute definitions / tags
												  // obviates all the boiler plate.


db.ModelSpace.Add(blockReference);				  // all done!

What if we want to ammend?

blockReference.Tags["PIPE"] = "Sewage"; 		  // let's ammend what we need. Or:
AttributeReference attributeReference = blockReference.Tags["PIPE"]; // blockReference.AttributeCollections.SetValue("PIPE", "SEWAGE"); 

attributeReference.Position = point3d; 			  // reposition

Written on November 19, 2022