.NET

Reply
Active Contributor
NayaraFJ
Posts: 42
Registered: ‎08-11-2011
Message 1 of 5 (355 Views)
Accepted Solution

Edit attributes within a block.

355 Views, 4 Replies
10-19-2011 05:57 AM

I'm trying to edit attributes of a block but is giving error. :smileysad:

 

 private void ChangingAttibutes1(ObjectId[] objectIdList)
        {
            for (int i = 0; i < objectIdList.Length; i++)
            {
                ObjectId objectId = objectIdList[i];
                BlockReference blockReference = (BlockReference)objectId.GetObject(OpenMode.ForWrite);
                BlockTableRecord blockTableRecord = (BlockTableRecord)blockReference.BlockTableRecord.GetObject(OpenMode.ForWrite);
                
                Entity Entity = null;

                foreach (ObjectId item in blockTableRecord)
                {
                    Entity = transaction.GetObject(item, OpenMode.ForWrite) as Entity;
                   /* if (Entity.GetType() == typeof(AttributeDefinition))
                    {*/
                        AttributeDefinition attributeDefinition = Entity as AttributeDefinition;
                        AttributeReference attributeReference = new AttributeReference();
                        attributeReference.SetAttributeFromBlock(attributeDefinition, blockReference.BlockTransform);
                        if (attributeReference.Tag == "CREV1")
                        {
                            attributeReference.TextString = myList[0];
                        }
                        else if (attributeReference.Tag == "TREV1")
                        {
                            attributeReference.TextString = myList[1];
                        }
                        else if (attributeReference.Tag == "DREV1")
                        {
                            attributeReference.TextString = myList[2];
                        }
                        else if (attributeReference.Tag == "VREV1")
                        {
                            attributeReference.TextString = myList[3];
                        }
                        else if (attributeReference.Tag == "AREV1")
                        {
                            attributeReference.TextString = myList[4];
                        }
                        else if (attributeReference.Tag == "DATAREV1")
                        {
                            attributeReference.TextString = myList[5];
                        }
                        else if (attributeReference.Tag == "SREV1")
                        {
                            attributeReference.TextString = myList[6];
                        }
                    //}
                }
            }
        }

 


Think easier yet to use Dictionary or SortedList to update attributes, e.g. :

 [CommandMethod("attupd")]
public static void AttributeUpdate()
{
bool success = true;
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
try
{
// create options object
PromptSelectionOptions pso = new PromptSelectionOptions();
// add messages to options object
pso.MessageForRemoval = "\n\tSelect a block references only!";
pso.MessageForAdding = "\n\tSelect a block references >> ";
// create filter object for attributed block references:
SelectionFilter filter = new SelectionFilter(new TypedValue[] { new TypedValue(0, "insert"), new TypedValue(66, 1) });
// do selection
PromptSelectionResult psr = ed.GetSelection(pso, filter);
//check if selection is succeed
if (psr.Status != PromptStatus.OK) return;
using (DocumentLock docloc = doc.LockDocument())
{
using (Transaction tr = db.TransactionManager.StartTransaction())
{
// get an array of ObjectIds
ObjectId[] ids = psr.Value.GetObjectIds();
//tags
string[] tags = { "TAG1", "TAG2", "TAG3", "TAG4" };
//to your settings (check yourself):
// string[] tags = { "CREV1", "TREV1", "DREV1", "VREV1", "AREV1", "DATAREV1", ",", "SREV1" };
//values
string[] values = { "FirstValue", "SecondValue", "ThirdValue", "ForthValue" };
//populate a dictionary with data:
Dictionary<string, string> dict = FillDictionary(tags, values);
//execute update command
AttUpdFromDict(tr, ids, dict);
// commit transaction, will be disposed automatically because if it's inside the "Using{}" code block
tr.Commit();
}
}
// you might be want to dispaly a message here in case if the program was ended up succesfully
// ed.WriteMessage("Done");
}
catch (System.Exception ex)
{
success = false;
Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace);
}
finally
{
//do nothing or display your message here
ed.WriteMessage("\nCommand ended up with result of \"{0}\"",success==true? "Success": "Error");
}
}
public static Dictionary<string, string> FillDictionary(string[] tags, string[] values)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
if (tags.Length != values.Length)
{
throw new System.Exception("Arrays have a different number of elements. Error...");
}
for (int i = 0; i < tags.Length; i++)
{
dict.Add(tags[i], values[i]);
}
return dict;
}
public static void AttUpdFromDict(Transaction tr, ObjectId[] objectIdList, Dictionary<string, string> dict)
{
for (int i = 0; i < objectIdList.Length; i++)
{
ObjectId objectId = objectIdList[i];
BlockReference blockReference = (BlockReference)tr.GetObject(objectId, OpenMode.ForWrite);
foreach (ObjectId item in blockReference.AttributeCollection)
{
Entity ent = tr.GetObject(item, OpenMode.ForWrite, false) as Entity;
if (ent.GetType() == typeof(AttributeReference))
{
AttributeReference attRef = ent as AttributeReference;
if (dict.ContainsKey(attRef.Tag))
attRef.TextString = dict[attRef.Tag];
}
}
}
}

 

Active Contributor
NayaraFJ
Posts: 42
Registered: ‎08-11-2011
Message 2 of 5 (349 Views)

Re: Edit attributes within a block.

