//Start trasaction
using (Transaction acTrans = db.TransactionManager.StartTransaction()) {
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
ObjectId blkRecId = ObjectId.Null;
BlockTableRecord acBlkTblRecord;
acBlkTblRecord = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],OpenMode.ForWrite) as BlockTableRecord;
//Check if block with this name exists in database
if (acBlkTbl.Has(blkName)) {
blkRecId = acBlkTbl[blkName];
} else {
//Create contour
Polyline acPoly = new Polyline();
acPoly.SetDatabaseDefaults();
//Create rectangular polyline
Point2dCollection points = new Point2dCollection() {
new Point2d(0, 0),
new Point2d(trackerWidth, 0),
new Point2d(trackerWidth, trackerLength),
new Point2d(0, trackerLength)
};
for (int i = 0; i < points.Count; i++) {
acPoly.AddVertexAt(i, points[i], 0, 0, 0);
}
acPoly.Closed = true;
//Create attribute
AttributeDefinition adAttr = new AttributeDefinition();
adAttr.Position = new Point3d(0, 0, 0);
adAttr.Tag = "Attribute";
//Creating new block
using (BlockTableRecord acBlkTblRec = new BlockTableRecord()) {
acBlkTblRec.Name = blkName;
// Set the insertion point for the block
acBlkTblRec.Origin = Point3d.Origin;
acBlkTbl.UpgradeOpen();
//Add block to blocktable
ObjectId btrId = acBlkTbl.Add(acBlkTblRec);
acTrans.AddNewlyCreatedDBObject(acBlkTblRec, true);
//Add elements to block
acBlkTblRec.AppendEntity(acPoly);
acTrans.AddNewlyCreatedDBObject(acPoly, true);
//Add attribute
acBlkTblRec.AppendEntity(adAttr);
acTrans.AddNewlyCreatedDBObject(adAttr, true);
//Get model space
BlockTableRecord btrModelSpace =
(BlockTableRecord) acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
//Create block instance
BlockReference brRefBlock = new BlockReference(Point3d.Origin, btrId);
//add instance to modelspace database
btrModelSpace.AppendEntity(brRefBlock);
acTrans.AddNewlyCreatedDBObject(brRefBlock, true);
//Set attribut
AttributeReference arAttr = new AttributeReference();
arAttr.SetAttributeFromBlock(adAttr, brRefBlock.BlockTransform);
arAttr.TextString = "Tracker";
brRefBlock.AttributeCollection.AppendAttribute(arAttr);
acTrans.AddNewlyCreatedDBObject(arAttr, true);
}
}
acTrans.Commit();