TheSwamp

Code Red => .NET => Topic started by: Mike Leslie on August 22, 2013, 04:32:16 PM

Title: Cannot set MdiActiveDocument
Post by: Mike Leslie on August 22, 2013, 04:32:16 PM
I cannot seem to set the MdiActiveDocument synchronously.

I have code inside a <CommandMethod> that creates a drawing and then writes any error information to the command line.  Since this is started in one document, if  a fatal error occurs and the drawing does not get created, that message goes to the original document's command line.

In the case where a drawing gets created with errors (say partial success), I would like the errors to appear in the new drawing (new active document's) command line.

The behavior when setting Core.Application.DocumentManager.MdiActiveDocument is peculiar.  The application can hang for a long time if you do not click anything.  If you click the document (from the taskbar or clicking on the window), it breaks out of the hang and continues to execute, but the active document is not changed.  The MdiActiveDocument still points to the original document.  You can also see that it does not change because doc.IsActive = False.  This state could be because when you clicked, you really did make the original document active (again? still?).  To break the hang, I think the click has to be on the original document.

On an example like http://www.theswamp.org/index.php?topic=44476.msg497357#msg497357 there is no action taken after MdiActiveDocument is set, so I assume that it is actually set when the command is completed, not synchronously.  I am not absolutely certain of this, though.

Code: [Select]

    <CommandMethod("AUTODRAWPN")> _
    Public Sub DrawPartNumber()
        Dim ed As Editor = Core.Application.DocumentManager.MdiActiveDocument.Editor

        If IsNothing(drwr) Then
            Try
                InitalizeAutodraw()
            Catch ex As System.Exception
                'exit quietly if it is cancelled by the user
                'print the error if an exception happened
                If ex.GetType <> GetType(OperationCanceledException) Then
                    ed.WriteMessage("Error: " & ex.Message)
                End If
                Exit Sub
            End Try
        End If

        Try
            Dim pr As PromptResult = ed.GetString("Part number to draw: ")
            If pr.Status <> PromptStatus.OK Then Exit Sub

            Dim doc As Document = drwr.CreateByPartNumber(pr.StringResult)
            'Core.Application.DocumentManager.MdiActiveDocument = doc       'does not work

            If drwr.Errors.Count > 0 Then
                ed = Core.Application.DocumentManager.MdiActiveDocument.Editor
                ed.WriteMessage("Autodraw Error(s):" & vbCrLf & String.Join(vbCrLf, drwr.Errors))
                ed.WriteMessage(vbCrLf)
            End If

        Catch ex As System.Exception
            ed.WriteMessage("Error: " & ex.Message)
        End Try

    End Sub


Is there a way to set the MDIActiveDocument?  Should it be hanging like this?  Should I be looking at an altogether different way to handle this?

Trying to use doc.Editor without setting the active causes a eNotApplicable error, so that is not a way out.

I am using AutoCAD 2013.  The following link implies that this could be a 2013 specific problem, but I do not know that for sure.
http://forums.autodesk.com/t5/NET/MDIActiveDocument-and-DocumentActivated/td-p/3629886

Thanks for whatever you guys can tell me!!
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff_M on August 22, 2013, 04:41:20 PM
I ran into issues with existing code when I migrated it to 2013 that stem from this exact issue. In prior versions, MdiActiveDocument becomes active much earlier in the process than it does in 2013+. I don't know what or why it was changed, but I had to do a lot of rewriting in order to get all of my code working properly.
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff H on August 22, 2013, 06:23:50 PM
Have you tried setting or checking DocumentCollection.DocumentActivationEnabled property?
Code - C#: [Select]
  1.             DocumentCollection docMgr = Application.DocumentManager;
  2.             Document doc = docMgr.Add("gjghjghjghjghjgjhgjhgj");
  3.             if (!docMgr.DocumentActivationEnabled)
  4.             {
  5.                 docMgr.DocumentActivationEnabled = true;
  6.             }
  7.             docMgr.MdiActiveDocument = doc;
  8.  
Title: Re: Cannot set MdiActiveDocument
Post by: BlackBox on August 22, 2013, 07:48:24 PM
... You two (Jeff & Jeff respectively  :-P), are endless sources of API knowledge; it's pretty schnazzy.  :mrgreen:
Title: Re: Cannot set MdiActiveDocument
Post by: Mike Leslie on August 23, 2013, 08:20:53 AM


DocumentActivationEnabled is already true in my code, but thanks for the idea.
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff_M on August 23, 2013, 09:45:44 AM
Jeff, a simple example. In versions prior to 2013 this DocumentActivated event handler would return the same values for the 2 string variables:
Code - C#: [Select]
  1. static void DocumentManager_DocumentCreated(object sender, DocumentCollectionEventArgs e)
  2.         {
  3.             Document doc = e.Document;
  4.             string docname = doc.Name;
  5.             string activedocname = Application.DocumentManager.MdiActiveDocument.Name;
  6.          }
  7.  
But in 2013 & 2014 this shows docname  as the new document but the ActiveDocument name is still the name of the drawing the command was invoked from.
Code - C#: [Select]
  1. static void DocumentManager_DocumentCreated(object sender, DocumentCollectionEventArgs e)
  2.         {
  3.             Document doc = e.Document;
  4.             string docname = doc.Name;
  5.             string activedocname = AcCore.Application.DocumentManager.MdiActiveDocument.Name;
  6.          }
  7.  
Title: Re: Cannot set MdiActiveDocument
Post by: Mike Leslie on August 23, 2013, 03:29:02 PM
I got it !!   :kewl:

The key was to declare my function as

 <CommandMethod("AUTODRAWPN", CommandFlags.Session)>

rather than

 <CommandMethod("AUTODRAWPN")>

This indicates that that the context is the entire AutoCAD session rather than running in only a specific document.  Now when I set MdiActiveDocument it takes and I can send my results to the correct Editor.

In fact, if I want, I don't even have to set the active document, since I now can write to doc.Editor without getting an eNotApplicable error.  This attribute definately opens up more cross-document abilities.

Title: Re: Cannot set MdiActiveDocument
Post by: mohnston on October 03, 2013, 02:57:18 PM
I ran into issues with existing code when I migrated it to 2013 that stem from this exact issue. In prior versions, MdiActiveDocument becomes active much earlier in the process than it does in 2013+. I don't know what or why it was changed, but I had to do a lot of rewriting in order to get all of my code working properly.
I just hit this land mine on a project. Was there no other way to set the active document to the . . um . . active document?
It worked properly prior to 2013.
I also tried Autodesk.AutoCAD.Internal.Utils.ActivateDocument(mydoc.Window.Handle) but that did not make it the active document either.
I'm facing the "a lot of rewriting" option if not and that's not good.
Title: Re: Cannot set MdiActiveDocument
Post by: WILL HATCH on October 03, 2013, 04:01:05 PM
It's strange the way it works now, but it seems you have to kill your thread and let the system do it's work.  I've found one way to achieve this is to set the active document in a function, end it, then continue work on a callback from the Application.Idle event  :ugly:
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 08, 2013, 09:19:27 PM
Will 
Code: [Select]
callback from the Application.Idle event  :ugly: I'm having a bit of trouble with.

Had some simple code that worked fine and now doesn't.
Basically 1) browse to a Library folder
2) open a drawing (calling zoomextents and a messagebox asking if you want to insert the dwg).
3) Close and discard
4) If no return  if yes insert the dwg  into the blocks.
5) Make a call to idle events and use a jig to insert the block.

