Skip to content
davidbl edited this page Sep 13, 2010 · 1 revision

I have never enjoyed writing code to use transactions in the managaged API for AutoCAD. It always seemed overly verbose and cumbersome to me. To wit: a C# snippet that cycles through modelspace and echos each enity type to the command line


[CommandMethod("OpenTransactionManager")]
public static void OpenTransactionManager()
{
  // Get the current document and database
  Document acDoc = Application.DocumentManager.MdiActiveDocument;
  Database acCurDb = acDoc.Database; 
  // Start a transaction
  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
  {
      // Open the Block table for read
      BlockTable acBlkTbl;
      acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,   OpenMode.ForRead) as BlockTable; 
      // Open the Block table record Model space for read
      BlockTableRecord acBlkTblRec;
      acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],  OpenMode.ForRead) as BlockTableRecord;
      // Step through the Block table record
      foreach (ObjectId asObjId in acBlkTblRec)
      {
          acDoc.Editor.WriteMessage("\nDXF name: " + asObjId.ObjectClass.DxfName);
          acDoc.Editor.WriteMessage("\n");
      }
      // Dispose of the transaction
  }
}

Some Ruby code using my TransHelper class, for comparison:

def trans_modelspace_example
   begin
     #create the helper
     helper = TransHelper.new
     #start a transaction, getting the block table record for modelspace (for reading)
     helper.trans([:ModelSpace]) do |tr, db, tables|
          #step through modelspace
          tables.ModelSpace.each do |object_id|
               puts object_id.ObjectClass.DxfName
          end
     end
  rescue Exception => e
     puts_ex e
  ensure
     helper.dispose   		
  end
end

The Ruby code may not be much shorter, but, to my eyes, it is much more readable.

The TransHelper class has a few more goodies. It can provide access to any/all of the AutoCAD symbol tables, Block, Linetype, Layer, TextStyle, Ucs, etc, just by passing in the appropriate symbol array to TransHelper#trans (eg, TransHelper#trans( [:Layer, :TextStyle]) will give you access to tables.Layer and tables.TextStyle within the code block). I use an OpenStruct to create the tables object.

There is also a TransHelper#get_obj(object_id, mode) which returns the entity associated with the object_id opened either for :Read or :Write. So to change the color of each entity in the above code snippet, one would only have to add

helper.get_obj(object_id, :Write).color_index = 8

in the tables.ModelSpace loop.

Clone this wiki locally