Author Topic: strange problem with events  (Read 7246 times)

0 Members and 1 Guest are viewing this topic.

sybold

  • Newt
  • Posts: 62
strange problem with events
« on: February 26, 2013, 05:55:30 AM »
i have a save handler problem, on loading it works, on opening a drawing it works.
but after a while it's gone and it doesn't work anymore.

it saves same attribute values to a sql server
the sql part works, also from a button on the ribbon, but i like to make it work on every save event.

my code:
Code - vb.net: [Select]
  1. Imports System
  2. Imports Autodesk.AutoCAD.Runtime
  3. Imports Autodesk.AutoCAD.ApplicationServices
  4. Imports Autodesk.AutoCAD.DatabaseServices
  5. Imports Autodesk.AutoCAD.Geometry
  6. Imports Autodesk.AutoCAD.EditorInput
  7. Imports System.IO
  8.  
  9.  
  10. <Assembly: ExtensionApplication(GetType(savehandler_2013.MyPlugin))>
  11.  
  12. Namespace savehandler_2013
  13.  
  14.     Public Class MyPlugin
  15.         Implements IExtensionApplication
  16.         Private _DocumentManager As DocumentCollection
  17.         Private Shared _Controllers As Dictionary(Of Document, PerDocController)
  18.         Public Sub Initialize() Implements IExtensionApplication.Initialize
  19.             '#### document controller ####
  20.             _DocumentManager = Application.DocumentManager
  21.             _Controllers = New Dictionary(Of Document, PerDocController)
  22.  
  23.             For Each document As Document In _DocumentManager
  24.                 _Controllers.Add(document, New PerDocController(document))
  25.             Next
  26.             AddHandler _DocumentManager.DocumentActivated, AddressOf DocumentActivated
  27.             AddHandler _DocumentManager.DocumentCreated, AddressOf DocumentCreated
  28.             AddHandler _DocumentManager.DocumentToBeDestroyed, AddressOf DocumentToBeDestroyed
  29.         End Sub
  30.  
  31.         Public Sub Terminate() Implements IExtensionApplication.Terminate
  32.             RemoveHandler _DocumentManager.DocumentActivated, AddressOf DocumentActivated
  33.             RemoveHandler _DocumentManager.DocumentCreated, AddressOf DocumentCreated
  34.             RemoveHandler _DocumentManager.DocumentToBeDestroyed, AddressOf DocumentToBeDestroyed
  35.         End Sub
  36.  
  37.         Private Sub DocumentActivated(sender As Object, e As DocumentCollectionEventArgs)
  38.             If Not (_Controllers.ContainsKey(e.Document)) Then
  39.                 _Controllers.Add(e.Document, New PerDocController(e.Document))
  40.                 e.Document.Editor.WriteMessage(vbCrLf + " - Document Activated! ")
  41.             End If
  42.  
  43.         End Sub
  44.         Private Sub DocumentToBeDestroyed(sender As Object, e As DocumentCollectionEventArgs)
  45.             If (_Controllers.ContainsKey(e.Document)) Then
  46.                 _Controllers(e.Document).Destroy()
  47.                 _Controllers.Remove(e.Document)
  48.             End If
  49.         End Sub
  50.         Private Sub DocumentCreated(sender As Object, e As DocumentCollectionEventArgs)
  51.             If Not (_Controllers.ContainsKey(e.Document)) Then
  52.                 _Controllers.Add(e.Document, New PerDocController(e.Document))
  53.                 e.Document.Editor.WriteMessage(vbCrLf + " - Document Created! ")
  54.             End If
  55.         End Sub
  56.  
  57.     End Class
  58.     Public Class PerDocController
  59.         Private _Document As Document
  60.         Public Sub New(ByVal document As Document)
  61.             _Document = document
  62.             If Not Getblockid("sqldataholder") = ObjectId.Null Then
  63.                 AddHandler _Document.Database.BeginSave, AddressOf BeginSave
  64.                 AddHandler _Document.Database.SaveComplete, AddressOf SaveComplete
  65.                 _Document.Editor.WriteMessage(vbCrLf + " - Savehandler Added! ")
  66.             End If
  67.         End Sub
  68.  
  69.         Public Sub Destroy()
  70.             RemoveHandler _Document.Database.BeginSave, AddressOf BeginSave
  71.             RemoveHandler _Document.Database.SaveComplete, AddressOf SaveComplete
  72.         End Sub
  73.  
  74.         Function Getblockid(ByVal blockName As String) As ObjectId
  75.             Dim RetBlkId As ObjectId = ObjectId.Null
  76.             Dim doc As Document = Application.DocumentManager.MdiActiveDocument
  77.             Dim db As Database = doc.Database
  78.             Dim ed As Editor = doc.Editor
  79.             Try
  80.                 Using tr As Transaction = db.TransactionManager.StartTransaction
  81.                     Dim bt As BlockTable = db.BlockTableId.GetObject(OpenMode.ForRead)
  82.                     Dim btr As BlockTableRecord = bt(blockName).GetObject(OpenMode.ForRead)
  83.                     Dim brefCount As Integer = 0
  84.                     For Each objId As ObjectId In btr.GetBlockReferenceIds(True, True)
  85.                         brefCount = btr.GetBlockReferenceIds(True, True).Count
  86.                         If brefCount > 1 Then
  87.                             ed.WriteMessage(vbCrLf & " - mutiple blocks found, check drawing!")
  88.                             Exit Function
  89.                         ElseIf brefCount = 0 Then
  90.                             ed.WriteMessage(vbCrLf & " - Block, " & blockName & " not found on screen")
  91.                             Exit Function
  92.                         Else
  93.                             Dim ent As Entity = objId.GetObject(OpenMode.ForRead)
  94.                             RetBlkId = ent.ObjectId
  95.                         End If
  96.                     Next
  97.                 End Using
  98.             Catch ex As Autodesk.AutoCAD.Runtime.Exception
  99.                 ed.WriteMessage(vbCrLf & " - Block, " & blockName & " not found")
  100.             End Try
  101.             Return RetBlkId
  102.         End Function
  103.  
  104.         Sub SetAttribute(ByVal blockId As ObjectId, ByVal attTag As String, ByVal attVal As String)
  105.             Dim doc As Document = Application.DocumentManager.MdiActiveDocument
  106.             Dim db As Database = doc.Database
  107.             Dim ed As Editor = doc.Editor
  108.             Try
  109.                 Using tr As Transaction = db.TransactionManager.StartTransaction
  110.                     Dim br As BlockReference
  111.                     Dim ac As AttributeCollection
  112.                     br = blockId.GetObject(OpenMode.ForWrite)
  113.                     ac = br.AttributeCollection
  114.                     Dim ent As ObjectId
  115.                     Dim ar As AttributeReference
  116.                     For Each ent In ac
  117.                         ar = ent.GetObject(OpenMode.ForWrite)
  118.                         If String.Compare(ar.Tag.ToUpper, attTag.ToUpper, True) = 0 Then
  119.                             ar.TextString = attVal
  120.                         End If
  121.                     Next
  122.                     tr.Commit()
  123.                     tr.Dispose()
  124.                 End Using
  125.             Catch ex As Autodesk.AutoCAD.Runtime.Exception
  126.                 ed.WriteMessage(vbCrLf & "Error: {0}" & vbCrLf & "Stack trace: {1}", ex.Message, ex.StackTrace)
  127.             End Try
  128.         End Sub
  129.  
  130.  
  131.         Private Sub BeginSave(sender As Object, e As DatabaseIOEventArgs)
  132.             _Document.Editor.WriteMessage(vbCrLf + " - Begin Save! ")
  133.  
  134.             If Not Getblockid("sqldataholder") = ObjectId.Null Then
  135.                 _Document.Editor.WriteMessage(vbCrLf + " - step 1! ")
  136.                 Try
  137.                     SetCustomProperty("sql", "true")
  138.                 Catch ex As Autodesk.AutoCAD.Runtime.Exception
  139.                     _Document.Editor.WriteMessage(vbCrLf & "Error: {0}" & vbCrLf & "Stack trace: {1}", ex.Message, ex.StackTrace)
  140.                 End Try
  141.                 _Document.Editor.WriteMessage(vbCrLf + " - step 2! ")
  142.                 Try
  143.                     SetCustomProperty("user", Environ$("USERNAME"))
  144.                 Catch ex As Autodesk.AutoCAD.Runtime.Exception
  145.                     _Document.Editor.WriteMessage(vbCrLf & "Error: {0}" & vbCrLf & "Stack trace: {1}", ex.Message, ex.StackTrace)
  146.                 End Try
  147.                 _Document.Editor.WriteMessage(vbCrLf + " - step 3! ")
  148.                 Try
  149.                     SetCustomProperty("DATEUPD", Format(Date.Now, "dd-MM-yy"))
  150.                 Catch ex As Autodesk.AutoCAD.Runtime.Exception
  151.                     _Document.Editor.WriteMessage(vbCrLf & "Error: {0}" & vbCrLf & "Stack trace: {1}", ex.Message, ex.StackTrace)
  152.                 End Try
  153.                 _Document.Editor.WriteMessage(vbCrLf + " - step 4! ")
  154.                 Try
  155.                     SetAttribute(Getblockid("testblock"), "tag", "value")
  156.                 Catch ex As Autodesk.AutoCAD.Runtime.Exception
  157.                     _Document.Editor.WriteMessage(vbCrLf & "Error: {0}" & vbCrLf & "Stack trace: {1}", ex.Message, ex.StackTrace)
  158.                 End Try
  159.             End If
  160.             '' send block data to sql db.
  161.             'sendtosqldb("sqldataholder")
  162.  
  163.             Dim w As StreamWriter = File.AppendText("c:\temp\savehandlerlog.txt")
  164.             logger(_Document.Name, w)
  165.             w.Close()
  166.  
  167.         End Sub
  168.  
  169.         Private Sub SaveComplete(sender As Object, e As DatabaseIOEventArgs)
  170.             _Document.Editor.WriteMessage(vbCrLf + " - Save Complete! ")
  171.  
  172.         End Sub
  173.         Private Sub logger(ByVal logMessage As String, ByVal w As TextWriter)
  174.             w.Write(ControlChars.CrLf & "Log Entry : ")
  175.             w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString())
  176.             w.WriteLine("  :")
  177.             w.WriteLine("  :{0}", logMessage)
  178.             w.WriteLine("-------------------------------")
  179.             ' Update the underlying file.
  180.             w.Flush()
  181.         End Sub
  182.         Sub SetCustomProperty(ByVal Name As String, ByVal Value As String)
  183.             Dim doc As Document = Application.DocumentManager.MdiActiveDocument
  184.             Dim db As Database = doc.Database
  185.             Dim ed As Editor = doc.Editor
  186.             Dim Builder As DatabaseSummaryInfoBuilder = New DatabaseSummaryInfoBuilder(db.SummaryInfo)
  187.  
  188.             If Builder.CustomPropertyTable.Contains(Name) Then
  189.                 Builder.CustomPropertyTable.Item(Name) = Value
  190.             Else
  191.                 Builder.CustomPropertyTable.Add(Name, Value)
  192.             End If
  193.  
  194.             db.SummaryInfo = Builder.ToDatabaseSummaryInfo
  195.         End Sub
  196.     End Class
  197. End Namespace