If I use CommandFlags.Session I cannot get the jig to work at all,
if not, everything works but on closing cad the autocad has stopped working error comes up.

As you can see I have used Tony's
Idle events helper class

Code: [Select]
       [CommandMethod("Library")]
       // [CommandMethod("Library", CommandFlags.Session)]
        public void Library()
        {
            if(Library2())
                IdleEvents.Add(acadApp_Idle);
        }

        public bool Library2()
        {
            Document doc = acadApp.DocumentManager.MdiActiveDocument;
            ObjectId BlockId = ObjectId.Null;
          // using (doc.LockDocument())
          // {
                string sPath = Util.Get.LibraryPath();
                OpenFileDialog openFileDia = new OpenFileDialog();
                string sFile = "";
                openFileDia.InitialDirectory = sPath + "Hardware\\";
                openFileDia.Filter = "Drawing (*.dwg)|*.dwg|All files (*.*)|*.*";
                openFileDia.Multiselect = false;
                openFileDia.RestoreDirectory = true;
                if (openFileDia.ShowDialog() == DialogResult.OK)
                {
                    sFile = openFileDia.FileName;
                }

                if (string.IsNullOrEmpty(sFile)) return false;
                string sBlock = Path.GetFileNameWithoutExtension(sFile);

                //if (!Openit(sFile, sBlock))
                //    return;
                bool isT = false;
                DocumentCollection docs = acadApp.DocumentManager;
                Document docBlock = docs.Open(sFile, true);
                string msg = "Would you like to insert the drawing " + sBlock + " as a block?";
                DialogResult res = MessageBox.Show(msg, "Find block", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (res == DialogResult.Yes) isT = true;
                docBlock.CloseAndDiscard();
                docs.MdiActiveDocument = doc;
                if (!isT) return false;
               
                Database db = doc.Database;               
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    if (bt.Has(sBlock))
                    {
                        BlockId = bt[sBlock];
                        tr.Commit();
                        goto Insert;
                    }
                }

                using (Database dbase = new Database(false, true))
                {
                    try
                    {
                        dbase.ReadDwgFile(sFile, System.IO.FileShare.Read, false, "");
                        BlockId = db.Insert(sBlock, dbase, false);
                        dbase.CloseInput(true);
                    }
                    catch (System.Exception EX)
                    {
                        dbase.CloseInput(true);
                        Util.Debug.Print(EX.Message);
                        acadApp.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\nThe path is incorrect.");
                        return false;
                        //throw;
                    }
                }
           //}
            Insert:
            libBlockid = BlockId;
            return true;
        }



        void acadApp_Idle(object sender, EventArgs e)
        {
            Document doc = acadApp.DocumentManager.MdiActiveDocument;
            using (doc.LockDocument())
            {
                if (libBlockid != ObjectId.Null) JigNew.InsertBlockJiggy.Insert(libBlockid, false, "", scalefactor);
            }
                //throw new NotImplementedException();
                IdleEvents.Remove(acadApp_Idle);
        }//end Library






        //Tony http://www.theswamp.org/index.php?topic=41536.msg466400#msg466400
    public static class IdleEvents
    {
        static List<EventHandler> queue = new List<EventHandler>();
        static bool idleHandled = false;

        static void onIdle( object sender, EventArgs e )
        {
          SetHandled( false );
          EventHandler[] array = queue.ToArray();
          queue.Clear();
          try
            {
                foreach( EventHandler handler in array )
                  handler( sender, e );
            }
        finally
          {
            SetHandled( queue.Count > 0 );
         }
        }

 
        static void SetHandled( bool handle )
        {
          if( handle ^ idleHandled )
          {
            if( handle )
            {
             idleHandled = true;
              acadApp.Idle += onIdle;
           }
           else
            {
              idleHandled = false;
             acadApp.Idle -= onIdle;
           }
          }
    }

 

    public static void Add( EventHandler handler )
    {
      if( handler == null )
       throw new ArgumentNullException( "handler" );
      if( ! queue.Contains( handler ) )
      {
       queue.Add( handler );
       SetHandled( queue.Count > 0 );
     }
   }

    public static void Remove( EventHandler handler )

   {
      queue.Remove( handler );

      SetHandled( queue.Count > 0 );
    }

  }





        public static bool Openit(string sFile, string sBlock)
        {
            DocumentCollection docs = acadApp.DocumentManager;
            Document docBlock = docs.Open(sFile, true);
            bool isT = false;
            using (docBlock.LockDocument())
            {
               
                string msg = "Would you like to insert the drawing " + sBlock + " as a block?";
                DialogResult res = MessageBox.Show(msg, "Find block", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (res == DialogResult.Yes) isT = true;
                //docBlock.CloseAndDiscard();
            }
             DocumentExtension.CloseAndDiscard(docBlock);
         
            return isT;

        } // end Openit


JigNew.InsertBlockJiggy.Insert(libBlockid, false, "", scalefactor);  is a call to  a jig that works fine but uses the editor like all jigs.
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff H on October 09, 2013, 11:33:37 AM
I started this last week and never finished and forgot about it.
 
Wrote some test commands that would add new a document and prompt for a string with Session flag set or not, from new and original document's editor, delegating it to DocumentManager.ExecuteInApplicationContext or not.
 
So I got different result for combinations of the following.
 
   The comments above each method should explain its behavior.
 
All the commands
   1.) Add a new document(Used a named that would fail so would revert back to using default template)
   2.) Prompt user for a string from using either the
        a.) Editor of the document that issued the command
             or
        b.) Editor of the newly added document
 
 
 
 
I needed to come up with better naming scheme but never got around to changing to them.
 
The name of the commands follow this scheme
AddDoc_(Document or Application depending on context)_(Initial or New depending on which document the editor prompts for string)
So
AddDoc_Application_Initial - has CommandFlags.Session and prompts from the Editor of document the command started in.
 
There are another set of commands that are follow same naming scheme but start with
AddDoc_Delegated which uses DocumentManager.ExecuteInApplicationContext to call function to add a document set the active document.
 
