using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.Civil.DatabaseServices;
using AcDb = Autodesk.AutoCAD.DatabaseServices;
namespace C3dTest
{
public class TestNetSCatsExtData
{
[CommandMethod("AddNetExtData")]
public void AddData()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
PromptEntityOptions entOpts = new PromptEntityOptions("\nSelect part: ");
entOpts.SetRejectMessage("\nThis is not part!");
entOpts.AddAllowedClass(typeof(Part), false);
PromptEntityResult entRes = ed.GetEntity(entOpts);
if (entRes.Status != PromptStatus.OK) return;
PromptResult stringRes = ed.GetString("\nString value: ");
if (stringRes.Status != PromptStatus.OK) return;
PromptDoubleResult doubleRes = ed.GetDouble("\nDouble value: ");
if (doubleRes.Status != PromptStatus.OK) return;
ObjectId netId;
using (Part part = entRes.ObjectId.Open(OpenMode.ForRead) as Part)
{
netId = part.NetworkId;
}
AddCustomData
(netId,
"CustomData",
new TypedValue((int)DxfCode.Text, stringRes.StringResult),
new TypedValue((int)DxfCode.Real, doubleRes.Value));
AddXData
(netId, "CustomData",
new TypedValue((int)DxfCode.ExtendedDataAsciiString, stringRes.StringResult),
new TypedValue((int)DxfCode.ExtendedDataReal, doubleRes.Value));
}
static void AddCustomData(ObjectId id, string key, params TypedValue[] values)
{
Database db = id.Database;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
AcDb.DBObject obj = tr.GetObject(id, OpenMode.ForRead);
ObjectId dictId = obj.ExtensionDictionary;
if (dictId == ObjectId.Null)
{
obj.UpgradeOpen();
obj.CreateExtensionDictionary();
dictId = obj.ExtensionDictionary;
}
DBDictionary xdict = (DBDictionary)tr.GetObject(dictId, OpenMode.ForRead);
Xrecord xrec;
if (xdict.Contains(key))
{
xrec = (Xrecord)tr.GetObject((ObjectId)xdict[key], OpenMode.ForWrite);
}
else
{
xdict.UpgradeOpen();
xrec = new Xrecord();
xdict.SetAt(key, xrec);
tr.AddNewlyCreatedDBObject(xrec, true);
}
xrec.Data = new ResultBuffer(values);
tr.Commit();
}
}
static void AddXData(ObjectId id, string appName, params TypedValue[] values)
{
Database db = id.Database;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
AcDb.DBObject obj = tr.GetObject(id, OpenMode.ForWrite);
AddRegAppTableRecord(db, appName);
using (ResultBuffer rb = new ResultBuffer(new TypedValue(1001, appName)))
{
foreach (TypedValue tVal in values)
{
rb.Add(tVal);
}
obj.XData = rb;
}
tr.Commit();
}
}
static void AddRegAppTableRecord(Database db, string regAppName)
{
using (Transaction tr = db.TransactionManager.StartTransaction())
{
RegAppTable table = tr.GetObject
(db.RegAppTableId, OpenMode.ForRead) as RegAppTable;
if (!table.Has(regAppName))
{
table.UpgradeOpen();
RegAppTableRecord record = new RegAppTableRecord();
record.Name = regAppName;
table.Add(record);
tr.AddNewlyCreatedDBObject(record, true);
}
tr.Commit();
}
}
}
}