« Last Edit: February 26, 2013, 01:09:36 PM by sybold »

BlackBox

  • King Gator
  • Posts: 3770
Re: strange problem with events
« Reply #1 on: February 26, 2013, 09:32:13 AM »
Quickly written example:

Code - C#: [Select]
  1.  
  2. using Autodesk.AutoCAD.ApplicationServices;
  3. using Autodesk.AutoCAD.DatabaseServices;
  4. using Autodesk.AutoCAD.EditorInput;
  5. using Autodesk.AutoCAD.Runtime;
  6.  
  7. using acApp = Autodesk.AutoCAD.ApplicationServices.Application;
  8.  
  9. [assembly: ExtensionApplication(typeof(TheSwamp.Sample.Events.Save))]
  10.  
  11. namespace TheSwamp.Sample.Events
  12. {
  13.     public class Save : IExtensionApplication
  14.     {
  15.         public void Initialize()
  16.         {
  17.             DocumentCollection acDocs = acApp.DocumentManager;
  18.             Document doc = acDocs.MdiActiveDocument;
  19.             Editor ed = doc.Editor;
  20.  
  21.             acDocs.DocumentCreated += OnDocumentCreated;
  22.             doc.CommandWillStart += OnCommandWillStart;
  23.         }
  24.  
  25.         public void Terminate()
  26.         {
  27.         }
  28.  
  29.         public void BowtiesAreCool() //<-- Change this to something useful
  30.         {
  31.             acApp.DocumentManager.MdiActiveDocument.Editor.WriteMessage(
  32.                 "\n** Bowties are cool ** \n"
  33.             );
  34.         }
  35.  
  36.         void OnCommandWillStart(object sender, CommandEventArgs e)
  37.         {
  38.             if (e.GlobalCommandName.ToUpper().Contains("SAVE"))
  39.                 BowtiesAreCool(); //<-- Change this to something useful
  40.         }
  41.  
  42.         void OnDocumentCreated(object sender, DocumentCollectionEventArgs e)
  43.         {
  44.             if (e.Document != null)
  45.                 e.Document.CommandWillStart += OnCommandWillStart;
  46.         }
  47.     }
  48. }
  49.  