Code - C#: [Select]
  1.  
  2.          ////// - Switches to new Document
  3.         ////// - Switches back to initial Document
  4.         ////// - Prompted for string
  5.         [CommandMethod("AddDoc_Document_Initial")]
  6.         public void AddDoc_Document_Initial()
  7.         {
  8.             Document doc = Application.DocumentManager.MdiActiveDocument;
  9.             Application.DocumentManager.Add("ButtFart.dwt");
  10.             var s = doc.Editor.GetString("\n").StringResult;
  11.         }
  12.  
  13.         ////////error
  14.         [CommandMethod("AddDoc_Application_Initial", CommandFlags.Session)]
  15.         public void AddDoc_Application_Initial()
  16.         {
  17.             Document doc = Application.DocumentManager.MdiActiveDocument;
  18.            Application.DocumentManager.Add("ButtFart.dwt");
  19.            var s = doc.Editor.GetString("\n").StringResult;
  20.         }
  21.         ////// - Switches to new Document
  22.         ////// - If you manually switch back to initial document you will be prompted for string
  23.         [CommandMethod("AddDoc_Delegated_Document_Initial")]
  24.         public void AddDoc_Delegated_Document_Initial()
  25.         {
  26.             Document doc = Application.DocumentManager.MdiActiveDocument;
  27.             Application.DocumentManager.ExecuteInApplicationContext(createNewDoc, null);
  28.             var s = doc.Editor.GetString("\n").StringResult;
  29.         }
  30.         ////// - Prompted for string
  31.         ////// - Switches to new Document
  32.         [CommandMethod("AddDoc_Delegated_Application_Initial", CommandFlags.Session)]
  33.         public void AddDoc_Delegated_Application_Initial()
  34.         {
  35.             Document doc = Application.DocumentManager.MdiActiveDocument;
  36.             Application.DocumentManager.ExecuteInApplicationContext(createNewDoc, null);
  37.             var s = doc.Editor.GetString("\n").StringResult;
  38.         }
  39.  
  40.  
  41.         ////////error
  42.         [CommandMethod("AddDoc_Document_New")]
  43.         public void AddDoc_Document_New()
  44.         {
  45.             Document doc = Application.DocumentManager.Add("ButtFart.dwt");
  46.             var s = doc.Editor.GetString("\n").StringResult;
  47.         }
  48.         ////// - Switches to new Document
  49.         ////// - Prompted for string
  50.         [CommandMethod("AddDoc_Application_New", CommandFlags.Session)]
  51.         public void AddDoc_Application_New()
  52.         {
  53.             Document doc = Application.DocumentManager.Add("ButtFart.dwt");
  54.             var s = doc.Editor.GetString("\n").StringResult;
  55.         }
  56.         ////// - Switches to new Document
  57.         ////// - ERROR If you manually switch back to initial document you will be prompted for string
  58.         [CommandMethod("AddDoc_Delegated_Document_New")]
  59.         public void AddDoc_Delegated_Document_New()
  60.         {
  61.             Application.DocumentManager.ExecuteInApplicationContext(createNewDoc, null);
  62.             var s = newDoc.Editor.GetString("\n").StringResult;
  63.         }
  64.         [CommandMethod("AddDoc_Delegated_Application_New", CommandFlags.Session)]
  65.         public void AddDoc_Delegated_Application_New()
  66.         {
  67.             Application.DocumentManager.ExecuteInApplicationContext(createNewDoc, null);
  68.             var s = newDoc.Editor.GetString("\n").StringResult;
  69.         }
  70.  
  71.         private Document newDoc = null;
  72.         private void createNewDoc(object userdata)
  73.         {
  74.             newDoc = Application.DocumentManager.Add("ButtFart.dwt");
  75.             Application.DocumentManager.MdiActiveDocument = newDoc;
  76.         }
  77.  
Title: Re: Cannot set MdiActiveDocument
Post by: MexicanCustard on October 09, 2013, 03:08:55 PM
Jeff H, was your post a question or a statement?  I hesitate to assume your asking a question since its rare that I would know the answer and you wouldn't.  :-)
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 09, 2013, 04:33:42 PM
I think the hard part is using the editor of the original dwg,
the comparisons you have made are cool though
Title: Re: Cannot set MdiActiveDocument
Post by: WILL HATCH on October 09, 2013, 10:10:14 PM
Bryco, I haven't had a chance to compile but at first glance I noticed that you aren't using tony's class properly. It automatically removes the event handler for you.
I have run into a similar error when creating overrule classes that weren't properly disposed, it is a very tricky error to track down.
Title: Re: Cannot set MdiActiveDocument
Post by: WILL HATCH on October 10, 2013, 01:47:04 AM
Bryco,

I played with your code.  Since you didn't include your jig I borrowed one from Kean at through the interface to play with your problem.

I could not get the newly opened document to display properly without commandflags.session set so I packaged the whole thing into a single function and had no issues running the jig or any issues closing autocad afterwards.  I suspect the issue you're running into is buried in one of your other classes.  Here's what I ended up with and it works fairly well:

