I have been chasing a bug for about three weeks now but have been unable to determine if my code is the cause or if the API is at fault. It made itself know when I was testing a complicated method involving SolidWorks, the SW API and the EPDM API. The scenario is this: I have a drawing file and an associated part file. Let's call them A.slddrw and A.sldprt respectively. The drawing is open in SolidWorks. I want to rename the drawing and the model to AA.slddrw and AA.sldprt and when all is said and done, the file open in SolidWorks will be AA.slddrw which is correctly pointing at AA.sldprt.
To achieve this, the code works as follows:
- CloseAndReopen is called for the drawing ModelDoc2 object. CloseAndReopen will cause a FileCloseNotify event to be fired.
- There is an event handler that is listening for the FileCloseNotify event. Inside the event handler, the file can be manipulated.
- The event handler method calls ForceReleaseLocks for the part ModelDoc2 object.
- The event handler method renames the part model file to AA.sldprt.
- The event handler method calls ReloadOrReplace for the part ModelDoc2 object passing in the new model name: AA.sldprt.
- The event handler method calls ReplaceReferencedDocuments for the drawing document to point it at the correct model: AA.sldprt.
- The event handler renames the drawing file to AA.slddrw.
- The event handler calls SetPromptFilename2, passing inAA.slddrw as the filename.
- The event handler returns 1.
- The drawing file is rebuilt and saved.
Sometimes, the code works perfectly. Other times it throws access violations. Not good. I would be happier of it failed 100% of the time with access violations. Failing some of the time typically points to threading issues or timing issues which will be just about impossible to overcome.
The problem occurs with both SW2015 and 2016. I've implemented it as a macro, an add-in and an EPDM add-in and all fail, sometimes. I've attached the Visual Studio project for the SW add-in and my test files A.sldprt and A.slddrw. I would appreciate it if someone could compile it and run it in Debug mode in Visual Studio and see what happens. To test it, open A.slddrw and then from the Tools menu select CloseAndReOpenError Addin...Test CloseAndReopen. Run it a few times and see what happens. If you get a series of successfuly runs, close the drawing, reopen it and try again. This often exposes the problem.
Some other interesting observations.
- As I noted in this post, ForceReleaseLocks doesn't properly clean up tilde files.
- Sometimes, but not all the time, a seemingly successful test run will actually result in the AA.sldprt file being locked by the SLDWORKS.exe process even after you close the drawing. You can make it visible via ModelDoc2::Visible, you can close it via SldWorks::CloseDoc or SldWorks::QuitDoc but it does not get released by SolidWorks.