Part Save-As tool

The code below was submitted by site user: <strong>peter.t</strong>.

The journal is intended to provide some options when making a copy of a part (native mode). The following options are available:
<ul>
<li>Save the work part with a higher revision: The journal will search for the corresponding drawing and copy that as well; the old files can be moved into a "trash" directory. For the drawing to be found, it must have the same base name as the model with "_dwg1" appended to it. If the model is "12345.prt", the drawing must be named "12345_dwg1.prt".</li>
<li>
Save the part with a different name and open it: The original part and drawing will be copied; the new drawing will reference the new part.</li>
<li>
Save the part with a different name and replace all occurrences in the session.</li>
<li>
Save the part with a different name and replace all occurrences in the session.</li>
</br>
Another big thank-you to <strong>peter.t</strong> for sharing his code!
If you would like to submit your own code to the site, contact me at info@nxjournaling.com.
<!--break-->
<vbnet>
'/////////////////////////////////////////////////////////////////
'// //
'// Teile speichern unter / kopieren / ändern //
'// //
'// //
'// //
'// Erstellt am 12.01.2016 //
'// peter.t //
'// //
'/////////////////////////////////////////////////////////////////

Option Strict Off
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Windows.Forms
Imports NXOpen
Imports NXOpen.Assemblies
Imports NXOpen.UF
Imports NXOpen.UI

Module save_as

Public theSession As Session = Session.GetSession()
Public displayPart As Part = theSession.Parts.Display
Public workPart As Part = theSession.Parts.Work

Dim theUFS As NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession()
Dim theUISession As UI = ui.GetUI

Sub Main()

' wenn kein Teil geladen ist, Fehler!
If IsNothing(theSession.Parts.Display) Then
theUISession.NXMessageBox.Show("Fehler", NXOpen.NXMessageBox.DialogType.Error, "Es ist kein Teil geladen. Abbruch ...")
Exit Sub
End If

' nach Arbeitsteil fragen
If IsNothing(theSession.Parts.Work) Then
theUISession.NXMessageBox.Show("Fehler", NXOpen.NXMessageBox.DialogType.Error, "Kein aktives Teil. Abbruch ...")
Exit Sub
End If

' Zeichnungen sollen nicht gespeichert werden, dies muss aus Mastermodell geschehen
If isDrawing(workPart) = True Then
theUISession.NXMessageBox.Show("Fehler", NXOpen.NXMessageBox.DialogType.Error, "Dargestelltes Teil ist eine Zeichnung. Abbruch ...")
Exit Sub
End If

If isDrawing(displayPart) = True Then
theUISession.NXMessageBox.Show("Fehler", NXOpen.NXMessageBox.DialogType.Error, "Teil ist eine Zeichnung. Abbruch ...")
Exit Sub
End If

' Fenster anzeigen
Dim myForm As New save_as_window

myForm.ShowDialog()

End Sub
Public Sub speichern_ErsatzTeil(ByVal bCopyDrw As Boolean)

Dim prtName As String = workPart.Leaf

Dim c As Component = getSelectedComp()
If IsNothing(c) = True Then
theUISession.NXMessageBox.Show("Fehler", NXOpen.NXMessageBox.DialogType.Error, "Mehr als eine oder keine Komponente ausgewählt!")
Exit Sub
End If

Dim selectedPart As Part = CType(theSession.Parts.FindObject(c.DisplayName), Part)

' Pfad suchen
Dim prtPath As String = selectedPart.FullPath.Replace(prtName & ".prt", "")
Dim drwName As String = selectedPart.FullPath.Replace(".prt", "_dwg1.prt")

' Speichern-Dialog aufrufen
Dim SFD As New SaveFileDialog

SFD.Title = "Bitte neuen Namen für Teil angeben"
SFD.Filter = "NX-Dateien (*.prt) |*.prt"
SFD.InitialDirectory = prtPath
SFD.FileName = selectedPart.Leaf

Dim newPartPath As String
Dim newPartName As String

If SFD.ShowDialog = DialogResult.OK Then

newPartPath = Replace(SFD.FileName, System.IO.Path.GetFileName(SFD.FileName), "")
newPartName = System.IO.Path.GetFileName(SFD.FileName)

Else

Exit Sub

End If

' falls Datei schon vorhanden Abbruch
If IO.File.Exists(newPartPath & newPartName) Then
theUISession.NXMessageBox.Show("Fehler", NXOpen.NXMessageBox.DialogType.Error, "Teil ist schon vorhanden. Speichern wird abgebrochen!")
Exit Sub
End If

' prüfen ob Teil modifiziert ist
doModifiedCheckPart(selectedPart)

Dim oldDrwName As String = selectedPart.Leaf & "_dwg1"

' neues Teil speichern (vorerst ohne Zeichnung)
If Not IsNothing(c) Then

' ///// DEBUGGING
'MsgBox("Komponente " & c.DisplayName & " ausgewählt!")
'MsgBox("Oberste Komponente: " & getCompParent(c).DisplayName)

IO.File.Copy(selectedPart.FullPath, newPartPath & newPartName)

Dim ls1 As PartLoadStatus
theSession.Parts.OpenDisplay(newPartPath & newPartName, ls1)

' neue Attribute einpflegen
theSession.Parts.Display.SetAttribute("PRTNO", getPartNumberFromFile(newPartName.Replace(".prt", "")))
theSession.Parts.Display.SetAttribute("PRTNAME", getPartNameFromFile(newPartName.Replace(".prt", "")))
' ////// Teil ist fertig

' Baugruppe suchen und öffnen um Teile auszutauschen
Dim selectedPartParent As Part = CType(theSession.Parts.FindObject(getCompParent(c).DisplayName), Part)

Dim ls2 As PartLoadStatus
theSession.Parts.SetDisplay(selectedPartParent, False, False, ls2)

Dim rcb As Assemblies.ReplaceComponentBuilder
rcb = selectedPartParent.AssemblyManager.CreateReplaceComponentBuilder()
rcb.ComponentsToReplace.Add(c)
rcb.ReplaceAllOccurrences = True
rcb.ReplacementPart = newPartPath & newPartName
rcb.SetComponentReferenceSetType(Assemblies.ReplaceComponentBuilder.ComponentReferenceSet.Maintain, Nothing)
rcb.Commit()

rcb.Destroy()

End If

' falls Zeichnung mitkopiert werden soll
If bCopyDrw = True Then

' prüfen ob Zeichnung modifiziert ist
If isDrwOpen(oldDrwName) = True Then doModifiedCheckDrw(theSession.Parts.FindObject(oldDrwName))

' neue Zeichnung benennen
Dim newDrw As String = newPartPath & newPartName.Replace(".prt", "_dwg1.prt")

' Dateien auf OS-Ebene kopieren
IO.File.Copy(drwName, newDrw)

' Zeichnung öffnen und Masterteil austauschen
If isDrwOpen(oldDrwName) = False Then

Dim ls As PartLoadStatus
theSession.Parts.OpenDisplay(newDrw, ls)
ls.Dispose()

End If

Dim prtDrw As Part = theSession.Parts.FindObject(newPartName.Replace(".prt", "_dwg1"))

Dim rcbDrw As Assemblies.ReplaceComponentBuilder

rcbDrw = prtDrw.AssemblyManager.CreateReplaceComponentBuilder()

Dim compDrw As Component = CType(prtDrw.ComponentAssembly.RootComponent.FindObject("COMPONENT " & oldDrwName.Replace("_dwg1", "") & " 1"), Component)

rcbDrw.ComponentsToReplace.Add(compDrw)
rcbDrw.ReplacementPart = newPartPath & newPartName
rcbDrw.SetComponentReferenceSetType(Assemblies.ReplaceComponentBuilder.ComponentReferenceSet.Maintain, Nothing)
rcbDrw.Commit()

rcbDrw.Destroy()

End If

' Hauptbaugruppe wieder aufrufen und geändertes Teil als workpart setzen
Dim ls3 As PartLoadStatus
theSession.Parts.SetDisplay(displayPart, False, False, ls3)
theSession.Parts.SetWork(CType(theSession.Parts.FindObject(newPartName.Replace(".prt", "")), Part))

' Ende des Programms
theUISession.NXMessageBox.Show("Speichern-Operation", NXOpen.NXMessageBox.DialogType.Information, "Speichern erfolgreich!")

End Sub
Public Sub speichern_NeuesTeil(ByVal bCopyDrw As Boolean)

