Author Topic: adding/deleting block attributes  (Read 21546 times)

0 Members and 1 Guest are viewing this topic.

Jeff H

  • Needs a day job
  • Posts: 6150
Re: adding/deleting block attributes
« Reply #30 on: February 01, 2013, 12:01:22 PM »
Here is the exact code with a couple of additions I tried.


-Added a event handler for ObjectClosed.
-Added after first Transaction

                ed.WriteMessage("\n" + ad.UnmanagedObject.ToString());
                ed.WriteMessage("\n" + ad.IsDisposed.ToString());
                ed.WriteMessage("\n" + ad.Tag);
                //ad.LockPositionInBlock = true;///// Boom


Notice how checking IsDisposed works because just checking managed wrappers properties
Code - C#: [Select]
  1.  
  2. public bool IsDisposed
  3. {
  4.     [return: MarshalAs(UnmanagedType.U1)]
  5.     get
  6.     {
  7.         GC.KeepAlive(this);
  8.         return (this.m_imp == IntPtr.Zero);
  9.     }
  10. }
  11.  


Checking its Tag property works.
AcDbAttribute::tag
Quote
This function returns a pointer to a copy of the tag string for the attribute. The tag string is the identifier you see if you explode the AcDbBlockReference that owns the attribute, so that the attribute reverts back to the AcDbAttributeDefinition that was part of the original reference's block definition.
The caller of this function is responsible for deallocating the memory used by the returned string. The acutDelString() global function should be used for this purpose.
The tag string is used for DXF group code 2.


Notice it is just using the Intptr for its address to marshal back a string.
Code - C#: [Select]
  1.  
  2.     get
  3.     {
  4.         char* chPtr = 0L;
  5.         try
  6.         {
  7.             chPtr = AcDbAttribute.tag((AcDbAttribute modopt(IsConst)* modopt(IsConst) modopt(IsConst)) this.GetImpObj());
  8.             return WcharToString((char modopt(IsConst)*) chPtr);
  9.         }
  10.         finally
  11.         {
  12.             acutDelBuffer((void** modopt(IsImplicitlyDereferenced)) &chPtr);
  13.         }
  14.         return null;
  15.     }
  16.  
  17.  
  18.  


Now ad.LockPositionInBlock will go boom since it tries to modify the object.


The line ad.Erase is where it goes booms but can be fixed with adding
tr.GetObject(ad.ObjectId, OpenMode.ForWrite); or ad.ObjectId.Open()


The word Dispose gets used and thrown around alot and usually is understood as releasing unmanaged memory, but I think it is a big NoNo to delete a object in ObjectARX and just call Close because they keep the objects in memory.
So it might better to think of Dispose and Transactions as just opening and closing objects instead of memory management.


So from what I can tell is Clone and other methods work because they just use the address(GetImpObj, DisposableWrapper.UnmanagedObject) to go get some information and marshal it back to you.


Erase is trying to modify an object and there is where I get a BOOM!


Also the ObjectClosed event fires for me during Commit as the code below shows some message boxes.


