1

I am working in AutoCAD 2014 using Visual Studio 2013.

With my code I access the MdiActiveDocument's database from the DocumentManager .

Using the database I start a transaction and use the GetObject method of the transaction to retrieve Entity objects.

            Database acCurDb = Application.DocumentManager.MdiActiveDocument.Database;
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                var obj = acTrans.GetObject(id, OpenMode.ForRead);
                if (obj is Entity)
                {
                   // do stuff
                }

                acTrans.Commit();
            }

This works fine while I am in development and start AutoCAD from inside of Visual Studio. In development I set the "Start external program" switch in the Debug tab of the application properties so it starts AutoCAD for me and everything works great.

The issue I am having is that in production when the app is loaded by AutoCAD via registry settings (I use demand loading) the MdiActiveDocument is null so the code crashes. I have discovered there is a document in the Application.DocumentManager but when I assign the database from that document to acCurDb the TransactionManager throws an error with I try to use the StartTransaction method.

                if (Application.DocumentManager.Count > 0)
                {
                    foreach(Document doc in Application.DocumentManager)
                    {
                        acCurDb = doc.Database;
                        break;
                    }
                }

                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                {

                } 

Can someone help me understand why the MdiActiveDocument is null and/or direct me to the proper way to get a Transaction object in AutoCAD?

Andreas
  • 7,991
  • 2
  • 28
  • 37
scott_f
  • 838
  • 8
  • 17

2 Answers2

1

Beginning in 2015, AutoCAD may have a null active document on startup depending on user system variables. It's just another check you have to add before running your routine.

  • Ok thanks for that. Do you have any ideas on how I would load the MdiActiveDocument myself or how to work around this? Also I didn't mention but I am working AutoCAD 2014. I will edit my question and put this in. – scott_f Feb 14 '15 at 04:09
0

As mentioned by @david-wolfe, AutoCAD 2015 may start with no active document (just a dashboard). In this case the MdiActiveDocument can be null.

Now you're on AutoCAD 2014, so a different scenario may happen: if your app is loading with AutoCAD, you code may run before anything is really ready. How are you running the code? Is it a CommandMethod? If is a command, the user can only run it from a command, so it will be a active document. But if you run it from other method (like direct call from the Ribbon or from a palette), it may be null.

Augusto Goncalves
  • 8,493
  • 2
  • 17
  • 44