[CommandMethod("DrawOrder")]
public void DrawOrder()
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
//Initialise list of xrefnames in order. Would be better to have it in a file and load it in or something instead of hardcoding.
//I use movetobottom so the first in this list will be on top of the others
List
<string> xrefNames
= new List
<string>() { "FS-X",
"BS-SN-x",
"BS-x_BS-G-x",
"EE-x",
"IB-x_SA-x",
"BS-AV-x",
"BS-AV-x_1"
};
// Build a selection filter looking for 'INSERT' objects (includes blocks and xrefs) from modelspace (DXF code 67 = 0)
TypedValue
[] tvs
= { new TypedValue
(0,
"INSERT"),
new TypedValue
(67,
0) }; SelectionFilter sf
= new SelectionFilter
(tvs
);
// Get objects matching the selection filter.
PromptSelectionResult psr = ed.SelectAll(sf);
// Initialise Dictionary -> so we can search with linq. Dict cause you cant find the name in Entity, but in the blocktablerecord
Dictionary
<string, Entity
> xRefDict
= new Dictionary
<string, Entity
>();
try
{
if (psr.Status == PromptStatus.OK)
{
// Get the object Ids from the selection.
ObjectId[] ids = psr.Value.GetObjectIds();
using (Transaction tr = db.TransactionManager.StartTransaction())
{
//get the modelSpace
BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
BlockTableRecord modelSpace = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
// Get the DrawOrderTable for ModelSpace
DrawOrderTable dot = tr.GetObject(modelSpace.DrawOrderTableId, OpenMode.ForWrite) as DrawOrderTable;
foreach (ObjectId id in ids)
{
// Get the block reference of the ID.
BlockReference bref = tr.GetObject(id, OpenMode.ForRead, false, true) as BlockReference;
// Get the block table record for the block reference.
BlockTableRecord btr = bref.BlockTableRecord.GetObject(OpenMode.ForRead) as BlockTableRecord;
// If the record is an external reference
if (btr.IsFromExternalReference)
{
// Get the entity for the record.
Entity ent = tr.GetObject(id, OpenMode.ForRead) as Entity;
//Add it with the name as key (used to search after)
xRefDict.Add(btr.Name, ent);
}
}
foreach (string xrefName in xrefNames)
{
ObjectId id
= new ObjectId
();
try
{
//get id of xref
id = xRefDict.Where(x => x.Key.Contains(xrefName)).FirstOrDefault().Value.ObjectId;
}
catch (Autodesk.AutoCAD.Runtime.Exception e)
{
ed.WriteMessage("\nError during finding id in Dict: " + e.Message);
}
//Has to be an idcollection even tho i want it to just move a single one
ObjectIdCollection entityIds
= new ObjectIdCollection
{
id
};
if (id != null)
{
dot.MoveToBottom(entityIds);
}
}
tr.Commit();
}
}
}
catch (Autodesk.AutoCAD.Runtime.Exception e)
{
ed.WriteMessage("\nError during dot.MoveToBottom: " + e.Message);
}
finally { db.Dispose(); }
}
}