"How we think determines what we do, and what we do determines what we get."

sybold

  • Newt
  • Posts: 62
Re: strange problem with events
« Reply #2 on: February 26, 2013, 11:08:36 AM »
that's another way how to do it.
in 2012 it works without a problem, in 2013 it works for a limited time.

we found this problem after upgrading a few workstations to 2013 to test, if it all worked as needed.
The save begin handle doesn't function anymore after some point, i can't figure out why and when.

BlackBox

  • King Gator
  • Posts: 3770
Re: strange problem with events
« Reply #3 on: February 26, 2013, 12:54:48 PM »
If the command Event handler is registered successfully, I do not understand how it would stop working prior to the Document being removed from the Document Collection... That suggests it's being unregistered AFAIK.

Silly question, but you don't by chance have multiple plug-ins with the same Method name for your command event handler do you? Perhaps one of those would-be variants is being unregistered?

I would assume not, but I thought I'd ask... Perhaps a more knowledgeable member can step in, and educate us both.
"How we think determines what we do, and what we do determines what we get."

sybold

  • Newt
  • Posts: 62
Re: strange problem with events
« Reply #4 on: February 26, 2013, 01:09:03 PM »
it's weird, this is the only plugin currently running on the dev/test machine.
maybe there is a way to visualy check if the handler is added,active or removed.


