<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
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?
callback from the Application.Idle event :ugly:
I'm having a bit of trouble with. [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
hmmm... it works fine for me on both 2013 and 2014 vanilla :|Worked for 2013 & 2014 for me
I've attached the .dll and project, does anybody else get the same error?
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
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?
#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 bitYes 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()
Code: [Select]#region Namespaces
When I run this I get "Drawing1.dwg" all 3 times as the active document regardless of which file I open.
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);
}
}
}
}
I don't use the ribbon but does anyone have problems w/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.
nextfiberworld=1 and the ribbon?
Trying that code snippet with 2013 and 64bit I get the new drawing name for last 2 message boxesI get the same result as Jeff. Windows 8 x64
nextfiberworld=1 and it works.What happens if you use OpenFileDialog from Autodesk.AutoCAD.Windows and remove reference from System.Windows.Form?
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?
I'll try test that tonight.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
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.
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.Changed Fiberworld = 1, the active drawing is now shown correctly.Can you confirm you restarted autocad after making the change?
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 willYes, I always restart after changing this.Changed Fiberworld = 1, the active drawing is now shown correctly.Can you confirm you restarted autocad after making the change?
Nextfiberworld = 1 may not be a good solution if it ruins a users ribbon.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.
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 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.
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.
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).