Author Topic: How to insert multiline attributes  (Read 1452 times)

0 Members and 1 Guest are viewing this topic.

Offline fixo

  • Full Member
  • ***
  • Posts: 135
  • Karma: +4/-0
  • Gender: Male
    • prefered language: C
    • Prog expertise: Good
    • View Profile
How to insert multiline attributes
« on: January 09, 2013, 08:07:58 PM »

Code: [Select]
        // based on code example from article by by Gopinath Taget here:
        //  http://adndevblog.typepad.com/autocad/2013/01/how-to-mimic-the-autocad-insert-command-in-arx-without-acedcommand-call.html

        [CommandMethod("testInsertCommand", "doi", CommandFlags.UsePickSet | CommandFlags.Redraw)]
        public static void DoInsert()
        {

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

            Editor ed = doc.Editor;

            Database db = doc.Database;
            // set your block name here
            string blockName = "UserName";

            ObjectId blockId;
            // dictionary to store pairs of tag-string
            Dictionary<string, string> dict = new Dictionary<string, string>();
            //populate dictionary with exact values to your block
            string[,] pairs = new string[,] { { "TAG1", "VALUE 1" },
            { "TAG2", "VALUE 2" },
            { "TAG3", "VALUE 3" },
            { "TAG4",
          "Some text in the default colour...\\P" +
          "{\\C1;Something red}\\P" +
          "{\\C2;Something yellow}\\P" +
          "{\\C3;And} {\\C4;something cyan}" } };

            for (int i=0;i<=pairs.GetUpperBound(0);i++)
                dict.Add(pairs[i,0], pairs[i,1]);
            //------------------------------------------------------------
            //  debug only:
            //  foreach (KeyValuePair<string, string> kvp in dict)
            //    ed.WriteMessage("\n{0}\t{1}\n", kvp.Key, kvp.Value);
            //------------------------------------------------------------

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                if (!bt.Has(blockName)) return;
                blockId = bt[blockName];
               
                PromptPointOptions ppo = new PromptPointOptions("\nPlease specify insertion point of block: ");
                PromptPointResult ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK) return;
                Point3d basePoint = ppr.Value;
                AddBlockWithAttributes(db, dict, blockId, basePoint);         
                tr.Commit();
                ed.UpdateScreen();
            }

        }


        //Here is the code for addBlockWithAttributes:

        // NOTE: You will have to update the code to properly set the

        // attribute values. The code below sets the value of each

        // attribute from dictionary.

        static public void AddBlockWithAttributes(Database db, Dictionary<string, string> dict, ObjectId blockId, Point3d basePoint)
        {
            try
            {
                Transaction tr = db.TransactionManager.StartTransaction();

                using (tr)
                {
                    //----- Step 1: Allocate a block reference object

                    BlockReference bref = new BlockReference(basePoint, blockId);

                    //----- Step 2: Set up the block reference to the newly

                    //----- created block definition

                    // pBlkRef.BlockTableRecord =blockId ;

                    //---- Give it the current UCS normal.

                    bref.Rotation = 0.0;

                    bref.Normal = new Vector3d(0.0, 0.0, 1.0);

                    //----- Step 3: Open current database's Model Space

                    //----- blockTableRecord

                    BlockTable bt;

                    BlockTableRecord btr;

                    bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                    btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                    //----- Append the block reference to the model space

                    //----- block table record

                    ObjectId newEntId;

                    newEntId = btr.AppendEntity(bref);

                    tr.AddNewlyCreatedDBObject(bref, true);

                    //----- Step 4: Open the block definition for read

                    BlockTableRecord blkDef;

                    blkDef = (BlockTableRecord)tr.GetObject(blockId, OpenMode.ForRead);

                    Entity ent;

                    AttributeDefinition attDef;

                    AttributeCollection attColl = bref.AttributeCollection;

                    foreach (ObjectId id in blkDef)
                    {
                        // Commented, you can use 'foreach' instead:
                        // BlockTableRecordEnumerator ienum = blkDef.GetEnumerator();
                        //while (ienum.MoveNext())
                        //{

                        //----- Get the next entity

                        // ent = (Entity)tr.GetObject(ienum.Current, OpenMode.ForRead);// commented
                        ent = (Entity)tr.GetObject(id, OpenMode.ForRead);
                        //----- Make sure the entity is an attribute definition

                        //----- and not a constant

                        attDef = ent as AttributeDefinition;

                        if (attDef != null && !attDef.Constant)
                        {

                            //----- We have a non-constant attribute definition

                            //----- so build an attribute entity

                            AttributeReference attRef = new AttributeReference();

                          //  attRef.SetAttributeFromBlock(attDef, bref.BlockTransform);

                            attRef.SetPropertiesFrom(attDef);

                            attRef.Visible = attDef.Visible;

                            //----- Translate attribute by block reference.

                            //----- To be really correct, entire block

                            //----- reference transform should be applied here.

                            basePoint = attDef.Position;

                            basePoint += bref.Position.GetAsVector();

                            attRef.Position = basePoint;

                            attRef.Height = attDef.Height;

                            attRef.Rotation = attDef.Rotation;

                            attRef.Tag = attDef.Tag;

                            attRef.FieldLength = attDef.FieldLength;

                            //----- Database Column value should be displayed

                            //----- INSERT would prompt for this...

                            //------ Update attribute value from dictionary by tag
                            if (attDef.IsMTextAttributeDefinition)
                            {
                                attRef.IsMTextAttribute = true;
                             
                                attRef.TextString = dict[attDef.Tag.ToUpper()];
                                attRef.ForceAnnoAllVisible = true;
                                attRef.UpdateMTextAttribute();
                               
                            }
                            else
                            {
                                attRef.TextString = dict[attDef.Tag.ToUpper()];
                            }
                            //----- Set Alignments

                            attRef.HorizontalMode = attDef.HorizontalMode;

                            attRef.VerticalMode = attDef.VerticalMode;

                            attRef.AdjustAlignment(db);
                            //----- Insert the attribute in the DWG

                            attColl.AppendAttribute(attRef);


                        }
                    }

                    bref.RecordGraphicsModified(true);//    optional
                   
                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                // MessageBox.Show(string.Format("Error: {0}\nTrace: {1}", ex.Message, ex.StackTrace));
                Console.WriteLine(string.Format("Error: {0}\nTrace: {1}", ex.Message, ex.StackTrace));
            }
            finally { }
        }

Offline bcinnv

  • Newbie
  • *
  • Posts: 9
  • Karma: +0/-0
    • prefered language: VB
    • Prog expertise: Good
    • View Profile
Re: How to insert multiline attributes
« Reply #1 on: November 18, 2013, 02:30:59 PM »
Thanks bud! You always have the answer :)