My code now *seems* to be working perfectly:
/// <summary>
/// Creates a temporary UCS which is aligned to the specified entity.
/// </summary>
/// <param name="surfaceId"></param>
/// <param name="editor"></param>
/// <param name="dwg"></param>
private void CreateUCSAlignedToEntity(ObjectId surfaceId, Editor editor, Database dwg)
{
// We're going to make an inquiry into the drawing DB so start a transaction
Transaction trans = editor.Document.Database.TransactionManager.StartTransaction();
try
{
// Change the Current UCS to that of the 'surface' we want to draw the panels on.
Entity entity = (Entity)trans.GetObject(surfaceId, OpenMode.ForRead);
// Gather the necessary data that defines the entity's unique coordinate system
Point3d entityOrigin = entity.GeometricExtents.MinPoint;
Point3d entityUR = entity.GeometricExtents.MaxPoint;
Vector3d entityXaxis = entity.Ecs.CoordinateSystem3d.Xaxis;
Point3d entityUL = new Point3d(entityOrigin.X, entityUR.Y, entityUR.Z); // Derive the upper-left corner from the coords of the origin & upper-right corner
Vector3d entityYaxis = new Vector3d(0, entityUL.Y - entityOrigin.Y, entityUL.Z - entityOrigin.Z); // Calculate the 3D Y-axis of the entity
// Get the Active Viewport
ViewportTableRecord viewportTableRecord = (ViewportTableRecord)trans.GetObject(editor.ActiveViewportId, OpenMode.ForWrite);
viewportTableRecord.IconAtOrigin = true;
viewportTableRecord.IconEnabled = true;
// Set the CurrentUCS to that of the Entity's UCS
editor.CurrentUserCoordinateSystem = Matrix3d.AlignCoordinateSystem(Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis, entityOrigin, entityXaxis, entityYaxis, entityXaxis.CrossProduct(entityYaxis));
viewportTableRecord.SetUcs(entityOrigin, entityXaxis, entityYaxis);
editor.UpdateTiledViewportsFromDatabase();
trans.Commit();
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
editor.WriteMessage("\nError: " + ex.Message);
}
finally
{
trans.Dispose();
}
}
}