Code - C#: [Select]
  1.     public class testing
  2.     {
  3.         [CommandMethod("Library", CommandFlags.Session)]
  4.         public void Library()
  5.         {
  6.             string sBlock;
  7.             string sFile;
  8.             Document doc;
  9.             Document docBlock;
  10.             ObjectId libBlockid;
  11.             doc = acadApp.DocumentManager.MdiActiveDocument;
  12.             string sPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
  13.             OpenFileDialog openFileDia = new OpenFileDialog();
  14.             openFileDia.InitialDirectory = sPath;
  15.             openFileDia.Filter = "Drawing (*.dwg)|*.dwg|All files (*.*)|*.*";
  16.             openFileDia.Multiselect = false;
  17.             openFileDia.RestoreDirectory = true;
  18.             if (openFileDia.ShowDialog() != DialogResult.OK) return;
  19.             sFile = openFileDia.FileName;
  20.             sBlock = Path.GetFileNameWithoutExtension(sFile);
  21.             docBlock = acadApp.DocumentManager.Open(sFile, true);
  22.             acadApp.DocumentManager.MdiActiveDocument = docBlock;
  23.             //Using a keyword prompt leaves the user free to zoom around the drawing and inspect it further if the initial view isn't enough
  24.             PromptKeywordOptions pko = new PromptKeywordOptions("\nPress ENTER to insert the drawing " + sBlock + " as a block?\nPress ESCAPE to cancel");
  25.             pko.AllowNone = true;
  26.             pko.AllowArbitraryInput = true;
  27.             if (docBlock.Editor.GetKeywords(pko).Status == PromptStatus.Cancel)
  28.             {
  29.                 docBlock.CloseAndDiscard();
  30.                 return;
  31.             }
  32.             using (doc.LockDocument())
  33.             {
  34.                 Database db = doc.Database;
  35.  
  36.                 using (Transaction tr = db.TransactionManager.StartTransaction())
  37.                 {
  38.                     BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
  39.                     if (bt.Has(sBlock))
  40.                         libBlockid = bt[sBlock];
  41.                     else
  42.                         libBlockid = db.Insert(sBlock, docBlock.Database, true);
  43.                     tr.Commit();
  44.                 }
  45.             }
  46.             acadApp.DocumentManager.MdiActiveDocument = doc;
  47.             docBlock.CloseAndDiscard();
  48.             using (doc.LockDocument())
  49.             {
  50.                 if (libBlockid == ObjectId.Null) return; // JigNew.InsertBlockJiggy.Insert(libBlockid, false, "", scalefactor);
  51.                 #region code to set up Keans jig
  52.                 using (Transaction tr = doc.TransactionManager.StartTransaction())
  53.                 {
  54.                     BlockTableRecord space = (BlockTableRecord)tr.GetObject(doc.Database.CurrentSpaceId, OpenMode.ForWrite);
  55.                     BlockReference br =
  56.                       new BlockReference(new Point3d(), libBlockid);
  57.                     space.AppendEntity(br);
  58.                     tr.AddNewlyCreatedDBObject(br, true);
  59.  
  60.                     Dictionary<ObjectId, AttInfo> attInfo =
  61.                       new Dictionary<ObjectId, AttInfo>();
  62.                     BlockTableRecord btr = (BlockTableRecord)tr.GetObject(libBlockid, OpenMode.ForRead);
  63.                     if (btr.HasAttributeDefinitions)
  64.                     {
  65.                         foreach (ObjectId id in btr)
  66.                         {
  67.                             DBObject obj =
  68.                               tr.GetObject(id, OpenMode.ForRead);
  69.                             AttributeDefinition ad =
  70.                               obj as AttributeDefinition;
  71.  
  72.                             if (ad != null && !ad.Constant)
  73.                             {
  74.                                 AttributeReference ar =
  75.                                   new AttributeReference();
  76.  
  77.                                 ar.SetAttributeFromBlock(ad, br.BlockTransform);
  78.                                 ar.Position =
  79.                                   ad.Position.TransformBy(br.BlockTransform);
  80.  
  81.                                 if (ad.Justify != AttachmentPoint.BaseLeft)
  82.                                 {
  83.                                     ar.AlignmentPoint =
  84.                                       ad.AlignmentPoint.TransformBy(br.BlockTransform);
  85.                                 }
  86.                                 if (ar.IsMTextAttribute)
  87.                                 {
  88.                                     ar.UpdateMTextAttribute();
  89.                                 }
  90.  
  91.                                 ar.TextString = ad.TextString;
  92.  
  93.                                 ObjectId arId =
  94.                                   br.AttributeCollection.AppendAttribute(ar);
  95.                                 tr.AddNewlyCreatedDBObject(ar, true);
  96.  
  97.                                 // Initialize our dictionary with the ObjectId of
  98.                                 // the attribute reference + attribute definition info
  99.  
  100.                                 attInfo.Add(
  101.                                   arId,
  102.                                   new AttInfo(
  103.                                     ad.Position,
  104.                                     ad.AlignmentPoint,
  105.                                     ad.Justify != AttachmentPoint.BaseLeft
  106.                                   )
  107.                                 );
  108.                             }
  109.                         }
  110.                     }
  111.                 #endregion
  112.                     // Run the jig
  113.                     BlockJig myJig = new BlockJig(tr, br, attInfo);
  114.  
  115.                     if (myJig.Run() != PromptStatus.OK)
  116.                         return;
  117.                     tr.Commit();
  118.                 }
  119.             }
  120.             //throw new NotImplementedException();
  121.             //IdleEvents.Remove(acadApp_Idle); <------------- not neccessary, Tony's class takes care of this.
  122.         }//end Library
  123.         #region A jig borrowed from Kean for the purpose of playing here
  124.         class AttInfo
  125.         {
  126.             private Point3d _pos;
  127.             private Point3d _aln;
  128.             private bool _aligned;
  129.  
  130.             public AttInfo(Point3d pos, Point3d aln, bool aligned)
  131.             {
  132.                 _pos = pos;
  133.                 _aln = aln;
  134.                 _aligned = aligned;
  135.             }
  136.  
  137.             public Point3d Position
  138.             {
  139.                 set { _pos = value; }
  140.                 get { return _pos; }
  141.             }
  142.  
  143.             public Point3d Alignment
  144.             {
  145.                 set { _aln = value; }
  146.                 get { return _aln; }
  147.             }
  148.  
  149.             public bool IsAligned
  150.             {
  151.                 set { _aligned = value; }
  152.                 get { return _aligned; }
  153.             }
  154.         }
  155.  
  156.         class BlockJig : EntityJig
  157.         {
  158.             private Point3d _pos;
  159.             private Dictionary<ObjectId, AttInfo> _attInfo;
  160.             private Transaction _tr;
  161.  
  162.             public BlockJig(
  163.               Transaction tr,
  164.               BlockReference br,
  165.               Dictionary<ObjectId, AttInfo> attInfo
  166.             )
  167.                 : base(br)
  168.             {
  169.                 _pos = br.Position;
  170.                 _attInfo = attInfo;
  171.                 _tr = tr;
  172.             }
  173.  
  174.             protected override bool Update()
  175.             {
  176.                 BlockReference br = Entity as BlockReference;
  177.  
  178.                 br.Position = _pos;
  179.  
  180.                 if (br.AttributeCollection.Count != 0)
  181.                 {
  182.                     foreach (ObjectId id in br.AttributeCollection)
  183.                     {
  184.                         DBObject obj =
  185.                           _tr.GetObject(id, OpenMode.ForRead);
  186.                         AttributeReference ar =
  187.                           obj as AttributeReference;
  188.  
  189.                         // Apply block transform to att def position
  190.  
  191.                         if (ar != null)
  192.                         {
  193.                             ar.UpgradeOpen();
  194.                             AttInfo ai = _attInfo[ar.ObjectId];
  195.                             ar.Position =
  196.                               ai.Position.TransformBy(br.BlockTransform);
  197.                             if (ai.IsAligned)
  198.                             {
  199.                                 ar.AlignmentPoint =
  200.                                   ai.Alignment.TransformBy(br.BlockTransform);
  201.                             }
  202.                             if (ar.IsMTextAttribute)
  203.                             {
  204.                                 ar.UpdateMTextAttribute();
  205.                             }
  206.                         }
  207.                     }
  208.                 }
  209.                 return true;
  210.             }
  211.  
  212.             protected override SamplerStatus Sampler(JigPrompts prompts)
  213.             {
  214.                 JigPromptPointOptions opts =
  215.                   new JigPromptPointOptions("\nSelect insertion point:");
  216.                 opts.BasePoint = new Point3d(0, 0, 0);
  217.                 opts.UserInputControls =
  218.                   UserInputControls.NoZeroResponseAccepted;
  219.  
  220.                 PromptPointResult ppr = prompts.AcquirePoint(opts);
  221.  
  222.                 if (_pos == ppr.Value)
  223.                 {
  224.                     return SamplerStatus.NoChange;
  225.                 }
  226.  
  227.                 _pos = ppr.Value;
  228.  
  229.                 return SamplerStatus.OK;
  230.             }
  231.  
  232.             public PromptStatus Run()
  233.             {
  234.                 Document doc =
  235.                   acadApp.DocumentManager.MdiActiveDocument;
  236.                 Editor ed = doc.Editor;
  237.  
  238.                 PromptResult promptResult = ed.Drag(this);
  239.                 return promptResult.Status;
  240.             }
  241.         }
  242.         #endregion

If you want a closer look at your jig implementation let me know
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 10, 2013, 09:07:36 PM
Thanks Will but I get an eNotapplicable at
if (docBlock.Editor.GetKeywords(pko).Status == PromptStatus.Cancel)

I'm using vanilla 2014 and get this using either
[CommandMethod("Library", CommandFlags.Session)]
or        [CommandMethod("Library")]
Title: Re: Cannot set MdiActiveDocument
Post by: WILL HATCH on October 10, 2013, 11:09:24 PM
hmmm... it works fine for me on both 2013 and 2014 vanilla  :|
I've attached the .dll and project, does anybody else get the same error?
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff H on October 11, 2013, 12:21:57 AM
hmmm... it works fine for me on both 2013 and 2014 vanilla  :|
I've attached the .dll and project, does anybody else get the same error?
Worked for 2013 & 2014 for me
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff H on October 11, 2013, 12:41:30 AM
Jeff H, was your post a question or a statement?  I hesitate to assume your asking a question since its rare that I would know the answer and you wouldn't.  :)
More of a statement but, now that I think about it a little is everyone that is having a problem setting the active document include either opening or creating a new document? OPEN, NEW & TABLET are the AutoCAD commands that are Nonreentrant
Quote
Command, Nonreentrant  A command that cannot be executed in more than one document at a time. Nonreentrancy can be used for commands that should not be available for more than one document at a time, or when the demands of supporting multiple instantiation are too great to be worth the overhead.
Wonder if something under the hood blocks you from doing that?
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 11, 2013, 12:40:40 PM
I couldn't load you proj as you have a different version (I'm using 2010 express) but copied it into a virtually blank proj and still the same problem.
Then I tried using the references from 2014 arx and still no go.  I did notice you are not using  the  using acadApp = Autodesk.AutoCAD.ApplicationServices.Core.Application;  the core part and changing that to using acadApp = Autodesk.AutoCAD.ApplicationServices..Application; made no difference.
Thanks will but I am still lost
Title: Re: Cannot set MdiActiveDocument
Post by: WILL HATCH on October 11, 2013, 01:23:02 PM
did the .dll have the same problem?
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 11, 2013, 04:35:48 PM
Yes  unfortunately.  My original code actually works fine but as I said cad crashes when you close the dwg (so not so fine)
Command: netload Cannot load assembly. Error details: System.IO.FileLoadException: Could not load file or assembly 'file:///C:\Users\bwalmsley\Documents\Visual Studio 2010\Projects\Library.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)
File name: 'file:///C:\Users\bwalmsley\Documents\Visual Studio 2010\Projects\Library.dll' ---> System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at Autodesk.AutoCAD.Runtime.ExtensionLoader.Load(String fileName)
   at loadmgd()
