AutoCAD Freezes after Code Execution

AutoCAD Freezes after Code Execution

Anonymous
Not applicable
804 Views
4 Replies
Message 1 of 5

AutoCAD Freezes after Code Execution

Anonymous
Not applicable

Hi,

 

I'm able to successfully execute my application below, however AutoCAD freezes at the end of the code execution. This is a modified version of _gile's publisher to open DWGs by passing the file location.

 

Any ideas why it could be hanging? My first thought is that I'm not closing the drawing database properly in PlotPdf()

 

Resource usage does get higher than normal, however there are no errors, other than VB debugger:

Managed Debugging Assistant 'ContextSwitchDeadlock' has detected a problem in 'C:\Program Files\Autodesk\AutoCAD 2017\acad.exe'.
Additional Information: The CLR has been unable to transition from COM context 0x248689a8 to COM context 0x24868758 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.
 occurred

 

 

        // Modified version of gileCAD code
        public abstract class PlotToFileConfig
        {
            // Private fields
            private string dsdFile, dwgFile, outputDir, outputFile, plotType;
            private int sheetNum;
            private IEnumerable<Layout> layouts;
            private const string LOG = "publish.log";

            // Base constructor
            public PlotToFileConfig(string outputDir, IEnumerable<Layout> layouts, string plotType)
            {
                Database db = HostApplicationServices.WorkingDatabase;
                this.dwgFile = db.Filename;
                this.outputDir = outputDir;
                this.dsdFile = Path.ChangeExtension(this.dwgFile, "dsd");
                this.layouts = layouts;
                this.plotType = plotType;
                string ext = plotType == "0" || plotType == "1" ? "dwf" : "pdf";
                this.outputFile = Path.Combine(
                    this.outputDir,
                    Path.ChangeExtension(Path.GetFileName(this.dwgFile), ext));
            }

            // Plot the layouts
            public void Publish()
            {
                if (TryCreateDSD())
                {
                    object bgp = Application.GetSystemVariable("BACKGROUNDPLOT");
                    object ctab = Application.GetSystemVariable("CTAB");
                    try
                    {
                        Application.SetSystemVariable("BACKGROUNDPLOT", 0);

                        Publisher publisher = Application.Publisher;
                        PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
                        publisher.PublishDsd(this.dsdFile, plotDlg);
                        plotDlg.Destroy();
                        File.Delete(this.dsdFile);
                    }
                    catch (System.Exception exn)
                    {
                        System.Windows.Forms.MessageBox.Show("Error: " + exn.Message + "\n\n" + exn.StackTrace, "Issue Drawings", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        throw;
                    }
                    finally
                    {
                        Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
                        Application.SetSystemVariable("CTAB", ctab);
                    }
                }
            }

            // Creates the DSD file from a template (default options)
            private bool TryCreateDSD()
            {
                using (DsdData dsd = new DsdData())
                using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
                {
                    if (dsdEntries == null || dsdEntries.Count <= 0) return false;

                    if (!Directory.Exists(this.outputDir))
                        Directory.CreateDirectory(this.outputDir);

                    this.sheetNum = dsdEntries.Count;
                    dsd.SetDsdEntryCollection(dsdEntries);
                    dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
                    dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
                    dsd.NoOfCopies = 1;
                    dsd.DestinationName = this.outputFile;
                    dsd.IsHomogeneous = false;
                    dsd.LogFilePath = Path.Combine(this.outputDir, LOG);

                    PostProcessDSD(dsd);

                    return true;
                }
            }

            // Creates an entry collection (one per layout) for the DSD file
            private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
            {
                DsdEntryCollection entries = new DsdEntryCollection();

                foreach (Layout layout in layouts)
                {
                    DsdEntry dsdEntry = new DsdEntry();
                    dsdEntry.DwgName = this.dwgFile;
                    dsdEntry.Layout = layout.LayoutName;
                    dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
                    dsdEntry.Nps = layout.TabOrder.ToString();
                    entries.Add(dsdEntry);
                }
                return entries;
            }

            // Writes the definitive DSD file from the templates and additional informations
            private void PostProcessDSD(DsdData dsd)
            {
                string str, newStr;
                string tmpFile = Path.Combine(this.outputDir, "temp.dsd");

                dsd.WriteDsd(tmpFile);

                using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
                using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
                {
                    while (!reader.EndOfStream)
                    {
                        str = reader.ReadLine();
                        if (str.Contains("Has3DDWF"))
                        {
                            newStr = "Has3DDWF=0";
                        }
                        else if (str.Contains("OriginalSheetPath"))
                        {
                            newStr = "OriginalSheetPath=" + this.dwgFile;
                        }
                        else if (str.Contains("Type"))
                        {
                            newStr = "Type=" + this.plotType;
                        }
                        else if (str.Contains("OUT"))
                        {
                            newStr = "OUT=" + this.outputDir;
                        }
                        else if (str.Contains("IncludeLayer"))
                        {
                            newStr = "IncludeLayer=TRUE";
                        }
                        else if (str.Contains("PromptForDwfName"))
                        {
                            newStr = "PromptForDwfName=FALSE";
                        }
                        else if (str.Contains("LogFilePath"))
                        {
                            newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
                        }
                        else
                        {
                            newStr = str;
                        }
                        writer.WriteLine(newStr);
                    }
                }
                File.Delete(tmpFile);
            }
        }

        // Class to plot one PDF file per sheet
        public class SingleSheetPdf : PlotToFileConfig
        {
            public SingleSheetPdf(string outputDir, IEnumerable<Layout> layouts)
                : base(outputDir, layouts, "5") { }
        }
        public static void PlotPdf(string dwg, string rev)
        {
            short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
            using (Database db = new Database(false, true))
            {
                HostApplicationServices.WorkingDatabase = db;
                db.ReadDwgFile(dwg, FileShare.ReadWrite, false, null);

                try
                {
                    Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
 
                        List<Layout> layouts = new List<Layout>();
                        DBDictionary layoutDict =
                            (DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
                        foreach (DBDictionaryEntry entry in layoutDict)
                        {
                            if (entry.Key != "Model")
                            {
                                layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
                            }
                        }
                        layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));

                        string filename = Path.ChangeExtension(db.Filename, "pdf");

                        SingleSheetPdf plotter = new SingleSheetPdf(filename, layouts);
                        plotter.Publish();

                        tr.Commit();
                    }
                }
                catch (System.Exception e)
                {
                    // Show this message
                    System.Windows.Forms.MessageBox.Show("Error: " + e.Message + "\n\n" + e.StackTrace, "Issue Drawings", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);

                }
                finally
                {
                    Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
                }
            }
        }
    }

 

 

 

 