Dim prtName As String = workPart.Leaf
Dim prtNameAndPath As String = workPart.FullPath

' Pfad suchen
Dim prtPath As String = workPart.FullPath.Replace(prtName & ".prt", "")
Dim drwName As String = workPart.FullPath.Replace(".prt", "_dwg1.prt")

' Speichern-Dialog aufrufen
Dim SFD As New SaveFileDialog

SFD.Title = "Bitte neuen Namen für Teil angeben"
SFD.Filter = "NX-Dateien (*.prt) |*.prt"
SFD.InitialDirectory = prtPath
SFD.FileName = prtName

Dim newPartPath As String
Dim newPartName As String

If SFD.ShowDialog = DialogResult.OK Then

newPartPath = Replace(SFD.FileName, System.IO.Path.GetFileName(SFD.FileName), "")
newPartName = System.IO.Path.GetFileName(SFD.FileName)

Else

Exit Sub

End If

' falls Datei schon vorhanden Abbruch
If IO.File.Exists(newPartPath & newPartName) Then
theUISession.NXMessageBox.Show("Fehler", NXOpen.NXMessageBox.DialogType.Error, "Teil ist schon vorhanden. Speichern wird abgebrochen!")
Exit Sub
End If

' prüfen ob Teil modifiziert ist
doModifiedCheckPart(workPart)

' falls Zeichnung mitkopiert werden soll
If bCopyDrw = True Then

' prüfen ob Zeichnung modifiziert ist
If isDrwOpen(workPart.Leaf & "_dwg1") = True Then doModifiedCheckDrw(theSession.Parts.FindObject(workPart.Leaf & "_dwg1"))

' neue Zeichnung benennen
Dim newDrw As String = newPartPath & newPartName.Replace(".prt", "_dwg1.prt")

' Dateien auf OS-Ebene kopieren
IO.File.Copy(workPart.FullPath, newPartPath & newPartName)
IO.File.Copy(drwName, newDrw)

Dim oldPrt As String = workPart.Leaf

' Zeichnung öffnen und Masterteil austauschen
Try

Dim ls As PartLoadStatus
theSession.Parts.OpenDisplay(newDrw, ls)
ls.Dispose()

Catch ex As Exception

End Try

Dim prtDrw As Part = theSession.Parts.FindObject(newPartName.Replace(".prt", "_dwg1"))

Dim rcb As Assemblies.ReplaceComponentBuilder

rcb = prtDrw.AssemblyManager.CreateReplaceComponentBuilder()

' tauscht NUR erste Instanz auf Zeichnung aus falls mehrere da sein sollten
Dim compDrw As Component = CType(prtDrw.ComponentAssembly.RootComponent.FindObject("COMPONENT " & oldPrt & " 1"), Component)

rcb.ComponentsToReplace.Add(compDrw)
rcb.ReplacementPart = newPartPath & newPartName
rcb.SetComponentReferenceSetType(Assemblies.ReplaceComponentBuilder.ComponentReferenceSet.Maintain, Nothing)
rcb.Commit()

rcb.Destroy()

' neues Teil öffnen falls noch nicht offen
Try

Dim ls1 As PartLoadStatus
theSession.Parts.OpenDisplay(newPartPath & newPartName, ls1)
ls1.Dispose()

Catch ex As Exception

' Teil ist schon offen
Dim prtNew As Part = theSession.Parts.FindObject(newPartName.Replace(".prt", ""))
Dim ls2 As PartLoadStatus
theSession.Parts.SetDisplay(prtNew, True, True, ls2)

End Try

' neue Attribute einpflegen
theSession.Parts.Display.SetAttribute("PRTNO", getPartNumberFromFile(newPartName.Replace(".prt", "")))
theSession.Parts.Display.SetAttribute("PRTNAME", getPartNameFromFile(newPartName.Replace(".prt", "")))

Else

' neues Teil speichern (ohne Zeichnung)
IO.File.Copy(workPart.FullPath, newPartPath & newPartName)

' neues Teil öffnen
Try

Dim ls1 As PartLoadStatus
theSession.Parts.OpenDisplay(newPartPath & newPartName, ls1)
ls1.Dispose()

' neue Attribute einpflegen
theSession.Parts.Display.SetAttribute("PRTNO", getPartNumberFromFile(newPartName.Replace(".prt", "")))
theSession.Parts.Display.SetAttribute("PRTNAME", getPartNameFromFile(newPartName.Replace(".prt", "")))

Catch ex As Exception

End Try

End If

' Ende des Programms
theUISession.NXMessageBox.Show("Speichern-Operation", NXOpen.NXMessageBox.DialogType.Information, "Speichern erfolgreich!")

End Sub
Public Sub speichern_Aenderungsstand(ByVal bCopyDrw As Boolean, ByVal bMoveOldFiles As Boolean, ByVal bAttributesSync As Boolean)

' Teil mit neuem Änderungsstand abspeichern
Dim prtName As String = workPart.Leaf
Dim prtNameAndPath As String = workPart.FullPath

' Pfad suchen
Dim prtPath As String = workPart.FullPath.Replace(prtName & ".prt", "")
Dim drwName As String = workPart.FullPath.Replace(".prt", "_dwg1.prt")

' Speichern-Dialog aufrufen
Dim SFD As New SaveFileDialog

SFD.Title = "Bitte neuen Namen für Teil angeben"
SFD.Filter = "NX-Dateien (*.prt) |*.prt"
SFD.InitialDirectory = prtPath
SFD.FileName = prtName

Dim newPartPath As String
Dim newPartName As String

If SFD.ShowDialog = DialogResult.OK Then

newPartPath = Replace(SFD.FileName, System.IO.Path.GetFileName(SFD.FileName), "")
newPartName = System.IO.Path.GetFileName(SFD.FileName)

Else

Exit Sub

End If

' falls Datei schon vorhanden Abbruch
If IO.File.Exists(newPartPath & newPartName) Then
theUISession.NXMessageBox.Show("Fehler", NXOpen.NXMessageBox.DialogType.Error, "Teil ist schon vorhanden. Speichern wird abgebrochen!")
Exit Sub
End If

' prüfen ob Teil modifiziert ist
'doModifiedCheckPart(workPart)

' falls Zeichnung mitkopiert werden soll
If bCopyDrw = True Then

' Zeichnung laden (falls noch nicht geschehen)
Try

Dim ls1 As PartLoadStatus
theSession.Parts.Open(drwName, ls1)
ls1.Dispose()

Catch ex As Exception

End Try

' neues Teil speichern
Dim saveStatus1 As PartSaveStatus = workPart.SaveAs(newPartPath & newPartName)
saveStatus1.Dispose()

' neue Zeichnungsnummer einpflegen
workPart.SetAttribute("PRTNO", getPartNumberFromFile(newPartName.Replace(".prt", "")))
If bAttributesSync = True Then workPart.SetAttribute("PRTNAME", getPartNameFromFile(newPartName.Replace(".prt", "")))

' Zeichnung speichern
Dim drwPart As Part = theSession.Parts.FindObject(drwName.Replace(".prt", ""))
Dim saveStatus2 As PartSaveStatus = drwPart.SaveAs(newPartPath & newPartName.Replace(".prt", "") & "_dwg1")
saveStatus2.Dispose()

Else

' neues Teil speichern (ohne Zeichnung)
Dim saveStatus1 As PartSaveStatus = workPart.SaveAs(newPartPath & newPartName)
saveStatus1.Dispose()

' neue Zeichnungsnummer einpflegen
workPart.SetAttribute("PRTNO", getPartNumberFromFile(newPartName))
If bAttributesSync = True Then workPart.SetAttribute("PRTNAME", getPartNameFromFile(newPartName.Replace(".prt", "")))

End If

' //// alte Dateien löschen wenn erwünscht
If bMoveOldFiles = True Then

Dim trashPath As String = IO.Path.GetDirectoryName(prtPath) & "\altes\"
' Überprüfung und ggf. Erstellung des Müllordners
If IO.Directory.Exists(trashPath) = False Then

If theUISession.NXMessageBox.Show("Ordner erstellen", NXOpen.NXMessageBox.DialogType.Question, "Der Ordner " & trashPath & " ist nicht vorhanden. Soll der Ordner erstellt werden?") = 1 Then

' Verzeichnis erstellen
IO.Directory.CreateDirectory(trashPath)

Else

theUISession.NXMessageBox.Show("Speichern-Operation", NXOpen.NXMessageBox.DialogType.Information, "Speichern erfolgreich! Die alten Dateien wurden nicht verschoben.")
Exit Sub