Code - C#: [Select]
  1.  
  2.         [CommandMethod("TransactionTesting")]
  3.         public void TestTransaction()
  4.         {
  5.             try
  6.             {
  7.                 Document doc = Application.DocumentManager.MdiActiveDocument;
  8.                 Editor ed = doc.Editor;
  9.                 Database db = doc.Database;
  10.                 PromptEntityOptions peo = new PromptEntityOptions("\nSelect attribute to add");
  11.                 peo.SetRejectMessage("\nNot an AttributeDefinition");
  12.                 peo.AddAllowedClass(typeof(AttributeDefinition), true);
  13.                 PromptEntityResult per = ed.GetEntity(peo);
  14.                 if (per.Status != PromptStatus.OK) return;
  15.                 ObjectId adId = per.ObjectId;
  16.                 peo = new PromptEntityOptions("\nSelect block to append attribute");
  17.                 peo.SetRejectMessage("\nNot a BlockReference");
  18.                 peo.AddAllowedClass(typeof(BlockReference), true);
  19.                 per = ed.GetEntity(peo);
  20.                 if (per.Status != PromptStatus.OK) return;
  21.                 ObjectId brId = per.ObjectId;
  22.                 AttributeDefinition ad = null;
  23.                 BlockReference br = null;
  24.                 using (Transaction tr = db.TransactionManager.StartTransaction())
  25.                 {
  26.                     try
  27.                     {
  28.                         AttributeDefinition ad1 = (AttributeDefinition)tr.GetObject(adId, OpenMode.ForWrite);
  29.                         ad1.ObjectClosed += ad1_ObjectClosed;
  30.                         BlockReference br1 = (BlockReference)tr.GetObject(brId, OpenMode.ForRead);
  31.                         Application.ShowAlertDialog("Before Commit");
  32.                         tr.Commit();
  33.                         Application.ShowAlertDialog("After Commit");
  34.                         ad = ad1;//will fail if disposed at tr.commit()
  35.                         br = br1;
  36.                     }
  37.                     catch (System.Exception e)
  38.                     {
  39.                         ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
  40.                     }
  41.                     Application.ShowAlertDialog("Before Transaction Closed");
  42.                 }
  43.                 Application.ShowAlertDialog("After Transaction Closed");
  44.                 ed.WriteMessage("\n" + ad.UnmanagedObject.ToString());
  45.                 ed.WriteMessage("\n" + ad.IsDisposed.ToString());
  46.                 ed.WriteMessage("\n" + ad.Tag);
  47.                 //ad.LockPositionInBlock = true;///// Boom
  48.                 using (Transaction tr = db.TransactionManager.StartTransaction())
  49.                 {
  50.                     try
  51.                     {
  52.  
  53.  
  54.                         BlockTableRecord btr = (BlockTableRecord)tr.GetObject(br.BlockTableRecord, OpenMode.ForWrite);
  55.                         AttributeDefinition NEWad = (AttributeDefinition)ad.Clone();
  56.                         NEWad.TransformBy(br.BlockTransform.Inverse()); //to set the AD to the BTR coordinate system
  57.                         ObjectId NEWadId = btr.AppendEntity(NEWad);
  58.                         tr.AddNewlyCreatedDBObject(NEWad, true);
  59.                         ObjectIdCollection blockIds = btr.GetBlockReferenceIds(true, true);
  60.                         if (!NEWad.Constant) //constant attributes are NOT added to the block reference
  61.                             foreach (ObjectId id in blockIds) //add attribute reference to all blocks
  62.                             {
  63.                                 br = (BlockReference)tr.GetObject(id, OpenMode.ForWrite);
  64.                                 AttributeReference ar = new AttributeReference();
  65.                                 ar.SetAttributeFromBlock(NEWad, br.BlockTransform);
  66.                                 ar.TextString = ad.TextString;
  67.                                 br.AttributeCollection.AppendAttribute(ar);
  68.                                 tr.AddNewlyCreatedDBObject(ar, true);
  69.                             }
  70.                         tr.GetObject(ad.ObjectId, OpenMode.ForWrite);//////Commit line out and Boom
  71.                         ad.Erase();//////Will only work if above line is commented out
  72.                         tr.Commit();
  73.                         ed.Regen();//Regen needed for constant attribute to correctly display
  74.                     }
  75.                     catch (Autodesk.AutoCAD.Runtime.Exception ex)
  76.                     {
  77.                         if (ex.ErrorStatus != ErrorStatus.NotOpenForWrite)
  78.                         {
  79.                             ed.WriteMessage("\nError: {0}\n{1}", ex.GetBaseException(), ex.StackTrace);
  80.                         }
  81.                         throw;
  82.                     }
  83.                 }
  84.                 BlockReference br2 = (BlockReference)br.Clone();//cloning outside of a transaction works
  85.                 using (Transaction tr = db.TransactionManager.StartTransaction())
  86.                 {
  87.  
  88.  
  89.                     AttributeDefinition ad1 = new AttributeDefinition();
  90.                     ad1.SetDatabaseDefaults();
  91.                     ad1.Tag = "tag";
  92.                     ad1.TextString = "textString";
  93.                     ad1.Constant = true;
  94.                     Matrix3d mat = br2.BlockTransform;
  95.                     ad1.TransformBy(mat);
  96.                     BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
  97.                     btr.AppendEntity(ad1);
  98.                     tr.AddNewlyCreatedDBObject(ad1, true);
  99.                     tr.Commit();
  100.                     ed.Regen();
  101.                 }
  102.  
  103.  
  104.             }
  105.             catch (Autodesk.AutoCAD.Runtime.Exception ex)
  106.             {
  107.  
  108.  
  109.                 ed.WriteMessage("\nError: {0}\n{1}", ex.GetBaseException(), ex.StackTrace);
  110.  
  111.  
  112.             }
  113.  
  114.  
  115.         }
  116.  
  117.  
  118.         void ad1_ObjectClosed(object sender, ObjectClosedEventArgs e)
  119.         {
  120.             Application.ShowAlertDialog("ObjectClosed");
  121.         }
  122.  
  123.  
  124.  

WILL HATCH

  • Bull Frog
  • Posts: 450
Re: adding/deleting block attributes
« Reply #31 on: February 01, 2013, 03:58:55 PM »
Thanks for that, I didn't know how to use the ObjectClosed event before this example...

I put your code into my compiler and didn't do anything aside from changing line 109 so it would compile, uncommenting line 47 where you lock the position in the block, and commenting out line and 70 where you reopen ad for write. Everything worked...  What version are you using?? Any add ons?

changed line 109 to:
Code - C#: [Select]
  1. Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\nError: {0}\n{1}", ex.GetBaseException(), ex.StackTrace);

Editor output after running:
Command: TRANSACTIONTESTING

Select attribute to add:  (BTW I never thought to simply check ad.IsDisposed)
Nothing Selected.

Select attribute to add:
Select block to append attribute:
693813248
False
MYTAGRegenerating model.
Regenerating model.


