// © Andrey Bushman, 2014
// Test code...
using System;
using System.Collections.Generic;
using System.Linq;
#if AUTOCAD
using cad = Autodesk.AutoCAD.ApplicationServices.Application;
using Rt = Autodesk.AutoCAD.Runtime;
using Db = Autodesk.AutoCAD.DatabaseServices;
using Ed = Autodesk.AutoCAD.EditorInput;
using Ap = Autodesk.AutoCAD.ApplicationServices;
#endif
namespace AcadTest {
public class Class1 {
[Rt.CommandMethod("test")]
public void Test() {
Ap.Document doc = cad.DocumentManager.MdiActiveDocument;
Ed.Editor ed = doc.Editor;
Db.Database db = doc.Database;
PurgeAll(db);
ed.WriteMessage("Database purged.\n");
}
public static void PurgeAll(Db.Database db) {
if (null == db)
throw new ArgumentNullException("db");
if (db.IsDisposed)
throw new ArgumentException("Database is disposed.");
Int32 prewCount = 0;
Int32 loop = 1;
Ed.Editor ed = cad.DocumentManager.MdiActiveDocument.Editor;
Dictionary<Rt.RXClass, List<Db.ObjectId>> dict =
GetObjectIdsGroupedByRXClass(db);
Rt.RXClass entRX = Rt.RXClass.GetClass(typeof(Db.Entity));
while (true) {
ed.WriteMessage("\n### Loop {0}...\n\n", loop);
IEnumerable<Db.ObjectId> dyn_ids = dict.Values.SelectMany(n => n)
.Where(n => !n.IsErased);
using (Db.ObjectIdCollection ids = new Db.ObjectIdCollection(
dyn_ids.ToArray())) {
db.Purge(ids);
using (Db.Transaction tr = db.TransactionManager.
StartTransaction()) {
foreach (Db.ObjectId id in ids) {
if (!id.IsErased && !id.ObjectClass.IsDerivedFrom(entRX)) {
Db.DBObject obj = tr.GetObject(id, Db.OpenMode.
ForWrite, false);
try {
obj.Erase();
}
catch (Exception ex) {
ed.WriteMessage("{0}\n", ex.Message);
ed.WriteMessage("Object Type: {0}, ObjectId = {1}, " +
"IsErased = {2}, IsDisposed = {3}\n\n", obj.GetType()
.ToString(), obj.ObjectId.ToString(), obj.IsErased,
obj.IsDisposed);
}
}
}
tr.Commit();
dict = GetObjectIdsGroupedByRXClass(db);
Int32 count = dict.Values.SelectMany(n => n).Where(
n => !n.IsErased).Count();
if (prewCount == count)
break;
prewCount = count;
}
}
++loop;
}
}
public static Dictionary<Rt.RXClass, List<Db.ObjectId>>
GetObjectIdsGroupedByRXClass(Db.Database db) {
if (null == db)
throw new ArgumentNullException("db");
if (db.IsDisposed)
throw new ArgumentException("Database is disposed.");
Dictionary<Rt.RXClass, List<Db.ObjectId>> dict = new Dictionary<
Rt.RXClass, List<Db.ObjectId>>();
Int32 approxNum = db.ApproxNumObjects;
for (Int64 i = db.BlockTableId.Handle.Value; i < db.Handseed.Value
&& approxNum > 0; i++, approxNum--) {
Db.ObjectId id = Db.ObjectId.Null;
Db.Handle h = new Db.Handle(i);
db.TryGetObjectId(h, out id);
if (id.IsValid && !id.IsErased) {
Rt.RXClass key = id.ObjectClass;
if (!dict.ContainsKey(key)) {
dict.Add(key, new List<Db.ObjectId>());
}
dict[key].Add(id);
}
}
return dict;
}
}
}