End If

End If

' alte Dateien verschieben (überschreiben bei Bedarf)
If IO.File.Exists(trashPath & prtName & ".prt") = True Then IO.File.Delete(trashPath & prtName & ".prt")
IO.File.Move(prtNameAndPath, trashPath & prtName & ".prt")

If IO.File.Exists(trashPath & prtName & "_dwg1.prt") = True Then IO.File.Delete(trashPath & prtName & "_dwg1.prt")
IO.File.Move(drwName, trashPath & prtName & "_dwg1.prt")

' PDF-Datei auch verschieben falls vorhanden
If IO.File.Exists(prtNameAndPath.Replace(".prt", "_dwg1.pdf")) = True Then

If IO.File.Exists(trashPath & prtName & "_dwg1.pdf") = True Then IO.File.Delete(trashPath & prtName & "_dwg1.pdf")
IO.File.Move(prtNameAndPath.Replace(".prt", "_dwg1.pdf"), trashPath & prtName & "_dwg1.pdf")

End If

End If

' Ende des Programms
theUISession.NXMessageBox.Show("Speichern-Operation", NXOpen.NXMessageBox.DialogType.Information, "Speichern erfolgreich!")

End Sub
Public Function getCompParent(ByVal comp As Component) As Component

Return comp.OwningComponent

End Function
Public Function getSelectedComp() As Component

' Abfrage ob ein Teil selektiert ist
Dim intNumSelected As Integer = theUI.SelectionManager.GetNumSelectedObjects()

If intNumSelected = 0 Then Exit Function

Dim SelectedList As New List(Of Component)
For i As Integer = 0 To intNumSelected - 1

Dim intType As Integer
Dim intSubType As Integer

Dim objSelected As NXObject = theUI.SelectionManager.GetSelectedObject(i)
theUFS.Obj.AskTypeAndSubtype(objSelected.Tag, intType, intSubType)

If intType = UFConstants.UF_component_type Then

Dim theComp As Component = DirectCast(objSelected, Component)
If inList(theComp, SelectedList) = False Then SelectedList.Add(theComp)

End If

Next

If SelectedList.Count = 1 Then

Return SelectedList.Item(0)

Else

theUISession.NXMessageBox.Show("Fehler", NXOpen.NXMessageBox.DialogType.Error, "Mehr als eine oder keine Komponente ausgewählt!")

End If

End Function
Public Function getCountSelectedComps() As Integer

' Abfrage wieviele Teile selektiert ist
Dim intNumSelected As Integer = theUI.SelectionManager.GetNumSelectedObjects()

Return intNumSelected

End Function
Public Function inList(ByVal comp As Component, ByVal l As List(Of Component)) As Boolean

For x As Integer = 0 To l.Count - 1

If l.Item(x).DisplayName = comp.DisplayName Then

Return True
Exit For

End If

Next

End Function
Public Function isDrawing(ByVal prt As Part) As Boolean

' prüft ob das mitgelieferte Teile eine Zeichnung ist
If Right(prt.Leaf, 5) = "_dwg1" Then

Return True

Else

Return False

End If

End Function
Public Function isDrwOpen(ByVal drwName As String) As Boolean

' prüft ob die mitgelieferte Zeichnung in Sitzung geöffnet ist
Try

Dim p As Part = theSession.Parts.FindObject(drwName)
Return True

Catch ex As Exception

Return False

End Try
End Function
Public Sub doModifiedCheckPart(ByVal prt As Part)

' prüft ob die anzugehende Datei noch vorher gespeichert werden soll
If theUfS.Part.IsModified(prt.Tag) = True Then

If theUISession.NXMessageBox.Show("Speichern", NXOpen.NXMessageBox.DialogType.Question, "Das Teil " & prt.Leaf & " ist modifiziert. Soll das Teil vorher gespeichert werden?") = 1 Then

Dim ss As PartSaveStatus = prt.Save(True, False)
ss.Dispose()

End If

End If

End Sub
Public Sub doModifiedCheckDrw(ByVal drw As Part)

' prüft ob die anzugehende Datei noch vorher gespeichert werden soll
If theUfS.Part.IsModified(drw.Tag) = True Then

If theUISession.NXMessageBox.Show("Speichern", NXOpen.NXMessageBox.DialogType.Question, "Die Zeichnung " & drw.Leaf & " ist modifiziert. Soll das Teil vorher gespeichert werden?") = 1 Then

Dim ss As PartSaveStatus = drw.Save(True, False)
ss.Dispose()

End If

End If

End Sub
Public Function hasDrawing(ByVal prt As Part) As Boolean

' prüft ob das mitgelieferte Teil eine Zeichnung hat
Dim drwFileName As String = prt.FullPath.Replace(".prt", "_dwg1.prt")

If IO.File.Exists(drwFileName) = False Then
Return False
Else
Return True
End If

End Function
Public Function getPartNameFromFile(ByVal file As String) As String

' Teilebenennung aus Dateinamen lesen
Try

Static Dim LastChar As Integer
Static Dim tmpBenennung As String

' Dateinamen einlesen und verarbeiten
Dim currentFile As String = file
Static Dim FileNameLength As Integer = currentFile.Length

' Baugruppen-Nummer mit Leerzeichen (xxx xx xxx_xx)
If currentFile.IndexOf("_", 0, 12) = 10 Then

LastChar = 14
tmpBenennung = currentFile.SubString(LastChar, FileNameLength - LastChar)

End If

' Baugruppen-Nummer mit Leerzeichen (xxx xx xx_xx)
If currentFile.IndexOf("_", 0, 12) = 9 Then

LastChar = 13
tmpBenennung = currentFile.SubString(LastChar, FileNameLength - LastChar)

End If

' Zg.-Nr. 8-stellige Nummer ohne Leerzeichen
If currentFile.IndexOf("_", 0, 10) = 8 Then

LastChar = 12
tmpBenennung = currentFile.SubString(LastChar, FileNameLength - LastChar)

End If

' Zg.-Nr. 7-stellige Nummer ohne Leerzeichen
If currentFile.IndexOf("_", 0, 10) = 7 Then

LastChar = 11
tmpBenennung = currentFile.SubString(LastChar, FileNameLength - LastChar)

End If

tmpBenennung = currentFile.SubString(LastChar, FileNameLength - LastChar)
Dim Benennung As String = tmpBenennung.Replace("_", " ")

Return Benennung

Catch ex As Exception

'MsgBox(ex.Message)

End Try

End Function
Public Function getPartNumberFromFile(ByVal file As String) As String

' Zeichnungsnummer aus Dateinamen lesen
Try

Static Dim ZgNr As String
Static Dim tmpZgNr As String
Static Dim LastChar As Integer

' Dateinamen einlesen und verarbeiten
Dim currentFile As String = file
Static Dim FileNameLength As Integer = currentFile.Length

' Baugruppen-Nummer mit Leerzeichen (xxx xx xxx_xx)
If currentFile.IndexOf("_", 0, 12) = 10 Then

ZgNr = currentFile.Substring(0, 13)
LastChar = 14

Return ZgNr

End If

' Baugruppen-Nummer mit Leerzeichen (xxx xx xx_xx)
If currentFile.IndexOf("_", 0, 12) = 9 Then

ZgNr = currentFile.Substring(0, 12)
LastChar = 13

Return ZgNr

End If

' Zg.-Nr. 8-stellige Nummer ohne Leerzeichen
If currentFile.IndexOf("_", 0, 10) = 8 Then

tmpZgNr = currentFile.Substring(0, 11)
LastChar = 12
Dim Teil1 As String = tmpZgNr.Substring(0, 3)
Dim Teil2 As String = tmpZgNr.Substring(3, 2)
Dim Teil3 As String = tmpZgNr.Substring(5, 6)
ZgNr = Teil1 & " " & Teil2 & " " & Teil3

Return ZgNr

End If

' Zg.-Nr. 7-stellige Nummer ohne Leerzeichen
If currentFile.IndexOf("_", 0, 10) = 7 Then

tmpZgNr = currentFile.Substring(0, 10)
LastChar = 11
Dim Teil1 As String = tmpZgNr.Substring(0, 3)
Dim Teil2 As String = tmpZgNr.Substring(3, 2)
Dim Teil3 As String = tmpZgNr.Substring(5, 5)
ZgNr = Teil1 & " " & Teil2 & " " & Teil3

Return ZgNr

