June 14, 2007

Creating a table of block attributes in AutoCAD using .NET - Part 1

This post was inspired by suggestions from a few different people (you know who you are! :-). I'm going to take it in two parts: this post will focus on creating a table automatically that lists the values of attribute references included in block references in the modelspace that point to a particular block table record selected by the user. Phew. The next post will add some functionality to create a "total" of one of the columns in the table we create, by using a table formula that performs a sum of the appropriate cells.

The below code is actually quite similar in behaviour to the Table sample on the ObjectARX SDK and also the EATTEXT command inside AutoCAD - both of which will help you create tables from block attributes. I wrote this code in AutoCAD 2007 (and it should work just fine in 2008, also). I haven't tested against prior versions.

One item of note is the ability to either embed or link the data placed in the table. "Embedding" means we just take a copy of the attribute values and place them as plain text in the cells; "linking" means we use a field to create a reference from the cell to the attribute's value (using the technique shown in the previous post).

The code is quite lengthy, but I've done my best to comment it to make it more clear what's going on. Here's the C# code:

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Geometry;

using Autodesk.AutoCAD.Runtime;

using System.Collections.Specialized;

using System;

namespace TableCreation

{

publicclassCommands

{

// Set up some formatting constants

// for the table

constdouble colWidth = 15.0;

constdouble rowHeight = 3.0;

constdouble textHeight = 1.0;

constCellAlignment cellAlign =

CellAlignment.MiddleCenter;

// Helper function to set text height

// and alignment of specific cells,

// as well as inserting the text

staticpublicvoid SetCellText(

Table tb,

int row,

int col,

string value

)

{

tb.SetAlignment(row, col, cellAlign);

tb.SetTextHeight(row, col, textHeight);

tb.SetTextString(row, col, value);

}

[CommandMethod("BAT")]

staticpublicvoid BlockAttributeTable()

{

Document doc =

Application.DocumentManager.MdiActiveDocument;

Database db = doc.Database;

Editor ed = doc.Editor;

// Ask for the name of the block to find

PromptStringOptions opt =

newPromptStringOptions(

"\nEnter name of block to list: "

);

PromptResult pr = ed.GetString(opt);

if (pr.Status == PromptStatus.OK)

{

string blockToFind =

pr.StringResult.ToUpper();

bool embed = false;

// Ask whether to embed or link the data

PromptKeywordOptions pko =

newPromptKeywordOptions(

"\nEmbed or link the attribute values: "

);

pko.AllowNone = true;

pko.Keywords.Add("Embed");

pko.Keywords.Add("Link");

pko.Keywords.Default = "Embed";

PromptResult pkr =

ed.GetKeywords(pko);

if (pkr.Status == PromptStatus.None ||

pkr.Status == PromptStatus.OK)

{

if (pkr.Status == PromptStatus.None ||

pkr.StringResult == "Embed")

embed = true;

else

embed = false;

}

Transaction tr =

doc.TransactionManager.StartTransaction();

using (tr)

{

// Let's check the block exists

BlockTable bt =

(BlockTable)tr.GetObject(

doc.Database.BlockTableId,

OpenMode.ForRead

);

if (!bt.Has(blockToFind))

{

ed.WriteMessage(

"\nBlock "

+ blockToFind

+ " does not exist."

);

}

else

{

// And go through looking for

// attribute definitions

StringCollection colNames =

newStringCollection();

BlockTableRecord bd =

(BlockTableRecord)tr.GetObject(

bt[blockToFind],

OpenMode.ForRead

);

foreach (ObjectId adId in bd)

{

DBObject adObj =

tr.GetObject(

adId,

OpenMode.ForRead

);

// For each attribute definition we find...

AttributeDefinition ad =

adObj asAttributeDefinition;

if (ad != null)

{

// ... we add its name to the list

colNames.Add(ad.Tag);

}

}

if (colNames.Count == 0)

{

ed.WriteMessage(

"\nThe block "

+ blockToFind

+ " contains no attribute definitions."

);

}

else

{

// Ask the user for the insertion point

// and then create the table

PromptPointResult ppr =

ed.GetPoint(

"\nEnter table insertion point: "

);

if (ppr.Status == PromptStatus.OK)

{

Table tb = newTable();

tb.TableStyle = db.Tablestyle;

tb.NumRows = 1;

tb.NumColumns = colNames.Count;

tb.SetRowHeight(rowHeight);

tb.SetColumnWidth(colWidth);

tb.Position = ppr.Value;

// Let's add our column headings

for (int i = 0; i < colNames.Count; i++)

{

SetCellText(tb, 0, i, colNames[i]);

}

// Now let's search for instances of

// our block in the modelspace

BlockTableRecord ms =

(BlockTableRecord)tr.GetObject(

bt[BlockTableRecord.ModelSpace],

OpenMode.ForRead

);

int rowNum = 1;

foreach (ObjectId objId in ms)

{

DBObject obj =

tr.GetObject(

objId,

OpenMode.ForRead

);

BlockReference br =

obj asBlockReference;

if (br != null)

{

BlockTableRecord btr =

(BlockTableRecord)tr.GetObject(

br.BlockTableRecord,

OpenMode.ForRead

);

using (btr)

{

if (btr.Name.ToUpper() == blockToFind)

{

// We have found one of our blocks,

// so add a row for it in the table

tb.InsertRows(

rowNum,

rowHeight,

1

);

// Assume that the attribute refs

// follow the same order as the

// attribute defs in the block

int attNum = 0;

foreach (

ObjectId arId in

br.AttributeCollection

)

{

DBObject arObj =

tr.GetObject(

arId,

OpenMode.ForRead

);

AttributeReference ar =

arObj asAttributeReference;

if (ar != null)

{

// Embed or link the values

string strCell;

if (embed)

{

strCell = ar.TextString;

}

else

{

string strArId =

arId.ToString();

strArId =

strArId.Trim(

newchar[] { '(', ')' }

);

strCell =

"%<\\AcObjProp Object("

+ "%<\\_ObjId "

+ strArId

+ ">%).TextString>%";

}

SetCellText(

tb,

rowNum,

attNum,

strCell

);

}

attNum++;

}

rowNum++;

}

}

}

}

tb.GenerateLayout();

ms.UpgradeOpen();

ms.AppendEntity(tb);

tr.AddNewlyCreatedDBObject(tb, true);

tr.Commit();

}

}

}

}

}

}

}

}

To test the code, I created a block called "DATA" containing attribute definitions for NAME, PARTNUM, MATERIAL and COST. I then created blocks corresponding to the data we had previously hard-coded.

Here's what happens when I used the BAT command on this data to create two tables - the top with "embedded" values, the bottom with them "linked":

In the next post we'll add a "Total" row at the bottom of the table, and use a formula to calculate the sum of a particular column (the logical one being COST, as it's numerical).