10-19-2011 06:25 AM in reply to: NayaraFJ
rivate void ChangingAttibutes1(ObjectId[] objectIdList)
        {
            for (int i = 0; i < objectIdList.Length; i++)
            {
                ObjectId objectId = objectIdList[i];
                BlockReference blockReference = (BlockReference)objectId.GetObject(OpenMode.ForWrite);
                BlockTableRecord blockTableRecord = (BlockTableRecord)blockReference.BlockTableRecord.GetObject(OpenMode.ForWrite);
                
                Entity Entity = null;

                foreach (ObjectId item in blockReference.AttributeCollection)
                {
                    Entity = transaction.GetObject(item, OpenMode.ForWrite) as Entity;
                    if (Entity.GetType() == typeof(AttributeReference))
                    {
                        AttributeReference attributeReference = Entity as AttributeReference;

                        if (attributeReference.Tag == "CREV1")
                        {
                            attributeReference.TextString = myList[0];
                        }
                        else if (attributeReference.Tag == "TREV1")
                        {
                            attributeReference.TextString = myList[1];
                        }
                        else if (attributeReference.Tag == "DREV1")
                        {
                            attributeReference.TextString = myList[2];
                        }
                        else if (attributeReference.Tag == "VREV1")
                        {
                            attributeReference.TextString = myList[3];
                        }
                        else if (attributeReference.Tag == "AREV1")
                        {
                            attributeReference.TextString = myList[4];
                        }
                        else if (attributeReference.Tag == "DATAREV1")
                        {
                            attributeReference.TextString = myList[5];
                        }
                        else if (attributeReference.Tag == "SREV1")
                        {
                            attributeReference.TextString = myList[6];
                        }
                    }
                }
            }
        }


 It worked! Thank you!

*Expert Elite*
Hallex
Posts: 1,569
Registered: ‎10-08-2008
Message 3 of 5 (313 Views)

Re: Edit attributes within a block.

10-23-2011 02:21 AM in reply to: NayaraFJ

Think easier yet to use Dictionary or SortedList to update attributes, e.g. :

         [CommandMethod("attupd")]
        public static void AttributeUpdate()
        {
            bool success = true;

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            try
            {
                // create options object

                PromptSelectionOptions pso = new PromptSelectionOptions();

                // add messages to options object

                pso.MessageForRemoval = "\n\tSelect a block references only!";

                pso.MessageForAdding = "\n\tSelect a block references >> ";

                // create filter object for attributed block references:

                SelectionFilter filter = new SelectionFilter(new TypedValue[] { new TypedValue(0, "insert"), new TypedValue(66, 1) });

                // do selection
                PromptSelectionResult psr = ed.GetSelection(pso, filter);

                //check if selection is succeed
                if (psr.Status != PromptStatus.OK) return;

                using (DocumentLock docloc = doc.LockDocument())
                {
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        // get an array of ObjectIds
                        ObjectId[] ids = psr.Value.GetObjectIds();

                        //tags
                        string[] tags = { "TAG1", "TAG2", "TAG3", "TAG4" };

                        //to your settings (check yourself):
                        // string[] tags = { "CREV1", "TREV1", "DREV1", "VREV1", "AREV1", "DATAREV1", ",", "SREV1" };

                        //values
                        string[] values = { "FirstValue", "SecondValue", "ThirdValue", "ForthValue" };

                        //populate a dictionary with data:
                        Dictionary<string, string> dict = FillDictionary(tags, values);

                        //execute update command
                        AttUpdFromDict(tr, ids, dict);    

                        // commit transaction, will be disposed automatically because if it's inside the "Using{}" code block
                        tr.Commit();
                    }
                }
                //  you might be want to dispaly a message here in case if the program was ended up succesfully
                //  ed.WriteMessage("Done");
            }


            catch (System.Exception ex)
            {
                success = false;
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
                //do nothing or display your message here
                ed.WriteMessage("\nCommand ended up with result of \"{0}\"",success==true? "Success": "Error");

            }
        }

        public static Dictionary<string, string> FillDictionary(string[] tags, string[] values)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();

            if (tags.Length != values.Length)
            {
                throw new System.Exception("Arrays have a different number of elements. Error...");

            }
            for (int i = 0; i < tags.Length; i++)
            {
                dict.Add(tags[i], values[i]);
            }
            return dict;
        }

        public static void AttUpdFromDict(Transaction tr, ObjectId[] objectIdList, Dictionary<string, string> dict)
        {
            for (int i = 0; i < objectIdList.Length; i++)
            {
                ObjectId objectId = objectIdList[i];

                BlockReference blockReference = (BlockReference)tr.GetObject(objectId, OpenMode.ForWrite);
                
                foreach (ObjectId item in blockReference.AttributeCollection)
                {
                    Entity ent = tr.GetObject(item, OpenMode.ForWrite, false) as Entity;

                    if (ent.GetType() == typeof(AttributeReference))
                    {
                        AttributeReference attRef = ent as AttributeReference;

                        if (dict.ContainsKey(attRef.Tag))
                            attRef.TextString = dict[attRef.Tag];
                    }
                }
            }
        }

 

_____________________________________
C6309D9E0751D165D0934D0621DFF27919
Active Contributor
NayaraFJ
Posts: 42
Registered: ‎08-11-2011
Message 4 of 5 (290 Views)

Re: Edit attributes within a block.

10-24-2011 02:57 AM in reply to: NayaraFJ

Thank you. I will adopt!

*Expert Elite*
Hallex
Posts: 1,569
Registered: ‎10-08-2008
Message 5 of 5 (285 Views)

Re: Edit attributes within a block.

10-24-2011 03:32 AM in reply to: NayaraFJ

You're welcome

Cheers :smileyhappy:

 

~'J'~

_____________________________________
C6309D9E0751D165D0934D0621DFF27919
Announcements
Are you familiar with the Autodesk Expert Elites? The Expert Elite program is made up of customers that help other customers by sharing knowledge and exemplifying an engaging style of collaboration. To learn more, please visit our Expert Elite website.
Need installation help?

Start with some of our most frequented solutions or visit the Installation and Licensing Forum to get help installing your software.