BlackBox

  • King Gator
  • Posts: 3770
Re: strange problem with events
« Reply #5 on: February 26, 2013, 01:15:08 PM »
it's weird, this is the only plugin currently running on the dev/test machine.
maybe there is a way to visualy check if the handler is added,active or removed.

What happens when you step through the code in debug?
"How we think determines what we do, and what we do determines what we get."

BlackBox

  • King Gator
  • Posts: 3770
Re: strange problem with events
« Reply #6 on: February 26, 2013, 01:16:15 PM »
it's weird, this is the only plugin currently running on the dev/test machine.
maybe there is a way to visualy check if the handler is added,active or removed.

What happens when you step through the code in debug?

Note - I would use a minimal framework version (such as what i posted) first, then begin adding more complexity to your plug-in incrementally to see where the breakdown occurs.
"How we think determines what we do, and what we do determines what we get."

kaefer

  • Guest
Re: strange problem with events
« Reply #7 on: February 26, 2013, 02:29:11 PM »
Don't you all think that it's a little bit preposterous to expect AutoCAD doing all this heavy lifting inside an event handler without demurring?

Please somebody confirm my suspicion that it's generally not the best idea to do computationally intensive operations on borrowed time. Reading around this place, I've come to the impression that even the command ended and quiescent state events could prove troublesome in that regard.

TheMaster

  • Guest
Re: strange problem with events
« Reply #8 on: February 26, 2013, 05:29:28 PM »
that's another way how to do it.
in 2012 it works without a problem, in 2013 it works for a limited time.

we found this problem after upgrading a few workstations to 2013 to test, if it all worked as needed.
The save begin handle doesn't function anymore after some point, i can't figure out why and when.


Per chance, are there 3D solids involved?

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: strange problem with events
« Reply #9 on: February 26, 2013, 05:34:14 PM »
that's another way how to do it.
in 2012 it works without a problem, in 2013 it works for a limited time.

