Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

Assembly Creation using a Text File

Status
Not open for further replies.

sdinesh134

Automotive
Apr 30, 2014
6
0
0
IN
thread561-350926
Hi
i am using the same code to create a assembly file with sub-parts/sub assembly .The error i get attached below.
This returns NXOpen.NXExcelption :The selected template doesn't exixts.
I had even run your code for getting templetes for your earlier post and the code is below for getting templetes.

XXXX_startpart_model.prt
XXX_startpart_assembly_mm.prt
XXX_startpart_drawing.prt
XXX_startpart_drawing_standalone.prt
XXX_startpart_drawing_schematics.prt
YYY_startpart_drawing.prt
YY_startpart_drawing_standalone.prt
ZZZ_startpart_drawing.prt
ZZZ_startpart_drawing_standalone.prt
FemNxNastranMetric.fem
SimNxNastranMetric.sim
FemNxThermalFlowMetric.fem
SimNxThermalFlowMetric.sim
FemAbaqusMetric.fem
SimAbaqusMetric.sim
Blank
Blank


The Code for obtaining this is
Option Strict Off
Imports System
Imports NXOpen

Module Module1

Sub Main()

Dim theSession As Session = Session.GetSession()
Dim workPart As Part = theSession.Parts.Work
Dim lw As ListingWindow = theSession.ListingWindow
lw.Open()

Dim templates() As String

templates = theSession.Parts.FileNew.GetAvailableTemplates
For Each temp As String In templates
lw.WriteLine(temp)
Next

lw.Close()
End Sub


Public Function GetUnloadOption(ByVal dummy As String) As Integer

'Unloads the image when the NX session terminates
GetUnloadOption = NXOpen.Session.LibraryUnloadOption.AtTermination

End Function

End Module


Could you please change my code for this particular template

The code i need that you need to change is,

'eng-tips thread561-350926

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


Module Module3

Dim theSession As Session = Session.GetSession()
Dim workPart As Part = theSession.Parts.Work
Dim displayPart As Part = theSession.Parts.Display
Dim lw As ListingWindow = theSession.ListingWindow
'************************************************************************
'folder that contains existing parts; new parts will be created here
'change the directory path as necessary
Const partFolder As String = "C:\Users\dinessu\Desktop\TA top gun\Assembly"
'************************************************************************

'************************************************************************
'string of characters that indicate the assembly structure in the text file
Const levelIndicator As String = "."
'main assembly.prt
'.first_sub.prt
'..comp1.prt
'..comp2.prt
'.second_sub.prt
'etc, etc.
'************************************************************************

Sub Main()

