'==============================================================================
' WARNING!! This file is overwritten by the Block UI Styler while generating
' the automation code. Any modifications to this file will be lost after
' generating the code again.
'
' Filename: C:\Users\NICO\Desktop\CreatePartsFromReferenceUI.vb
'
' This file was generated by the NX Block UI Styler
' Created by: NICO
' Version: NX 9
' Date: 02-07-2015 (Format: mm-dd-yyyy)
' Time: 15:51 (Format: hh-mm)
'
'==============================================================================
'==============================================================================
' Purpose: This TEMPLATE file contains VB.NET source to guide you in the
' construction of your Block application dialog. The generation of your
' dialog file (.dlx extension) is the first step towards dialog construction
' within NX. You must now create a NX Open application that
' utilizes this file (.dlx).
'
' The information in this file provides you with the following:
'
' 1. Help on how to load and display your Block UI Styler dialog in NX
' using APIs provided in NXOpen.BlockStyler namespace
' 2. The empty callback methods (stubs) associated with your dialog items
' have also been placed in this file. These empty methods have been
' created simply to start you along with your coding requirements.
' The method name, argument list and possible return values have already
' been provided for you.
'==============================================================================
'------------------------------------------------------------------------------
'These imports are needed for the following template code
'------------------------------------------------------------------------------
Option Strict Off
Imports System
Imports NXOpen
Imports NXOpen.BlockStyler
Imports System.IO
Imports MiniSnap
'------------------------------------------------------------------------------
'Represents Block Styler application class
'------------------------------------------------------------------------------
Public Class CreatePartsFromReferenceUI
'class members
Private Shared theSession As Session
Private Shared theUI As UI
' Manipulated; Added Class Members:
Private Shared refPart As Part
Private Shared displayPart As Part
Private theDlxFileName As String
Private theDialog As NXOpen.BlockStyler.BlockDialog
Private stringInputName0 As NXOpen.BlockStyler.StringBlock ' Block type: String
Private assyNoInteger As NXOpen.BlockStyler.IntegerBlock
Private secAssyNoInput As NXOpen.BlockStyler.IntegerBlock
Private groupBody As NXOpen.BlockStyler.Group ' Block type: Group
Private bodySelect As NXOpen.BlockStyler.BodyCollector ' Block type: Body Collector
Private fileBrowser0 As NXOpen.BlockStyler.FileSelection ' Block type: NativeFileBrowser
'------------------------------------------------------------------------------
'Bit Option for Property: EntityType
'------------------------------------------------------------------------------
Public Shared ReadOnly EntityType_AllowBodies As Integer = 64
'------------------------------------------------------------------------------
'Bit Option for Property: BodyRules
'------------------------------------------------------------------------------
Public Shared ReadOnly BodyRules_SingleBody As Integer = 1
Public Shared ReadOnly BodyRules_FeatureBodies As Integer = 2
Public Shared ReadOnly BodyRules_BodiesinGroup As Integer = 4
#Region "Block Styler Dialog Designer generator code"
'------------------------------------------------------------------------------
'Constructor for NX Styler class
'------------------------------------------------------------------------------
Public Sub New()
Try
theSession = Session.GetSession()
theUI = UI.GetUI()
theDlxFileName = "C:\Users\NICO\Documents\Visual Studio 2013\Projects\CreatePartsFromReference\CreatePartsFromReference\CreatePartsFromReferenceUI.dlx"
theDialog = theUI.CreateDialog(theDlxFileName)
theDialog.AddApplyHandler(AddressOf apply_cb)
theDialog.AddOkHandler(AddressOf ok_cb)
theDialog.AddUpdateHandler(AddressOf update_cb)
theDialog.AddInitializeHandler(AddressOf initialize_cb)
theDialog.AddDialogShownHandler(AddressOf dialogShown_cb)
'Check if correct Product Structure is opened
refPart = theSession.Parts.Work
displayPart = theSession.Parts.Display
If Not ExternalFunctions.correctProductOpened(displayPart, refPart) Then
' If not correct: Throw an Exception and refer to the Users Guide.
Dispose()
Throw (New Exception("Opened Part Structure not allowed to use this Makro. See Guide for more Information."))
End If
Catch ex As Exception
theUI.NXMessageBox.Show("Exception at Makro Start", NXMessageBox.DialogType.Error, ex.ToString)
'---- Enter your exception handling code here -----
Throw ex
End Try
End Sub
#End Region
'------------------------------- DIALOG LAUNCHING ---------------------------------
'
' Before invoking this application one needs to open any part/empty part in NX
' because of the behavior of the blocks.
'
' Make sure the dlx file is in one of the following locations:
' 1.) From where NX session is launched
' 2.) $UGII_USER_DIR/application
' 3.) For released applications, using UGII_CUSTOM_DIRECTORY_FILE is highly
' recommended. This variable is set to a full directory path to a file
' containing a list of root directories for all custom applications.
' e.g., UGII_CUSTOM_DIRECTORY_FILE=$UGII_ROOT_DIR\menus\custom_dirs.dat
'
' You can create the dialog using one of the following way:
'
' 1. Journal Replay
'
' 1) Replay this file through Tool->Journal->Play Menu.
'
' 2. USER EXIT
'
' 1) Create the Shared Library -- Refer "Block UI Styler programmer's guide"
' 2) Invoke the Shared Library through File->Execute->NX Open menu.
'
'------------------------------------------------------------------------------
Public Shared Sub Main()
Dim theCreatePartsFromReferenceUI As CreatePartsFromReferenceUI = Nothing
Try
theCreatePartsFromReferenceUI = New CreatePartsFromReferenceUI()
' The following method shows the dialog immediately
theCreatePartsFromReferenceUI.Show()
Catch ex As Exception
'---- Enter your exception handling code here -----
theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString)
Finally
If theCreatePartsFromReferenceUI IsNot Nothing Then
theCreatePartsFromReferenceUI.Dispose()
theCreatePartsFromReferenceUI = Nothing
End If
End Try
End Sub
'------------------------------------------------------------------------------
' This method specifies how a shared image is unloaded from memory
' within NX. This method gives you the capability to unload an
' internal NX Open application or user exit from NX. Specify any
' one of the three constants as a return value to determine the type
' of unload to perform:
'
'
' Immediately : unload the library as soon as the automation program has completed
' Explicitly : unload the library from the "Unload Shared Image" dialog
' AtTermination : unload the library when the NX session terminates
'
'
' NOTE: A program which associates NX Open applications with the menubar
' MUST NOT use this option since it will UNLOAD your NX Open application image
' from the menubar.
'------------------------------------------------------------------------------
Public Shared Function GetUnloadOption(ByVal arg As String) As Integer
'Return CType(Session.LibraryUnloadOption.Explicitly, Integer)
Return CType(Session.LibraryUnloadOption.Immediately, Integer)
' Return CType(Session.LibraryUnloadOption.AtTermination, Integer)
End Function
'------------------------------------------------------------------------------
' Following method cleanup any housekeeping chores that may be needed.
' This method is automatically called by NX.
'------------------------------------------------------------------------------
Public Shared Sub UnloadLibrary(ByVal arg As String)
Try
Catch ex As Exception
'---- Enter your exception handling code here -----
theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString)
End Try
End Sub
'------------------------------------------------------------------------------
'This method shows the dialog on the screen
'------------------------------------------------------------------------------
Public Sub Show()
Try
theDialog.Show()
Catch ex As Exception
'---- Enter your exception handling code here -----
theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString)
End Try
End Sub
'------------------------------------------------------------------------------
'Method Name: Dispose
'------------------------------------------------------------------------------
Public Sub Dispose()
If theDialog IsNot Nothing Then
theDialog.Dispose()
theDialog = Nothing
End If
End Sub
'------------------------------------------------------------------------------
'---------------------Block UI Styler Callback Functions--------------------------
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
'Callback Name: initialize_cb
'------------------------------------------------------------------------------
Public Sub initialize_cb()
Try
stringInputName0 = CType(theDialog.TopBlock.FindBlock("string0"), NXOpen.BlockStyler.StringBlock)
groupBody = CType(theDialog.TopBlock.FindBlock("group0"), NXOpen.BlockStyler.Group)
bodySelect = CType(theDialog.TopBlock.FindBlock("bodySelect00"), NXOpen.BlockStyler.BodyCollector)
fileBrowser0 = CType(theDialog.TopBlock.FindBlock("nativeFileBrowser0"), NXOpen.BlockStyler.FileSelection)
assyNoInteger = CType(theDialog.TopBlock.FindBlock("assyNoInteger"), NXOpen.BlockStyler.IntegerBlock)
secAssyNoInput = CType(theDialog.TopBlock.FindBlock("secAssyNoInput"), NXOpen.BlockStyler.IntegerBlock)
Catch ex As Exception
'---- Enter your exception handling code here -----
theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString)
End Try
End Sub
'------------------------------------------------------------------------------
'Callback Name: dialogShown_cb
'This callback is executed just before the dialog launch. Thus any value set
'here will take precedence and dialog will be launched showing that value.
'------------------------------------------------------------------------------
Public Sub dialogShown_cb()
Try
'---- Enter your callback code here -----
Catch ex As Exception
'---- Enter your exception handling code here -----
theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString)
End Try
End Sub
'------------------------------------------------------------------------------
'Callback Name: apply_cb
'------------------------------------------------------------------------------
Public Function apply_cb() As Integer
Dim errorCode As Integer = 0
Try
Dim sourcePath As String = ExternalFunctions.checkPath(fileBrowser0.Path)
Dim fullPath As String = refPart.FullPath
Dim targetPath As String = ExternalFunctions.splitFullPath(fullPath)
Dim inputName As String = stringInputName0.Value
Dim assyNo As String = integerToString(assyNoInteger.Value, 2)
Dim secAssyNo As String = integerToString(secAssyNoInput.Value, 2)
Dim dieName As String = getDieName(refPart)
Dim partNumber As Integer = 119
Dim partName As String = ""
Dim selectedBodies As TaggedObject()
selectedBodies = bodySelect.GetSelectedObjects()
For bodyCounter As Integer = 0 To (selectedBodies.Length - 1)
Dim currentBody As Body = CType(selectedBodies(bodyCounter), Body)
' Create a new Body
' Tries to Copy Body from Directory to Die Path
' If Die Path contains a Part with the same Name, Number in Name increases
' Try again until Sucess
Dim copyError As Integer = 0
Do While copyError = 0
partNumber += 1
partName = assyNo & "_" & secAssyNo & "_" & partNumber & "__" & inputName & "__" & dieName & "_ID" & hexNumber()
copyError = ExternalFunctions.createPartsInDirectory(targetPath, sourcePath, partName)
Loop
' Catch Exception from Part Creation
If copyError = -1 Then Return 1
refPart = theSession.Parts.Work
displayPart = theSession.Parts.Display
' Set the Parent Assembly activ
Dim nullAssemblies_Component As Assemblies.Component = Nothing
Dim pls1 As PartLoadStatus
theSession.Parts.SetWorkComponent( _
nullAssemblies_Component, pls1)
Dim rootPart As Part = theSession.Parts.Work
pls1.Dispose()
' Add a Component to the Assembly
Dim destinationPath As String = targetPath & partName '& ".prt"
Dim newComponent As Assemblies.Component = addComponent(rootPart, destinationPath, partName)
' Set the inserted Part as the Work Part
Dim pls2 As PartLoadStatus
theSession.Parts.SetWorkComponent(newComponent, pls2)
Dim newPart As Part = theSession.Parts.Work
pls2.Dispose()
'Set the Feature that the Bodies will be copied activ
Try
Dim activFeatureGroup As Features.FeatureGroup = CType( _
newPart.Features.FindObject("FEATURE_SET(23)"), Features.FeatureGroup)
activFeatureGroup.SetGroupActive(True)
Catch ex As Exception
Exit Try
End Try
' Copy one of the selected Bodies into this Part
waveGeoLinkBody(newPart, currentBody)
Next bodyCounter
'---- Enter your callback code here -----
Catch ex As Exception
'---- Enter your exception handling code here -----
errorCode = 1
theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString)
End Try
apply_cb = errorCode
End Function
'------------------------------------------------------------------------------
'Callback Name: update_cb
'------------------------------------------------------------------------------
Public Function update_cb(ByVal block As NXOpen.BlockStyler.UIBlock) As Integer
Try
If block Is stringInputName0 Then
'---- Enter your code here -----
ElseIf block Is bodySelect Then
'---- Enter your code here -----
ElseIf block Is fileBrowser0 Then
'---- Enter your code here -----
ElseIf block Is assyNoInteger Then
'---- Enter your code here -----
ElseIf block Is secAssyNoInput Then
'---- Enter your code here -----
End If
Catch ex As Exception
'---- Enter your exception handling code here -----
theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString)
End Try
update_cb = 0
End Function
'------------------------------------------------------------------------------
'Callback Name: ok_cb
'------------------------------------------------------------------------------
Public Function ok_cb() As Integer
Dim errorCode As Integer = 0
Try
'---- Enter your callback code here -----
errorCode = apply_cb()
Catch ex As Exception
'---- Enter your exception handling code here -----
errorCode = 1
theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString)
End Try
ok_cb = errorCode
End Function
'------------------------------------------------------------------------------
'Function Name: GetBlockProperties
'Returns the propertylist of the specified BlockID
'------------------------------------------------------------------------------
Public Function GetBlockProperties(ByVal blockID As String) As PropertyList
GetBlockProperties = Nothing
Try
GetBlockProperties = theDialog.GetBlockProperties(blockID)
Catch ex As Exception
'---- Enter your exception handling code here -----
theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString)
End Try
End Function
End Class
Public Module ExternalFunctions
'''
''' Copys a File from sourcepath to targetpath and checks if Part Number in given Name is already used.
'''
''' Destination path, ends with "\"
''' Path of Template Part, ends with "\"
''' Name of the Part File, without ".prt"
''' 0 if Part already exists, -1 if Exception occurs, 1 if copying was successfull.
'''
Public Function createPartsInDirectory(ByVal targetPath As String, ByVal sourcePath As String, ByVal saveName As String) As Integer
' Check whether the file exists or not
' Therefor:
' Save all the Names of the Files from the Save Directory to an Array
' Check each Name in this Array whether it contains the Position Number that is given to the Part
Dim fileArray As String() = Directory.GetFiles(targetPath)
Dim testString As String = Left(saveName, 10)
For Each fileName As String In fileArray
If fileName.Contains(testString) Then Return 0
Next
Dim filepath As String = targetPath & saveName & ".prt"
Try
File.Copy(sourcePath, filepath)
InfoWindow.WriteLine("Kopiert nach: " & targetPath & saveName)
Return 1
Catch ex As Exception
Throw ex
Return -1
End Try
End Function
Public Function splitFullPath(ByVal fullPath) As String
Dim parts As String() = fullPath.Split(New Char() {"\"})
Dim combi As String = ""
For i As Integer = 0 To parts.Length - 2
combi = combi & parts(i) & "\"
Next i
splitFullPath = combi
End Function
Public Function hexNumber() As String
Dim rand As New Random()
Dim result As String = ""
For i As Integer = 0 To 6
Dim randNum As Integer = rand.Next(0, 15)
result = result & Hex(randNum.ToString)
Next
hexNumber = result
End Function
Public Function checkPath(ByVal path As String) As String
If Not File.Exists(path) Then
Throw New Exception("Input Path does not exist.")
End If
checkPath = path
End Function
Public Sub waveGeoLinkBody(ByRef destinationPart As Part, ByRef bodyToLink As Body)
' Initialize any Body
Dim nullFeaturesFeature As Features.Feature = Nothing
' If Part is opened in History Free Mode throw Exception with Message
If Not destinationPart.Preferences.Modeling.GetHistoryMode Then
Throw (New Exception("Create or edit of a Feature was recorded in History Mode but playback is in History-Free Mode."))
End If
' Common Builder that is necessary to set Selection Option and to initialize other Builders for Geometry selection
Dim waveLinkBuilder1 As Features.WaveLinkBuilder
waveLinkBuilder1 = destinationPart.BaseFeatures.CreateWaveLinkBuilder(nullFeaturesFeature)
' Creates a Builder that allows to select Extract Faces (Bodys, Sheet Faces etc.)
Dim extractFaceBuilder1 As Features.ExtractFaceBuilder
extractFaceBuilder1 = waveLinkBuilder1.ExtractFaceBuilder
' Set Option to allow only Body Faces which are connected
extractFaceBuilder1.FaceOption = Features.ExtractFaceBuilder.FaceOptionType.FaceChain
extractFaceBuilder1.ParentPart = Features.ExtractFaceBuilder.ParentPartType.OtherPart
'extractFaceBuilder1.AngleTolerance = 45.0
' Types of Features to select: Bodys
waveLinkBuilder1.Type = Features.WaveLinkBuilder.Types.BodyLink
' Wave Geometry Linker Settings: Default for Daimler Die Design
'extractFaceBuilder1.Associative = True
'extractFaceBuilder1.HideOriginal = False
'extractFaceBuilder1.InheritDisplayProperties = True
'extractFaceBuilder1.FixAtCurrentTimestamp = False
'extractFaceBuilder1.MakePositionIndependent = False
'extractFaceBuilder1.CopyThreads = True
extractFaceBuilder1.Associative = True
extractFaceBuilder1.MakePositionIndependent = False
extractFaceBuilder1.FixAtCurrentTimestamp = False
extractFaceBuilder1.HideOriginal = True
extractFaceBuilder1.InheritDisplayProperties = False
extractFaceBuilder1.CopyThreads = True
' Create New Collector for Extract Faces
Dim scCollector1 As ScCollector
scCollector1 = extractFaceBuilder1.ExtractBodyCollector
'extractFaceBuilder1.FeatureOption = Features.ExtractFaceBuilder.FeatureOptionType.OneFeatureForAllBodies
' Dim sourceComponent As Assemblies.Component = bodyToLink.OwningComponent
' Write the selected Body in an Array
Dim bodies1(0) As Body
bodies1(0) = bodyToLink
Dim bodyDumbRule1 As BodyDumbRule
bodyDumbRule1 = destinationPart.ScRuleFactory.CreateRuleBodyDumb(bodies1, True)
Dim rules1(0) As SelectionIntentRule
rules1(0) = bodyDumbRule1
scCollector1.ReplaceRules(rules1, False)
Dim nXObject1 As NXObject
nXObject1 = waveLinkBuilder1.Commit()
waveLinkBuilder1.Destroy()
End Sub
Public Function correctProductOpened(ByVal displayedPart As Part, ByVal workpart As Part) As Boolean
Dim comp As NXOpen.Assemblies.ComponentAssembly = displayedPart.ComponentAssembly
' If there is no Assy opened --> End Function with result "False"
If IsNothing(comp.RootComponent) Then Return False
' If it is an Assy, check all Children
' if the Work Part is a Child: Opened Assembly Structure is correct
For Each child As Assemblies.Component In comp.RootComponent.GetChildren()
If child.DisplayName = workpart.JournalIdentifier Then Return True
Next
'
correctProductOpened = False
End Function
Public Function integerToString(ByVal number As Integer, ByVal digits As Byte) As String
integerToString = number.ToString
While integerToString.Length() < digits
integerToString = "0" & integerToString
End While
End Function
Public Function getDieName(ByVal workPart As Part) As String
Dim workString As String = workPart.JournalIdentifier
Dim substrings As String() = Split(workString, "_")
getDieName = substrings(substrings.Length - 1)
End Function
Public Function addComponent(ByVal activPart As Part, _
ByVal fullPath As String, _
ByVal displayedName As String) _
As NXOpen.Assemblies.Component
' Add Point and Orientation Matrix - Default 0, 0, 0 and x,y,z from datum axis
Dim basePoint As Point3d = New Point3d(0.0, 0.0, 0.0)
Dim orientation As Matrix3x3
orientation.Xx = 1.0
orientation.Xy = 0.0
orientation.Xz = 0.0
orientation.Yx = 0.0
orientation.Yy = 1.0
orientation.Yz = 0.0
orientation.Zx = 0.0
orientation.Zy = 0.0
orientation.Zz = 1.0
Dim compo As Assemblies.Component
Dim pls As PartLoadStatus
Try
compo = activPart.ComponentAssembly.AddComponent( _
fullPath, "FINAL_PART", displayedName, _
basePoint, orientation, -1, pls, True)
Catch ex As Exception
Return Nothing
End Try
pls.Dispose()
addComponent = compo
End Function
'Public Function addElement(ByVal array As String(), ByVal element As String) As String()
' Dim list As List(Of String) = array.ToList()
' list.Add(element)
' Return list.ToArray()
'End Function
End Module