Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

NX Journal - Assign Material to All bodies in part; Assign Description to "Description Attribut 1

Status
Not open for further replies.

CADologist

Mechanical
Aug 20, 2024
1
0
0
ES
From long hours of research, I have a made a NX Journal to automate assigning materials and Descriptions to a massive set of parts

Uses:
- Migration into NX from another platform

Requirements:
- CSV File with part names, material names, and descriptions
- uses Custom materials library
- Material name in CSV must match exactly to material name in material library

Downsides:
- If there are multiple Bodies within a part with different materials, this code will not help you.
- Can cause computer crashes if done on thousands of Parts. It is recommended to break up your assembly and perform action in tranches

Key Features of Code:
- Does assign materials to bodies and adds description simultaneously
- Uses CSV files for data allocation
- Uses custom materials library
- Quick operation saving many hours of manually work


Code:
' PURPOSE: 
' Read CSV file, 
' Open parts according to name, 
' Assign Description and Material to all bodies within part,
' Save and close

' Written by CADologist and ChatGPT
'
' Versioning
'V001 - RELEASE DATE; AUGUST 20, 2024
'

'________MAIN IMPORTS______________________________________________________________________________
Option Strict Off
Imports System
Imports System.IO
Imports NXOpen
Imports NXOpen.UF
Imports NXOpen.Utilities
Imports System.Collections.Generic
Imports NXOpen.Assemblies
'______________________________________________________________________________________


Module NXJournal
    Dim theSession As Session = Session.GetSession()
    Dim theUI As UI = UI.GetUI()
    Dim workPart As Part = theSession.Parts.Work
    Dim displayPart As Part = theSession.Parts.Display

    Sub Main()
	
	
'____________CONFUGURATION SETTINGS: ADJUST FILE DIRECTORIES FOR YOUR CASE_____________
		' Specify the path to your CSV file
        Dim csvFilePath As String = "C:\path_to_your_file\materials_and_desc.csv"

        ' Specify the directory where the part files are located
        Dim partDirectoryPath As String = "C:\path_to_your_part_files\"
'______________________________________________________________________________________				
'FORMAT FOR CSV file
'PartNumber,Description,MaterialName,
'Part-XXXXXXXX,Blah Blah,Al 6061-T6,
'________________________________________
' MATERIAL NAME SHOULD BE EXACTLY HOW ITS FOUND IN CUSTOMIZED LIBRARY

        ' Open the CSV file for reading
        Dim csvFile As New StreamReader(csvFilePath)

        ' Skip the header row
        Dim header As String = csvFile.ReadLine()

        ' Initialize the Listing Window for logging
        Dim lw As ListingWindow = theSession.ListingWindow
        lw.Open()

        While Not csvFile.EndOfStream
            Dim line As String = csvFile.ReadLine()
            Dim fields() As String = line.Split(","c)

            Dim partNumber As String = fields(0).Trim()
            Dim description As String = fields(1).Trim()
            Dim materialName As String = fields(2).Trim()

            ' Skip if description or material name is invalid
            If String.IsNullOrEmpty(description) Then
                lw.WriteLine("Skipping part " & partNumber & " due to empty description.")
                Continue While
            End If

            If String.IsNullOrEmpty(materialName) OrElse materialName = "No Material" OrElse materialName = "Product" Then
                lw.WriteLine("Skipping part " & partNumber & " due to invalid material name.")
                Continue While
            End If

            Try
                ' Attempt to open the part
                Dim partFile As String = Path.Combine(partDirectoryPath, partNumber & ".prt")
                Dim loadStatus As PartLoadStatus
                Dim part As BasePart = theSession.Parts.OpenDisplay(partFile, loadStatus)
                workPart = CType(theSession.Parts.Work, Part)

                ' Assign the description to the work part header
                workPart.SetUserAttribute("Description", -1, description, Update.Option.Now)
                lw.WriteLine("Assigned description to part: " & partNumber)

                ' Check if the material is already loaded in the part
                Dim material As NXOpen.PhysicalMaterial = Nothing
                Try
                    material = workPart.MaterialManager.PhysicalMaterials.FindObject("PhysicalMaterial[" & materialName & "]")
                Catch ex As Exception
                    lw.WriteLine("Error finding material in part: " & partNumber & " - " & ex.Message)
                End Try
		' EDIT YOUR CUSTOM MATERIAL LIBRARY HERE (YOUR_CUSTOM_LIBRARY.xml NEEDS TO BE CHANGED)
		'__________________________________________________________________________________________________
				
                ' If material is not found, load it from the library
                If material Is Nothing Then
                    material = workPart.MaterialManager.PhysicalMaterials.LoadFromMatmlLibrary("C:\Program Files\Siemens\NX2312\UGII\materials\YOUR_CUSTOM_LIBRARY.xml", materialName)
                    lw.WriteLine("Material " & materialName & " loaded for part " & partNumber)
                Else
                    lw.WriteLine("Material " & materialName & " already loaded for part " & partNumber)
                End If
		'__________________________________________________________________________________________________
				
                ' Check if material was loaded or found successfully
                If material Is Nothing Then
                    lw.WriteLine("Material " & materialName & " not found in library or failed to load for part " & partNumber & ". Skipping material assignment.")
                Else
                    ' Loop through each body in the part and assign the material
                    For Each body As Body In workPart.Bodies
                        material.AssignObjects(New NXOpen.NXObject() {body})
                    Next
                    lw.WriteLine("Assigned " & materialName & " to all bodies in " & partNumber)
                End If

                ' Save and close the part
                workPart.Save(BasePart.SaveComponents.True, BasePart.CloseAfterSave.False)

                ' Close the part properly
                Dim closeResponses As PartCloseResponses = theSession.Parts.NewPartCloseResponses()
                workPart.Close(BasePart.CloseWholeTree.True, BasePart.CloseModified.CloseModified, closeResponses)

            Catch ex As Exception
                lw.WriteLine("Error processing part " & partNumber & ": " & ex.Message)
            End Try

        End While

        ' Close the CSV file and listing window
        csvFile.Close()
        lw.WriteLine("Material and description assignment completed.")
        lw.Close()
    End Sub

    Public Function GetUnloadOption(ByVal dummy As String) As Integer
        Return NXOpen.Session.LibraryUnloadOption.Immediately
    End Function
End Module

Let me know if this helps!
Cheers,
CADologist
-
 
Status
Not open for further replies.
Back
Top