I'm even more confused at this point, I've read through the ARX documentation and everything there seems to agree with what you're telling me but it's not what I'm seeing  :lmao:
« Last Edit: February 01, 2013, 04:02:26 PM by WILL HATCH »

Jeff H

  • Needs a day job
  • Posts: 6150
Re: adding/deleting block attributes
« Reply #32 on: February 01, 2013, 07:43:43 PM »

2013 Vanilla flavour but this machine Design Suite(MEP, Revit, and crap like SkecthBook Designer that f**ks up all your dynamic blocks with wipeouts being stretched--sotty for the rant)

I thought a ObjectId or using the UnmanagedObject property would be valid until its database is destroyed which it is not ,but how your getting around not closing it or modifying it without opening it, I have no idea.


Does the ObjectClosed Event fire?


Wonder if OpenedForModify event fires before you erase it.


I really do not know,
Speaking of dispose earlier and to add another point I have code that plays different fart sounds for dispose.
A  loud, hard, quick trumpet sounding fart for when I explicitly call dispose on it, and a long slow squeaker if called in Finalization method
Which makes complete sense to me so it goes to show they could be doing anything they want in Dispose call.


 





WILL HATCH

  • Bull Frog
  • Posts: 450
Re: adding/deleting block attributes
« Reply #33 on: February 01, 2013, 09:56:00 PM »
 :lmao:
I remember coming across your notifier before.
The closed notification fires properly, at the very end of the command, and again when I hit undo, etc.  I'll add some more notifications and post them to the command line so I can show you here next week.

TheMaster

  • Guest
Re: adding/deleting block attributes
« Reply #34 on: February 02, 2013, 12:31:35 PM »
Hugo, Jeff,

What version are you using?  I'm trying to wrap my head around why things are working here if they object is apparently closed with the transaction  :-o.  If this is something version dependent then my code will be failing on different versions of AutoCAD... I can see how it would make logical sense that as the transaction was disposed the objects opened for write would be downgraded to read only to prevent any modification later.  Can anybody explain what is going on here?

Cheers

Only the outer-most transaction actually closes an object (or cancels it if the transaction is aborted). Inner or nested transactions are only markers that tell the transactionmanager what objects belong to what transactions. If you open an object for write in a transaction, the object stays open for write until the outer-most transaction is comitted or aborted. You will find that objects that are opened for read may still be usable after the outer-most transaction they were opened in has ended, but that is undocumented behavior that should never be relied on.

WILL HATCH

  • Bull Frog
  • Posts: 450
Re: adding/deleting block attributes
« Reply #35 on: February 02, 2013, 01:04:51 PM »
So that said, me experiencing objects which are still writable after a transaction is an anomaly that shouldn't happen   :blank:
I'm going to try to figure out why this is happening... I have written several functions that use this methodology...

How does that translate to your GetObjects extension method or the standard ObjectId.GetObject method? Do I need to use those inside a transaction to increase the stability of my code on different platforms?

owenwengerd

  • Bull Frog
  • Posts: 451
Re: adding/deleting block attributes
« Reply #36 on: February 02, 2013, 04:43:10 PM »
So that said, me experiencing objects which are still writable after a transaction is an anomaly that shouldn't happen   :blank:

I don't think you understood Tony's explanation. If you modify a database resident object, and AutoCAD does not close with a fatal error, then the object is open, period. Either it was opened directly, or it belongs to an open transaction. It sounds like the latter in your case. It doesn't have to be a transaction that your code started. You're probably using a vertical that starts a transaction every time a command executes. If you are, your code will fail in vanilla AutoCAD.

WILL HATCH

  • Bull Frog
  • Posts: 450
Re: adding/deleting block attributes
« Reply #37 on: February 02, 2013, 07:09:17 PM »
Thanks for explicitly pointing out some versions will create a transaction implicitly... I was going to try to add an event to top transaction being opened and closed and see if that happens at the start and end of every routine.

In our office we run mechanical 2012 and also CADWORX on regular autocad 2012

TheMaster

  • Guest
Re: adding/deleting block attributes
« Reply #38 on: February 28, 2013, 12:21:06 AM »
So that said, me experiencing objects which are still writable after a transaction is an anomaly that shouldn't happen   :blank:
I'm going to try to figure out why this is happening... I have written several functions that use this methodology...


I didn't say writeable, I said that objects that were opened for read can still be accessed after the outer-most transaction they were opened in has ended. As far as I know, if an object was obtained from a transaction using OpenMode.ForWrite, the transaction will close the object when it ends (the outer-most transaction, that is), and you shouldn't be able to modify any object after that happens. 

Quote


How does that translate to your GetObjects extension method or the standard ObjectId.GetObject method? Do I need to use those inside a transaction to increase the stability of my code on different platforms?

Use those as opposed to ..... ?

WILL HATCH

  • Bull Frog
  • Posts: 450
Re: adding/deleting block attributes
« Reply #39 on: February 28, 2013, 01:26:42 PM »
You can pretty well ignore those questions at this point... There was a transaction being wrapped around my command that I was unaware of and it was the reason for the confusion.

Thank you for the clarification!