Happy to know you get it work.
Just some improvements to your code.
If you use SelectAll, take care it select entities in all the layouts (model and paer spaces). A good practice with a selection is to use a SelectionFilter. In this case you should filter on the entity type (INSERT for block references and the current space).
Do not make things in loops (foreach, for, while) if they could be done only once outside of the loop scope.
Here's an example:
[CommandMethod("XPLODETEST1")]
public static void ExplodeTest1()
{
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;
var ed = doc.Editor;
// Create a filter to select all the block references in the current space
string ctab = (string)Application.GetSystemVariable("CTAB");
var filter = new SelectionFilter(new[] {
new TypedValue(0, "INSERT"),
new TypedValue(410, ctab) });
PromptSelectionResult pr = ed.SelectAll(filter);
if (pr.Status == PromptStatus.OK)
{
using (var tr = db.TransactionManager.StartTransaction())
{
// Open the current space outside of the foreach loop
var curSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
foreach (var id in pr.Value.GetObjectIds())
{
// We know all entities within the selection set are block references
var blockRef = (BlockReference)tr.GetObject(id, OpenMode.ForWrite);
var entitySet = TryExplodeMaintainingXdata(blockRef);
if (entitySet != null)
{
foreach (Entity ent in entitySet)
{
curSpace.AppendEntity(ent);
tr.AddNewlyCreatedDBObject(ent, true);
}
// Erase the source block reference outside of the foearch loop
blockRef.Erase();
}
else
{
ed.WriteMessage("\nSelected entity cannot be exploded.");
}
}
tr.Commit();
}
}
}
Instead of SelectAll, you could also directly iterate throug all the entities int the current space checking for the entity type to get only block references. This method is not slower than the SelectAll with filter which internally does the same thing.
[CommandMethod("XPLODETEST2")]
public static void ExplodeTest2()
{
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;
var ed = doc.Editor;
using (var tr = db.TransactionManager.StartTransaction())
{
// Open the current space
var curSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
foreach (ObjectId id in curSpace)
{
// Check if the id is one of a block reference
if (id.ObjectClass.DxfName == "INSERT")
{
var blockRef = (BlockReference)tr.GetObject(id, OpenMode.ForWrite);
var entitySet = TryExplodeMaintainingXdata(blockRef);
if (entitySet != null)
{
foreach (Entity ent in entitySet)
{
curSpace.AppendEntity(ent);
tr.AddNewlyCreatedDBObject(ent, true);
}
// Erase the source block reference outside of the foreach loop
blockRef.Erase();
}
else
{
ed.WriteMessage("\nSelected entity cannot be exploded.");
}
}
}
tr.Commit();
}
}