0 Likes
Accepted solutions (1)
805 Views
4 Replies
Replies (4)
Message 2 of 5

Virupaksha_aithal
Autodesk Support
Autodesk Support

Hi

 

Looks like you are setting a temporary database as working database (HostApplicationServices.WorkingDatabase ) in PlotPdf.  Try removing that step or set the "correct" working database at the end of your function.

 

 



Virupaksha Aithal KM
Developer Technical Services
Autodesk Developer Network

0 Likes
Message 3 of 5

Anonymous
Not applicable

Hi,

 

Great idea, I tried capturing the current doc on my entry method, then resetting the active document after my foreach loop for PlotPdf finishes:

        private void runEISD_Click(object sender, EventArgs e)
        {
            Document currDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            // Create a new instance of Dictionary<string, string>
            foreach (ListViewItem v in dwgList.Items)
            {
                Program.PlotPdf(v.SubItems[2].Text, v.SubItems[1].Text);
                GC.Collect();
            }
            Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument = currDoc;
            this.Close();
            System.Windows.Forms.Application.Exit();
        }

Unfortunately this didn't work for me.

 

My application opens a dialog box that allows a user to select multiple DWGs and PDF them when a button is clicked. The drawings are not open, hence switching active databases for each drawing.

 

Have I applied this correctly?

0 Likes
Message 4 of 5

Alexander.Rivilis
Mentor
Mentor
Accepted solution

@Anonymous wrote:

System.Windows.Forms.Application.Exit();

???

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

0 Likes
Message 5 of 5

Anonymous
Not applicable

Wow.

 

Thank you, this issue was driving me nuts. In hindsight, it makes perfect sense because of where the crash was happening.

 

Apologies for posting a VB issue & not an AutoCAD Dev Issue.

0 Likes