Title: Re: Cannot set MdiActiveDocument
Post by: mohnston on October 11, 2013, 06:28:33 PM
This is driving me crazy. I had it fixed and must have done something to cause it to stop working but can't for the life of me think of what.

I went back to basics and found that the problem still happens.
Code: [Select]
#region Namespaces
using System;
using System.Xml;
using System.Windows.Forms;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.ApplicationServices;
using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;
#endregion

namespace AutoCADCodeSample
{
    public class Commands
    {
        [CommandMethod("Test",CommandFlags.Session)]
        public static void Test()
        {
            string fileName = string.Empty;
            System.Windows.Forms.OpenFileDialog ofd =
                new System.Windows.Forms.OpenFileDialog();
            ofd.Filter = "AutoCAD drawing files|*.dwg";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                fileName = ofd.FileName;
                MessageBox.Show("Before opening drawing active document is " +
                    acadApp.DocumentManager.MdiActiveDocument.Name);
                // Open a file
                Document doc = acadApp.DocumentManager.Open(fileName);
                MessageBox.Show("After opening " + fileName + " active document is " +
                    acadApp.DocumentManager.MdiActiveDocument.Name);
                // Set the opened document to be the active document
                acadApp.DocumentManager.MdiActiveDocument = doc;
                MessageBox.Show("After setting " + doc.Name +
                    " to be the active document the actual active document is " +
                    acadApp.DocumentManager.MdiActiveDocument.Name);
            }
        }
    }
}
VS 2012 - Acad 2013 both 32 bit
When I run this I get "Drawing1.dwg" all 3 times as the active document regardless of which file I open.

This is causing problems not only with active document but save and close functionality.
Any help would be appreciated.
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 11, 2013, 07:27:46 PM
I'm looking into the command sequence a little
AutoCAD menu utilities loaded.
Command:
Command: COMMANDLINE
Command: properties
Command: EXTERNALREFERENCES
Command:
Command:
Command:

this is what I see when I open vanilla 2014  w/ no code pre  loaded. (after the Customization file loaded successfully. Customization Group yadayda)

Regenerating model.
AutoCAD menu utilities loaded.
Command:
Command:
Command:
Command:

this is after opening a new dwg.     4 unexplained  command:

Is this typ?


Command: Library Regenerating model.
Regenerating model.
Regenerating model.
Regenerating model.
Command: *Cancel*
Command: *Cancel*
Command: *Cancel*
Command: *Cancel*

running MY CODE w/ 4 regens added (they show up in both dwgs  on the command line so each editor is working)
now the 4 empty commands have Cancel next to them


If I run my code then open a new dwg then swith back to the old dwg there is no crash
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 11, 2013, 08:15:45 PM
from help
This function returns the document having current context. The associated function, mdiActiveDocument(), returns the MDI active document. curDocument() and mdiActiveDocument() can be different. You can call curDocument() to make a document "current" without actually activating it. After finish your AcDbDatabase operation under the temporary current document, call setCurDocument(acDocManager->mdiActiveDocument()) to reset the MDI active document as the current document.

