Example #7 Continued - Various Database examples
These methods were in the DatabaseExamples class from the previous post, but I had to remove them in order to shorten the post to the required size limit. Put these back in the class.
Code:
//Page 15 lists the steps, Page 17 lists the code
//Adding objects to a database
//The six steps revealed!
[CommandMethod("CreateCircle")]
public void DrawCircle ()
{
//Step one - Start a transaction
using (Transaction trans = StartActiveDatabaseTransaction())
{
//Step two - Create the new object
Circle newCircle = CreateCircle();
//Step three - Open the symbol table
BlockTableRecord modelSpace = OpenActiveModelSpaceForWrite(trans);
//Step four - Append the object to the symbol table
modelSpace.AppendEntity(newCircle);
//Step five - Inform the transactionmanager of the new object
trans.TransactionManager.AddNewlyCreatedDBObject(newCircle, true);
//Step six - Commit the transaction
trans.Commit();
}
}
private Transaction StartActiveDatabaseTransaction()
{
return HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction();
}
private Circle CreateCircle()
{
Point3d centerPoint = new Point3d(0, 0, 0);
Vector3d normal = new Vector3d(0, 0, 1);
double radius = 4.5;
return new Circle(centerPoint, normal, radius);
}
private BlockTableRecord OpenActiveModelSpaceForWrite(Transaction trans)
{
return (BlockTableRecord)trans.GetObject(GetActiveModelSpaceId(), OpenMode.ForWrite);
}
private ObjectId GetActiveModelSpaceId ()
{
using (Transaction trans = StartActiveDatabaseTransaction())
{
BlockTable bt = (BlockTable)trans.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead);
return (ObjectId) bt[BlockTableRecord.ModelSpace];
}
}
//Page 16
//Adding non graphic objects
//Variations of the six steps
public static ObjectId CreateLayer(string layerName, Database targetDatabase)
{
//Step one - Start a transaction
using (Transaction trans =targetDatabase.TransactionManager.StartTransaction())
{
ObjectId layerTableId = targetDatabase.LayerTableId;
//Step three - Open the symbol table
//This table has only been opened for reading
LayerTable layers = (LayerTable)trans.GetObject(layerTableId, OpenMode.ForRead);
if (layers.Has(layerName))
{
return layers[layerName];
}
else
{
//Step two - Create the new object
LayerTableRecord newLayer = new LayerTableRecord();
newLayer.Name = layerName;
//Step three - Open the symbol table for writing
layers.UpgradeOpen();
//Step four - Append the object to the symbol table
layers.Add(newLayer);
//Step five - Inform the transactionmanager of the new object
trans.TransactionManager.AddNewlyCreatedDBObject(newLayer, true);
//Step six - Commit the transaction
trans.Commit();
return newLayer.ObjectId;
}
}
}
[CommandMethod("CreateLayer")]
public void CreateLayer()
{
string newLayerName = "AU2005";
CreateLayer(newLayerName, HostApplicationServices.WorkingDatabase);
}