I want to insert a blockreference with attibutes.
The following are the codes:
public class Class1
{
[CommandMethod("INSRTBLK")]
public void InsertBlk()
{
Database curDb = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
PromptResult stringRes = ed.GetString("\nEnter Block Name: ");
string blkName = stringRes.StringResult;
if (stringRes.Status != PromptStatus.OK && blkName.Length == 0)
{
ed.WriteMessage("\nInvalid block name.");
return;
}
DBTrans tm = curDb.TransactionManager;
using (Transaction trans = tm.StartTransaction())
{
BlockTable blkTable = (BlockTable)tm.GetObject(curDb.BlockTableId, OpenMode.ForRead);
if (blkTable.Has(blkName) == false)
{
ed.WriteMessage(string.Format("\nBlock definition {0} not found. ", blkName));
return;
}
ObjectId blkId = blkTable[blkName];
BlockTableRecord blkTableRecord = (BlockTableRecord)tm.GetObject(blkTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
PromptPointOptions pointOpt = new PromptPointOptions("\nPick insertion point: ");
pointOpt.AllowNone = false;
PromptPointResult pointRes = ed.GetPoint(pointOpt);
BlockReference insrtObj = new BlockReference(pointRes.Value, blkId);
BlockTableRecord blkDefRecord = (BlockTableRecord)tm.GetObject(blkId, OpenMode.ForRead);
if (blkDefRecord.HasAttributeDefinitions)
{
foreach (ObjectId defId in blkDefRecord)
{
AttributeDefinition attDef = tm.GetObject(defId, OpenMode.ForRead) as AttributeDefinition;
if (attDef != null && attDef.Constant == false)
{
AttributeReference att = new AttributeReference();
att.SetPropertiesFrom(attDef);
att.Invisible = attDef.Invisible;
Point3d basePt = attDef.Position;
basePt = basePt + insrtObj.Position.GetAsVector();
att.Position = basePt;
att.Height = attDef.Height;
att.Rotation = attDef.Rotation;
string tagPrompt = attDef.Tag;
att.Tag = tagPrompt;
tagPrompt = attDef.Prompt;
ed.WriteMessage(string.Format("{0}{1}", "\n", tagPrompt));
att.FieldLength = 25;
att.TextString = "This is a test";
insrtObj.AttributeCollection.AppendAttribute(att);
}
}
}
blkTableRecord.AppendEntity(insrtObj);
tm.AddNewlyCreatedDBObject(insrtObj, true);
trans.Commit();
}
}
}
But when i run it in the AutoCAD,I get the errors:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Autodesk.AutoCAD.Runtime.Exception: eNoDatabase