we found this problem after upgrading a few workstations to 2013 to test, if it all worked as needed.
The save begin handle doesn't function anymore after some point, i can't figure out why and when.


Per chance, are there 3D solids involved?

Wow, that's a question really skirting the edges of the problem !!
I assume it's experience based ; or are you psychic, Tony ? :)
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

BlackBox

  • King Gator
  • Posts: 3770
Re: strange problem with events
« Reply #10 on: February 26, 2013, 05:38:17 PM »
Don't you all think that it's a little bit preposterous to expect AutoCAD doing all this heavy lifting inside an event handler without demurring?

Couldn't say, as I didn't even bother to look at the 'heavy lifting' being performed... The OP couldn't get the Save reactor to fire as expected, so I simply thought I'd start there.
"How we think determines what we do, and what we do determines what we get."

TheMaster

  • Guest
Re: strange problem with events
« Reply #11 on: February 26, 2013, 05:38:33 PM »
Don't you all think that it's a little bit preposterous to expect AutoCAD doing all this heavy lifting inside an event handler without demurring?

Please somebody confirm my suspicion that it's generally not the best idea to do computationally intensive operations on borrowed time. Reading around this place, I've come to the impression that even the command ended and quiescent state events could prove troublesome in that regard.

There are limitations on what you can do inside event handlers, but generally what point would there be in notifying you about something, if you can't act on it? In some cases, you can simply set a flag and check it at some later point, and if set, do the heavy lifting, but in the case of saving a file, you really don't have a choice if the work you need to do is supposed to be saved with the drawing that's about to be written.

Event handlers can bog down AutoCAD if they are doing a lot of work, and the events fire frequently. The ones you cite (Command-related and Quiescent state-related) could fire frequently only under scripting (for example, a LISP script that executes one or more commands many times in a loop), but in non-scripting scenarios, those events are not fired often since there is usually user-interaction involved. However, because scripting is most-likely in use, one should consider the command-related events as high-frequency events for all intents and purposes.

The really 'high-frequency' events are usually the ones that notify you about events at the object-level, like the ObjectModified/Erased/Appended events of the Database. The Application's Idle event is another one that can fire often (on every mouse move and keypress), which is why it's a good idea to avoid doing a lot of work every time that event fires.
« Last Edit: February 26, 2013, 05:42:22 PM by TT »

TheMaster

  • Guest
Re: strange problem with events
« Reply #12 on: February 26, 2013, 05:46:17 PM »
that's another way how to do it.
in 2012 it works without a problem, in 2013 it works for a limited time.

we found this problem after upgrading a few workstations to 2013 to test, if it all worked as needed.
The save begin handle doesn't function anymore after some point, i can't figure out why and when.


Per chance, are there 3D solids involved?

Wow, that's a question really skirting the edges of the problem !!
I assume it's experience based ; or are you psychic, Tony ? :)

AutoCAD 2013 introduces local caching of 3D graphics, which (obviously) must happen when a file is saved :wink:


BlackBox

  • King Gator
  • Posts: 3770
Re: strange problem with events
« Reply #13 on: February 26, 2013, 05:54:12 PM »
Don't you all think that it's a little bit preposterous to expect AutoCAD doing all this heavy lifting inside an event handler without demurring?

Please somebody confirm my suspicion that it's generally not the best idea to do computationally intensive operations on borrowed time. Reading around this place, I've come to the impression that even the command ended and quiescent state events could prove troublesome in that regard.

There are limitations on what you can do inside event handlers, but generally what point would there be in notifying you about something, if you can't act on it? In some cases, you can simply set a flag and check it at some later point, and if set, do the heavy lifting, but in the case of saving a file, you really don't have a choice if the work you need to do is supposed to be saved with the drawing that's about to be written.

Event handlers can bog down AutoCAD if they are doing a lot of work, and the events fire frequently. The ones you cite (Command-related and Quiescent state-related) could fire frequently only under scripting (for example, a LISP script that executes one or more commands many times in a loop), but in non-scripting scenarios, those events are not fired often since there is usually user-interaction involved. However, because scripting is most-likely in use, one should consider the command-related events as high-frequency events for all intents and purposes.

