I'm struggling with copying objects from one db into a new one, I have done very little with Documents and new db's , blocks etc so any help would be great.
It works but if I open the new drawing with objects that contained xdata in the original there are errors.
Will this mean I need to 'deep' clone? I'll give it a go anyhow and see how it goes.
Here's what I have so far -
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.GraphicsInterface;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Windows.ToolPalette;
namespace copytester
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class Class1
{
[CommandMethod("TESTCOPY")]
public static void CopyToNewDb()
{
Editor ed =
Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
//Get an entiy to copy to new drg:
PromptEntityResult res = ed.GetEntity("\nSelect an entity to copy to new drg:");
if(res.Status == PromptStatus.Cancel || res.Status != PromptStatus.OK)
return;
Database db = HostApplicationServices.WorkingDatabase;
Transaction tr = db.TransactionManager.StartTransaction();
try
{
//Get the ent to copy:
Entity ent = tr.GetObject(res.ObjectId,OpenMode.ForWrite) as Entity;
if(ent == null)
return;
//new db from template, new trans:
Database newdb = new Database(false,true);
newdb.ReadDwgFile(@"C:\DCS_3D\dcs_std.dwt", System.IO.FileShare.None, false,null);
Transaction tr2 = newdb.TransactionManager.StartTransaction();
try
{
BlockTable bt = tr2.GetObject(newdb.BlockTableId, OpenMode.ForRead, false) as BlockTable;
BlockTableRecord btr = tr2.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
if(btr == null)
return;
//copy our entity to make a new ent to add to new db:
Entity newent = ent.Clone() as Entity;
//append entity to new db:
if(newent == null)
return;
btr.AppendEntity(newent);
tr2.AddNewlyCreatedDBObject(newent,true);
//use existing ent handle for now for drg names:
string filename = @"C:\DCS_3D\testdrgs\drg" + ent.Handle.Value.ToString() + ".dwg";
newdb.SaveAs(filename,null);
tr2.Commit();
}
finally
{
tr2.Dispose();
newdb.Dispose();
}
tr.Commit();
}
finally
{
tr.Dispose();
}
}
}
}