using System;
using System.Diagnostics.Eventing.Reader;
using System.IO;
using System.Reflection;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using BDuct_Global;
namespace BDuct
{
public class AutoCADFunctions
{
public static void InsertBlock(string blockName)
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
using (var tr = db.TransactionManager.StartTransaction())
{
// Get the ObjectId of the block definition
var btrId = GetBlock(blockName, db);
if (btrId.IsNull)
{
ed.WriteMessage($"\nBlock '{blockName}' not found.");
return;
}
// Create a block reference
using (var ghost
= new BlockReference
(Point3d
.Origin, btrId
)) {
Main main = GlobalVariables.MainWindow;
//string ObjLayer = main.Duct_Type.SelectedNode.Tag.ToString();
//ghost.Layer = ObjLayer;
var cLtScale = db.Ltscale;
ghost.TransformBy(ed.CurrentUserCoordinateSystem);
SetDynamicProperties(ghost, 40.0);
// Insert and rotate a new 'blockName' reference
var insertJig
= new InsertBlockJig
(ghost
); // Set dynamic properties (except "DUCT_1")
var promptResult = ed.Drag(insertJig);
if (promptResult.Status == PromptStatus.OK)
{
DynamicBlockReferenceProperty property = GetProperty(ghost, "DUCT_1");
if (property == null)
{
property = GetProperty(ghost, "LENGTH");
}
db.Ltscale = 10000;
SetDynamicProperties(ghost, -1);
var rotateJig
= new RotateResizeBlockJig
(ghost, property
); promptResult = ed.Drag(rotateJig);
if (promptResult.Status == PromptStatus.OK)
{
var currentSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
var br
= new BlockReference
(ghost
.Position, btrId
) { Rotation
= ghost
.Rotation }; currentSpace.AppendEntity(br);
tr.AddNewlyCreatedDBObject(br, true);
SetDynamicProperties(br, rotateJig.Distance);
//br.Layer = ObjLayer;
}
}
db.Ltscale = cLtScale;
tr.Commit();
}
}
}
public static void SetDynamicProperties(BlockReference br, double distance)
{
Main main = GlobalVariables.MainWindow;
double NewValue = 6;
foreach (DynamicBlockReferenceProperty prop in br.DynamicBlockReferencePropertyCollection)
{
if (!prop.ReadOnly) // Replace "YourDynamicProperty"
{
switch (prop.PropertyName)
{
case "DUCT_1" or "LENGTH":
if (distance > 0)
{
if ((double)prop.Value != distance)
{
prop.Value = distance;
}
}
break;
case "SIZE_1" or "SIZE_1_WIDTH":
if (main
.Insulation_Clear.Checked == true && main
.Insulation_Internal.Checked == true) {
NewValue = Convert.ToDouble((double)main.Dim_Width.Value % double.MaxValue) + (Convert.ToDouble((double)main.Insulation_Internal_SetSize.Value % double.MaxValue) * 2);
}
else
{
NewValue = Convert.ToDouble((double)main.Dim_Width.Value % double.MaxValue);
}
if ((double)prop.Value != NewValue)
{
prop.Value = NewValue;
}
break;
case "SIZE_1_HEIGHT":
if (main
.Insulation_Clear.Checked == true && main
.Insulation_Internal.Checked == true) {
NewValue = Convert.ToDouble((double)main.Dim_Height.Value % double.MaxValue) + (Convert.ToDouble((double)main.Insulation_Internal_SetSize.Value % double.MaxValue) * 2);
}
else
{
NewValue = Convert.ToDouble((double)main.Dim_Height.Value % double.MaxValue);
}
if ((double)prop.Value != NewValue)
{
prop.Value = NewValue;
}
break;
case "INSULATION":
string NewValue_Ins = "EXTERNAL";
if (main
.Insulation_External.Checked == true && main
.Insulation_Internal.Checked == true) {
NewValue_Ins = "BOTH";
}
else
{
if(main
.Insulation_External.Checked == true) {
NewValue_Ins = "EXTERNAL";
}
else
{
if(main
.Insulation_Internal.Checked == true) {
NewValue_Ins = "INTERNAL";
}
else
{
NewValue_Ins = "NONE";
}
}
}
if ((string)prop.Value != NewValue_Ins)
{
prop.Value = NewValue_Ins;
}
break;
case "INSULATION_INTERNAL":
NewValue = Convert.ToDouble((double)main.Insulation_Internal_SetSize.Value % double.MaxValue);
if ((double)prop.Value != NewValue)
{
prop.Value = NewValue;
}
break;
case "INSULATION_EXTERNAL":
NewValue = Convert.ToDouble((double)main.Insulation_External_SetSize.Value % double.MaxValue);
if ((double)prop.Value != NewValue)
{
prop.Value = NewValue;
}
break;
default:
break;
}
}
}
}
private static ObjectId GetBlock(string blockName, Database db)
{
// Search in the drawing BlockTable
var blockTable = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead);
if (blockTable.Has(blockName))
{
return blockTable[blockName];
}
// Search in the current directory
string fileName = Path.Combine(Directory.GetCurrentDirectory(), $@"Blocks\{blockName}.dwg");
if (File.Exists(fileName))
{
using (var xDb
= new Database
(false,
true)) {
xDb.ReadDwgFile(fileName, FileOpenMode.OpenForReadAndAllShare, true, null);
return db.Insert(fileName, xDb, true);
}
}
// Search in the Support File Search Paths
try
{
fileName = HostApplicationServices.Current.FindFile($@"{blockName}.dwg", db, FindFileHint.Default);
using (var xDb
= new Database
(false,
true)) {
xDb.ReadDwgFile(fileName, FileOpenMode.OpenForReadAndAllShare, true, null);
return db.Insert(blockName, xDb, true);
}
}
catch { return ObjectId.Null; }
}
private static DynamicBlockReferenceProperty GetProperty(BlockReference br, string propertyName)
{
foreach (DynamicBlockReferenceProperty property in br.DynamicBlockReferencePropertyCollection)
{
if (propertyName.Equals(property.PropertyName, StringComparison.CurrentCultureIgnoreCase))
{
return property;
}
}
return null;
}
}
internal class InsertBlockJig : EntityJig
{
protected Point3d dragPoint;
protected BlockReference br;
public InsertBlockJig(BlockReference br)
: base(br)
{
this.br = br;
}
protected override SamplerStatus Sampler(JigPrompts prompts)
{
var options
= new JigPromptPointOptions
("\nSpecify insertion point: "); options.UserInputControls =
UserInputControls.Accept3dCoordinates
| UserInputControls.UseBasePointElevation
| UserInputControls.GovernedByOrthoMode
| UserInputControls.NoDwgLimitsChecking
| UserInputControls.NoNegativeResponseAccepted
| UserInputControls.NoZeroResponseAccepted;
var result = prompts.AcquirePoint(options);
if (dragPoint.IsEqualTo(result.Value))
return SamplerStatus.NoChange;
dragPoint = result.Value;
return SamplerStatus.OK;
}
protected override bool Update()
{
br.Position = dragPoint;
AutoCADFunctions.SetDynamicProperties(br, -1);
return true;
}
}
internal class RotateResizeBlockJig : EntityJig
{
protected BlockReference br;
protected Point3d dragPoint;
protected Plane plane;
protected DynamicBlockReferenceProperty property;
public double Distance => br.Position.DistanceTo(dragPoint);
public RotateResizeBlockJig(BlockReference br, DynamicBlockReferenceProperty property)
: base(br)
{
this.br = br;
this.property = property;
plane
= new Plane
(Point3d
.Origin, br
.Normal); }
protected override SamplerStatus Sampler(JigPrompts prompts)
{
var options
= new JigPromptPointOptions
("\nSpecify End Point: "); options.UseBasePoint = true;
options.BasePoint = br.Position;
options.Cursor = CursorType.RubberBand;
options.UserInputControls =
UserInputControls.Accept3dCoordinates
| UserInputControls.UseBasePointElevation
| UserInputControls.GovernedByOrthoMode
| UserInputControls.NoDwgLimitsChecking
| UserInputControls.NoNegativeResponseAccepted
| UserInputControls.NoZeroResponseAccepted;
var result = prompts.AcquirePoint(options);
if (dragPoint.IsEqualTo(result.Value))
{
return SamplerStatus.NoChange;
}
else
{
dragPoint = result.Value;
}
property.Value = Distance;
return SamplerStatus.OK;
}
protected override bool Update()
{
AutoCADFunctions.SetDynamicProperties(br, -1);
br.Rotation = br.Position.GetVectorTo(dragPoint).AngleOnPlane(plane);
return true;
}
}
}