The really 'high-frequency' events are usually the ones that notify you about events at the object-level, like the ObjectModified/Erased/Appended events of the Database. The Application's Idle event is another one that can fire often (on every mouse move and keypress), which is why it's a good idea to avoid doing a lot of work every time that event fires.

Thanks Keafer for posing the question, and Tony for the clarification... Seemed very commonsensical having read your response, but always helpful/educational.

Cheers :beer:
"How we think determines what we do, and what we do determines what we get."

sybold

  • Newt
  • Posts: 62
Re: strange problem with events
« Reply #14 on: March 04, 2013, 02:53:14 PM »
after some day's of testing. I've came to a couple of things.

autocad 2009, no problems all works like it should.
autocad 2010, 2011, 2012 no problems all works like it should.


2013 works, until 1 document hits an autosave and the savehandlers are gone.

i know events have limitations, but it has been working for the last 5 years, why did it break in 2013.
the code hasn't changed much between the autocad versions.

Remember that this is not a full database app, i'm only doing a insert or update query to a sql database with 8 block attribute values.
there is no timing issue, or network delay.

i hope a fix is available, otherwise we will stay on 2012.

Jeff H

  • Needs a day job
  • Posts: 6150
Re: strange problem with events
« Reply #15 on: March 04, 2013, 03:14:35 PM »
In the BeginSave event have you tried checking DatabaseIOEventArgs.FileName and dropping out if file extension is 'sv$'?

TheMaster

  • Guest
Re: strange problem with events
« Reply #16 on: March 04, 2013, 03:19:33 PM »
after some day's of testing. I've came to a couple of things.

autocad 2009, no problems all works like it should.
autocad 2010, 2011, 2012 no problems all works like it should.


2013 works, until 1 document hits an autosave and the savehandlers are gone.

i know events have limitations, but it has been working for the last 5 years, why did it break in 2013.
the code hasn't changed much between the autocad versions.

Remember that this is not a full database app, i'm only doing a insert or update query to a sql database with 8 block attribute values.
there is no timing issue, or network delay.

i hope a fix is available, otherwise we will stay on 2012.

Most I know who are using customization have passed on AutoCAD 2013, because of many issues. That's what appens when new releases create more problems than they solve.

sybold

  • Newt
  • Posts: 62
Re: strange problem with events
« Reply #17 on: March 04, 2013, 03:31:08 PM »
In the BeginSave event have you tried checking DatabaseIOEventArgs.FileName and dropping out if file extension is 'sv$'?

just tried it, same result. it magically gone

sybold

  • Newt
  • Posts: 62
Re: strange problem with events
« Reply #18 on: March 04, 2013, 03:33:21 PM »
i've got a slim version running now with only printing savebegin and savecomplete in the commandline, not doing any other stuff. same problem.

Jeff H

  • Needs a day job
  • Posts: 6150
Re: strange problem with events
« Reply #19 on: March 04, 2013, 03:58:39 PM »
In first example where does _Document variable come from, which Document is it pointing to?
How about posting a simple project that you can produce the problem with.

trembre

  • Guest
Re: strange problem with events
« Reply #20 on: March 04, 2013, 04:43:10 PM »
 I had the same issue - http://www.theswamp.org/index.php?topic=42961.msg481822#msg481822 - with AutoCAD 2011.

 The problem always arose using BeginSave when multiple drawings were open and an Autosave was fired off - for some reason the event handlers "disappear".  Despite targetting the apparently correct database for my handler as per the above thread, the problem persisted.  To get around this, I started intercepting saves by global command name, which does work well except for one issue - if the user tries to close a drawing without saving, AutoCAD offers them the option, and they click Yes, the code is bypassed. Will be trying the OnCommandWillStart option to see if that fixes it.

Jeff H

  • Needs a day job
  • Posts: 6150
Re: strange problem with events
« Reply #21 on: March 04, 2013, 06:00:59 PM »
I had the same issue - http://www.theswamp.org/index.php?topic=42961.msg481822#msg481822 - with AutoCAD 2011.

 The problem always arose using BeginSave when multiple drawings were open and an Autosave was fired off - for some reason the event handlers "disappear".  Despite targetting the apparently correct database for my handler as per the above thread, the problem persisted.  To get around this, I started intercepting saves by global command name, which does work well except for one issue - if the user tries to close a drawing without saving, AutoCAD offers them the option, and they click Yes, the code is bypassed. Will be trying the OnCommandWillStart option to see if that fixes it.


