using System.Collections.Generic; using System.IO; using System.Text; public class GenerateBillOfMaterial { // --- HIER KONFIGURIEREN --- // Tragen Sie hier die exakten Namen Ihrer Fertigungsdaten-Export-Schemata ein. private readonly List _exportSchemes = new List { "XXX.AUSWERTUNG1", "XXX.AUSWERTUNG2" // Fügen Sie hier bei Bedarf weitere Schemata hinzu }; // Optional: Legt fest, ob die Ausgabedateien in einem eigenen Unterordner gespeichert werden sollen. // Wenn der Wert leer ist (""), werden die Dateien direkt im Zielordner gespeichert. private const string OutputSubfolder = "Fertigungsdaten"; // --- ENDE KONFIGURATION --- // Name für unser temporäres Filterschema. private const string TempFilterSchemeName = "TempScriptFilter_GenerateBOM"; [Eplan.EplApi.Scripting.DeclareAction("GenerateMultipleBOMs")] public void Action() { // Projektinformationen über den PathMap-Dienst abrufen. string projectName = Eplan.EplApi.Base.PathMap.SubstitutePath("$(PROJECTNAME)"); string projectPathFull = Eplan.EplApi.Base.PathMap.SubstitutePath("$(PROJECTPATH)$(PROJECTNAME).elk"); if (string.IsNullOrEmpty(projectName)) { System.Windows.Forms.MessageBox.Show("Es ist kein Projekt geöffnet. Bitte öffnen Sie ein Projekt und versuchen Sie es erneut.", "Fehler", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return; } // WICHTIG: Die aktuelle Auswahl des Benutzers ermitteln. string selectedId = GetFirstSelectedId(); if (string.IsNullOrEmpty(selectedId)) { System.Windows.Forms.MessageBox.Show("Es wurde keine Auswahl im Stücklistennavigator getroffen.\nBitte wählen Sie eine Gruppe aus und starten Sie das Skript erneut.", "Keine Auswahl", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); return; } // Erstelle und setze den temporären Filter if (!CreateAndSetTemporaryFilter(projectPathFull, selectedId)) { System.Windows.Forms.MessageBox.Show("Der temporäre Filter für die Auswahl konnte nicht erstellt werden.", "Filter-Fehler", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return; } // Basis-Ausgabepfad mit EPLAN-Variablen definieren. string outputDirectoryWithVars = @"$(ENVVAR_SystemDrive)\EPLAN_TMP\$(ENVVAR_USERNAME)"; string resolvedOutputDirectory = Eplan.EplApi.Base.PathMap.SubstitutePath(outputDirectoryWithVars); // Unterordner für Ausgabe erstellen, falls konfiguriert if (!string.IsNullOrEmpty(OutputSubfolder)) { resolvedOutputDirectory = Path.Combine(resolvedOutputDirectory, OutputSubfolder); if (!Directory.Exists(resolvedOutputDirectory)) { try { Directory.CreateDirectory(resolvedOutputDirectory); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show("Der Ausgabe-Unterordner konnte nicht erstellt werden:\n" + resolvedOutputDirectory + "\n\nFehler: " + ex.Message, "Kritischer Fehler", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); RemoveTemporaryFilter(projectPathFull); // Aufräumen im Fehlerfall return; } } } // --- NEU: Vorab-Prüfung der Schreibrechte --- try { } catch { } List successLog = new List(); List errorLog = new List(); // Schleife durch alle konfigurierten Schemata foreach (string schemeName in _exportSchemes) { string safeFilterValue = selectedId.Replace("+", "").Replace("=", "").Replace("/", "_"); string outputFileName = string.Format("{0}_{1}_{2}.xml", projectName, safeFilterValue, schemeName); string fullOutputPathWithVars = Path.Combine(outputDirectoryWithVars, outputFileName); // Parameter für die 'export'-Aktion erstellen Eplan.EplApi.ApplicationFramework.ActionCallingContext context = new Eplan.EplApi.ApplicationFramework.ActionCallingContext(); context.AddParameter("TYPE", "filebasedreports"); context.AddParameter("SCHEME", schemeName); context.AddParameter("EXPORTFILE", fullOutputPathWithVars); context.AddParameter("PROJECTNAME", projectPathFull); context.AddParameter("FILTERSCHEME", TempFilterSchemeName); try { Eplan.EplApi.ApplicationFramework.ActionManager oAM = new Eplan.EplApi.ApplicationFramework.ActionManager(); Eplan.EplApi.ApplicationFramework.Action oAction = oAM.FindAction("export"); if (oAction != null) { bool executionSuccess = oAction.Execute(context); if (!executionSuccess) { // Da wir Schreibrechte bereits geprüft haben, grenzen wir den Fehler ein. throw new System.Exception("Die Aktion 'export' wurde von EPLAN nicht erfolgreich ausgeführt.\n Mögliche Ursachen:\n - Das Schema '" + schemeName + "' existiert nicht.\n - Für das Schema wurden mit dem Filter '" + selectedId + "' keine Objekte gefunden.\n - Fehlende Schreibrechte im Zielordner."); } } else { throw new System.Exception("Die EPLAN-Standardaktion 'export' konnte nicht gefunden werden."); } successLog.Add(string.Format("'{0}' erfolgreich exportiert nach:\n -> {1}", schemeName, Eplan.EplApi.Base.PathMap.SubstitutePath(fullOutputPathWithVars))); } catch (System.Exception ex) { errorLog.Add(string.Format("Fehler beim Export von '{0}'\n -> Grund: {1}", schemeName, ex.Message)); } } // Abschließendes Feedback ShowResultDialog(successLog, errorLog); // WICHTIG: Temporären Filter nach getaner Arbeit wieder löschen RemoveTemporaryFilter(projectPathFull); } /// /// Ermittelt die ID des ersten ausgewählten Objekts über eine Hilfsaktion. /// private string GetFirstSelectedId() { string id = ""; Eplan.EplApi.ApplicationFramework.ActionCallingContext context = new Eplan.EplApi.ApplicationFramework.ActionCallingContext(); context.AddParameter("id", "???"); // EPLAN füllt diesen Parameter mit der ID Eplan.EplApi.ApplicationFramework.ActionManager oAM = new Eplan.EplApi.ApplicationFramework.ActionManager(); Eplan.EplApi.ApplicationFramework.Action oAction = oAM.FindAction("GetSelectedId"); if (oAction != null) { oAction.Execute(context); context.GetParameter("id", ref id); } if (id == "???") { return string.Empty; } return id; } /// /// Erstellt und aktiviert ein temporäres Filterschema für den Export. /// private bool CreateAndSetTemporaryFilter(string projectPath, string filterValue) { try { // Filterstring für "Aufstellungsort (vollständig)" (Eigenschafts-ID 1019) string filterString = string.Format("1019,0,0,0,0,0,0,{0},0,0,0,1,1,0;", filterValue); Eplan.EplApi.ApplicationFramework.ActionCallingContext filterContext = new Eplan.EplApi.ApplicationFramework.ActionCallingContext(); filterContext.AddParameter("PROJECTNAME", projectPath); filterContext.AddParameter("FILTERNAME", TempFilterSchemeName); filterContext.AddParameter("FILTERSTRING", filterString); Eplan.EplApi.ApplicationFramework.ActionManager oAM = new Eplan.EplApi.ApplicationFramework.ActionManager(); Eplan.EplApi.ApplicationFramework.Action oAction = oAM.FindAction("SetProjectFilter"); if (oAction != null) { return oAction.Execute(filterContext); } return false; } catch { return false; } } /// /// Entfernt das temporäre Filterschema aus dem Projekt. /// private void RemoveTemporaryFilter(string projectPath) { try { Eplan.EplApi.ApplicationFramework.ActionCallingContext filterContext = new Eplan.EplApi.ApplicationFramework.ActionCallingContext(); filterContext.AddParameter("PROJECTNAME", projectPath); filterContext.AddParameter("FILTERNAME", TempFilterSchemeName); Eplan.EplApi.ApplicationFramework.ActionManager oAM = new Eplan.EplApi.ApplicationFramework.ActionManager(); Eplan.EplApi.ApplicationFramework.Action oAction = oAM.FindAction("DeleteProjectFilter"); if (oAction != null) { oAction.Execute(filterContext); } } catch { /* Fehler beim Löschen ignorieren, da nicht kritisch */ } } /// /// Zeigt einen zusammenfassenden Dialog mit den Ergebnissen der Exporte an. /// private static void ShowResultDialog(List successLog, List errorLog) { StringBuilder message = new StringBuilder(); string title; if (errorLog.Count == 0 && successLog.Count > 0) { title = "Exporte erfolgreich abgeschlossen"; message.AppendLine(string.Format("{0} Exporte wurden erfolgreich ausgeführt:\n", successLog.Count)); foreach (string log in successLog) { message.AppendLine("- " + log); } } else { title = "Exporte mit Fehlern abgeschlossen"; if (successLog.Count > 0) { message.AppendLine(string.Format("{0} von {1} Exporten erfolgreich:\n", successLog.Count, successLog.Count + errorLog.Count)); foreach (string log in successLog) { message.AppendLine("- " + log); } message.AppendLine("\n--------------------------------------------------\n"); } message.AppendLine(string.Format("{0} Exporte sind fehlgeschlagen:\n", errorLog.Count)); foreach (string log in errorLog) { message.AppendLine("- " + log.Replace("\n", "\n ")); } } using (ResultForm resultDialog = new ResultForm(title, message.ToString())) { resultDialog.ShowDialog(); } } /// /// Ein einfaches Formular zur Anzeige von Ergebnissen, das das Kopieren von Text erlaubt. /// private class ResultForm : System.Windows.Forms.Form { public ResultForm(string title, string logText) { this.Text = title; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Size = new System.Drawing.Size(600, 400); System.Windows.Forms.RichTextBox richTextBox = new System.Windows.Forms.RichTextBox(); richTextBox.Dock = System.Windows.Forms.DockStyle.Fill; richTextBox.ReadOnly = true; richTextBox.Text = logText; richTextBox.Font = new System.Drawing.Font("Consolas", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); richTextBox.BackColor = System.Drawing.Color.White; richTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None; richTextBox.Margin = new System.Windows.Forms.Padding(10); System.Windows.Forms.Button closeButton = new System.Windows.Forms.Button(); closeButton.Text = "Schließen"; closeButton.Dock = System.Windows.Forms.DockStyle.Bottom; closeButton.Height = 40; closeButton.Click += (sender, e) => { this.Close(); }; System.Windows.Forms.Panel panel = new System.Windows.Forms.Panel(); panel.Dock = System.Windows.Forms.DockStyle.Fill; panel.Padding = new System.Windows.Forms.Padding(10); panel.Controls.Add(richTextBox); this.Controls.Add(panel); this.Controls.Add(closeButton); this.AcceptButton = closeButton; } } }