End If

Catch ex As Exception

'MsgBox(ex.Message)

End Try

End Function
Public Function GetUnloadOption(ByVal dummy As String) As Integer

Return Session.LibraryUnloadOption.Immediately

End Function
Public Class save_as_window

Private Sub bOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bOK.Click

Me.Visible = False
Me.Close()

If cbAction.Text = "Änderungsstand erzeugen" Then speichern_Aenderungsstand(cbZg.Checked, cbMove.Checked, False)

If cbAction.Text = "als neues Teil speichern und öffnen" Then speichern_NeuesTeil(cbZg.Checked)

If cbAction.Text = "als neues Teil speichern und ersetzen (alle in Sitzung)" Then speichern_Aenderungsstand(cbZg.Checked, False, True)

If cbAction.Text = "selektiertes Teil speichern und in BG ersetzen" Then speichern_ErsatzTeil(cbZg.Checked)

End Sub
Private Sub cbAction_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbAction.SelectedIndexChanged

If cbAction.Text = "Änderungsstand erzeugen" Then
cbMove.Enabled = True
Me.Text = "Speichern unter: " & workPart.Leaf

' Zeichnungsprüfung
If hasDrawing(workPart) = True Then

pbZg.ImageLocation = „set path to icon that says yes„
lblZg.Text = "Zeichnung vorhanden"
Else

pbZg.ImageLocation = „set path to icon that says no„
lblZg.Text = "Zeichnung nicht vorhanden"
cbZg.Checked = False
cbZg.Enabled = False
End If

End If

If cbAction.Text = "als neues Teil speichern und ersetzen (alle in Sitzung)" Then
cbMove.Enabled = False
Me.Text = "Speichern unter: " & workPart.Leaf

' Zeichnungsprüfung
If hasDrawing(workPart) = True Then

pbZg.ImageLocation = "set path to icon that says yes"
lblZg.Text = "Zeichnung vorhanden"
Else

pbZg.ImageLocation = "set path to icon that says no"
lblZg.Text = "Zeichnung nicht vorhanden"
cbZg.Checked = False
cbZg.Enabled = False
End If

End If

If cbAction.Text = "als neues Teil speichern und öffnen" Then
cbMove.Enabled = False
Me.Text = "Speichern unter: " & workPart.Leaf

' Zeichnungsprüfung
If hasDrawing(workPart) = True Then

pbZg.ImageLocation = "set path to icon that says yes"
lblZg.Text = "Zeichnung vorhanden"
Else

pbZg.ImageLocation = "set path to icon that says no"
lblZg.Text = "Zeichnung nicht vorhanden"
cbZg.Checked = False
cbZg.Enabled = False
End If

End If

If cbAction.Text = "selektiertes Teil speichern und in BG ersetzen" Then
cbMove.Enabled = False

If IsNothing(getSelectedComp) Then
Me.Close()
Exit Sub
End If

Me.Text = "Speichern unter: " & getSelectedComp.DisplayName

' Zeichnungsprüfung
If hasDrawing(CType(theSession.Parts.FindObject(getSelectedComp.DisplayName), Part)) = True Then

pbZg.ImageLocation = "set path to icon that says yes"
lblZg.Text = "Zeichnung vorhanden"
Else

pbZg.ImageLocation = "set path to icon that says no"
lblZg.Text = "Zeichnung nicht vorhanden"
cbZg.Checked = False
cbZg.Enabled = False

End If

End If

End Sub
Private Sub save_as_window_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

' Initialisieren
cbAction.Items.Add("Änderungsstand erzeugen")

' falls Teil oberste Baugruppe ist, soll es keine Möglichkeit geben, etwas zu ersetzen
If Not displayPart.Equals(workPart) Then cbAction.Items.Add("als neues Teil speichern und ersetzen (alle in Sitzung)")
cbAction.Items.Add("als neues Teil speichern und öffnen")

' falls Teil ausgewählt ist letzte Option auch anzeigen
If getCountSelectedComps > 0 Then cbAction.Items.Add("selektiertes Teil speichern und in BG ersetzen")

' Vorauswahl
cbAction.Text = "Änderungsstand erzeugen"

' Hakenvorbelegung
cbZg.Checked = True
cbMove.Checked = True

End Sub
Private Sub bCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bCancel.Click
Me.Close()
End Sub
End Class

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class save_as_window
Inherits System.Windows.Forms.Form

'Das Formular überschreibt den Löschvorgang, um die Komponentenliste zu bereinigen.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub

'Wird vom Windows Form-Designer benötigt.
Private components As System.ComponentModel.IContainer