If Not My.Computer.FileSystem.DirectoryExists(partFolder) Then
MessageBox.Show("The specified folder, " & partFolder & ", does not exist..." & ControlChars.CrLf & _
"The journal will now exit.", "Folder does not exist", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End If

lw.Open()

Dim asmTextFile As String = GetTextFile()
If asmTextFile Is Nothing Then
'user pressed cancel in the select file dialog
Return
End If

Dim textFileTree As NXTree(Of String) = TextFileToTree(asmTextFile)

Dim processedPRTFiles As New List(Of String)

ProcessTree(textFileTree.Root, processedPRTFiles)

lw.WriteLine("Done")
lw.Close()

End Sub

Sub ProcessTree(ByVal BOMTree As NXTreeNode(Of String), ByRef listFinished As List(Of String))

If listFinished.Contains(BOMTree.NodeObject) Then
'we've already processed this part, move along...
Return
End If


'part has not been processed
If My.Computer.FileSystem.FileExists(BOMTree.NodeObject) Then
'file exists, compare it to the BOM

Dim myAssembly As New NXTree(Of String)
Dim extraComps As NXTreeNode(Of String) = myAssembly.MakeRoot(BOMTree.NodeObject)
Dim myPart As Part

'create part list from actual CAD file
Try
myPart = GetPart(BOMTree.NodeObject)
Dim c As ComponentAssembly = myPart.ComponentAssembly
If Not IsNothing(c.RootComponent) Then
'*** insert code to process 'root component' (assembly file)
For Each child As Component In c.RootComponent.GetChildren()
If Not IsNothing(child.Prototype.OwningPart.FullPath) Then
extraComps.AddChild(child.Prototype.OwningPart.FullPath)
Else
lw.WriteLine("component not found: " & child.Name)
End If

Next

End If
Catch e As Exception
theSession.ListingWindow.WriteLine("Failed: " & e.ToString)
End Try

'add missing components
For Each tempNode As NXTreeNode(Of String) In BOMTree.Children
ProcessTree(tempNode, listFinished)
Dim found As Boolean = False

For Each existingNode As NXTreeNode(Of String) In myAssembly.Root.Children
If existingNode.NodeObject = tempNode.NodeObject Then
found = True
For i As Integer = 1 To tempNode.Quantity - existingNode.Quantity
AddComponent(myPart, tempNode.NodeObject, Nothing, Nothing)
Next
End If
Next

If Not found Then
'add it
For i As Integer = 1 To tempNode.Quantity
AddComponent(myPart, tempNode.NodeObject, Nothing, Nothing)
Next
End If
Next

Else
'file does not exist, create it and add components per BOM
Dim myNewFile As Part = GetPart(BOMTree.NodeObject)
For Each newComponent As NXTreeNode(Of String) In BOMTree.Children
ProcessTree(newComponent, listFinished)
For i As Integer = 1 To newComponent.Quantity
AddComponent(myNewFile, newComponent.NodeObject, "", Nothing)
Next
Next
End If

listFinished.Add(BOMTree.NodeObject)


End Sub


#Region "text file to assembly tree functions"

Function GetTextFile() As String

Dim openFileDialog1 As New OpenFileDialog()

openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 1
openFileDialog1.RestoreDirectory = True

If openFileDialog1.ShowDialog() = DialogResult.OK Then
Return openFileDialog1.FileName
Else
Return Nothing
End If

End Function

Function TextFileToTree(ByVal textFile As String) As NXTree(Of String)

Dim separators(0) As String
separators(0) = ControlChars.CrLf

Using sr As StreamReader = New StreamReader(textFile)
Try
Dim asmStructure() As String
asmStructure = sr.ReadToEnd.Split(separators, StringSplitOptions.RemoveEmptyEntries)
Dim newPart As String = IO.Path.Combine(partFolder, asmStructure(0))

Dim myAssembly As New NXTree(Of String)
Dim root As NXTreeNode(Of String) = myAssembly.MakeRoot(newPart)

AddChildren(root, asmStructure, 0, levelIndicator)

Return myAssembly

Catch E As Exception
MessageBox.Show(E.Message, "Error")
Return Nothing

End Try
End Using

End Function

Function CountIndent(ByVal myString As String, ByVal indentChar As String) As Integer

If myString.Substring(0, indentChar.Length) = indentChar Then
Return CountIndent(myString.Substring(indentChar.Length, myString.Length - indentChar.Length), indentChar) + 1
Else
Return 0
End If

End Function

Sub AddChildren(ByVal assemNode As NXTreeNode(Of String), ByVal asmStructure() As String, ByVal item As Integer, ByVal levelIndicator As String)

Dim j As Integer = 0
Dim iLevel As Integer = 0
Dim jLevel As Integer = 0
Dim childPart As String

iLevel = CountIndent(asmStructure(item), levelIndicator)
'Dim prtI As String = asmStructure(item).Substring(iLevel * levelIndicator.Length, asmStructure(item).Length - iLevel * levelIndicator.Length)
Dim prtJ As String

For j = item + 1 To UBound(asmStructure)
jLevel = CountIndent(asmStructure(j), levelIndicator)

If jLevel <= iLevel Then
Return
ElseIf jLevel = iLevel + 1 Then

prtJ = asmStructure(j).Substring(jLevel * levelIndicator.Length, asmStructure(j).Length - jLevel * levelIndicator.Length)
childPart = IO.Path.Combine(partFolder, prtJ)

'Dim child1 As TreeNode(Of Person) = root.AddChild(New Person("First Level Node 1"))
Dim child1 As NXTreeNode(Of String) = assemNode.AddChild(childPart)

'add component as child
AddChildren(child1, asmStructure, j, levelIndicator)

End If

Next

End Sub

#End Region

#Region "File functions"

Function GetPart(ByVal partPath As String) As Part

Try
Dim markId1 As Session.UndoMarkId
markId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Change Display Part")

Dim part1 As Part = CType(theSession.Parts.FindObject(IO.Path.GetFileNameWithoutExtension(partPath)), Part)

Dim partLoadStatus1 As PartLoadStatus
Dim status1 As PartCollection.SdpsStatus
status1 = theSession.Parts.SetDisplay(part1, False, False, partLoadStatus1)

workPart = theSession.Parts.Work
displayPart = theSession.Parts.Display
partLoadStatus1.Dispose()
theSession.DeleteUndoMark(markId1, "Change Display Part")
Return part1

Catch ex As NXException
If ex.ErrorCode = 3520016 Then
'part wasn't found in session
If My.Computer.FileSystem.FileExists(partPath) Then
'open part
Try
Return OpenPart(partPath)
Catch ex2 As Exception
MessageBox.Show(ex2.Message, "Error opening part", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Else
'part file does not exist
Return NewFile(partPath)
End If
End If
End Try

Return Nothing

End Function

Function NewFile(ByVal filePath As String) As Part

Dim markId1 As Session.UndoMarkId
markId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "new file")

Dim fileNew1 As FileNew
fileNew1 = theSession.Parts.FileNew()
'change template as necessary
fileNew1.TemplateFileName = "model-plain-1-inch-template.prt"
fileNew1.Application = FileNewApplication.Modeling
'change part units as necessary (Inches, Millimeters)
fileNew1.Units = Part.Units.Inches
fileNew1.NewFileName = filePath
fileNew1.MasterFileName = ""
fileNew1.UseBlankTemplate = False
fileNew1.MakeDisplayedPart = True

Dim nXObject1 As NXObject
nXObject1 = fileNew1.Commit()

workPart = theSession.Parts.Work
displayPart = theSession.Parts.Display

fileNew1.Destroy()

Dim markId5 As Session.UndoMarkId
markId5 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Name Parts")

workPart.AssignPermanentName(filePath)

theSession.DeleteUndoMark(markId5, Nothing)

Dim partSaveStatus1 As PartSaveStatus
partSaveStatus1 = workPart.Save(BasePart.SaveComponents.True, BasePart.CloseAfterSave.False)

partSaveStatus1.Dispose()

lw.WriteLine("New file created: " & filePath)

Return nXObject1

End Function

Function OpenPart(ByVal myPart As String) As Part

Dim thePart As Part
Dim partLoadStatus1 As PartLoadStatus
Try
thePart = theSession.Parts.OpenDisplay(myPart, partLoadStatus1)
partLoadStatus1.Dispose()

workPart = theSession.Parts.Work
displayPart = theSession.Parts.Display

Return thePart

Catch ex As NXException
MsgBox(ex.ErrorCode & ": " & ex.Message, vbCritical + vbOKOnly, "OpenPart error")
Return Nothing
End Try

End Function

Sub AddComponent(ByVal parentPart As Part, ByVal compPath As String, ByVal refSet As String, Optional ByVal compName As String = Nothing)

Dim markId1 As Session.UndoMarkId
markId1 = theSession.SetUndoMark(Session.MarkVisibility.Visible, "Add Component")

Dim nErrs1 As Integer
nErrs1 = theSession.UpdateManager.DoUpdate(markId1)

Dim basePoint1 As Point3d = New Point3d(0.0, 0.0, 0.0)
Dim orientation1 As Matrix3x3
orientation1.Xx = 1.0
orientation1.Xy = 0.0
orientation1.Xz = 0.0
orientation1.Yx = 0.0
orientation1.Yy = 1.0
orientation1.Yz = 0.0
orientation1.Zx = 0.0
orientation1.Zy = 0.0
orientation1.Zz = 1.0
Dim partLoadStatus1 As PartLoadStatus
Dim component1 As Assemblies.Component
component1 = parentPart.ComponentAssembly.AddComponent(compPath, refSet, compName, basePoint1, orientation1, 1, partLoadStatus1, True)

partLoadStatus1.Dispose()

lw.WriteLine(parentPart.FullPath & " -> component added: " & compPath)

End Sub

#End Region

Public Function GetUnloadOption(ByVal dummy As String) As Integer

'Unloads the image when the NX session terminates
GetUnloadOption = NXOpen.Session.LibraryUnloadOption.AtTermination

End Function

End Module

#Region "NXTree and Node classes"
'class adapted from:
Public Class NXTree(Of T)

Private m_Root As NXTreeNode(Of T) = Nothing
'<Description("The tree's root node."), Category("Data")> _
Public Property Root() As NXTreeNode(Of T)
Get
Return m_Root
End Get

Set(ByVal value As NXTreeNode(Of T))
m_Root = value
End Set

End Property

Public Sub Clear()
m_Root = Nothing
End Sub

Public Function MakeRoot(ByVal node_item As T) As NXTreeNode(Of T)
m_Root = New NXTreeNode(Of T)(node_item)
Return m_Root
End Function

Public Overrides Function ToString() As String
Return m_Root.ToString()
End Function

End Class


Public Class NXTreeNode(Of T)
Public NodeObject As T
Public Children As New List(Of NXTreeNode(Of T))
Public Quantity As Integer = 1

Public Sub New(ByVal node_object As T)
NodeObject = node_object
End Sub

Public Function AddChild(ByVal node_item As T) As NXTreeNode(Of T)
Dim child_node As New NXTreeNode(Of T)(node_item)

For Each tempNode As NXTreeNode(Of T) In Children
If tempNode.NodeObject.Equals(node_item) Then
tempNode.Quantity += 1
Return tempNode
End If
Next

Children.Add(child_node)
Return child_node

End Function

Public Shadows Function ToString(Optional ByVal indent As Integer = 0) As String
Dim txt As String
txt = New String(" "c, indent) & NodeObject.ToString & " x" & Quantity.ToString & vbCrLf

For Each child As NXTreeNode(Of T) In Children
txt &= child.ToString(indent + 2)
Next child

Return txt
End Function
End Class

#End Region



Please do the needful
 
Replies continue below

Recommended for you

Hello Sdinesh134,

This highlighted portion of example code needs to be changed to specify directory path on you computer that has write access.

HTH,
Joe

Code:
'************************************************************************
'folder that contains existing parts; new parts will be created here
'change the directory path as necessary
Const partFolder As String = "[highlight #FCE94F]C:\Users\dinessu\Desktop\TA top gun\Assembly[/highlight]"
'************************************************************************
 
Hey Joe
Thanks for your effort.
The folder is in Desktop ,so there are no issues with that.The issue is with the Template file.That i had changed now .
Dim fileNew1 As FileNew
fileNew1 = theSession.Parts.FileNew()
'change template as necessary
fileNew1.TemplateFileName = [highlight #FCE94F]"model-plain-1-inch-template.prt"[/highlight]
fileNew1.Application = FileNewApplication.Modeling
'change part units as necessary (Inches, Millimeters)
fileNew1.Units = Part.Units.Inches
fileNew1.NewFileName = filePath
fileNew1.MasterFileName = ""
fileNew1.UseBlankTemplate = False
fileNew1.MakeDisplayedPart = True


But i get my part file getting created rather as an assembly.
1
.2
.3
.4

The error i get now is

NXopen .NX Exception:Attempt to add a componnet to a part flaggedas apiece part
at NXopen.Assemblies.ComponentAssembly.AddComponnet(String part toAdd,string referenceset Name,String component Name,Ponit3d basepoint,Matrix3x3xorientation,Int32layer,PartLoadStatus,Boolean uomAsNgc)
at Module3.AddComponent(Part parentPart,String comp Path,String refSet,String compName) in
C:\Users\dinessu\Appdata\local\Temp\NXJournel95040\journel0.vb.line 352
at Module3.Process Tree(NXTreeNode1 BOMTree,List1_ListFinished) in C:\Users\dinessu\Appdata\local\Temp\NXJournel95040\journel0.vb.line 126
at Module3.Main() in C:\Users\dinessu\Appdata\local\Temp\NXJournel95040\journel0.vb.line 55

Please suggest.
Thanks


 
Hello Sdinesh134,

That sounds like the template part has been saved with "Enforce Piece Part" set to ON.

Either use a different template part or edit and save the template part file after using "File->Utilities->Enforce Piece Part...", Uncheck "Enforce as Piece Part"

Hope this helps,
Joe
 
Hello Joe
Please find the attached image.
Enforced Piece Part is greyed in my case .I am unable to nither turn it on nor turn it off.
They are my default settings.We have certain requirements to use the same template.
Please suggest.
Thanks
 
There is no file attached...

Ignoring the journal code for a moment, using interactive commands: can you create a new file based on the template and add components to it? Or do you get a similar message about it being marked as a piece part?

www.nxjournaling.com
 
Hello Sdinesh134,

In this particular case the corporate customer specific add-ons are intentionally making this NX menu option unavailable.
Please accept my apology but I cannot in good conscience offer additional assistance to contravene corporate standards.
You may want to consider contacting someone in the IT/DC, CAD Systemgestaltung department.

HTH,
Joe


 
Status
Not open for further replies.
Back
Top