using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.GraphicsSystem;
using Autodesk.AutoCAD.Colors;
using ALD_DetailTools;
namespace ALD_DetailTools
{
internal class ConvertDetailGeometry
{
public static string SelectBlockFilePath()
{
using (OpenFileDialog openFileDialog
= new OpenFileDialog
()) {
var workingFolder = Path.GetDirectoryName(Active.Document.Name);
openFileDialog.InitialDirectory = workingFolder;
openFileDialog.Filter = ".dwg files (*.dwg)|*.dwg";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
Active.Editor.WriteMessage("\nPath: " + openFileDialog.FileName);
return (openFileDialog.FileName);
}
else
{
return null;
}
}
}
public static void InsertDetailBlock(string filePath)
{
using (Active.Document.LockDocument())
{
using (var sourceDb
= new Database
(false,
true)) {
sourceDb.ReadDwgFile(filePath, FileOpenMode.OpenForReadAndAllShare, true, null);
sourceDb.CloseInput(true);
using (var tr = Active.Document.TransactionManager.StartOpenCloseTransaction())
{
var sourceBlockTable = (BlockTable)tr.GetObject(sourceDb.BlockTableId, OpenMode.ForRead);
var sourceBlockTableRecord = (BlockTableRecord)tr.GetObject(sourceBlockTable[BlockTableRecord.ModelSpace], OpenMode.ForRead);
var currentBlockTable = (BlockTable)tr.GetObject(Active.Database.BlockTableId, OpenMode.ForWrite);
var currentBlockTableRecord = (BlockTableRecord)tr.GetObject(currentBlockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
foreach (ObjectId id in sourceBlockTableRecord)
{
var retrievedObject = tr.GetObject(id, OpenMode.ForRead);
Entity retrievedEntity = (Entity)retrievedObject.Clone();
try
{
currentBlockTableRecord.AppendEntity(retrievedEntity);
tr.AddNewlyCreatedDBObject(retrievedEntity, true);
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
Active.Editor.WriteMessage("\nFailed to append" +
retrievedEntity.ObjectId +
" " +
ex.Message);
}
}
tr.Commit();
}
}
}
}
}
}