'Hinweis: Die folgende Prozedur ist für den Windows Form-Designer erforderlich.
'Das Bearbeiten ist mit dem Windows Form-Designer möglich.
'Das Bearbeiten mit dem Code-Editor ist nicht möglich.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.MenuStrip1 = New System.Windows.Forms.MenuStrip
Me.cbAction = New System.Windows.Forms.ComboBox
Me.pbZg = New System.Windows.Forms.PictureBox
Me.lblZg = New System.Windows.Forms.Label
Me.cbZg = New System.Windows.Forms.CheckBox
Me.cbMove = New System.Windows.Forms.CheckBox
'Me.cbReplaceAll = New System.Windows.Forms.CheckBox
Me.bOK = New System.Windows.Forms.Button
Me.bCancel = New System.Windows.Forms.Button
CType(Me.pbZg, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'MenuStrip1
'
Me.MenuStrip1.Location = New System.Drawing.Point(0, 0)
Me.MenuStrip1.Name = "MenuStrip1"
Me.MenuStrip1.Size = New System.Drawing.Size(394, 24)
Me.MenuStrip1.TabIndex = 1
Me.MenuStrip1.Text = "MenuStrip1"
'
'cbAction
'
Me.cbAction.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.cbAction.FormattingEnabled = True
Me.cbAction.Location = New System.Drawing.Point(22, 15)
Me.cbAction.Name = "cbAction"
Me.cbAction.Size = New System.Drawing.Size(350, 25)
Me.cbAction.TabIndex = 2
'
'pbZg
'
Me.pbZg.Location = New System.Drawing.Point(20, 52)
Me.pbZg.Name = "pbZg"
Me.pbZg.Size = New System.Drawing.Size(20, 20)
Me.pbZg.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
Me.pbZg.TabIndex = 3
Me.pbZg.TabStop = False
'
'lblZg
'
Me.lblZg.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblZg.Location = New System.Drawing.Point(52, 55)
Me.lblZg.Name = "lblZg"
Me.lblZg.Size = New System.Drawing.Size(261, 16)
Me.lblZg.TabIndex = 4
Me.lblZg.Text = "Zeichnung vorhanden / nicht vorhanden"
'
'cbZg
'
Me.cbZg.Location = New System.Drawing.Point(22, 86)
Me.cbZg.Name = "cbZg"
Me.cbZg.Size = New System.Drawing.Size(180, 20)
Me.cbZg.TabIndex = 5
Me.cbZg.Text = "Zeichnung mitkopieren"
Me.cbZg.UseVisualStyleBackColor = True
'
'cbMove
'
Me.cbMove.Location = New System.Drawing.Point(22, 112)
Me.cbMove.Name = "cbMove"
Me.cbMove.Size = New System.Drawing.Size(300, 20)
Me.cbMove.TabIndex = 6
Me.cbMove.Text = "alte Daten in Ordner ""altes"" verschieben"
Me.cbMove.UseVisualStyleBackColor = True
'
'cbReplaceAll
'
'Me.cbReplaceAll.Location = New System.Drawing.Point(22, 138)
'Me.cbReplaceAll.Name = "cbReplaceAll"
'Me.cbReplaceAll.Size = New System.Drawing.Size(320, 20)
'Me.cbReplaceAll.TabIndex = 7
'Me.cbReplaceAll.Text = "alle Vorkommnisse austauschen (in Sitzung)"
'Me.cbReplaceAll.UseVisualStyleBackColor = True
'
'bOK
'
Me.bOK.Location = New System.Drawing.Point(253, 150)
Me.bOK.Name = "bOK"
Me.bOK.Size = New System.Drawing.Size(120, 35)
Me.bOK.TabIndex = 8
Me.bOK.Text = "&Weiter"
Me.bOK.UseVisualStyleBackColor = True
'
'bCancel
'
Me.bCancel.Location = New System.Drawing.Point(127, 150)
Me.bCancel.Name = "bCancel"
Me.bCancel.Size = New System.Drawing.Size(120, 35)
Me.bCancel.TabIndex = 9
Me.bCancel.Text = "&Abbrechen"
Me.bCancel.UseVisualStyleBackColor = True
'
'save_as_window
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(8.0!, 17.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(394, 222 - 25)
Me.Controls.Add(Me.bCancel)
Me.Controls.Add(Me.bOK)
'Me.Controls.Add(Me.cbReplaceAll)
Me.Controls.Add(Me.cbMove)
Me.Controls.Add(Me.cbZg)
Me.Controls.Add(Me.lblZg)
Me.Controls.Add(Me.pbZg)
Me.Controls.Add(Me.cbAction)
Me.Controls.Add(Me.MenuStrip1)
Me.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow
Me.MainMenuStrip = Me.MenuStrip1
Me.Margin = New System.Windows.Forms.Padding(4, 4, 4, 4)
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "save_as_window"
Me.Text = "Speichern unter"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
CType(Me.pbZg, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()

End Sub
Friend WithEvents MenuStrip1 As System.Windows.Forms.MenuStrip
Friend WithEvents cbAction As System.Windows.Forms.ComboBox
Friend WithEvents pbZg As System.Windows.Forms.PictureBox
Friend WithEvents lblZg As System.Windows.Forms.Label
Friend WithEvents cbZg As System.Windows.Forms.CheckBox
Friend WithEvents cbMove As System.Windows.Forms.CheckBox
'Friend WithEvents cbReplaceAll As System.Windows.Forms.CheckBox
Friend WithEvents bOK As System.Windows.Forms.Button
Friend WithEvents bCancel As System.Windows.Forms.Button

End Class

End Module
</vbnet>

Comments

While working through the code, site user Junya Mizuta translated all the comments to english and spotted an inconsistent variable name which has been corrected in the code above.

Thanks to peter.t for the code and Junya for the translations.

<vbnet>
'/////////////////////////////////////////////////////////////////
'// //
'// Teile speichern unter / kopieren / andern //
'// //
'// //
'// //
'// Erstellt am 12.01.2016 //
'// peter.t //
'// //
'/////////////////////////////////////////////////////////////////

Option Strict Off
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Windows.Forms
Imports NXOpen
Imports NXOpen.Assemblies
Imports NXOpen.UF
Imports NXOpen.UI

Module save_as

Public theSession As Session = Session.GetSession()
Public displayPart As Part = theSession.Parts.Display
Public workPart As Part = theSession.Parts.Work

Dim theUFS As NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession()
' Dim theUI As UI = ui.GetUI
Dim theUISession As UI = UI.GetUI

Sub Main()

' when no part is loaded, error!
If IsNothing(theSession.Parts.Display) Then
theUISession.NXMessageBox.Show("Error", NXOpen.NXMessageBox.DialogType.Error, "There is no part loaded...")
Exit Sub
End If

' ask for work
If IsNothing(theSession.Parts.Work) Then
theUISession.NXMessageBox.Show("Error", NXOpen.NXMessageBox.DialogType.Error, "No active part ...")
Exit Sub
End If

' Drawings are not to be stored, it must be done from the master model
If isDrawing(workPart) = True Then
theUISession.NXMessageBox.Show("Error", NXOpen.NXMessageBox.DialogType.Error, "Illustrated part is a drawing. ...")
Exit Sub
End If

If isDrawing(displayPart) = True Then
theUISession.NXMessageBox.Show("Error", NXOpen.NXMessageBox.DialogType.Error, "Part is a drawing ...")
Exit Sub
End If

'Show window
Dim myForm As New save_as_window

myForm.ShowDialog()

End Sub
Public Sub speichern_ErsatzTeil(ByVal bCopyDrw As Boolean)

Dim prtName As String = workPart.Leaf

Dim c As Component = getSelectedComp()
If IsNothing(c) = True Then
theUISession.NXMessageBox.Show("Error", NXOpen.NXMessageBox.DialogType.Error, "More than one or no component selected!")
Exit Sub
End If

Dim selectedPart As Part = CType(theSession.Parts.FindObject(c.DisplayName), Part)

' Search path
Dim prtPath As String = selectedPart.FullPath.Replace(prtName & ".prt", "")
Dim drwName As String = selectedPart.FullPath.Replace(".prt", "_dwg1.prt")

' Calling Save dialog
Dim SFD As New SaveFileDialog

SFD.Title = "Specify a new name for part"
SFD.Filter = "NX-Dateien (*.prt) |*.prt"
SFD.InitialDirectory = prtPath
SFD.FileName = selectedPart.Leaf

Dim newPartPath As String
Dim newPartName As String

If SFD.ShowDialog = DialogResult.OK Then

newPartPath = Replace(SFD.FileName, System.IO.Path.GetFileName(SFD.FileName), "")
newPartName = System.IO.Path.GetFileName(SFD.FileName)

Else

Exit Sub

End If

' If file already exists demolition
If IO.File.Exists(newPartPath & newPartName) Then
theUISession.NXMessageBox.Show("Error", NXOpen.NXMessageBox.DialogType.Error, "Teil ist schon vorhanden. Speichern wird abgebrochen!")
Exit Sub
End If

' TESTING whether part is modified
doModifiedCheckPart(selectedPart)

Dim oldDrwName As String = selectedPart.Leaf & "_dwg1"

' save new part (first without drawing)
If Not IsNothing(c) Then

' ///// DEBUGGING
'MsgBox("components " & c.DisplayName & " selected!")
'MsgBox("Supreme component: " & getCompParent(c).DisplayName)

IO.File.Copy(selectedPart.FullPath, newPartPath & newPartName)

Dim ls1 As PartLoadStatus
theSession.Parts.OpenDisplay(newPartPath & newPartName, ls1)

' Populate new attributes
theSession.Parts.Display.SetAttribute("PRTNO", getPartNumberFromFile(newPartName.Replace(".prt", "")))
theSession.Parts.Display.SetAttribute("PRTNAME", getPartNameFromFile(newPartName.Replace(".prt", "")))
' ////// Part is finished

' Search module and open parts exchange
Dim selectedPartParent As Part = CType(theSession.Parts.FindObject(getCompParent(c).DisplayName), Part)

Dim ls2 As PartLoadStatus
theSession.Parts.SetDisplay(selectedPartParent, False, False, ls2)

Dim rcb As Assemblies.ReplaceComponentBuilder
rcb = selectedPartParent.AssemblyManager.CreateReplaceComponentBuilder()
rcb.ComponentsToReplace.Add(c)
rcb.ReplaceAllOccurrences = True
rcb.ReplacementPart = newPartPath & newPartName
rcb.SetComponentReferenceSetType(Assemblies.ReplaceComponentBuilder.ComponentReferenceSet.Maintain, Nothing)
rcb.Commit()

rcb.Destroy()

End If

' falls Zeichnung mitkopiert werden soll
If bCopyDrw = True Then

' if drawing is to be copied
If isDrwOpen(oldDrwName) = True Then doModifiedCheckDrw(theSession.Parts.FindObject(oldDrwName))

' appoint new drawing
Dim newDrw As String = newPartPath & newPartName.Replace(".prt", "_dwg1.prt")

' copy files at the OS level
IO.File.Copy(drwName, newDrw)

' Open Drawing and replace master part
If isDrwOpen(oldDrwName) = False Then

Dim ls As PartLoadStatus
theSession.Parts.OpenDisplay(newDrw, ls)
ls.Dispose()

End If

Dim prtDrw As Part = theSession.Parts.FindObject(newPartName.Replace(".prt", "_dwg1"))

Dim rcbDrw As Assemblies.ReplaceComponentBuilder

rcbDrw = prtDrw.AssemblyManager.CreateReplaceComponentBuilder()

Dim compDrw As Component = CType(prtDrw.ComponentAssembly.RootComponent.FindObject("COMPONENT " & oldDrwName.Replace("_dwg1", "") & " 1"), Component)

rcbDrw.ComponentsToReplace.Add(compDrw)
rcbDrw.ReplacementPart = newPartPath & newPartName
rcbDrw.SetComponentReferenceSetType(Assemblies.ReplaceComponentBuilder.ComponentReferenceSet.Maintain, Nothing)
rcbDrw.Commit()

rcbDrw.Destroy()

End If

' Calling the main assembly back and put geandertes part than work part
Dim ls3 As PartLoadStatus
theSession.Parts.SetDisplay(displayPart, False, False, ls3)
theSession.Parts.SetWork(CType(theSession.Parts.FindObject(newPartName.Replace(".prt", "")), Part))

' End of program
theUISession.NXMessageBox.Show("Save-Ope", NXOpen.NXMessageBox.DialogType.Information, "Successfully saved!")

End Sub
Public Sub speichern_NeuesTeil(ByVal bCopyDrw As Boolean)

Dim prtName As String = workPart.Leaf
Dim prtNameAndPath As String = workPart.FullPath

' Search path
Dim prtPath As String = workPart.FullPath.Replace(prtName & ".prt", "")
Dim drwName As String = workPart.FullPath.Replace(".prt", "_dwg1.prt")

' Calling Save dialog
Dim SFD As New SaveFileDialog

SFD.Title = "Bitte neuen Namen fur Teil angeben"
SFD.Filter = "NX-Dateien (*.prt) |*.prt"
SFD.InitialDirectory = prtPath
SFD.FileName = prtName

Dim newPartPath As String
Dim newPartName As String

If SFD.ShowDialog = DialogResult.OK Then

newPartPath = Replace(SFD.FileName, System.IO.Path.GetFileName(SFD.FileName), "")
newPartName = System.IO.Path.GetFileName(SFD.FileName)

Else

Exit Sub

End If

' If file already exists demolition
If IO.File.Exists(newPartPath & newPartName) Then
theUISession.NXMessageBox.Show("Error", NXOpen.NXMessageBox.DialogType.Error, "Part already exists. Save is canceled!")
Exit Sub
End If

' TESTING whether part is modified
doModifiedCheckPart(workPart)

' falls Zeichnung mitkopiert werden soll
If bCopyDrw = True Then

' prufen ob Zeichnung modifiziert ist
If isDrwOpen(workPart.Leaf & "_dwg1") = True Then doModifiedCheckDrw(theSession.Parts.FindObject(workPart.Leaf & "_dwg1"))

' if drawing is to be copied
Dim newDrw As String = newPartPath & newPartName.Replace(".prt", "_dwg1.prt")

' copy files at the OS level
IO.File.Copy(workPart.FullPath, newPartPath & newPartName)
IO.File.Copy(drwName, newDrw)

Dim oldPrt As String = workPart.Leaf

' Open Drawing and replace master part
Try

Dim ls As PartLoadStatus
theSession.Parts.OpenDisplay(newDrw, ls)
ls.Dispose()

Catch ex As Exception

End Try

Dim prtDrw As Part = theSession.Parts.FindObject(newPartName.Replace(".prt", "_dwg1"))

Dim rcb As Assemblies.ReplaceComponentBuilder

rcb = prtDrw.AssemblyManager.CreateReplaceComponentBuilder()

' ONLY exchanged first instance on drawing out if several there
Dim compDrw As Component = CType(prtDrw.ComponentAssembly.RootComponent.FindObject("COMPONENT " & oldPrt & " 1"), Component)

rcb.ComponentsToReplace.Add(compDrw)
rcb.ReplacementPart = newPartPath & newPartName
rcb.SetComponentReferenceSetType(Assemblies.ReplaceComponentBuilder.ComponentReferenceSet.Maintain, Nothing)
rcb.Commit()

rcb.Destroy()

' Open a new part if not already open
Try

Dim ls1 As PartLoadStatus
theSession.Parts.OpenDisplay(newPartPath & newPartName, ls1)
ls1.Dispose()

Catch ex As Exception

' Part is already open
Dim prtNew As Part = theSession.Parts.FindObject(newPartName.Replace(".prt", ""))
Dim ls2 As PartLoadStatus
theSession.Parts.SetDisplay(prtNew, True, True, ls2)

End Try

'Populate new attributes
theSession.Parts.Display.SetAttribute("PRTNO", getPartNumberFromFile(newPartName.Replace(".prt", "")))
theSession.Parts.Display.SetAttribute("PRTNAME", getPartNameFromFile(newPartName.Replace(".prt", "")))

Else

' Add a new member (without drawing)
IO.File.Copy(workPart.FullPath, newPartPath & newPartName)

' Open a new part
Try

Dim ls1 As PartLoadStatus
theSession.Parts.OpenDisplay(newPartPath & newPartName, ls1)
ls1.Dispose()

'Populate new attributes
theSession.Parts.Display.SetAttribute("PRTNO", getPartNumberFromFile(newPartName.Replace(".prt", "")))
theSession.Parts.Display.SetAttribute("PRTNAME", getPartNameFromFile(newPartName.Replace(".prt", "")))

Catch ex As Exception

End Try

End If

' End of program
theUISession.NXMessageBox.Show("Save operation", NXOpen.NXMessageBox.DialogType.Information, "Successfully saved!")

End Sub
Public Sub speichern_Aenderungsstand(ByVal bCopyDrw As Boolean, ByVal bMoveOldFiles As Boolean, ByVal bAttributesSync As Boolean)

' save part with a new change status
Dim prtName As String = workPart.Leaf
Dim prtNameAndPath As String = workPart.FullPath

' Search path
Dim prtPath As String = workPart.FullPath.Replace(prtName & ".prt", "")
Dim drwName As String = workPart.FullPath.Replace(".prt", "_dwg1.prt")

' Calling Save dialog
Dim SFD As New SaveFileDialog

SFD.Title = "Bitte neuen Namen fur Teil angeben"
SFD.Filter = "NX-Dateien (*.prt) |*.prt"
SFD.InitialDirectory = prtPath
SFD.FileName = prtName

Dim newPartPath As String
Dim newPartName As String

If SFD.ShowDialog = DialogResult.OK Then

newPartPath = Replace(SFD.FileName, System.IO.Path.GetFileName(SFD.FileName), "")
newPartName = System.IO.Path.GetFileName(SFD.FileName)

Else

Exit Sub

End If

'If file already exists demolition
If IO.File.Exists(newPartPath & newPartName) Then
theUISession.NXMessageBox.Show("Error", NXOpen.NXMessageBox.DialogType.Error, "Teil ist schon vorhanden. Speichern wird abgebrochen!")
Exit Sub
End If

' TESTING whether part is modified
' and Modified check Part (Part work)

' if drawing is to be copied
If bCopyDrw = True Then

' Load drawing (if not already done)
Try

Dim ls1 As PartLoadStatus
theSession.Parts.Open(drwName, ls1)
ls1.Dispose()

Catch ex As Exception

End Try

' save new part
Dim saveStatus1 As PartSaveStatus = workPart.SaveAs(newPartPath & newPartName)
saveStatus1.Dispose()

' Populate the new account number
workPart.SetAttribute("PRTNO", getPartNumberFromFile(newPartName.Replace(".prt", "")))
If bAttributesSync = True Then workPart.SetAttribute("PRTNAME", getPartNameFromFile(newPartName.Replace(".prt", "")))

' Save drawing
Dim drwPart As Part = theSession.Parts.FindObject(drwName.Replace(".prt", ""))
Dim saveStatus2 As PartSaveStatus = drwPart.SaveAs(newPartPath & newPartName.Replace(".prt", "") & "_dwg1")
saveStatus2.Dispose()

Else

' Add a new member (without drawing)
Dim saveStatus1 As PartSaveStatus = workPart.SaveAs(newPartPath & newPartName)
saveStatus1.Dispose()

' Populate the new account number
workPart.SetAttribute("PRTNO", getPartNumberFromFile(newPartName))
If bAttributesSync = True Then workPart.SetAttribute("PRTNAME", getPartNameFromFile(newPartName.Replace(".prt", "")))

End If

' //// delete old files when erwunscht
If bMoveOldFiles = True Then

Dim trashPath As String = IO.Path.GetDirectoryName(prtPath) & "\altes\"
' Review and possible creation of Mullordners
If theUISession.NXMessageBox.Show("Ordner erstellen", NXOpen.NXMessageBox.DialogType.Question, "Der Ordner " & trashPath & " ist nicht vorhanden. Soll der Ordner erstellt werden?") = 1 Then

If theUISession.NXMessageBox.Show("create folder", NXOpen.NXMessageBox.DialogType.Question, "The folder " & trashPath & " is not present. To be created, the folder?") = 1 Then

' Verzeichnis erstellen
IO.Directory.CreateDirectory(trashPath)

Else

theUISession.NXMessageBox.Show("Save operation", NXOpen.NXMessageBox.DialogType.Information, "Successfully saved! The old files were not moved.")
Exit Sub

End If

End If

' move old files (overwrite as needed)
If IO.File.Exists(trashPath & prtName & ".prt") = True Then IO.File.Delete(trashPath & prtName & ".prt")
IO.File.Move(prtNameAndPath, trashPath & prtName & ".prt")

If IO.File.Exists(trashPath & prtName & "_dwg1.prt") = True Then IO.File.Delete(trashPath & prtName & "_dwg1.prt")
IO.File.Move(drwName, trashPath & prtName & "_dwg1.prt")

' move 'PDF file even if exists
If IO.File.Exists(prtNameAndPath.Replace(".prt", "_dwg1.pdf")) = True Then

If IO.File.Exists(trashPath & prtName & "_dwg1.pdf") = True Then IO.File.Delete(trashPath & prtName & "_dwg1.pdf")
IO.File.Move(prtNameAndPath.Replace(".prt", "_dwg1.pdf"), trashPath & prtName & "_dwg1.pdf")

End If

End If

' Ende des Programms
theUISession.NXMessageBox.Show("Save operation", NXOpen.NXMessageBox.DialogType.Information, "Successfully saved!")

End Sub
Public Function getCompParent(ByVal comp As Component) As Component

Return comp.OwningComponent

End Function
Public Function getSelectedComp() As Component

' Query is whether a part is selected
Dim intNumSelected As Integer = theUISession.SelectionManager.GetNumSelectedObjects()

If intNumSelected = 0 Then Exit Function

Dim SelectedList As New List(Of Component)
For i As Integer = 0 To intNumSelected - 1

Dim intType As Integer
Dim intSubType As Integer

Dim objSelected As NXObject = theUISession.SelectionManager.GetSelectedObject(i)
theUFS.Obj.AskTypeAndSubtype(objSelected.Tag, intType, intSubType)

If intType = UFConstants.UF_component_type Then

Dim theComp As Component = DirectCast(objSelected, Component)
If inList(theComp, SelectedList) = False Then SelectedList.Add(theComp)

End If

Next

If SelectedList.Count = 1 Then

Return SelectedList.Item(0)

Else

theUISession.NXMessageBox.Show("Error", NXOpen.NXMessageBox.DialogType.Error, "More than one or no component selected!")

End If

End Function
Public Function getCountSelectedComps() As Integer

' Query is selected as many parts
Dim intNumSelected As Integer = theUISession.SelectionManager.GetNumSelectedObjects()

Return intNumSelected

End Function
Public Function inList(ByVal comp As Component, ByVal l As List(Of Component)) As Boolean

For x As Integer = 0 To l.Count - 1

If l.Item(x).DisplayName = comp.DisplayName Then

Return True
Exit For

End If

Next

End Function
Public Function isDrawing(ByVal prt As Part) As Boolean

' pruft whether the supplied parts is a drawing
If Right(prt.Leaf, 5) = "_dwg1" Then

Return True

Else

Return False

End If

End Function
Public Function isDrwOpen(ByVal drwName As String) As Boolean

' checks whether the supplied drawing is open in session
Try

Dim p As Part = theSession.Parts.FindObject(drwName)
Return True

Catch ex As Exception

Return False

End Try
End Function
Public Sub doModifiedCheckPart(ByVal prt As Part)

' checks if the incoming file should still be stored in advance
If theUfS.Part.IsModified(prt.Tag) = True Then

If theUISession.NXMessageBox.Show("Save", NXOpen.NXMessageBox.DialogType.Question, "The part " & prt.Leaf & " is modified. If the part can be stored in advance?") = 1 Then

Dim ss As PartSaveStatus = prt.Save(True, False)
ss.Dispose()

End If

End If

End Sub
Public Sub doModifiedCheckDrw(ByVal drw As Part)

' checks if the incoming file should still be stored in advance
If theUfS.Part.IsModified(drw.Tag) = True Then

If theUISession.NXMessageBox.Show("Save", NXOpen.NXMessageBox.DialogType.Question, "The drawing " & drw.Leaf & " is modified. If the part can be stored in advance?") = 1 Then

Dim ss As PartSaveStatus = drw.Save(True, False)
ss.Dispose()

End If

End If

End Sub
Public Function hasDrawing(ByVal prt As Part) As Boolean

' pruft whether the supplied part has a drawing
Dim drwFileName As String = prt.FullPath.Replace(".prt", "_dwg1.prt")

If IO.File.Exists(drwFileName) = False Then
Return False
Else
Return True
End If

End Function
Public Function getPartNameFromFile(ByVal file As String) As String

' Read part designation from filenames
Try

Static Dim LastChar As Integer
Static Dim tmpBenennung As String

' read and process filename
Dim currentFile As String = file
Static Dim FileNameLength As Integer = currentFile.Length

' Assembly number with spaces (xxx xx xxx_xx)
If currentFile.IndexOf("_", 0, 12) = 10 Then

LastChar = 14
tmpBenennung = currentFile.SubString(LastChar, FileNameLength - LastChar)

End If

' Assembly number with spaces (xxx xx xx xx)
If currentFile.IndexOf("_", 0, 12) = 9 Then

LastChar = 13
tmpBenennung = currentFile.SubString(LastChar, FileNameLength - LastChar)

End If

' Drawing no 8-digit number with no spaces
If currentFile.IndexOf("_", 0, 10) = 8 Then

LastChar = 12
tmpBenennung = currentFile.SubString(LastChar, FileNameLength - LastChar)

End If

' Drawing no 7-digit number without spaces
If currentFile.IndexOf("_", 0, 10) = 7 Then

LastChar = 11
tmpBenennung = currentFile.SubString(LastChar, FileNameLength - LastChar)

End If

tmpBenennung = currentFile.SubString(LastChar, FileNameLength - LastChar)
Dim Benennung As String = tmpBenennung.Replace("_", " ")

Return Benennung

Catch ex As Exception

'MsgBox(ex.Message)

End Try

End Function
Public Function getPartNumberFromFile(ByVal file As String) As String

' Read drawing number from filenames
Try

Static Dim ZgNr As String
Static Dim tmpZgNr As String
Static Dim LastChar As Integer

' read and process filename
Dim currentFile As String = file
Static Dim FileNameLength As Integer = currentFile.Length

' Assembly number with spaces (xxx xx xxx_xx)
If currentFile.IndexOf("_", 0, 12) = 10 Then

ZgNr = currentFile.Substring(0, 13)
LastChar = 14

Return ZgNr

End If

' Assembly number with spaces (xxx xx xxx_xx)
If currentFile.IndexOf("_", 0, 12) = 9 Then

ZgNr = currentFile.Substring(0, 12)
LastChar = 13

Return ZgNr

End If

' Drawing no 8-digit number with no spaces
If currentFile.IndexOf("_", 0, 10) = 8 Then

tmpZgNr = currentFile.Substring(0, 11)
LastChar = 12
Dim Teil1 As String = tmpZgNr.Substring(0, 3)
Dim Teil2 As String = tmpZgNr.Substring(3, 2)
Dim Teil3 As String = tmpZgNr.Substring(5, 6)
ZgNr = Teil1 & " " & Teil2 & " " & Teil3

Return ZgNr

End If

' Drawing no 7-digit number without spaces
If currentFile.IndexOf("_", 0, 10) = 7 Then

tmpZgNr = currentFile.Substring(0, 10)
LastChar = 11
Dim Teil1 As String = tmpZgNr.Substring(0, 3)
Dim Teil2 As String = tmpZgNr.Substring(3, 2)
Dim Teil3 As String = tmpZgNr.Substring(5, 5)
ZgNr = Teil1 & " " & Teil2 & " " & Teil3

Return ZgNr

End If

Catch ex As Exception

'MsgBox(ex.Message)

End Try

End Function
Public Function GetUnloadOption(ByVal dummy As String) As Integer

Return Session.LibraryUnloadOption.Immediately

End Function
Public Class save_as_window

Private Sub bOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bOK.Click

Me.Visible = False
Me.Close()

If cbAction.Text = "Make Revision" Then speichern_Aenderungsstand(cbZg.Checked, cbMove.Checked, False)

If cbAction.Text = "Save as a new part and open" Then speichern_NeuesTeil(cbZg.Checked)

If cbAction.Text = "Save as a new part and replace (all in session)" Then speichern_Aenderungsstand(cbZg.Checked, False, True)

If cbAction.Text = "save-selected part and replace in BG" Then speichern_ErsatzTeil(cbZg.Checked)

End Sub
Private Sub cbAction_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbAction.SelectedIndexChanged

If cbAction.Text = "Make Revision" Then
cbMove.Enabled = True
Me.Text = "Save as: " & workPart.Leaf

' drawing inspection
If hasDrawing(workPart) = True Then

pbZg.ImageLocation = "set path to icon that says yes"
lblZg.Text = "drawing is available"
Else

pbZg.ImageLocation = "set path to icon that says no"
lblZg.Text = "Drawing No"
cbZg.Checked = False
cbZg.Enabled = False
End If

End If

If cbAction.Text = "Save as a new part and replace (all in session)" Then
cbMove.Enabled = False
Me.Text = "Save as: " & workPart.Leaf

' drawing inspection
If hasDrawing(workPart) = True Then

pbZg.ImageLocation = "set path to icon that says yes"
lblZg.Text = "drawing is available"
Else

pbZg.ImageLocation = "set path to icon that says no"
lblZg.Text = "Drawing No"
cbZg.Checked = False
cbZg.Enabled = False
End If

End If

If cbAction.Text = "als neues Teil speichern und offnen" Then
cbMove.Enabled = False
Me.Text = "Save as: " & workPart.Leaf

' drawing inspection
If hasDrawing(workPart) = True Then

pbZg.ImageLocation = "set path to icon that says yes"
lblZg.Text = "drawing is available"
Else

pbZg.ImageLocation = "set path to icon that says no"
lblZg.Text = "Drawing No"
cbZg.Checked = False
cbZg.Enabled = False
End If

End If

If cbAction.Text = "selektiertes Teil speichern und in BG ersetzen" Then
cbMove.Enabled = False

If IsNothing(getSelectedComp) Then
Me.Close()
Exit Sub
End If

Me.Text = "Save as: " & getSelectedComp.DisplayName

' drawing inspection
If hasDrawing(CType(theSession.Parts.FindObject(getSelectedComp.DisplayName), Part)) = True Then

pbZg.ImageLocation = "set path to icon that says yes"
lblZg.Text = "drawing is available"
Else

pbZg.ImageLocation = "set path to icon that says no"
lblZg.Text = "Drawing No"
cbZg.Checked = False
cbZg.Enabled = False

End If

End If

End Sub
Private Sub save_as_window_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

' Initialize
cbAction.Items.Add("Make Revision")

' if part is top assembly, there will be no way to replace some
If Not displayPart.Equals(workPart) Then cbAction.Items.Add("als neues Teil speichern und ersetzen (alle in Sitzung)")
cbAction.Items.Add("Save as a new part and open")

'if part is selected last option See also
If getCountSelectedComps > 0 Then cbAction.Items.Add("selektiertes Teil speichern und in BG ersetzen")

' preselection
cbAction.Text = "Make Revision"

' Hakenvorbelegung
cbZg.Checked = True
cbMove.Checked = True

End Sub
Private Sub bCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bCancel.Click
Me.Close()
End Sub
End Class

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class save_as_window
Inherits System.Windows.Forms.Form

'The form overrides the deletion to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub

'If needed by the Windows Form Designer.
Private components As System.ComponentModel.IContainer

'Note: The following procedure is required for the Windows Form Designer.
'Editing is possible with the Windows Form Designer.
'Do not modify the code editor is not possible.

<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.MenuStrip1 = New System.Windows.Forms.MenuStrip
Me.cbAction = New System.Windows.Forms.ComboBox
Me.pbZg = New System.Windows.Forms.PictureBox
Me.lblZg = New System.Windows.Forms.Label
Me.cbZg = New System.Windows.Forms.CheckBox
Me.cbMove = New System.Windows.Forms.CheckBox
'Me.cbReplaceAll = New System.Windows.Forms.CheckBox
Me.bOK = New System.Windows.Forms.Button
Me.bCancel = New System.Windows.Forms.Button
CType(Me.pbZg, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'MenuStrip1
'
Me.MenuStrip1.Location = New System.Drawing.Point(0, 0)
Me.MenuStrip1.Name = "MenuStrip1"
Me.MenuStrip1.Size = New System.Drawing.Size(394, 24)
Me.MenuStrip1.TabIndex = 1
Me.MenuStrip1.Text = "MenuStrip1"
'
'cbAction
'
Me.cbAction.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.cbAction.FormattingEnabled = True
Me.cbAction.Location = New System.Drawing.Point(22, 15)
Me.cbAction.Name = "cbAction"
Me.cbAction.Size = New System.Drawing.Size(350, 25)
Me.cbAction.TabIndex = 2
'
'pbZg
'
Me.pbZg.Location = New System.Drawing.Point(20, 52)
Me.pbZg.Name = "pbZg"
Me.pbZg.Size = New System.Drawing.Size(20, 20)
Me.pbZg.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
Me.pbZg.TabIndex = 3
Me.pbZg.TabStop = False
'
'lblZg
'
Me.lblZg.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblZg.Location = New System.Drawing.Point(52, 55)
Me.lblZg.Name = "lblZg"
Me.lblZg.Size = New System.Drawing.Size(261, 16)
Me.lblZg.TabIndex = 4
Me.lblZg.Text = "drawing is available / not available"
'
'cbZg
'
Me.cbZg.Location = New System.Drawing.Point(22, 86)
Me.cbZg.Name = "cbZg"
Me.cbZg.Size = New System.Drawing.Size(180, 20)
Me.cbZg.TabIndex = 5
Me.cbZg.Text = "Copy drawing"
Me.cbZg.UseVisualStyleBackColor = True
'
'cbMove
'
Me.cbMove.Location = New System.Drawing.Point(22, 112)
Me.cbMove.Name = "cbMove"
Me.cbMove.Size = New System.Drawing.Size(300, 20)
Me.cbMove.TabIndex = 6
Me.cbMove.Text = "old data in folders ""old one"" move"
Me.cbMove.UseVisualStyleBackColor = True
'
'cbReplaceAll
'
'Me.cbReplaceAll.Location = New System.Drawing.Point(22, 138)
'Me.cbReplaceAll.Name = "cbReplaceAll"
'Me.cbReplaceAll.Size = New System.Drawing.Size(320, 20)
'Me.cbReplaceAll.TabIndex = 7
'Me.cbReplaceAll.Text = "Replace all occurrences (in session)"
'Me.cbReplaceAll.UseVisualStyleBackColor = True
'
'bOK
'
Me.bOK.Location = New System.Drawing.Point(253, 150)
Me.bOK.Name = "bOK"
Me.bOK.Size = New System.Drawing.Size(120, 35)
Me.bOK.TabIndex = 8
Me.bOK.Text = "&Continue"
Me.bOK.UseVisualStyleBackColor = True
'
'bCancel
'
Me.bCancel.Location = New System.Drawing.Point(127, 150)
Me.bCancel.Name = "bCancel"
Me.bCancel.Size = New System.Drawing.Size(120, 35)
Me.bCancel.TabIndex = 9
Me.bCancel.Text = "&abort"
Me.bCancel.UseVisualStyleBackColor = True
'
'save_as_window
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(8.0!, 17.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(394, 222 - 25)
Me.Controls.Add(Me.bCancel)
Me.Controls.Add(Me.bOK)
'Me.Controls.Add(Me.cbReplaceAll)
Me.Controls.Add(Me.cbMove)
Me.Controls.Add(Me.cbZg)
Me.Controls.Add(Me.lblZg)
Me.Controls.Add(Me.pbZg)
Me.Controls.Add(Me.cbAction)
Me.Controls.Add(Me.MenuStrip1)
Me.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow
Me.MainMenuStrip = Me.MenuStrip1
Me.Margin = New System.Windows.Forms.Padding(4, 4, 4, 4)
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "save_as_window"
Me.Text = "Save as"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
CType(Me.pbZg, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()

End Sub
Friend WithEvents MenuStrip1 As System.Windows.Forms.MenuStrip
Friend WithEvents cbAction As System.Windows.Forms.ComboBox
Friend WithEvents pbZg As System.Windows.Forms.PictureBox
Friend WithEvents lblZg As System.Windows.Forms.Label
Friend WithEvents cbZg As System.Windows.Forms.CheckBox
Friend WithEvents cbMove As System.Windows.Forms.CheckBox
'Friend WithEvents cbReplaceAll As System.Windows.Forms.CheckBox
Friend WithEvents bOK As System.Windows.Forms.Button
Friend WithEvents bCancel As System.Windows.Forms.Button

End Class

End Module
</vbnet>