setCurDocument may be the key, is it possible to get an entry point for this?

 
Title: Re: Cannot set MdiActiveDocument
Post by: WILL HATCH on October 11, 2013, 08:41:55 PM
Yes  unfortunately.  My original code actually works fine but as I said cad crashes when you close the dwg (so not so fine)
Command: netload Cannot load assembly. Error details: System.IO.FileLoadException: Could not load file or assembly 'file:///C:\Users\bwalmsley\Documents\Visual Studio 2010\Projects\Library.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)
File name: 'file:///C:\Users\bwalmsley\Documents\Visual Studio 2010\Projects\Library.dll' ---> System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at Autodesk.AutoCAD.Runtime.ExtensionLoader.Load(String fileName)
   at loadmgd()

You need to unblock the assembly before you can run it unless you change the autocad.exe.config file to allow it.  Download the zip, right click and go to properties, select 'Unblock' and pull the .dll out of there.

btw are you also running 32bit?
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 12, 2013, 12:35:33 PM
That worked but I still got an unhandled-eNotapplicable
I'm running windows 7 Pro
Title: Re: Cannot set MdiActiveDocument
Post by: mohnston on October 14, 2013, 05:03:28 PM

Code: [Select]
#region Namespaces
using System;
using System.Xml;
using System.Windows.Forms;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.ApplicationServices;
using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;
#endregion

namespace AutoCADCodeSample
{
    public class Commands
    {
        [CommandMethod("Test",CommandFlags.Session)]
        public static void Test()
        {
            string fileName = string.Empty;
            System.Windows.Forms.OpenFileDialog ofd =
                new System.Windows.Forms.OpenFileDialog();
            ofd.Filter = "AutoCAD drawing files|*.dwg";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                fileName = ofd.FileName;
                MessageBox.Show("Before opening drawing active document is " +
                    acadApp.DocumentManager.MdiActiveDocument.Name);
                // Open a file
                Document doc = acadApp.DocumentManager.Open(fileName);
                MessageBox.Show("After opening " + fileName + " active document is " +
                    acadApp.DocumentManager.MdiActiveDocument.Name);
                // Set the opened document to be the active document
                acadApp.DocumentManager.MdiActiveDocument = doc;
                MessageBox.Show("After setting " + doc.Name +
                    " to be the active document the actual active document is " +
                    acadApp.DocumentManager.MdiActiveDocument.Name);
            }
        }
    }
}
When I run this I get "Drawing1.dwg" all 3 times as the active document regardless of which file I open.

Can anyone confirm this behavior for me?
Just try the simple code posted if you will.
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff H on October 14, 2013, 05:52:51 PM
Trying that code snippet with 2013 and 64bit I get the new drawing name for last 2 message boxes
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 14, 2013, 07:06:30 PM
Do you have dual processors?   I have a quad core (NVidia quadro 40000 but not dual processors)

acad 2014 64 bit  vs2010 express   same result as mohnston
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff_M on October 14, 2013, 07:12:03 PM
I, too, get the same result as Bryco & mohnston.
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 14, 2013, 09:06:07 PM
nextfiberworld=1  and it works.
Even loading Will's dll works.
I thought you only had to set that to debug while using windows forms.

I don't use the ribbon but does anyone have problems w/
nextfiberworld=1 and the ribbon?
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff_M on October 14, 2013, 10:01:02 PM
I don't use the ribbon but does anyone have problems w/
nextfiberworld=1 and the ribbon?
Yes. When debugging I use this setting but, in Civil3D 2013 & 2014, when i open the first drawing I must select a command on the ribbon that brings up a toolbar in order for it to complete the loading of the drawing, else it will sit there and not accept any commands. A royal PITA so when doing real work I always make sure to set it back to 0. It sounds like what you are seeing may be related to what I see.
Title: Re: Cannot set MdiActiveDocument
Post by: WILL HATCH on October 14, 2013, 11:28:45 PM
Trying that code snippet with 2013 and 64bit I get the new drawing name for last 2 message boxes
I get the same result as Jeff. Windows 8 x64

After switching NEXTFIBERWORLD to 0 I get the same problems you guys are having.  I've never switched it before to debug like was mentioned by Kean http://through-the-interface.typepad.com/through_the_interface/2011/09/no-source-available-when-debugging-an-autocad-plug-in.html (http://through-the-interface.typepad.com/through_the_interface/2011/09/no-source-available-when-debugging-an-autocad-plug-in.html)

I found something posted by Fenton Webb that confirms this behavior http://forums.autodesk.com/t5/NET/Visual-Studio-Edit-and-Continue-not-working-anymore/m-p/4310378#M35693 (http://forums.autodesk.com/t5/NET/Visual-Studio-Edit-and-Continue-not-working-anymore/m-p/4310378#M35693)
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff H on October 15, 2013, 09:48:42 AM
nextfiberworld=1  and it works.
Even loading Will's dll works.
I thought you only had to set that to debug while using windows forms.

I don't use the ribbon but does anyone have problems w/
nextfiberworld=1 and the ribbon?
What happens if you use OpenFileDialog from Autodesk.AutoCAD.Windows and remove reference from System.Windows.Form?
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 15, 2013, 11:13:39 AM
I'll try test that tonight.
I have to press escape sometimes to work in a dwg I have just opened.
So perhaps that is part of the fiber thing.

Interesting to me is that Will's dll loaded no matter what the fiber setting was after I had initially changed the setting.
Title: Re: Cannot set MdiActiveDocument
Post by: WILL HATCH on October 15, 2013, 11:17:35 AM
I'll try test that tonight.
I have to press escape sometimes to work in a dwg I have just opened.
So perhaps that is part of the fiber thing.

Interesting to me is that Will's dll loaded no matter what the fiber setting was after I had initially changed the setting.
did you restart autocad after changing that value? A restart is required to change things, which is why we have write access to the NEXTFIBERWORLD variable and not FIBERWORLD
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 15, 2013, 02:27:48 PM
I THOUGHT I DID,  this time at 0  it errors out
is your dll from debug or release?
Title: Re: Cannot set MdiActiveDocument
Post by: WILL HATCH on October 15, 2013, 03:53:43 PM
It's probably a debug version, I didn't do anything for that except create a new project, paste in code, and compile
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff H on October 15, 2013, 04:34:53 PM
How about someone having problems load up a project?
 
Try loading one like the attached example how you would do with source control.
Where no reason to resolve any references etc....
Should open and build with no changes and see if any difference.
 
 
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff_M on October 15, 2013, 05:21:31 PM
Using MdiDoc project:
This was with Fiberworld=0 in C3D2014
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff_M on October 15, 2013, 05:26:14 PM
Changed Fiberworld = 1, the active drawing is now shown correctly.
Title: Re: Cannot set MdiActiveDocument
Post by: WILL HATCH on October 15, 2013, 05:58:10 PM
Changed Fiberworld = 1, the active drawing is now shown correctly.
Can you confirm you restarted autocad after making the change?
Title: Re: Cannot set MdiActiveDocument
Post by: mohnston on October 15, 2013, 06:26:26 PM
Thanks everyone for testing and exploring.
Nextfiberworld = 0   - fail
Nextfiberworld = 1 then restart AutoCAD   - success

