<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: Run a sample command (with parameters) using c# .NET in .NET Forum</title>
    <link>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335082#M758</link>
    <description>&lt;P&gt;Hi,&lt;/P&gt;
&lt;P&gt;The Editor.Command method takes the same argument types à the AutoLISP command function.&lt;/P&gt;
&lt;P&gt;AutoLISP:&lt;/P&gt;
&lt;LI-CODE lang="lisp"&gt;(command "_-PDFATTACH" PdfPath pageText '(0. 0. 0.) 1.0 0.0)&lt;/LI-CODE&gt;
&lt;P&gt;C#:&lt;/P&gt;
&lt;LI-CODE lang="csharp"&gt;ed.Command("_-PDFATTACH", PdfPath, pageText, startPoint, 1.0, 0.0);&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Iif you want to pass all the arguments as strings, you have to convert the point X and Y coordinates into strings.&lt;/P&gt;
&lt;P&gt;C#&lt;/P&gt;
&lt;LI-CODE lang="csharp"&gt;ed.Command("_-PDFATTACH", PdfPath , pageText , startPoint.X.ToString() + "," + startPoint.Y.ToString(), "1", "0");&lt;/LI-CODE&gt;
&lt;P&gt;or&lt;/P&gt;
&lt;LI-CODE lang="csharp"&gt;ed.Command("_-PDFATTACH", PdfPath , pageText , $"{startPoint.X},{startPoint.Y}", "1", "0");&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
    <pubDate>Sun, 23 Feb 2025 17:24:07 GMT</pubDate>
    <dc:creator>_gile</dc:creator>
    <dc:date>2025-02-23T17:24:07Z</dc:date>
    <item>
      <title>Run a sample command (with parameters) using c# .NET</title>
      <link>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13334844#M757</link>
      <description>&lt;P&gt;I am trying to call a command "-PDFIMPORT" in a button_click event, but got an "invalid input".&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;I am new on .Net (I used to work with Autolisp). Thanks !&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="csharp"&gt;private void BtImport_Click(object sender, EventArgs e)
{
    Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
    Database db = doc.Database;
    Editor ed = doc.Editor;
string pageText = TxPages.Text;
string PdfPath = TxPdfPath.Text;
Point3d startPoint = new Point3d(0, 0, 0); 
ed.Command("-PDFATTACH", PdfPath , pageText , startPoint.X, startPoint.Y, "1", "0");
}   &lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Sun, 23 Feb 2025 13:48:20 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13334844#M757</guid>
      <dc:creator>Kh.mbkh</dc:creator>
      <dc:date>2025-02-23T13:48:20Z</dc:date>
    </item>
    <item>
      <title>Re: Run a sample command (with parameters) using c# .NET</title>
      <link>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335082#M758</link>
      <description>&lt;P&gt;Hi,&lt;/P&gt;
&lt;P&gt;The Editor.Command method takes the same argument types à the AutoLISP command function.&lt;/P&gt;
&lt;P&gt;AutoLISP:&lt;/P&gt;
&lt;LI-CODE lang="lisp"&gt;(command "_-PDFATTACH" PdfPath pageText '(0. 0. 0.) 1.0 0.0)&lt;/LI-CODE&gt;
&lt;P&gt;C#:&lt;/P&gt;
&lt;LI-CODE lang="csharp"&gt;ed.Command("_-PDFATTACH", PdfPath, pageText, startPoint, 1.0, 0.0);&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Iif you want to pass all the arguments as strings, you have to convert the point X and Y coordinates into strings.&lt;/P&gt;
&lt;P&gt;C#&lt;/P&gt;
&lt;LI-CODE lang="csharp"&gt;ed.Command("_-PDFATTACH", PdfPath , pageText , startPoint.X.ToString() + "," + startPoint.Y.ToString(), "1", "0");&lt;/LI-CODE&gt;
&lt;P&gt;or&lt;/P&gt;
&lt;LI-CODE lang="csharp"&gt;ed.Command("_-PDFATTACH", PdfPath , pageText , $"{startPoint.X},{startPoint.Y}", "1", "0");&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Sun, 23 Feb 2025 17:24:07 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335082#M758</guid>
      <dc:creator>_gile</dc:creator>
      <dc:date>2025-02-23T17:24:07Z</dc:date>
    </item>
    <item>
      <title>Re: Run a sample command (with parameters) using c# .NET</title>
      <link>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335104#M759</link>
      <description>&lt;P&gt;Thanks Gile,&amp;nbsp;&lt;/P&gt;&lt;P&gt;It's still not working (Tried it with sample command&amp;nbsp;ed.Command("_Line", startPoint, EndPoint); )&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;span class="lia-inline-image-display-wrapper lia-image-align-inline" image-alt="Khmbkh_0-1740332563077.png" style="width: 600px;"&gt;&lt;img src="https://forums.autodesk.com/t5/image/serverpage/image-id/1470161i1242C24DE8D0947D/image-size/medium?v=v2&amp;amp;px=400" role="button" title="Khmbkh_0-1740332563077.png" alt="Khmbkh_0-1740332563077.png" /&gt;&lt;/span&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Sun, 23 Feb 2025 17:43:17 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335104#M759</guid>
      <dc:creator>Kh.mbkh</dc:creator>
      <dc:date>2025-02-23T17:43:17Z</dc:date>
    </item>
    <item>
      <title>Re: Run a sample command (with parameters) using c# .NET</title>
      <link>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335241#M760</link>
      <description>&lt;P&gt;You should show the code which shows the dialog because&amp;nbsp; you can only call Editor.Command in the document context (i.e., a modal dialog) not in the application context (i.e., a modeless dialog).&lt;/P&gt;
&lt;P&gt;About the basic of AutoCAD and User Interfaces (dialog boxes, palettes), you can read &lt;A href="https://gilecad.azurewebsites.net/UserInterfaces_en.aspx" target="_blank" rel="noopener"&gt;this 'tutotrial'&lt;/A&gt;.&lt;/P&gt;</description>
      <pubDate>Sun, 23 Feb 2025 20:52:15 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335241#M760</guid>
      <dc:creator>_gile</dc:creator>
      <dc:date>2025-02-23T20:52:15Z</dc:date>
    </item>
    <item>
      <title>Re: Run a sample command (with parameters) using c# .NET</title>
      <link>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335242#M761</link>
      <description>&lt;BLOCKQUOTE&gt;&lt;HR /&gt;&lt;a href="https://forums.autodesk.com/t5/user/viewprofilepage/user-id/8942850"&gt;@Kh.mbkh&lt;/a&gt;&amp;nbsp;wrote:&lt;BR /&gt;&lt;P&gt;Thanks Gile,&amp;nbsp;&lt;/P&gt;&lt;P&gt;It's still not working (Tried it with sample command&amp;nbsp;ed.Command("_Line", startPoint, EndPoint); )&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;span class="lia-inline-image-display-wrapper lia-image-align-inline" image-alt="Khmbkh_0-1740332563077.png" style="width: 600px;"&gt;&lt;img src="https://forums.autodesk.com/t5/image/serverpage/image-id/1470161i1242C24DE8D0947D/image-size/medium?v=v2&amp;amp;px=400" role="button" title="Khmbkh_0-1740332563077.png" alt="Khmbkh_0-1740332563077.png" /&gt;&lt;/span&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;HR /&gt;&lt;/BLOCKQUOTE&gt;&lt;P&gt;I'm guessing the problem is elsewhere ( not the code shown here ).&lt;/P&gt;&lt;P&gt;More details will be required.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Perhaps ( temporarily )replace that code with a simple WriteMessage&lt;/P&gt;&lt;P&gt;and adding a try, catch block around your code.&lt;BR /&gt;&lt;BR /&gt;&lt;/P&gt;&lt;P&gt;Perhaps the "Location" displayed in your message is an indicator.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Regards,&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Sun, 23 Feb 2025 20:53:38 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335242#M761</guid>
      <dc:creator>kerry_w_brown</dc:creator>
      <dc:date>2025-02-23T20:53:38Z</dc:date>
    </item>
    <item>
      <title>Re: Run a sample command (with parameters) using c# .NET</title>
      <link>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335258#M762</link>
      <description>&lt;P&gt;It's a UserControl that is used in a PaletteSet (see code bellow), so I am trying to call Editor.Command() method from a button event of that UserControl. (Maybe this is why it's not possible ?)&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="csharp"&gt;namespace TestForms2
{
    public class Class1
    {
        [CommandMethod("ShowMyPalette")]
        public void ShowMyPalette()
        {
            // Create a new instance of your user control
            UserControl1 myControl = new UserControl1();

            // Create a new PaletteSet and add the control
            PaletteSet myPaletteSet = new PaletteSet("My Custom Palette");
            myPaletteSet.Add("My Control", myControl);

            // Set the size of the palette
            myPaletteSet.Size = new System.Drawing.Size(300, 200);

            // Show the palette
            myPaletteSet.Visible = true;
        }


    }
}&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Sun, 23 Feb 2025 21:13:14 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335258#M762</guid>
      <dc:creator>Kh.mbkh</dc:creator>
      <dc:date>2025-02-23T21:13:14Z</dc:date>
    </item>
    <item>
      <title>Re: Run a sample command (with parameters) using c# .NET</title>
      <link>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335293#M763</link>
      <description>&lt;P&gt;A Palette is a modeless user interface which runs in the application context. As explained in &lt;A href="https://gilecad.azurewebsites.net/UserInterfaces_en.aspx#paletteWinForm" target="_blank" rel="noopener"&gt;this part&lt;/A&gt; of the upper linked tutorial, from a palette set, you need to use the DocumentCollection.ExecuteInCommandContextAsync method to force the document context to be able to call Editor.Command method.&lt;/P&gt;
&lt;P&gt;Something like this:&lt;/P&gt;
&lt;LI-CODE lang="csharp"&gt;private async void BtImport_Click(object sender, EventArgs e)
{
    DocumentCollection docs = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager;
    Document doc = docs.MdiActiveDocument;
    Editor ed = doc.Editor;
    string pageText = TxPages.Text;
    string PdfPath = TxPdfPath.Text;
	Point3d startPoint = Point3d.Origin;
    await docs.ExecuteInCommandContextAsync(_ =&amp;gt;
    {
        ed.Command("_-PDFATTACH", PdfPath, pageText, startPoint, 1.0, 0.0);
        return Task.CompletedTask;
    },
    null);
}&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Sun, 23 Feb 2025 21:50:53 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335293#M763</guid>
      <dc:creator>_gile</dc:creator>
      <dc:date>2025-02-23T21:50:53Z</dc:date>
    </item>
    <item>
      <title>Re: Run a sample command (with parameters) using c# .NET</title>
      <link>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335435#M764</link>
      <description>&lt;P&gt;&lt;a href="https://forums.autodesk.com/t5/user/viewprofilepage/user-id/109424"&gt;@_gile&lt;/a&gt;&amp;nbsp;shows an example of how to call Command() from a click handler on a PaletteSet, but if you have many buttons on a paletteSet or other modeless UI that need to do this, then you should try to avoid the "copy and paste" style of programming that replicates all of that code in every button click event handler you need to use it from, and instead consolidate the code into a reusable method that makes things a bit simpler at the click-handler level, and also safer.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Another thing, is that I never recommend the use of ExecuteInCommandContextAsync() without issuing a stern &lt;EM&gt;caveat emptor&lt;/EM&gt;, which is that this is a &lt;STRONG&gt;&lt;EM&gt;highly-volatile&lt;/EM&gt; &lt;/STRONG&gt;API that can &lt;EM&gt;crash AutoCAD very easily&lt;/EM&gt; (any exception that's thrown by the delegate will do that).&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;So with that, below is a class with an extension method you can add to your project, that makes calling Command() from the click-handler of a button both easier and safer, that I've relied on for some time:&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="csharp"&gt;public static partial class DocumentCollectionExtensions
{
   /// &amp;lt;summary&amp;gt;
   /// A version of the Editor's Command() method that
   /// can be safely called from the application context. 
   /// 
   /// This method targets the DocumentCollection and 
   /// always operates on the active document. 
   /// 
   /// Calls to the method can be awaited to execute 
   /// code that follows after the command sequence 
   /// has executed.
   ///
   /// Important:
   ///
   /// Calls to this method should _always_ be wrapped
   /// in a try{} block, that's followed by a catch{}
   /// block that handles any exception that may be
   /// thrown by the Editor's Command() method (e.g.,
   /// ErrorStatus.InvalidInput).
   ///
   /// Failing to catch exceptions thrown by this method,
   /// or by any statements that follow an await'ed call 
   /// to this method will most-likely crash AutoCAD.
   ///
   /// &amp;lt;/summary&amp;gt;
   /// &amp;lt;param name="args"&amp;gt;The command arguments.&amp;lt;/param&amp;gt;

   public static async Task CommandAsync(this DocumentCollection docs,
      params object[] args)
   {
      if(docs == null)
         throw new ArgumentNullException(nameof(docs));
      if(!docs.IsApplicationContext)
         throw new InvalidOperationException("invalid context");
      Document doc = docs.MdiActiveDocument;
      Task task = Task.CompletedTask;
      await docs.ExecuteInCommandContextAsync(
         delegate (object unused)
         {
            try
            {
               doc.Editor.Command(args);
               return task;
            }
            catch(System.Exception ex)
            {
               return task = Task.FromException(ex);
            }
         },
         null
      );
      if(task.IsFaulted)
      {
         throw task.Exception ??
            new AggregateException(
               new InvalidOperationException("Unspecified error"));
      }
   }
}&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;With the above class added to your project, executing commands from modeless button click handlers is no more complicated than this:&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="csharp"&gt;private async void MyButton_Click(object sender, EventArgs e)
{
   DocumentCollection docs = Application.DocumentManager;
   await docs.CommandAsync("_-PDFATTACH", "path", "pagetext", Point3d.Origin, 1.0, 0.0);
}&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;What is shown above is the absolute bare-minimum amount of code needed to execute commands, but is not the recommended way of using it, because of the danger of an exception, which will crash AutoCAD if left unhandled.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;This is a safer and more-correct implementation:&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="csharp"&gt;private async void MyButton_Click(object sender, EventArgs e)
{
   DocumentCollection docs = Application.DocumentManager;

   try    // &amp;lt;- this is NOT optional!
   {
      await docs.CommandAsync("_-PDFATTACH", "path", "pagetext", Point3d.Origin, 1.0, 0.0);
      
      // TODO: add code here that runs *after* the commands have executed
   }
   catch(System.Exception ex)
   {
      docs.MdiActiveDocument.Editor.WriteMessage($"Operation failed: {ex.Message}");
   }
}&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Mon, 24 Feb 2025 05:04:51 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13335435#M764</guid>
      <dc:creator>ActivistInvestor</dc:creator>
      <dc:date>2025-02-24T05:04:51Z</dc:date>
    </item>
    <item>
      <title>Re: Run a sample command (with parameters) using c# .NET</title>
      <link>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13337357#M765</link>
      <description>&lt;P&gt;Thanks&amp;nbsp;&lt;a href="https://forums.autodesk.com/t5/user/viewprofilepage/user-id/109424"&gt;@_gile&lt;/a&gt;&amp;nbsp;&lt;a href="https://forums.autodesk.com/t5/user/viewprofilepage/user-id/4476837"&gt;@ActivistInvestor&lt;/a&gt;&amp;nbsp;Both those 2 methods fixed the issue, However, whene I am trying to do more things with PDFunderlay just added by this command, I noticed that I can not access the&amp;nbsp;DBDictionary pdfDict (eLockViolation&amp;nbsp; error given)&lt;/P&gt;&lt;P&gt;DBDictionary pdfDict= Tx.GetObject(nod.GetAt(defDictKey), OpenMode.ForWrite) as DBDictionary;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;My code was:&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="csharp"&gt;foreach (int Page in pageNumbers)
{
    startPoint = new Point3d(X, Y, 0);
    try    
    { 
        await docs.ExecuteInCommandContextAsync(_ =&amp;gt;
        {
            ed.Command("_-PDFATTACH", PdfPath, Page.ToString(), Point3d.Origin, 1.0, 0.0);
            ObjectId? result = PdfHandle.LoadUnloadPDFunderlay(PdfPath, Page.ToString(), "Unload");
            return Task.CompletedTask;
            },
        null);
    } 
    catch (System.Exception ex)
    {
        docs.MdiActiveDocument.Editor.WriteMessage($"Operation failed: {ex.Message}");
    }
}&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;And the&amp;nbsp;&amp;nbsp;LoadUnloadPDFunderlay method I am trying to call is in another class with something like:&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="csharp"&gt;public class PdfHandle
{
    public static ObjectId? LoadUnloadPDFunderlay(string pdfPath, string pageNumber, string loadOrUnload)
    {
        Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        Database db = doc.Database;
        Editor ed = doc.Editor;
        if (string.IsNullOrEmpty(pdfPath) || string.IsNullOrEmpty(pageNumber) || string.IsNullOrEmpty(loadOrUnload))
        {
            ed.WriteMessage("Invalid arguments. Provide PDF path, page number, and load/unload action.");
            return null;
                }
        using (Transaction Tx = db.TransactionManager.StartTransaction())
        {
            // Get Named Objects Dictionary (NOD)
            DBDictionary nod = Tx.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead) as DBDictionary;
            string defDictKey = UnderlayDefinition.GetDictionaryKey(typeof(PdfDefinition));
            if (!nod.Contains(defDictKey))
            {
                ed.WriteMessage("No PDF underlays found.");
                return null;
            }
     
            DBDictionary pdfDict = Tx.GetObject(nod.GetAt(defDictKey), OpenMode.ForWrite) as DBDictionary; // Here got eLockViolation  error

....&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;BR /&gt;N.B: When I use this&amp;nbsp;LoadUnloadPDFunderlay methos elsewhere it's working well.&lt;/P&gt;</description>
      <pubDate>Mon, 24 Feb 2025 22:48:30 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13337357#M765</guid>
      <dc:creator>Kh.mbkh</dc:creator>
      <dc:date>2025-02-24T22:48:30Z</dc:date>
    </item>
    <item>
      <title>Re: Run a sample command (with parameters) using c# .NET</title>
      <link>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13337617#M766</link>
      <description>&lt;P&gt;You're not showing the point in the first method you show, where you access the second method, but the problem is most-likely because your code is running in the &lt;EM&gt;application context&lt;/EM&gt;, and you're trying to access the document without locking it, which triggers a lock violation.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;You need to lock the document before you access elements in it:&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="csharp"&gt;Document doc = Application.DocumentManager.MdiActiveDocument;
using(doc.LockDocument())
{
   // Here, the document is locked and can
   // be safely accessed.
}
// Here, the document is no-longer locked.&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;The other issue you have is that your code is using ExecuteInCommandContextAsync() directly, and without any exception handling in the delegate. If any code in the delegate throws an exception, the catch{} handler will not catch it, and it will crash AutoCAD.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;The solution I posted earlier was specifically for executing commands from the application context. Here is the more-general solution I use as an alternative to ExecuteInCommandContextAsync() to execute code in the document context, without running the risk of crashing AutoCAD:&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="csharp"&gt;// add this at the top of the code file:
using AcRx = Autodesk.AutoCAD.Runtime;

public static partial class AsyncDocExtensions
{
   public static async Task InvokeAsCommandAsync(this DocumentCollection docs, 
      Action&amp;lt;Document&amp;gt; action)
   {
      if(docs == null)
         throw new ArgumentNullException(nameof(docs));
      if(action == null)
         throw new ArgumentNullException(nameof(action));
      Document doc = docs.MdiActiveDocument;
      if(doc == null)
         throw new AcRx.Exception(AcRx.ErrorStatus.NoDocument);
      if(!docs.IsApplicationContext)
         throw new AcRx.Exception(AcRx.ErrorStatus.InvalidContext);
      Task task = Task.CompletedTask;
      await docs.ExecuteInCommandContextAsync(
         delegate (object unused)
         {
            try
            {
               action(doc);
               return task;
            }
            catch(System.Exception ex)
            {
               return task = Task.FromException(ex);
            }
         },
         null
      );
      if(task.IsFaulted)
      {
         throw task.Exception;
      }
   }
}&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Using the above extension provides a safety net that prevents AutoCAD from crashing if an exception occurs in the code you pass into the method. If you use ExecuteInCommandContextAsync() as your above code does, and the delegate throws an exception, your catch{} handler &lt;STRONG&gt;&lt;EM&gt;will not catch it&lt;/EM&gt;&lt;/STRONG&gt;, and AutoCAD will crash. With the InvokeAsCommandAsync() method, your catch{} handler will catch any exception thrown, including one thrown by the delegate you pass it.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Here is how you would adapt your code to use it:&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="csharp"&gt;   startPoint = new Point3d(X, Y, 0);
   try    
   { 
     await docs.InvokeAsCommandAsync(doc =&amp;gt;
     {
         ed.Command("_-PDFATTACH", PdfPath, Page.ToString(), Point3d.Origin, 1.0, 0.0);
         ObjectId? result = PdfHandle.LoadUnloadPDFunderlay(PdfPath, Page.ToString(), "Unload");
     });
   } 
   catch (System.Exception ex)
   {
     docs.MdiActiveDocument.Editor.WriteMessage($"Operation failed: {ex.Message}");
   }
   &lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Tue, 25 Feb 2025 03:28:28 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/net-forum/run-a-sample-command-with-parameters-using-c-net/m-p/13337617#M766</guid>
      <dc:creator>ActivistInvestor</dc:creator>
      <dc:date>2025-02-25T03:28:28Z</dc:date>
    </item>
  </channel>
</rss>

