Compare commits

...

3 Commits

Author SHA1 Message Date
aj 32e8379e9b refactor: extract CutTemplate from BomItem for all-item BOM tracking
BomItems are now created for every BOM item regardless of whether they
produce a DXF. Sheet metal cut data (thickness, k-factor, bend radius,
DXF path, content hash) moved to a new CutTemplate entity with a 1:1
optional relationship. Non-sheet-metal items are counted as "skipped"
instead of "failed" in the export summary. Added Cut Templates tab to
the UI with a DataGridView for viewing cut template records.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 15:32:17 -05:00
aj 0ace378eff docs: update README to reflect local export and .NET 8 migration
Remove CutFab API references and document the current architecture:
local file export, SQL Server tracking, and .NET 8.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 22:35:41 -05:00
aj 697463f61e feat: disable SolidWorks user input during export
Sets CommandInProgress to block user interaction with SolidWorks
while the DXF export is running, preventing accidental interference.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 22:32:12 -05:00
11 changed files with 883 additions and 95 deletions
+13
View File
@@ -8,6 +8,7 @@ namespace ExportDXF.Data
{ {
public DbSet<ExportRecord> ExportRecords { get; set; } public DbSet<ExportRecord> ExportRecords { get; set; }
public DbSet<BomItem> BomItems { get; set; } public DbSet<BomItem> BomItems { get; set; }
public DbSet<CutTemplate> CutTemplates { get; set; }
public ExportDxfDbContext() : base() public ExportDxfDbContext() : base()
{ {
@@ -38,6 +39,7 @@ namespace ExportDXF.Data
entity.Property(e => e.SourceFilePath).HasMaxLength(500); entity.Property(e => e.SourceFilePath).HasMaxLength(500);
entity.Property(e => e.OutputFolder).HasMaxLength(500); entity.Property(e => e.OutputFolder).HasMaxLength(500);
entity.Property(e => e.ExportedBy).HasMaxLength(100); entity.Property(e => e.ExportedBy).HasMaxLength(100);
entity.Property(e => e.PdfContentHash).HasMaxLength(64);
entity.HasMany(e => e.BomItems) entity.HasMany(e => e.BomItems)
.WithOne(b => b.ExportRecord) .WithOne(b => b.ExportRecord)
@@ -54,7 +56,18 @@ namespace ExportDXF.Data
entity.Property(e => e.PartName).HasMaxLength(200); entity.Property(e => e.PartName).HasMaxLength(200);
entity.Property(e => e.ConfigurationName).HasMaxLength(100); entity.Property(e => e.ConfigurationName).HasMaxLength(100);
entity.Property(e => e.Material).HasMaxLength(100); entity.Property(e => e.Material).HasMaxLength(100);
entity.HasOne(e => e.CutTemplate)
.WithOne(ct => ct.BomItem)
.HasForeignKey<CutTemplate>(ct => ct.BomItemId)
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<CutTemplate>(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.CutTemplateName).HasMaxLength(100); entity.Property(e => e.CutTemplateName).HasMaxLength(100);
entity.Property(e => e.ContentHash).HasMaxLength(64);
}); });
} }
} }
+43 -13
View File
@@ -36,6 +36,8 @@ namespace ExportDXF.Forms
logEventsDataGrid = new System.Windows.Forms.DataGridView(); logEventsDataGrid = new System.Windows.Forms.DataGridView();
bomTab = new System.Windows.Forms.TabPage(); bomTab = new System.Windows.Forms.TabPage();
bomDataGrid = new System.Windows.Forms.DataGridView(); bomDataGrid = new System.Windows.Forms.DataGridView();
cutTemplatesTab = new System.Windows.Forms.TabPage();
cutTemplatesDataGrid = new System.Windows.Forms.DataGridView();
equipmentBox = new System.Windows.Forms.ComboBox(); equipmentBox = new System.Windows.Forms.ComboBox();
label1 = new System.Windows.Forms.Label(); label1 = new System.Windows.Forms.Label();
label2 = new System.Windows.Forms.Label(); label2 = new System.Windows.Forms.Label();
@@ -45,12 +47,14 @@ namespace ExportDXF.Forms
((System.ComponentModel.ISupportInitialize)logEventsDataGrid).BeginInit(); ((System.ComponentModel.ISupportInitialize)logEventsDataGrid).BeginInit();
bomTab.SuspendLayout(); bomTab.SuspendLayout();
((System.ComponentModel.ISupportInitialize)bomDataGrid).BeginInit(); ((System.ComponentModel.ISupportInitialize)bomDataGrid).BeginInit();
cutTemplatesTab.SuspendLayout();
((System.ComponentModel.ISupportInitialize)cutTemplatesDataGrid).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// runButton // runButton
// //
runButton.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; runButton.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right;
runButton.Location = new System.Drawing.Point(656, 13); runButton.Location = new System.Drawing.Point(514, 13);
runButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); runButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
runButton.Name = "runButton"; runButton.Name = "runButton";
runButton.Size = new System.Drawing.Size(100, 30); runButton.Size = new System.Drawing.Size(100, 30);
@@ -74,7 +78,7 @@ namespace ExportDXF.Forms
viewFlipDeciderBox.FormattingEnabled = true; viewFlipDeciderBox.FormattingEnabled = true;
viewFlipDeciderBox.Location = new System.Drawing.Point(137, 43); viewFlipDeciderBox.Location = new System.Drawing.Point(137, 43);
viewFlipDeciderBox.Name = "viewFlipDeciderBox"; viewFlipDeciderBox.Name = "viewFlipDeciderBox";
viewFlipDeciderBox.Size = new System.Drawing.Size(502, 25); viewFlipDeciderBox.Size = new System.Drawing.Size(365, 25);
viewFlipDeciderBox.TabIndex = 3; viewFlipDeciderBox.TabIndex = 3;
// //
// mainTabControl // mainTabControl
@@ -82,11 +86,12 @@ namespace ExportDXF.Forms
mainTabControl.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; mainTabControl.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
mainTabControl.Controls.Add(logEventsTab); mainTabControl.Controls.Add(logEventsTab);
mainTabControl.Controls.Add(bomTab); mainTabControl.Controls.Add(bomTab);
mainTabControl.Controls.Add(cutTemplatesTab);
mainTabControl.Location = new System.Drawing.Point(15, 74); mainTabControl.Location = new System.Drawing.Point(15, 74);
mainTabControl.Name = "mainTabControl"; mainTabControl.Name = "mainTabControl";
mainTabControl.Padding = new System.Drawing.Point(20, 5); mainTabControl.Padding = new System.Drawing.Point(20, 5);
mainTabControl.SelectedIndex = 0; mainTabControl.SelectedIndex = 0;
mainTabControl.Size = new System.Drawing.Size(741, 586); mainTabControl.Size = new System.Drawing.Size(599, 330);
mainTabControl.TabIndex = 12; mainTabControl.TabIndex = 12;
// //
// logEventsTab // logEventsTab
@@ -95,7 +100,7 @@ namespace ExportDXF.Forms
logEventsTab.Location = new System.Drawing.Point(4, 30); logEventsTab.Location = new System.Drawing.Point(4, 30);
logEventsTab.Name = "logEventsTab"; logEventsTab.Name = "logEventsTab";
logEventsTab.Padding = new System.Windows.Forms.Padding(3); logEventsTab.Padding = new System.Windows.Forms.Padding(3);
logEventsTab.Size = new System.Drawing.Size(733, 552); logEventsTab.Size = new System.Drawing.Size(591, 296);
logEventsTab.TabIndex = 0; logEventsTab.TabIndex = 0;
logEventsTab.Text = "Log Events"; logEventsTab.Text = "Log Events";
logEventsTab.UseVisualStyleBackColor = true; logEventsTab.UseVisualStyleBackColor = true;
@@ -107,7 +112,7 @@ namespace ExportDXF.Forms
logEventsDataGrid.GridColor = System.Drawing.Color.WhiteSmoke; logEventsDataGrid.GridColor = System.Drawing.Color.WhiteSmoke;
logEventsDataGrid.Location = new System.Drawing.Point(6, 6); logEventsDataGrid.Location = new System.Drawing.Point(6, 6);
logEventsDataGrid.Name = "logEventsDataGrid"; logEventsDataGrid.Name = "logEventsDataGrid";
logEventsDataGrid.Size = new System.Drawing.Size(721, 540); logEventsDataGrid.Size = new System.Drawing.Size(579, 282);
logEventsDataGrid.TabIndex = 0; logEventsDataGrid.TabIndex = 0;
// //
// bomTab // bomTab
@@ -116,7 +121,7 @@ namespace ExportDXF.Forms
bomTab.Location = new System.Drawing.Point(4, 30); bomTab.Location = new System.Drawing.Point(4, 30);
bomTab.Name = "bomTab"; bomTab.Name = "bomTab";
bomTab.Padding = new System.Windows.Forms.Padding(3); bomTab.Padding = new System.Windows.Forms.Padding(3);
bomTab.Size = new System.Drawing.Size(733, 552); bomTab.Size = new System.Drawing.Size(982, 549);
bomTab.TabIndex = 1; bomTab.TabIndex = 1;
bomTab.Text = "Bill Of Materials"; bomTab.Text = "Bill Of Materials";
bomTab.UseVisualStyleBackColor = true; bomTab.UseVisualStyleBackColor = true;
@@ -128,9 +133,30 @@ namespace ExportDXF.Forms
bomDataGrid.GridColor = System.Drawing.Color.WhiteSmoke; bomDataGrid.GridColor = System.Drawing.Color.WhiteSmoke;
bomDataGrid.Location = new System.Drawing.Point(6, 6); bomDataGrid.Location = new System.Drawing.Point(6, 6);
bomDataGrid.Name = "bomDataGrid"; bomDataGrid.Name = "bomDataGrid";
bomDataGrid.Size = new System.Drawing.Size(721, 540); bomDataGrid.Size = new System.Drawing.Size(970, 535);
bomDataGrid.TabIndex = 1; bomDataGrid.TabIndex = 1;
// //
// cutTemplatesTab
//
cutTemplatesTab.Controls.Add(cutTemplatesDataGrid);
cutTemplatesTab.Location = new System.Drawing.Point(4, 30);
cutTemplatesTab.Name = "cutTemplatesTab";
cutTemplatesTab.Padding = new System.Windows.Forms.Padding(3);
cutTemplatesTab.Size = new System.Drawing.Size(982, 549);
cutTemplatesTab.TabIndex = 2;
cutTemplatesTab.Text = "Cut Templates";
cutTemplatesTab.UseVisualStyleBackColor = true;
//
// cutTemplatesDataGrid
//
cutTemplatesDataGrid.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
cutTemplatesDataGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
cutTemplatesDataGrid.GridColor = System.Drawing.Color.WhiteSmoke;
cutTemplatesDataGrid.Location = new System.Drawing.Point(6, 6);
cutTemplatesDataGrid.Name = "cutTemplatesDataGrid";
cutTemplatesDataGrid.Size = new System.Drawing.Size(970, 535);
cutTemplatesDataGrid.TabIndex = 2;
//
// equipmentBox // equipmentBox
// //
equipmentBox.FormattingEnabled = true; equipmentBox.FormattingEnabled = true;
@@ -151,7 +177,7 @@ namespace ExportDXF.Forms
// label2 // label2
// //
label2.AutoSize = true; label2.AutoSize = true;
label2.Location = new System.Drawing.Point(354, 15); label2.Location = new System.Drawing.Point(321, 15);
label2.Name = "label2"; label2.Name = "label2";
label2.Size = new System.Drawing.Size(56, 17); label2.Size = new System.Drawing.Size(56, 17);
label2.TabIndex = 2; label2.TabIndex = 2;
@@ -160,15 +186,15 @@ namespace ExportDXF.Forms
// drawingNoBox // drawingNoBox
// //
drawingNoBox.FormattingEnabled = true; drawingNoBox.FormattingEnabled = true;
drawingNoBox.Location = new System.Drawing.Point(416, 12); drawingNoBox.Location = new System.Drawing.Point(383, 12);
drawingNoBox.Name = "drawingNoBox"; drawingNoBox.Name = "drawingNoBox";
drawingNoBox.Size = new System.Drawing.Size(223, 25); drawingNoBox.Size = new System.Drawing.Size(119, 25);
drawingNoBox.TabIndex = 13; drawingNoBox.TabIndex = 13;
// //
// MainForm // MainForm
// //
AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
ClientSize = new System.Drawing.Size(768, 672); ClientSize = new System.Drawing.Size(626, 416);
Controls.Add(drawingNoBox); Controls.Add(drawingNoBox);
Controls.Add(equipmentBox); Controls.Add(equipmentBox);
Controls.Add(mainTabControl); Controls.Add(mainTabControl);
@@ -180,7 +206,7 @@ namespace ExportDXF.Forms
Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0); Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
MaximizeBox = false; MaximizeBox = false;
MinimumSize = new System.Drawing.Size(643, 355); MinimumSize = new System.Drawing.Size(642, 455);
Name = "MainForm"; Name = "MainForm";
StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
Text = "ExportDXF"; Text = "ExportDXF";
@@ -189,6 +215,8 @@ namespace ExportDXF.Forms
((System.ComponentModel.ISupportInitialize)logEventsDataGrid).EndInit(); ((System.ComponentModel.ISupportInitialize)logEventsDataGrid).EndInit();
bomTab.ResumeLayout(false); bomTab.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)bomDataGrid).EndInit(); ((System.ComponentModel.ISupportInitialize)bomDataGrid).EndInit();
cutTemplatesTab.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)cutTemplatesDataGrid).EndInit();
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }
@@ -203,6 +231,8 @@ namespace ExportDXF.Forms
private System.Windows.Forms.TabPage bomTab; private System.Windows.Forms.TabPage bomTab;
private System.Windows.Forms.DataGridView logEventsDataGrid; private System.Windows.Forms.DataGridView logEventsDataGrid;
private System.Windows.Forms.DataGridView bomDataGrid; private System.Windows.Forms.DataGridView bomDataGrid;
private System.Windows.Forms.TabPage cutTemplatesTab;
private System.Windows.Forms.DataGridView cutTemplatesDataGrid;
private System.Windows.Forms.ComboBox equipmentBox; private System.Windows.Forms.ComboBox equipmentBox;
private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label2;
+90 -4
View File
@@ -23,6 +23,7 @@ namespace ExportDXF.Forms
private CancellationTokenSource _cancellationTokenSource; private CancellationTokenSource _cancellationTokenSource;
private readonly BindingList<LogEvent> _logEvents; private readonly BindingList<LogEvent> _logEvents;
private readonly BindingList<BomItem> _bomItems; private readonly BindingList<BomItem> _bomItems;
private readonly BindingList<CutTemplate> _cutTemplates;
private List<DrawingInfo> _allDrawings; private List<DrawingInfo> _allDrawings;
public MainForm(ISolidWorksService solidWorksService, IDxfExportService exportService, IFileExportService fileExportService, Func<ExportDxfDbContext> dbContextFactory = null) public MainForm(ISolidWorksService solidWorksService, IDxfExportService exportService, IFileExportService fileExportService, Func<ExportDxfDbContext> dbContextFactory = null)
@@ -38,10 +39,12 @@ namespace ExportDXF.Forms
_dbContextFactory = dbContextFactory ?? (() => new ExportDxfDbContext()); _dbContextFactory = dbContextFactory ?? (() => new ExportDxfDbContext());
_logEvents = new BindingList<LogEvent>(); _logEvents = new BindingList<LogEvent>();
_bomItems = new BindingList<BomItem>(); _bomItems = new BindingList<BomItem>();
_cutTemplates = new BindingList<CutTemplate>();
_allDrawings = new List<DrawingInfo>(); _allDrawings = new List<DrawingInfo>();
InitializeViewFlipDeciders(); InitializeViewFlipDeciders();
InitializeLogEventsGrid(); InitializeLogEventsGrid();
InitializeBomGrid(); InitializeBomGrid();
InitializeCutTemplatesGrid();
InitializeDrawingDropdowns(); InitializeDrawingDropdowns();
} }
@@ -215,6 +218,61 @@ namespace ExportDXF.Forms
bomDataGrid.DataSource = _bomItems; bomDataGrid.DataSource = _bomItems;
} }
private void InitializeCutTemplatesGrid()
{
cutTemplatesDataGrid.Columns.Clear();
cutTemplatesDataGrid.AutoGenerateColumns = false;
cutTemplatesDataGrid.AllowUserToAddRows = false;
cutTemplatesDataGrid.AllowUserToDeleteRows = false;
cutTemplatesDataGrid.ReadOnly = true;
cutTemplatesDataGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
cutTemplatesDataGrid.Columns.Add(new DataGridViewTextBoxColumn
{
DataPropertyName = nameof(CutTemplate.CutTemplateName),
HeaderText = "Template Name",
Width = 150
});
cutTemplatesDataGrid.Columns.Add(new DataGridViewTextBoxColumn
{
DataPropertyName = nameof(CutTemplate.DxfFilePath),
HeaderText = "DXF File",
Width = 250
});
cutTemplatesDataGrid.Columns.Add(new DataGridViewTextBoxColumn
{
DataPropertyName = nameof(CutTemplate.Thickness),
HeaderText = "Thickness",
Width = 80
});
cutTemplatesDataGrid.Columns.Add(new DataGridViewTextBoxColumn
{
DataPropertyName = nameof(CutTemplate.KFactor),
HeaderText = "K-Factor",
Width = 80
});
cutTemplatesDataGrid.Columns.Add(new DataGridViewTextBoxColumn
{
DataPropertyName = nameof(CutTemplate.DefaultBendRadius),
HeaderText = "Bend Radius",
Width = 90
});
cutTemplatesDataGrid.Columns.Add(new DataGridViewTextBoxColumn
{
DataPropertyName = nameof(CutTemplate.ContentHash),
HeaderText = "Content Hash",
Width = 150
});
cutTemplatesDataGrid.DataSource = _cutTemplates;
}
private void InitializeDrawingDropdowns() private void InitializeDrawingDropdowns()
{ {
try try
@@ -319,9 +377,12 @@ namespace ExportDXF.Forms
return; return;
} }
// Parse drawing number from active document title // Use equipment/drawing values from the UI dropdowns
var drawingInfo = DrawingInfo.Parse(activeDoc.Title); var equipment = equipmentBox.Text?.Trim();
var filePrefix = drawingInfo != null ? $"{drawingInfo.EquipmentNo} {drawingInfo.DrawingNo}" : activeDoc.Title; var drawingNo = drawingNoBox.Text?.Trim();
var filePrefix = !string.IsNullOrEmpty(equipment) && !string.IsNullOrEmpty(drawingNo)
? $"{equipment} {drawingNo}"
: activeDoc.Title;
var viewFlipDecider = GetSelectedViewFlipDecider(); var viewFlipDecider = GetSelectedViewFlipDecider();
var exportContext = new ExportContext var exportContext = new ExportContext
@@ -335,12 +396,15 @@ namespace ExportDXF.Forms
BomItemCallback = AddBomItem BomItemCallback = AddBomItem
}; };
// Clear previous BOM items // Clear previous BOM items and cut templates
_bomItems.Clear(); _bomItems.Clear();
_cutTemplates.Clear();
LogMessage($"Started at {DateTime.Now:t}"); LogMessage($"Started at {DateTime.Now:t}");
LogMessage($"Exporting to: {_fileExportService.OutputFolder}"); LogMessage($"Exporting to: {_fileExportService.OutputFolder}");
_solidWorksService.SetCommandInProgress(true);
await Task.Run(() => _exportService.Export(exportContext), token); await Task.Run(() => _exportService.Export(exportContext), token);
LogMessage("Done."); LogMessage("Done.");
@@ -356,6 +420,7 @@ namespace ExportDXF.Forms
} }
finally finally
{ {
_solidWorksService.SetCommandInProgress(false);
UpdateUIForExportComplete(); UpdateUIForExportComplete();
_cancellationTokenSource?.Dispose(); _cancellationTokenSource?.Dispose();
_cancellationTokenSource = null; _cancellationTokenSource = null;
@@ -402,6 +467,22 @@ namespace ExportDXF.Forms
var activeDoc = _solidWorksService.GetActiveDocument(); var activeDoc = _solidWorksService.GetActiveDocument();
var docTitle = activeDoc?.Title ?? "No Document Open"; var docTitle = activeDoc?.Title ?? "No Document Open";
this.Text = $"ExportDXF - {docTitle}"; this.Text = $"ExportDXF - {docTitle}";
// Parse the file name and fill Equipment/Drawing dropdowns
if (activeDoc != null)
{
var drawingInfo = DrawingInfo.Parse(activeDoc.Title);
if (drawingInfo != null)
{
if (!equipmentBox.Items.Contains(drawingInfo.EquipmentNo))
equipmentBox.Items.Add(drawingInfo.EquipmentNo);
equipmentBox.Text = drawingInfo.EquipmentNo;
if (!drawingNoBox.Items.Contains(drawingInfo.DrawingNo))
drawingNoBox.Items.Add(drawingInfo.DrawingNo);
drawingNoBox.Text = drawingInfo.DrawingNo;
}
}
} }
private void LogMessage(string message, LogLevel level = LogLevel.Info, string file = null) private void LogMessage(string message, LogLevel level = LogLevel.Info, string file = null)
@@ -448,6 +529,11 @@ namespace ExportDXF.Forms
return; return;
} }
_bomItems.Add(item); _bomItems.Add(item);
if (item.CutTemplate != null)
{
_cutTemplates.Add(item.CutTemplate);
}
} }
private void LogEventsDataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) private void LogEventsDataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
@@ -0,0 +1,188 @@
// <auto-generated />
using System;
using ExportDXF.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace ExportDXF.Migrations
{
[DbContext(typeof(ExportDxfDbContext))]
[Migration("20260214195856_ExtractCutTemplate")]
partial class ExtractCutTemplate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.11")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("ExportDXF.Models.BomItem", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("ID"));
b.Property<string>("ConfigurationName")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("Description")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.Property<int>("ExportRecordId")
.HasColumnType("int");
b.Property<string>("ItemNo")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<string>("Material")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("PartName")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("PartNo")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<int?>("Qty")
.HasColumnType("int");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<int?>("TotalQty")
.HasColumnType("int");
b.HasKey("ID");
b.HasIndex("ExportRecordId");
b.ToTable("BomItems");
});
modelBuilder.Entity("ExportDXF.Models.CutTemplate", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("BomItemId")
.HasColumnType("int");
b.Property<string>("ContentHash")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("CutTemplateName")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<double?>("DefaultBendRadius")
.HasColumnType("float");
b.Property<string>("DxfFilePath")
.HasColumnType("nvarchar(max)");
b.Property<double?>("KFactor")
.HasColumnType("float");
b.Property<double?>("Thickness")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("BomItemId")
.IsUnique();
b.ToTable("CutTemplates");
});
modelBuilder.Entity("ExportDXF.Models.ExportRecord", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("DrawingNumber")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<DateTime>("ExportedAt")
.HasColumnType("datetime2");
b.Property<string>("ExportedBy")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("OutputFolder")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.Property<string>("PdfContentHash")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("SourceFilePath")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.HasKey("Id");
b.ToTable("ExportRecords");
});
modelBuilder.Entity("ExportDXF.Models.BomItem", b =>
{
b.HasOne("ExportDXF.Models.ExportRecord", "ExportRecord")
.WithMany("BomItems")
.HasForeignKey("ExportRecordId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ExportRecord");
});
modelBuilder.Entity("ExportDXF.Models.CutTemplate", b =>
{
b.HasOne("ExportDXF.Models.BomItem", "BomItem")
.WithOne("CutTemplate")
.HasForeignKey("ExportDXF.Models.CutTemplate", "BomItemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("BomItem");
});
modelBuilder.Entity("ExportDXF.Models.BomItem", b =>
{
b.Navigation("CutTemplate");
});
modelBuilder.Entity("ExportDXF.Models.ExportRecord", b =>
{
b.Navigation("BomItems");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,114 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ExportDXF.Migrations
{
/// <inheritdoc />
public partial class ExtractCutTemplate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ContentHash",
table: "BomItems");
migrationBuilder.DropColumn(
name: "CutTemplateName",
table: "BomItems");
migrationBuilder.DropColumn(
name: "DefaultBendRadius",
table: "BomItems");
migrationBuilder.DropColumn(
name: "DxfFilePath",
table: "BomItems");
migrationBuilder.DropColumn(
name: "KFactor",
table: "BomItems");
migrationBuilder.DropColumn(
name: "Thickness",
table: "BomItems");
migrationBuilder.CreateTable(
name: "CutTemplates",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
DxfFilePath = table.Column<string>(type: "nvarchar(max)", nullable: true),
ContentHash = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true),
CutTemplateName = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true),
Thickness = table.Column<double>(type: "float", nullable: true),
KFactor = table.Column<double>(type: "float", nullable: true),
DefaultBendRadius = table.Column<double>(type: "float", nullable: true),
BomItemId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CutTemplates", x => x.Id);
table.ForeignKey(
name: "FK_CutTemplates_BomItems_BomItemId",
column: x => x.BomItemId,
principalTable: "BomItems",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_CutTemplates_BomItemId",
table: "CutTemplates",
column: "BomItemId",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "CutTemplates");
migrationBuilder.AddColumn<string>(
name: "ContentHash",
table: "BomItems",
type: "nvarchar(64)",
maxLength: 64,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "CutTemplateName",
table: "BomItems",
type: "nvarchar(100)",
maxLength: 100,
nullable: true);
migrationBuilder.AddColumn<double>(
name: "DefaultBendRadius",
table: "BomItems",
type: "float",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "DxfFilePath",
table: "BomItems",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<double>(
name: "KFactor",
table: "BomItems",
type: "float",
nullable: true);
migrationBuilder.AddColumn<double>(
name: "Thickness",
table: "BomItems",
type: "float",
nullable: true);
}
}
}
@@ -0,0 +1,185 @@
// <auto-generated />
using System;
using ExportDXF.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace ExportDXF.Migrations
{
[DbContext(typeof(ExportDxfDbContext))]
partial class ExportDxfDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.11")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("ExportDXF.Models.BomItem", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("ID"));
b.Property<string>("ConfigurationName")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("Description")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.Property<int>("ExportRecordId")
.HasColumnType("int");
b.Property<string>("ItemNo")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<string>("Material")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("PartName")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("PartNo")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<int?>("Qty")
.HasColumnType("int");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<int?>("TotalQty")
.HasColumnType("int");
b.HasKey("ID");
b.HasIndex("ExportRecordId");
b.ToTable("BomItems");
});
modelBuilder.Entity("ExportDXF.Models.CutTemplate", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("BomItemId")
.HasColumnType("int");
b.Property<string>("ContentHash")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("CutTemplateName")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<double?>("DefaultBendRadius")
.HasColumnType("float");
b.Property<string>("DxfFilePath")
.HasColumnType("nvarchar(max)");
b.Property<double?>("KFactor")
.HasColumnType("float");
b.Property<double?>("Thickness")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("BomItemId")
.IsUnique();
b.ToTable("CutTemplates");
});
modelBuilder.Entity("ExportDXF.Models.ExportRecord", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("DrawingNumber")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<DateTime>("ExportedAt")
.HasColumnType("datetime2");
b.Property<string>("ExportedBy")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("OutputFolder")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.Property<string>("PdfContentHash")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("SourceFilePath")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.HasKey("Id");
b.ToTable("ExportRecords");
});
modelBuilder.Entity("ExportDXF.Models.BomItem", b =>
{
b.HasOne("ExportDXF.Models.ExportRecord", "ExportRecord")
.WithMany("BomItems")
.HasForeignKey("ExportRecordId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ExportRecord");
});
modelBuilder.Entity("ExportDXF.Models.CutTemplate", b =>
{
b.HasOne("ExportDXF.Models.BomItem", "BomItem")
.WithOne("CutTemplate")
.HasForeignKey("ExportDXF.Models.CutTemplate", "BomItemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("BomItem");
});
modelBuilder.Entity("ExportDXF.Models.BomItem", b =>
{
b.Navigation("CutTemplate");
});
modelBuilder.Entity("ExportDXF.Models.ExportRecord", b =>
{
b.Navigation("BomItems");
});
#pragma warning restore 612, 618
}
}
}
+3 -21
View File
@@ -1,5 +1,3 @@
using System;
namespace ExportDXF.Models namespace ExportDXF.Models
{ {
public class BomItem public class BomItem
@@ -14,29 +12,13 @@ namespace ExportDXF.Models
public string PartName { get; set; } = ""; public string PartName { get; set; } = "";
public string ConfigurationName { get; set; } = ""; public string ConfigurationName { get; set; } = "";
public string Material { get; set; } = ""; public string Material { get; set; } = "";
public string CutTemplateName { get; set; } = "";
public string DxfFilePath { get; set; } = "";
// Sheet metal properties
private double? _thickness;
public double? Thickness
{
get => _thickness;
set => _thickness = value.HasValue ? Math.Round(value.Value, 8) : null;
}
public double? KFactor { get; set; }
private double? _defaultBendRadius;
public double? DefaultBendRadius
{
get => _defaultBendRadius;
set => _defaultBendRadius = value.HasValue ? Math.Round(value.Value, 8) : null;
}
// EF Core relationship to ExportRecord // EF Core relationship to ExportRecord
public int ExportRecordId { get; set; } public int ExportRecordId { get; set; }
public virtual ExportRecord ExportRecord { get; set; } public virtual ExportRecord ExportRecord { get; set; }
// Optional 1:1 relationship to CutTemplate (only for sheet metal parts)
public virtual CutTemplate CutTemplate { get; set; }
} }
public struct Size public struct Size
+33
View File
@@ -0,0 +1,33 @@
using System;
namespace ExportDXF.Models
{
public class CutTemplate
{
public int Id { get; set; }
public string DxfFilePath { get; set; } = "";
public string ContentHash { get; set; }
public string CutTemplateName { get; set; } = "";
// Sheet metal properties (moved from BomItem)
private double? _thickness;
public double? Thickness
{
get => _thickness;
set => _thickness = value.HasValue ? Math.Round(value.Value, 8) : null;
}
public double? KFactor { get; set; }
private double? _defaultBendRadius;
public double? DefaultBendRadius
{
get => _defaultBendRadius;
set => _defaultBendRadius = value.HasValue ? Math.Round(value.Value, 8) : null;
}
// FK back to BomItem
public int BomItemId { get; set; }
public virtual BomItem BomItem { get; set; }
}
}
+175 -44
View File
@@ -2,11 +2,14 @@ using ExportDXF.Data;
using ExportDXF.Extensions; using ExportDXF.Extensions;
using ExportDXF.ItemExtractors; using ExportDXF.ItemExtractors;
using ExportDXF.Models; using ExportDXF.Models;
using ExportDXF.Utilities;
using ExportDXF; using ExportDXF;
using Microsoft.EntityFrameworkCore;
using SolidWorks.Interop.sldworks; using SolidWorks.Interop.sldworks;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
namespace ExportDXF.Services namespace ExportDXF.Services
{ {
@@ -161,18 +164,29 @@ namespace ExportDXF.Services
// Determine drawing number for file naming // Determine drawing number for file naming
var drawingNumber = ParseDrawingNumber(context); var drawingNumber = ParseDrawingNumber(context);
// Resolve output folder: /{outputDir}/{equipmentNo}/{drawingNo}/ or flat fallback
var drawingOutputFolder = _fileExportService.GetDrawingOutputFolder(drawingNumber);
// Export drawing to PDF // Export drawing to PDF
var tempDir = CreateTempWorkDir(); var tempDir = CreateTempWorkDir();
_drawingExporter.ExportToPdf(drawing, tempDir, context); _drawingExporter.ExportToPdf(drawing, tempDir, context);
// Copy PDF to output folder // Copy PDF to output folder with versioning
string pdfStashPath = null;
string savedPdfPath = null;
try try
{ {
var pdfs = Directory.GetFiles(tempDir, "*.pdf"); var pdfs = Directory.GetFiles(tempDir, "*.pdf");
if (pdfs.Length > 0) if (pdfs.Length > 0)
{ {
var savedPath = _fileExportService.SavePdfFile(pdfs[0], drawingNumber); // Determine the destination path to stash the existing file
LogProgress(context, $"Saved PDF: {Path.GetFileName(savedPath)}", LogLevel.Info); var pdfFileName = !string.IsNullOrEmpty(drawingNumber)
? $"{drawingNumber}.pdf"
: Path.GetFileName(pdfs[0]);
var pdfDestPath = Path.Combine(drawingOutputFolder, pdfFileName);
pdfStashPath = _fileExportService.StashFile(pdfDestPath);
savedPdfPath = _fileExportService.SavePdfFile(pdfs[0], drawingNumber, drawingOutputFolder);
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -186,15 +200,40 @@ namespace ExportDXF.Services
{ {
using (var db = _dbContextFactory()) using (var db = _dbContextFactory())
{ {
db.Database.EnsureCreated(); db.Database.Migrate();
exportRecord = new ExportRecord exportRecord = new ExportRecord
{ {
DrawingNumber = drawingNumber ?? context.ActiveDocument.Title, DrawingNumber = drawingNumber ?? context.ActiveDocument.Title,
SourceFilePath = context.ActiveDocument.FilePath, SourceFilePath = context.ActiveDocument.FilePath,
OutputFolder = _fileExportService.OutputFolder, OutputFolder = drawingOutputFolder,
ExportedAt = DateTime.Now, ExportedAt = DateTime.Now,
ExportedBy = System.Environment.UserName ExportedBy = System.Environment.UserName
}; };
// Handle PDF versioning - compute hash and compare with previous
if (savedPdfPath != null)
{
HandlePdfVersioning(savedPdfPath, exportRecord.DrawingNumber, exportRecord, context);
// Archive or discard old PDF based on hash comparison
if (pdfStashPath != null)
{
var previousRecord = db.ExportRecords
.Where(r => r.DrawingNumber == exportRecord.DrawingNumber && r.PdfContentHash != null)
.OrderByDescending(r => r.Id)
.FirstOrDefault();
if (previousRecord != null && previousRecord.PdfContentHash == exportRecord.PdfContentHash)
{
_fileExportService.DiscardStash(pdfStashPath);
}
else
{
_fileExportService.ArchiveFile(pdfStashPath, savedPdfPath);
}
}
}
db.ExportRecords.Add(exportRecord); db.ExportRecords.Add(exportRecord);
db.SaveChanges(); db.SaveChanges();
LogProgress(context, $"Created export record (ID: {exportRecord.Id})", LogLevel.Info); LogProgress(context, $"Created export record (ID: {exportRecord.Id})", LogLevel.Info);
@@ -202,11 +241,13 @@ namespace ExportDXF.Services
} }
catch (Exception ex) catch (Exception ex)
{ {
// Clean up stash on error
_fileExportService.DiscardStash(pdfStashPath);
LogProgress(context, $"Database error creating export record: {ex.Message}", LogLevel.Error); LogProgress(context, $"Database error creating export record: {ex.Message}", LogLevel.Error);
} }
// Export parts to DXF (directly to output folder) and save BOM items // Export parts to DXF and save BOM items
ExportItems(items, _fileExportService.OutputFolder, context, exportRecord?.Id); ExportItems(items, drawingOutputFolder, context, exportRecord?.Id);
} }
#endregion #endregion
@@ -268,6 +309,7 @@ namespace ExportDXF.Services
private void ExportItems(List<Item> items, string saveDirectory, ExportContext context, int? exportRecordId = null) private void ExportItems(List<Item> items, string saveDirectory, ExportContext context, int? exportRecordId = null)
{ {
int successCount = 0; int successCount = 0;
int skippedCount = 0;
int failureCount = 0; int failureCount = 0;
int sortOrder = 0; int sortOrder = 0;
@@ -284,54 +326,62 @@ namespace ExportDXF.Services
// PartExporter will handle template drawing creation through context // PartExporter will handle template drawing creation through context
_partExporter.ExportItem(item, saveDirectory, context); _partExporter.ExportItem(item, saveDirectory, context);
// Always create BomItem for every item (sheet metal or not)
var bomItem = new BomItem
{
ExportRecordId = exportRecordId ?? 0,
ItemNo = item.ItemNo ?? "",
PartNo = item.FileName ?? item.PartName ?? "",
SortOrder = sortOrder++,
Qty = item.Quantity,
TotalQty = item.Quantity,
Description = item.Description ?? "",
PartName = item.PartName ?? "",
ConfigurationName = item.Configuration ?? "",
Material = item.Material ?? ""
};
// Only create CutTemplate if DXF was exported successfully
if (!string.IsNullOrEmpty(item.FileName)) if (!string.IsNullOrEmpty(item.FileName))
{ {
successCount++; successCount++;
LogProgress(context, $"Exported: {item.FileName}.dxf", LogLevel.Info);
// Create BOM item
var dxfPath = Path.Combine(saveDirectory, item.FileName + ".dxf"); var dxfPath = Path.Combine(saveDirectory, item.FileName + ".dxf");
var bomItem = new BomItem bomItem.CutTemplate = new CutTemplate
{ {
ExportRecordId = exportRecordId ?? 0, DxfFilePath = dxfPath,
ItemNo = item.ItemNo ?? "", ContentHash = item.ContentHash,
PartNo = item.FileName ?? item.PartName ?? "",
SortOrder = sortOrder++,
Qty = item.Quantity,
TotalQty = item.Quantity,
Description = item.Description ?? "",
PartName = item.PartName ?? "",
ConfigurationName = item.Configuration ?? "",
Material = item.Material ?? "",
Thickness = item.Thickness > 0 ? item.Thickness : null, Thickness = item.Thickness > 0 ? item.Thickness : null,
KFactor = item.KFactor > 0 ? item.KFactor : null, KFactor = item.KFactor > 0 ? item.KFactor : null,
DefaultBendRadius = item.BendRadius > 0 ? item.BendRadius : null, DefaultBendRadius = item.BendRadius > 0 ? item.BendRadius : null
DxfFilePath = dxfPath
}; };
// Add to UI // Compare hash with previous export to decide archive/discard
context.BomItemCallback?.Invoke(bomItem); HandleDxfVersioning(item, dxfPath, context);
// Save BOM item to database if we have an export record
if (exportRecordId.HasValue)
{
try
{
using (var db = _dbContextFactory())
{
db.BomItems.Add(bomItem);
db.SaveChanges();
}
}
catch (Exception dbEx)
{
LogProgress(context, $"Database error saving BOM item: {dbEx.Message}", LogLevel.Error);
}
}
} }
else else
{ {
failureCount++; skippedCount++;
}
// Add to UI
context.BomItemCallback?.Invoke(bomItem);
// Save BOM item to database if we have an export record
if (exportRecordId.HasValue)
{
try
{
using (var db = _dbContextFactory())
{
db.BomItems.Add(bomItem);
db.SaveChanges();
}
}
catch (Exception dbEx)
{
LogProgress(context, $"Database error saving BOM item: {dbEx.Message}", LogLevel.Error);
}
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -341,8 +391,10 @@ namespace ExportDXF.Services
} }
} }
LogProgress(context, $"Export complete: {successCount} succeeded, {failureCount} failed", var summary = $"Export complete: {successCount} exported, {skippedCount} skipped";
failureCount > 0 ? LogLevel.Warning : LogLevel.Info); if (failureCount > 0)
summary += $", {failureCount} failed";
LogProgress(context, summary, failureCount > 0 ? LogLevel.Warning : LogLevel.Info);
if (exportRecordId.HasValue) if (exportRecordId.HasValue)
{ {
@@ -352,6 +404,85 @@ namespace ExportDXF.Services
#endregion #endregion
#region Versioning
private void HandleDxfVersioning(Item item, string dxfPath, ExportContext context)
{
if (string.IsNullOrEmpty(item.ContentHash))
return;
try
{
using (var db = _dbContextFactory())
{
var previousCutTemplate = db.CutTemplates
.Where(ct => ct.DxfFilePath == dxfPath && ct.ContentHash != null)
.OrderByDescending(ct => ct.Id)
.FirstOrDefault();
if (previousCutTemplate != null && previousCutTemplate.ContentHash == item.ContentHash)
{
// Content unchanged - discard the stashed file
_fileExportService.DiscardStash(item.StashedFilePath);
LogProgress(context, $"DXF unchanged: {item.FileName}.dxf", LogLevel.Info);
}
else
{
// Content changed or first export - archive the old file
if (!string.IsNullOrEmpty(item.StashedFilePath))
{
_fileExportService.ArchiveFile(item.StashedFilePath, dxfPath);
LogProgress(context, $"DXF updated, previous version archived: {item.FileName}.dxf", LogLevel.Info);
}
else
{
LogProgress(context, $"Exported: {item.FileName}.dxf", LogLevel.Info);
}
}
}
}
catch (Exception ex)
{
// Don't fail the export if versioning fails - just discard the stash
_fileExportService.DiscardStash(item.StashedFilePath);
LogProgress(context, $"Versioning check failed for {item.FileName}: {ex.Message}", LogLevel.Warning);
}
}
private void HandlePdfVersioning(string pdfPath, string drawingNumber, ExportRecord exportRecord, ExportContext context)
{
try
{
var newHash = ContentHasher.ComputeFileHash(pdfPath);
using (var db = _dbContextFactory())
{
var previousRecord = db.ExportRecords
.Where(r => r.DrawingNumber == drawingNumber && r.PdfContentHash != null)
.OrderByDescending(r => r.Id)
.FirstOrDefault();
if (previousRecord != null && previousRecord.PdfContentHash == newHash)
{
LogProgress(context, $"PDF unchanged: {Path.GetFileName(pdfPath)}", LogLevel.Info);
}
else
{
LogProgress(context, $"Saved PDF: {Path.GetFileName(pdfPath)}", LogLevel.Info);
}
}
if (exportRecord != null)
exportRecord.PdfContentHash = newHash;
}
catch (Exception ex)
{
LogProgress(context, $"PDF versioning check failed: {ex.Message}", LogLevel.Warning);
}
}
#endregion
#region Helper Methods #region Helper Methods
private string CreateTempWorkDir() private string CreateTempWorkDir()
+16
View File
@@ -88,6 +88,13 @@ namespace ExportDXF.Services
/// <param name="enable">True to enable user control, false to disable.</param> /// <param name="enable">True to enable user control, false to disable.</param>
void EnableUserControl(bool enable); void EnableUserControl(bool enable);
/// <summary>
/// Sets whether a command is in progress. When true, user input to
/// SolidWorks is disabled and interactive dialogs are suppressed.
/// </summary>
/// <param name="inProgress">True to block user input, false to re-enable.</param>
void SetCommandInProgress(bool inProgress);
/// <summary> /// <summary>
/// Gets the SolidWorks application instance. /// Gets the SolidWorks application instance.
/// </summary> /// </summary>
@@ -188,6 +195,15 @@ namespace ExportDXF.Services
} }
} }
/// <inheritdoc />
public void SetCommandInProgress(bool inProgress)
{
if (_sldWorks != null)
{
_sldWorks.CommandInProgress = inProgress;
}
}
/// <summary> /// <summary>
/// Gets the native SolidWorks application instance. /// Gets the native SolidWorks application instance.
/// Use this when you need direct access to the SolidWorks API. /// Use this when you need direct access to the SolidWorks API.
+23 -13
View File
@@ -1,6 +1,6 @@
# ExportDXF # ExportDXF
A Windows desktop application that automates exporting flat pattern DXF files from SolidWorks drawings, assemblies, and parts. Built for sheet metal fabrication workflows, it extracts BOM data, generates DXF flat patterns with etch/bend line markings, exports drawing PDFs, and uploads everything to a CutFab API for downstream cut programming. A Windows desktop application that automates exporting flat pattern DXF files from SolidWorks drawings, assemblies, and parts. Built for sheet metal fabrication workflows, it extracts BOM data, generates DXF flat patterns with etch/bend line markings, and exports drawing PDFs to a local output folder with SQL Server tracking.
## Features ## Features
@@ -8,17 +8,19 @@ A Windows desktop application that automates exporting flat pattern DXF files fr
- **Flat pattern generation** with automatic sheet metal detection - **Flat pattern generation** with automatic sheet metal detection
- **Etch line insertion** on bend-up lines for fabrication reference (via EtchBendLines library) - **Etch line insertion** on bend-up lines for fabrication reference (via EtchBendLines library)
- **PDF export** of SolidWorks drawings - **PDF export** of SolidWorks drawings
- **CutFab API integration** -- uploads DXFs, PDFs, and BOM data with sheet metal properties (thickness, K-factor, bend radius, material) - **Local file export** -- saves DXFs and PDFs to a configurable output folder
- **SQL Server database** -- tracks export history and BOM data via Entity Framework Core
- **View flip control** with automatic, manual, and prefer-up strategies - **View flip control** with automatic, manual, and prefer-up strategies
- **Drawing selection UI** that connects to SolidWorks and displays the active document - **Active document tracking** -- connects to SolidWorks and displays the active document in the title bar
- **BOM extraction** from drawing BOM tables or assembly component trees - **BOM extraction** from drawing BOM tables or assembly component trees
- **Drawing history dropdowns** -- equipment and drawing number filters populated from past exports
## Requirements ## Requirements
- Windows 10/11 - Windows 10/11
- .NET Framework 4.8 - .NET 8.0
- SolidWorks (installed and licensed) - SolidWorks (installed and licensed)
- CutFab API server (default: `http://localhost:7027`) - SQL Server (default: `localhost`, database: `ExportDxfDb`, Windows auth)
## Solution Structure ## Solution Structure
@@ -33,17 +35,19 @@ ExportDXF.sln
| Namespace | Purpose | | Namespace | Purpose |
|-----------|---------| |-----------|---------|
| `ExportDXF.Services` | Core services -- SolidWorks connection, DXF export, BOM extraction, PDF export, API client | | `ExportDXF.Services` | Core services -- SolidWorks connection, DXF export, BOM extraction, PDF export, file export |
| `ExportDXF.Forms` | WinForms UI -- drawing selection and main export form | | `ExportDXF.Forms` | WinForms UI -- main export form with log and BOM grids |
| `ExportDXF.Models` | Data models -- BomItem, ExportContext, SolidWorksDocument | | `ExportDXF.Models` | Data models -- BomItem, ExportRecord, ExportContext, SolidWorksDocument |
| `ExportDXF.Data` | Entity Framework Core DbContext for SQL Server persistence |
| `ExportDXF.ViewFlipDeciders` | Strategies for determining if a flat pattern view should be flipped | | `ExportDXF.ViewFlipDeciders` | Strategies for determining if a flat pattern view should be flipped |
| `ExportDXF.ItemExtractors` | Extract component items from BOM tables and assemblies | | `ExportDXF.ItemExtractors` | Extract component items from BOM tables and assemblies |
| `ExportDXF.Utilities` | SolidWorks helpers, sheet metal property extraction, text utilities | | `ExportDXF.Utilities` | SolidWorks helpers, sheet metal property extraction, text utilities |
| `ExportDXF.Extensions` | Extension methods for SolidWorks, UI, unit conversion, strings, TimeSpan |
| `EtchBendLines` | Post-processes DXF files to add etch marks on bend-up lines | | `EtchBendLines` | Post-processes DXF files to add etch marks on bend-up lines |
## How It Works ## How It Works
1. **Startup** -- Connects to a running SolidWorks instance (or launches one). Shows a drawing selection form that pulls equipment/drawing data from the CutFab API and displays the active SolidWorks document. 1. **Startup** -- Connects to a running SolidWorks instance (or launches one) asynchronously. Loads past export history from the database to populate equipment/drawing dropdowns. Displays the active SolidWorks document name in the title bar.
2. **Export** -- Based on the active document type: 2. **Export** -- Based on the active document type:
- **Drawing**: Extracts BOM items from BOM tables, exports the drawing as PDF, then iterates through each component to generate flat pattern DXFs. - **Drawing**: Extracts BOM items from BOM tables, exports the drawing as PDF, then iterates through each component to generate flat pattern DXFs.
@@ -52,21 +56,27 @@ ExportDXF.sln
3. **Post-processing** -- Each exported DXF is run through the EtchBendLines library, which identifies bend-up lines and adds short etch marks at their endpoints on a dedicated `ETCH` layer. Only up bends are etched because SolidWorks automatically flips the flat pattern so the shortest flange is the first bend. The etch marks let the press brake operator verify part orientation right off the laser table without flipping -- the first bend (shortest flange) will always have an etch line. 3. **Post-processing** -- Each exported DXF is run through the EtchBendLines library, which identifies bend-up lines and adds short etch marks at their endpoints on a dedicated `ETCH` layer. Only up bends are etched because SolidWorks automatically flips the flat pattern so the shortest flange is the first bend. The etch marks let the press brake operator verify part orientation right off the laser table without flipping -- the first bend (shortest flange) will always have an etch line.
4. **Upload** -- DXF files (zipped), PDFs, and BOM item data are uploaded to the CutFab API along with sheet metal properties. The API auto-links cut templates based on material and thickness. 4. **Save** -- DXF and PDF files are copied to the configured output folder. Export records and BOM items (with sheet metal properties) are saved to the SQL Server database.
## Configuration ## Configuration
The API base URL is configured in `App.config`: Settings are in `App.config`:
```xml ```xml
<appSettings> <appSettings>
<add key="CutFab.ApiBaseUrl" value="http://localhost:7027" /> <add key="MaxBendRadius" value="2.0" />
<add key="ExportOutputFolder" value="C:\ExportDXF\Output" />
</appSettings> </appSettings>
<connectionStrings>
<add name="ExportDxfDb"
connectionString="Server=localhost;Database=ExportDxfDb;Trusted_Connection=True;TrustServerCertificate=True;"
providerName="Microsoft.Data.SqlClient" />
</connectionStrings>
``` ```
## DXF Filename Format ## DXF Filename Format
Exported files follow the pattern: `{EquipmentNo} {DrawingNo} PT{ItemNo}.dxf` Exported files follow the pattern: `{DrawingNumber} PT{ItemNo}.dxf`
Example: `5007 A02 PT01.dxf` Example: `5007 A02 PT01.dxf`