Title: Re: Cannot set MdiActiveDocument
Post by: Jeff_M on October 15, 2013, 06:57:24 PM
Changed Fiberworld = 1, the active drawing is now shown correctly.
Can you confirm you restarted autocad after making the change?
Yes, I always restart after changing this.
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 15, 2013, 09:03:58 PM
Nextfiberworld = 1 may not be a good solution if it ruins a users ribbon.

I tried Will Hatches dll, the debug   didn't do so good on  Nextfiberworld = 0, but the release did ok
So it may pay to make sure you use release.

Perhaps someone else could  test that too
Title: Re: Cannot set MdiActiveDocument
Post by: WILL HATCH on October 16, 2013, 12:12:00 AM
Changed Fiberworld = 1, the active drawing is now shown correctly.
Can you confirm you restarted autocad after making the change?
Yes, I always restart after changing this.
Thanks, just trying to wrap my little brain around this. Can anybody else on C3D confirm this behaviour?  If I get time to install C3D tomorrow and play I will

Nextfiberworld = 1 may not be a good solution if it ruins a users ribbon.

I tried Will Hatches dll, the debug   didn't do so good on  Nextfiberworld = 0, but the release did ok
So it may pay to make sure you use release.

Perhaps someone else could  test that too
You confuse me with this statement... I thought that NEXTFIBERWORLD=1 is the default behavior, I've also never noticed a difference between release and debug builds aside from compiler optimizations.

Why Autodesk... WHY!?!?!  :realmad:
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff H on October 16, 2013, 03:08:46 AM
AutoCAD uses or will be "used" fibers for swapping call stacks within a thread. Microsoft has deprecated fibers and so is AutoCAD or until fiber8 comes out with VBA8
"Application Context" is a separate fiber which is common between documents, and used for switching document.
 
When NEXTFIBERWORLD = 0 and AutoCAD is restarted and "fiberless" instead of switching call stacks it has to "return" from the document, before executing in "Applicaton context"
In "fiberless" mode the actual activation is delayed or deferred and any prompt will never leave document context.
 
With Fiberless Open, Add. etc... or anything that uses AcApDocManager(DocumentManager) is effected.
 
With NEXTFIBERWORLD = 0 and restarted("fiberless")then a function started in a document must return before it is able to switch.
Also anything that uses acedcmd or acedcommand will fail, when AutoCAD is "fiberless".
 
So if you set AutoCAD to "fiberless" then code scripted via pinvoking acedcmd should fail.
 
Mac has no concept of fibers and look at AutoCAD for MAC documentation for acedcmdS or acedcmdP or acedcmdN or acedcmdC,  acedcmd followed by two different letters.
 
On the upside acedCommand relies on fibers and .NET does not support fibers and the main reason why never exposed so in when fiberless switch is made they should expose it.
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff H on October 16, 2013, 03:27:05 AM
... You two (Jeff & Jeff respectively  :P ), are endless sources of API knowledge; it's pretty schnazzy.  :mrgreen:
That just comes from spending the time of opening Reflector (http://www.red-gate.com/products/dotnet-development/reflector/) or ILSPY (http://ilspy.net/) and opening every assembley in AutoCAD install folder then remove all the ones that are red and seeing how they handle it themselves for parts of the software that exposed through .NET.
Just skimmed through quickly and most are crap but highlighted ones are ones you actually use in product.(I think)
 
 
 
Title: Re: Cannot set MdiActiveDocument
Post by: Kean on October 16, 2013, 05:38:37 AM
Hello everyone,

Kerry pinged me to take a look at this thread. I only skimmed it, so please tell me if it seems obvious I've missed something important.

I went ahead and tried the code with AutoCAD 2014, Windows 7 64-bit.

It works for me with fibers turned on (FIBERWORLD == 1). It fails with fibers turned off (FIBERWORLD == 0) with the eNotApplicable error on any use of docBlock.Editor, but I believe that’s due to 2014’s fiberless implementation being incomplete.

I also tested the code on an internal build with fibers off and it seems to work properly. So I wouldn’t be worried about getting it working in AutoCAD 2014 with fibers off, for now (using fibers is still the supported mode of operation for 2014, I only ever turn them off when needing to debug specific pieces of code).

Hopefully this helps and I didn't miss the point.
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff_M on October 16, 2013, 10:35:19 AM
Thanks for chiming in on this, Kean.

One other thing to note and be aware of. When Fiberworld=0, and the Activedocument is not the document you think it should be, the WorkingDatabase WILL be the new database:
Title: Re: Cannot set MdiActiveDocument
Post by: Kean on October 16, 2013, 11:55:55 AM
Interesting. Based on your comment I just tried setting HostApplicationServices.WorkingDatabase to docBlock.Database, to see whether that stopped the exception when running fiberless, but it didn't change anything.

The problem is no doubt deeper, and unlikely to be possible to work around (other than setting NEXTFIBERWORLD to 1 and restarting, that is ;-)).
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff H on October 16, 2013, 02:07:05 PM
Hi Kean,
 
Will Hatch posted a link to one of your blog entries in a earlier post
http://through-the-interface.typepad.com/through_the_interface/2011/09/no-source-available-when-debugging-an-autocad-plug-in.html (http://through-the-interface.typepad.com/through_the_interface/2011/09/no-source-available-when-debugging-an-autocad-plug-in.html)
 
A snippet from the very bottom.
Quote