If you read link posted by trembe Tony mentions problems adding handler multiple times and take a look at your DocumentedCreated and DocumentedActivated handlers.


Using 2013 with AutoSave and no problems.
Fires for each save and still fires after AutoSave has saved for multiple documents.


Code - C#: [Select]
  1. using System;
  2. using Autodesk.AutoCAD.Runtime;
  3. using Autodesk.AutoCAD.ApplicationServices;
  4. using Autodesk.AutoCAD.DatabaseServices;
  5. using Autodesk.AutoCAD.Geometry;
  6. using Autodesk.AutoCAD.EditorInput;
  7. using System.IO;
  8.  
  9.  
  10. // This line is not mandatory, but improves loading performances
  11. [assembly: ExtensionApplication(typeof(AutoCAD_CSharp_plug_in1.MyPlugin))]
  12.  
  13.  
  14. namespace AutoCAD_CSharp_plug_in1
  15. {
  16.  
  17.  
  18.     // This class is instantiated by AutoCAD once and kept alive for the
  19.     // duration of the session. If you don't do any one time initialization
  20.     // then you should remove this class.
  21.     public class MyPlugin : IExtensionApplication
  22.     {
  23.  
  24.  
  25.         void IExtensionApplication.Initialize()
  26.         {
  27.             DocumentCollection docs = Application.DocumentManager;
  28.             foreach (Document doc in docs)
  29.             {
  30.                 doc.Database.BeginSave += new DatabaseIOEventHandler(Database_BeginSave);
  31.             }
  32.  
  33.  
  34.             docs.DocumentCreated += new DocumentCollectionEventHandler(docs_DocumentCreated); ;
  35.         }
  36.  
  37.  
  38.         void docs_DocumentCreated(object sender, DocumentCollectionEventArgs e)
  39.         {
  40.            
  41.             e.Document.Database.BeginSave += new DatabaseIOEventHandler(Database_BeginSave);
  42.         }
  43.  
  44.  
  45.         void Database_BeginSave(object sender, DatabaseIOEventArgs e)
  46.         {
  47.             if (Path.GetExtension(e.FileName) != ".sv$")
  48.             {
  49.                 Application.ShowAlertDialog(e.FileName);
  50.             }
  51.            
  52.         }
  53.  
  54.  
  55.         void IExtensionApplication.Terminate()
  56.         {
  57.             // Do plug-in application clean up here
  58.         }
  59.  
  60.  
  61.     }
  62.  
  63.  
  64. }

trembre

  • Guest
Re: strange problem with events
« Reply #22 on: March 04, 2013, 07:36:30 PM »
Thanks Jeff - your code solves the problems I was having - my event only fires once, survives autosaves and works on close-save.  Now to figure out why - when I changed my code as per Tony and n.yuan's input, I wasn't too far off what you've written yet still had that issue...

Jeff H

  • Needs a day job
  • Posts: 6150
Re: strange problem with events
« Reply #23 on: March 04, 2013, 08:37:00 PM »
Thanks Jeff - your code solves the problems I was having - my event only fires once, survives autosaves and works on close-save.  Now to figure out why - when I changed my code as per Tony and n.yuan's input, I wasn't too far off what you've written yet still had that issue...
I thought the code posted was following Tony and Norman's(n.yuan) advice.

trembre

  • Guest
Re: strange problem with events
« Reply #24 on: March 04, 2013, 11:03:52 PM »
It is, hence my confusion!  I'll have to dig out that code from my repository and compare it to yours.  While I got the point Tony and Norman were making at the time, I must have botched something else in the code... 

EDIT: After resurrecting that code turns out it does follow the same logic and does work.  :ugly:  Must've mixed up my dlls when I was testing - I'll get my coat.
« Last Edit: March 05, 2013, 07:39:27 PM by trembre »

sybold

  • Newt
  • Posts: 62
Re: strange problem with events
« Reply #25 on: March 28, 2013, 08:16:00 AM »
it has been a while, been very busy.

this is great, i now realize what i was doing wrong.

all is working again