[CommandMethod("ReplaceBlock")]
public void ReplaceBlock()
{
PromptStringOptions pso
= new PromptStringOptions
("\nEnter Block Name to Replace"); pso.AllowSpaces = true;
PromptResult pr = Ed.GetString(pso);
if (pr.Status != PromptStatus.OK) return;
string blockName = pr.StringResult.ToLower();
PromptStringOptions psoNew
= new PromptStringOptions
("\nEnter Block Name to replace with"); psoNew.AllowSpaces = true;
PromptResult prNew = Ed.GetString(psoNew);
if (prNew.Status != PromptStatus.OK) return;
string blockNameNew = prNew.StringResult.ToLower();
using (Transaction trx = Db.TransactionManager.StartTransaction())
{
BlockTable bt = Db.BlockTable();
if (!bt.Has(blockName))
{
Ed.WriteLine("\n {0} is not in drawing", blockName);
return;
}
if (!bt.Has(blockNameNew))
{
Ed.WriteLine("\n {0} is not in drawing", blockNameNew);
return;
}
AllowedClassFilter acf
= new AllowedClassFilter
(typeof(BlockReference
)); PromptSelectionResult psr = Ed.GetSelection(acf);
if (psr.Status != PromptStatus.OK) return;
BlockTableRecord currentSpace = Db.CurrentSpace(OpenMode.ForWrite);
BlockTableRecord btr = bt[blockNameNew].GetDBObject<BlockTableRecord>();
var attDefs = btr.GetAttributeDefinitions().Where(att => !att.Constant).ToList();
ObjectContextManager ocm = Db.ObjectContextManager;
ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES");
foreach (ObjectId id in psr.Value.GetObjectIds())
{
BlockReference bref = id.GetEntity<BlockReference>();
if (bref.GetEffectiveName().ToLower() == blockName)
{
using (BlockReference newBref
= new BlockReference
(bref
.Position, btr
.ObjectId)) {
newBref.Rotation = bref.Rotation;
newBref.LayerId = bref.LayerId;
if (btr.Annotative == AnnotativeStates.True)
{
ObjectContexts.AddContext(newBref, occ.CurrentContext);
}
else
{
newBref.ScaleFactors = bref.ScaleFactors;
}
currentSpace.AppendEntity(newBref);
trx.AddNewlyCreatedDBObject(newBref, true);
foreach (var attDef in attDefs)
{
using (AttributeReference attRef
= new AttributeReference
()) {
attRef.SetAttributeFromBlock(attDef, newBref.BlockTransform);
attRef.XData = attDef.XData;
newBref.AttributeCollection.AppendAttribute(attRef);
trx.AddNewlyCreatedDBObject(attRef, true);
}
}
}
bref.UpgradeOpen();
bref.Erase();
}
}
trx.Commit();
}
}