For ADN members interested in a bit more background on this topic, see this DevNote (http://adn.autodesk.com/adn/servlet/devnote?siteID=4814862&id=16637351&linkID=4900524) and an article in this newsletter edition (http://adn.autodesk.com/adn/servlet/item?siteID=4814862&id=15529308).
The link from this newsletter edition (http://adn.autodesk.com/adn/servlet/item?siteID=4814862&id=15529308) has some information and contains a link to a white paper with more information.
 
It would be very useful for all to have access to the information. 
 
With ADN OPEN you think they could publish that at ADNBlog or made publicly somewhere?
 
 
 
Title: Re: Cannot set MdiActiveDocument
Post by: Kean on October 16, 2013, 02:08:11 PM
I would think so. I'll ping ADN and ask them to do so.
Title: Re: Cannot set MdiActiveDocument
Post by: Kerry on October 16, 2013, 03:13:09 PM
Thanks Kean.
Regards,
Title: Re: Cannot set MdiActiveDocument
Post by: Bryco on October 16, 2013, 09:52:22 PM
Thanks Kean as well.

I found a few autocad commands going crazy while I had fiber =0.
From the docs it makes sense xopen wouldn't work  but not being able to put an object on a turned off layer w/ the layer manager and being able to do it with the properties window makes me wonder how the Layer Control toolbar is thread/ fiber related
Title: Re: Cannot set MdiActiveDocument
Post by: Kean on October 17, 2013, 02:32:57 AM
There're a whole load of issues that crop up in 2014 with fibers off, some of which indeed don't seem to relate to multi-document operations.

BTW - it seems the DevNote I linked to has made it onto the AutoCAD DevBlog:

http://adndevblog.typepad.com/autocad/2012/12/breakpoints-in-custom-form-not-hit-when-debugging-net-addin-for-autocad-2012-from-visual-studio-2010.html (http://adndevblog.typepad.com/autocad/2012/12/breakpoints-in-custom-form-not-hit-when-debugging-net-addin-for-autocad-2012-from-visual-studio-2010.html)

Unfortunately the whitepaper hasn't as it's quite out-of-date: much of the information contained is no longer accurate. The ADN team will definitely be publishing more on the topic in due course (as will I).
Title: Re: Cannot set MdiActiveDocument
Post by: hperison on January 09, 2014, 06:14:55 PM
This is an interesting and very confusing topic especially when I see the phrase used in one of Kean's blogs that states: "still uses fibers".   As I keep reading about this subject, it seems that AutoCad is eventually going to be fiberless or am I mistaken.

Anyways, it is interesting that I have an application that will work with the opposite results.  It appears that all were having issues during runtime when NEXTFIBERWORLD = 0 and did not experience any successes until they set the value to 1.

I am the opposite as I can run seamlessly during the debug phase with NEXTFIBERWORLD = 1 but will experience a Fatal Error during release mode.    This will always happen when I rerun the application a couple of times in a row without engaging a new drawing session. 

FYI, my application is creating numerous drawings from a master document and requires switching back to the master/parent document before creating another.  Once the new drawing file has been created, the file is then saved and subsequently closed/discarded.  The application will then return to the parent to create another.   

However, when I set NEXTFIBERWORLD to 0, I can rerun my application in release mode numerous times with complete success and no Fatal Errors.

Is there any documentation on NEXTFIBERWORLD?   
Isn't NEXTFIBERWORLD = 1 the AutoCAD default?

It probably would be better if I knew which commands or functions didn't like NEXTFIBREWORLD = 1 and then I could adjust accordingly and not have to set my AutoCAD to use a value of 0.  Currently, I have to reset NEXTFIBERWORLD back to 1, when I am done, in order to prevent other issues.  A real 'pain in the a$$'
Title: Re: Cannot set MdiActiveDocument
Post by: Kean on January 10, 2014, 12:57:57 AM
Microsoft deprecated their fiber technology some years ago. Eventually Visual Studio stopped being able to debug fibers properly, hence the need to turn them off to use VS2010 to debug event callbacks, jigs, etc., in AutoCAD.

It's actually very natural that your code works well with fibers on (FIBERWORLD == 1) when not being run from the VS debugger. AutoCAD's fiberless implementation (FIBERWORLD == 0) is still incomplete in AutoCAD 2014: we recommend turning fibers off if you need to to debug, but you should turn them right back on afterwards. AutoCAD for Mac doesn't have the luxury of being able to use fibers, so we're most of the way there, implementation-wise. But there are still some quirks we need to iron out (and we're working hard on them).

I get strange behaviour after opening drawings in AutoCAD 2014 with fibers off, for instance: the input-throat just starts swallowing keyboard input until I hit Ctrl-C a few times (and then cancel the COPYCLIP command). Then things seem to work OK, but still.

To be clear: I've mentioned FIBERWORLD above, as that's the read-only sysvar that tells you whether fibers are on (1) or off (0) for the active session. NEXTFIBERWORLD sets whether fibers will be on (1) or off (0) for the next session, as you can't switch that on-the-fly for the current session.

The default in AutoCAD 2014 is currently for fibers to be on, but the writing is very clearly on the wall (and has been for many years, in fairness to Microsoft). Fibers are, at some point in the future, going away completely.

Kean
Title: Re: Cannot set MdiActiveDocument
Post by: hperison on January 10, 2014, 11:14:57 AM
Thank you for the clarification.  You write much better than me.  ;-)      My apologies to all for continuing to take this topic off course.

Kean, To clear up a misconception. I previously wrote that my program did the following ( a synopsis):

For NEXTFIBERWORLD ==1    (AutoCAD 2010/2014 build with VS2010 or VS2012 [for PC])

Release Mode:     produces a FATAL ERROR      e0434352h    @ fda2a49dh     (Fatal Error occurs if the application is executed more than once, back to back.)
Debug Mode:       works very well    (this is where I did all of my development)


For NEXTFIBERWORLD ==0     (AutoCAD 2010/2014 build with VS2010 or VS2012 [for PC])

Release Mode:     executes nicely   (I can execute the application numerous times back to back without error)
Debug Mode:       works very well

       (After the program is complete, subsequent AutoCAD functions do not work very well.  Many times I receive the "spinning wheel of death")

So this just appears to be strange because for everything that I read about NEXTFIBERWORLD == 0 my program shouldn't work very well at all except during debug.   Release should have issues where there are none.

I know for a definite fact that I am not that good of a programmer.
Title: Re: Cannot set MdiActiveDocument
Post by: Kean on January 10, 2014, 11:41:23 AM
Now I understand your point (I really shouldn't try to answer questions before my 3rd cup of tea in the morning, which I was guilty of with my previous response). Thanks for spelling it out for me.

In debug mode there are things that happen that might lead to crashes not happening, as I'm sure you're aware (for instance, uninitialised memory gets zeroed out, which means certain checks work in debug but not in release). So that's understandable, even if it'll probably be tricky to track down.

As for fibers on vs. off... I can see this is a bit strange, but it makes sense when I see that you're working across multiple documents. It's very likely that there's a problem with the way you're currently coordinating documents that doesn't occur when fibers are off, as things are working a bit differently. It sounds as though this needs some deeper analysis, especially if you get problems once the code finishes.

Thanks for your patience - I should have really understood your point sooner, looking back. Unfortunately I don't have a magic answer, though.

Kean
Title: Re: Cannot set MdiActiveDocument
Post by: hperison on January 10, 2014, 12:15:02 PM
Thanks, no magic answer required, I just thought it strange as well that I can execute "fiberless" where I shouldn't. 
This will be a nightmare to figure out.

I will just have to inform my users to the fact that multiple runs of the application should not be implemented
without setting the value from 1 to 0 and they will have to reset the value back when they are done.
Until I get this resolved, they won't be happy.

Draftsmen, such a whinny bunch of girls....   hehe :laugh:
Title: Re: Cannot set MdiActiveDocument
Post by: Jeff H on January 10, 2014, 12:25:34 PM
After you change setting are you closing AutoCAD and then restarting AutoCAD so it will take effect?
Title: Re: Cannot set MdiActiveDocument
Post by: hperison on January 10, 2014, 12:32:10 PM
You betcha...