Quantcast
Channel: NX Journaling - Journaling / NXOpen API
Viewing all 787 articles
Browse latest View live

how to hide a layer with category name instead of layer no

$
0
0

HI

I have some layers in my nx file

I want to hide a layer

I recorded a journal which gives the below code

Dim stateArray3(0) As NXOpen.Layer.StateInfo
stateArray3(0) = New NXOpen.Layer.StateInfo(64, NXOpen.Layer.State.Hidden)
workPart.Layers.ChangeStates(stateArray3, False)

this code hides the layer number 64,

how can i edit it so that i can use layer category name


Creating a point in a certain direction from the first point

$
0
0

I can create a point on face and would like to create another point on the same face (in a user defined direction).

At this point I can create a point on face and get the coordinate of that point and also can get user defined directions. What is the best way or is there any example of creating a second point relative to first point in a user defined direction (X &Y) ?

Journal for Opening a html page.

$
0
0

Is there anyway, by which we can open an html page in NX via Journal?
If there is any sort of journal please share.

Modifying the code which loops through names in an assembly

$
0
0

My code is posted after my question.

The array FLART(3) has the names of components within our database. Array values (0), (1), (2) are single components and value (3) is an assembly with sub assemblies in it. When I run the code with the array in this order it works fine(I was simply testing if I could return the top level name of each item). If I run the code with value (3) swapped with any other value it fails because it's opening an assembly and then trying to open a single component afterwards. I'm not sure how to get around this issue.

My end goal for this test code was to return the name of every part I open. If it's an assembly return the name of the assembly, sub assemblies, and components and if it's a single part return the name of the single part.

The final part I'm having trouble with is how to Save-As WorkPart New Item within CPLM.

Ultimately I want to take all of the names I gathered and check them against a two dimensional array where the first dimension is the current name of components I may be opening and the second dimension is a new name I want to save them as.

Creating the two dimensional array and checking against it has been figured out it's just navigating OpenNX that has me confused.

'Journal to recursively walk through the assembly structure
' will run on assemblies or piece parts
' will step through all components of the displayed part
'NX 7.5, native
'NXJournaling.com February 24, 2012
 
Option Strict Off
 
Imports System
Imports NXOpen
Imports NXOpen.UF
Imports NXOpen.Assemblies
 
Module NXJournal
 
    Public theSession As Session = Session.GetSession()
    Public ufs As UFSession = UFSession.GetUFSession()
    Public lw As ListingWindow = theSession.ListingWindow
 
    Sub Main()
	Dim workPart As NXOpen.Part = theSession.Parts.Work
	Dim dispPart as NXOpen.Part = theSession.Parts.Display
	Dim fileNameNoExt As String
	Dim basePart1 As NXOpen.BasePart = Nothing
	Dim partLoadStatus1 As NXOpen.PartLoadStatus = Nothing
 
	Dim PartNames(0) As String
	Dim FLART(3) as string
	Dim ArrayIndex as integer = 0
	Dim i as integer
	Dim theUISession As UI = UI.GetUI
	Dim c As ComponentAssembly = dispPart.ComponentAssembly
 
	FLART(0) = "Part1"
	FLART(1) = "Part2"
	FLART(2) = "Part3"
	FLART(3) = "Assembly1"
 
    lw.Open
 
 
for i = 0 to 3
 
			'TRIES TO OPEN THE PART SPECIFIED IN THE ARRAY
			basePart1 = theSession.Parts.OpenActiveDisplay("@DB/" & FLART(i) & "/" & 1, NXOpen.DisplayPartOption.AllowAdditional, partLoadStatus1)
 
	lw.writeline("ForLoop: " & i)
 
        if not IsNothing(c.RootComponent) then
 
			if ArrayIndex = 0 then
			lw.writeline("Is first part and is an assembly")
				fileNameNoExt = c.RootComponent.DisplayName
				fileNameNoExt = fileNameNoExt.Substring(0, Len(fileNameNoExt)-2) 'GETS THE DISPLAYED PART NAME AND TRIMS OFF TWO LETTERS FROM THE STRING IN ORDER TO REMOVE THE FORWARD SLASH AND REVISION NUMBER
				PartNames(ArrayIndex) = FileNameNoExt
				lw.WriteLine("Assembly: " & PartNames(ArrayIndex))
				ArrayIndex = ArrayIndex + 1
			else
				lw.writeline("Not first part and is an assembly")
				Redim Preserve PartNames(ArrayIndex)
				fileNameNoExt = c.RootComponent.DisplayName
				fileNameNoExt = fileNameNoExt.Substring(0, Len(fileNameNoExt)-2) 'GETS THE DISPLAYED PART NAME AND TRIMS OFF TWO LETTERS FROM THE STRING IN ORDER TO REMOVE THE FORWARD SLASH AND REVISION NUMBER
				PartNames(ArrayIndex) = fileNameNoExt
				lw.WriteLine("Assembly: " & PartNames(ArrayIndex))
				ArrayIndex = ArrayIndex + 1
			end if
 
            '*** insert code to process 'root component' (assembly file)
            'lw.WriteLine(" + Active Arrangement: " & c.ActiveArrangement.Name)
            '*** end of code to process root component
            'ReportComponentChildren(c.RootComponent, 0)
        else
            '*** insert code to process piece part
 
				lw.writeline("Piece Part")
			if ArrayIndex = 0 then
 
				lw.writeline("First Part is a Piece Part")
				'UPDATES THE WORK VIEW TO THE NEW PART THAT WAS JUST OPENED IN ORDER TO MAKE THE DISPLAYED PART THE WORK PART
				'dispPart.ModelingViews.WorkView.UpdateDisplay()
				'MAKES THE DISPLAYED PART THE WORK PART
				dispPart = theSession.Parts.Display
				fileNameNoExt = dispPart.FullPath
				fileNameNoExt = fileNameNoExt.Substring(0, Len(fileNameNoExt)-2) 'GETS THE DISPLAYED PART NAME AND TRIMS OFF TWO LETTERS FROM THE STRING IN ORDER TO REMOVE THE FORWARD SLASH AND REVISION NUMBER
				lw.writeline("FileNameNoExt: " & fileNameNoExt) 'WRITES THE NAME OF THE OBJECT TO THE LISTING WINDOW
				PartNames(ArrayIndex) = fileNameNoExt
				ArrayIndex = ArrayIndex + 1
 
			else
 
				lw.writeline("Not First part and is Piece Part")
				'UPDATES THE WORK VIEW TO THE NEW PART THAT WAS JUST OPENED IN ORDER TO MAKE THE DISPLAYED PART THE WORK PART
				'dispPart.ModelingViews.WorkView.UpdateDisplay()
				'MAKES THE DISPLAYED PART THE WORK PART
				dispPart = theSession.Parts.Display
				Redim Preserve PartNames(ArrayIndex)
				fileNameNoExt = dispPart.FullPath
				fileNameNoExt = fileNameNoExt.Substring(0, Len(fileNameNoExt)-2) 'GETS THE DISPLAYED PART NAME AND TRIMS OFF TWO LETTERS FROM THE STRING IN ORDER TO REMOVE THE FORWARD SLASH AND REVISION NUMBER
				lw.writeline("FileNameNoExt: " & fileNameNoExt) 'WRITES THE NAME OF THE OBJECT TO THE LISTING WINDOW
				PartNames(ArrayIndex) = fileNameNoExt
				ArrayIndex = ArrayIndex + 1
 
			end if
 
            lw.WriteLine(PartNames(UBound(PartNames)))
 
 
        end if
 
 
	theSession.CleanUpFacetedFacesAndEdges()
	theSession.Parts.Display.Close(BasePart.CloseWholeTree.True, BasePart.CloseModified.UseResponses, Nothing)
 
next
 
	lw.Close
 
    End Sub
 
'**********************************************************
    Sub reportComponentChildren( ByVal comp As Component, _
        ByVal indent As Integer)
 
        For Each child As Component In comp.GetChildren()
            '*** insert code to process component or subassembly
            lw.WriteLine(New String(" ", indent * 2) & child.DisplayName())
            '*** end of code to process component or subassembly
            if child.GetChildren.Length <> 0 then
                '*** this is a subassembly, add code specific to subassemblies
                lw.WriteLine(New String(" ", indent * 2) & _
                    "* subassembly with " & _
                    child.GetChildren.Length & " components")
                lw.WriteLine(New String(" ", indent * 2) & _
                    " + Active Arrangement: " & _
                    child.OwningPart.ComponentAssembly.ActiveArrangement.Name)
                '*** end of code to process subassembly
            else
                'this component has no children (it is a leaf node)
                'add any code specific to bottom level components
            end if
            reportComponentChildren(child, indent + 1)
        Next
    End Sub
'**********************************************************
    Public Function GetUnloadOption(ByVal dummy As String) As Integer
        Return Session.LibraryUnloadOption.Immediately
    End Function
'**********************************************************
 
End Module
<code>

SAVE-AS in PLM

$
0
0

This is the code I've developed so far using record macro but it's not working. The code executes without errors but doesn't actually save-as a new part. Any advice?

'Journal to recursively walk through the assembly structure
' will run on assemblies or piece parts
' will step through all components of the displayed part
'NX 7.5, native
'NXJournaling.com February 24, 2012
 
Option Strict Off
 
Imports System
Imports NXOpen
Imports NXOpen.UF
Imports NXOpen.Assemblies
 
Module NXJournal
 
    Public theSession As Session = Session.GetSession()
    Public ufs As UFSession = UFSession.GetUFSession()
    Public lw As ListingWindow = theSession.ListingWindow
 
	Public workPart As NXOpen.Part = theSession.Parts.Work
	Public dispPart as NXOpen.Part = theSession.Parts.Display
	Public fileNameNoExt As String
	Public basePart1 As NXOpen.BasePart = Nothing
	Public partLoadStatus1 As NXOpen.PartLoadStatus = Nothing
 
	Public PartNames(0) As String
	Public FLART(3) as string
	Public ArrayIndex as integer = 0
	Public i as integer = 0
	Public j as integer
	Public match as integer = 0
	Public theUISession As UI = UI.GetUI
	Public c As ComponentAssembly = dispPart.ComponentAssembly
	Public partOperationCopyBuilder1 As NXOpen.PDM.PartOperationCopyBuilder = Nothing
 
    Sub Main()
 
 
	FLART(0) = "MY_PART"
	FLART(1) = 
	FLART(2) = 
	FLART(3) = 
 
    lw.Open
 
			Dim selectedparts1(0) As NXOpen.BasePart
			Dim failedparts1() As NXOpen.BasePart
			Dim logicalobjects1() As NXOpen.PDM.LogicalObject
			Dim sourceobjects1() As NXOpen.NXObject
			Dim attributePropertiesBuilder1 As NXOpen.AttributePropertiesBuilder = Nothing
			Dim objects2(0) As NXOpen.NXObject
			Dim nullNXOpen_BasePart As NXOpen.BasePart = Nothing
 
			'TRIES TO OPEN THE PART SPECIFIED IN THE ARRAY
			basePart1 = theSession.Parts.OpenActiveDisplay("@DB/" & FLART(i) & "/" & 1, NXOpen.DisplayPartOption.AllowAdditional, partLoadStatus1)
			workPart = theSession.parts.work
			dispPart = thesession.parts.display
			c = dispPart.ComponentAssembly
			selectedparts1(0) = workPart
 
			partOperationCopyBuilder1 = theSession.PdmSession.CreateCopyOperationBuilder(NXOpen.PDM.PartOperationBuilder.OperationType.SaveAs)
			partOperationCopyBuilder1.SetOperationSubType(NXOpen.PDM.PartOperationCopyBuilder.OperationSubType.Default)
			partOperationCopyBuilder1.DefaultDestinationFolder = ":Newstuff"
			partOperationCopyBuilder1.DependentFilesToCopyOption = NXOpen.PDM.PartOperationCopyBuilder.CopyDependentFiles.All
			partOperationCopyBuilder1.ReplaceAllComponentsInSession = True
			partOperationCopyBuilder1.SetDialogOperation(NXOpen.PDM.PartOperationBuilder.OperationType.SaveAs)
 
			selectedparts1(0) = workPart
			partOperationCopyBuilder1.SetSelectedPartsToCopy(selectedparts1, failedparts1)
			partOperationCopyBuilder1.CreateLogicalObjects(logicalobjects1)
 
			sourceobjects1 = logicalobjects1(0).GetUserAttributeSourceObjects()
 
			attributePropertiesBuilder1 = theSession.AttributeManager.CreateAttributePropertiesBuilder(nullNXOpen_BasePart, objects2, NXOpen.AttributePropertiesBuilder.OperationType.None)
 
			objects2(0) = sourceobjects1(0)
			attributePropertiesBuilder1.SetAttributeObjects(objects2)
 
			attributePropertiesBuilder1.Title = "DB_PART_NO"
			attributePropertiesBuilder1.Category = "N4_NonDesignPart"
			attributePropertiesBuilder1.StringValue = "TEMP_DELETE_ITEM"
 
			partOperationCopyBuilder1.ValidateLogicalObjectsToCommit()
 
			partOperationCopyBuilder1.Destroy()
 
			attributePropertiesBuilder1.Destroy()
 
 
	theSession.CleanUpFacetedFacesAndEdges()
	theSession.Parts.Display.Close(BasePart.CloseWholeTree.True, BasePart.CloseModified.UseResponses, Nothing)
 
	lw.Close
 
    End Sub<code>

How can I reference a child in an assembly?

$
0
0

If I want to reference a child of an assembly as an object so that I can save it specifically instead of the top level component how would I do that.

This is how I would do it with a non assembly.

Public dispPart as NXOpen.Part = theSession.Parts.Display
dispPart = thesession.parts.display
part1 = dispPart <code>
 
But I want to reference a child in the assembly specifically so I can save that child as a new part.
 
<code> For Each child As Component In comp.GetChildren()
            '*** insert code to process component or subassembly
				fileNameNoExt = Child.DisplayName<code>
 
This wont be the correct code but I want something like
 
<code> part1 = child<code>
 
Thanks for all the help i know i've been asking a lot of questions lately.

Renaming children in an assembly not working

$
0
0

This is my code and I want to rename the the assembly and then each child in the assembly but it's not working for me.

'Journal to recursively walk through the assembly structure' will run on assemblies or piece parts' will step through all components of the displayed part'NX 7.5, native'NXJournaling.com February 24, 2012 
Option Strict Off
 
Imports System
Imports NXOpen
Imports NXOpen.UFImports NXOpen.AssembliesImports NXOpenUI
Imports System.Collections.GenericImports System.Windows.Forms 
Module NXJournal
 
    Public theSession As Session = Session.GetSession()Public ufs As UFSession = UFSession.GetUFSession()Public lw As ListingWindow = theSession.ListingWindow 
	Public workPart As NXOpen.Part= theSession.Parts.WorkPublic dispPart as NXOpen.Part= theSession.Parts.DisplayPublic fileNameNoExt AsStringPublic basePart1 As NXOpen.BasePart=NothingPublic partLoadStatus1 As NXOpen.PartLoadStatus=NothingPublic childpart as NXOpen.PartPublic childrenpart as NXOpen.Part 
	Public PartNames(0)AsStringPublic ArrayIndex asinteger=0Public i asinteger=0Public j asintegerPublic match asinteger=0Public theUISession As UI = UI.GetUIPublic c As ComponentAssembly = dispPart.ComponentAssembly 
	Public errorMessageHandler4 As NXOpen.PDM.ErrorMessageHandler=NothingPublic selectedparts1(0)As NXOpen.BasePartPublic failedparts1()As NXOpen.BasePartPublic logicalobjects1()As NXOpen.PDM.LogicalObjectPublic sourceobjects1()As NXOpen.NXObjectPublic partOperationCopyBuilder1 As NXOpen.PDM.PartOperationCopyBuilder=NothingPublic readOnly1 AsBoolean=NothingPublic part1 As NXOpen.Part=NothingPublic sourceobjects2()As NXOpen.NXObjectPublic sourceobjects3()As NXOpen.NXObjectPublic sourceobjects4()As NXOpen.NXObjectPublic sourceobjects5()As NXOpen.NXObjectPublic sourceobjects6()As NXOpen.NXObjectPublic selectedparts2(0)As NXOpen.BasePartPublic failedparts2()As NXOpen.BasePartPublic logicalobjects2()As NXOpen.PDM.LogicalObjectPublic sourceobjects7()As NXOpen.NXObjectPublic sourceobjects8()As NXOpen.NXObjectPublic sourceobjects9()As NXOpen.NXObjectPublic sourceobjects10()As NXOpen.NXObjectPublic nullNXOpen_BasePart As NXOpen.BasePart=NothingPublic objects1(-1)As NXOpen.NXObjectPublic attributePropertiesBuilder1 As NXOpen.AttributePropertiesBuilder=NothingPublic objects2(0)As NXOpen.NXObjectPublic changed1 AsBoolean=NothingPublic sourceobjects11()As NXOpen.NXObjectPublic attributetitles1(-1)AsStringPublic titlepatterns1(-1)AsStringPublic nXObject1 As NXOpen.NXObject=NothingPublic objects3(0)As NXOpen.NXObjectPublic properties1(0)As NXOpen.NXObjectPublic errorList1 As NXOpen.ErrorList=NothingPublic errorMessageHandler1 As NXOpen.PDM.ErrorMessageHandler=NothingPublic markId2 As NXOpen.Session.UndoMarkId=NothingPublic markId3 As NXOpen.Session.UndoMarkId=NothingPublic errorMessageHandler2 As NXOpen.PDM.ErrorMessageHandler=NothingPublic errorMessageHandler3 As NXOpen.PDM.ErrorMessageHandler=NothingPublic nXObject2 As NXOpen.NXObject=NothingPublic partstocheckin1(0)As NXOpen.BasePartPublic checkininput1 As NXOpen.PDM.PdmPart.CheckinInput=New NXOpen.PDM.PdmPart.CheckinInput(False, True, False)Public operationErrors1 As NXOpen.PDM.OperationErrors=NothingPublic row AsLong=1Public column AsLong=1Public index asinteger=0Public lg As LogFile = theSession.LogFilePublic intchecker asintegerPublic savename asstringPublic PartNames2DArray(0,0)AsString 
 
    Sub Main() 
	Dim excelBom AsString= ChooseBomFile()If excelBom =""Then'USER PRESSED CANCEL
			theUISession.NXMessageBox.Show("Error", NXMessageBox.DialogType.Error, "User did not select a file, journal exiting")ExitSubEndIf 
 'CREATE EXCEL OBJECTDim objExcel =CreateObject("Excel.Application")If objExcel IsNothingThen'USER PRESSED CANCEL
            theUISession.NXMessageBox.Show("Error", NXMessageBox.DialogType.Error, "Could not start Excel, journal exiting")ExitSubEndIf 
'OPEN EXCEL FILEDim objWorkbook = objExcel.Workbooks.Open(excelBom)
        objExcel.visible=True 
 
		objWorkbook.activesheet.cells(row, column).select() 
		Dim lastRow AsLong 
        Const xlUp AsInteger=-4162Const xlNone AsInteger=-4142 
        lastRow = objWorkbook.ActiveSheet.Cells(objWorkbook.activesheet.Rows.Count, column).End(xlUp).Row 
		Dim TempArray(lastRow,1)asstring 
		PartNames2DArray = TempArray
 
		lw.WriteLine("Excel File Name: "& excelBom)
		lw.WriteLine("Last Row: "& lastRow) 
        Do Until row > lastRow
			objWorkbook.ActiveSheet.Cells(row,1).value=Replace(objWorkbook.ActiveSheet.Cells(row,1).value, vbCr, " ")
			objWorkbook.ActiveSheet.Cells(row,1).value=Replace(objWorkbook.ActiveSheet.Cells(row,1).value, vbLf, " ")	
			objWorkbook.ActiveSheet.Cells(row,1).value=Replace(objWorkbook.ActiveSheet.Cells(row,1).value, vbCrLf, " ")	
			objWorkbook.ActiveSheet.Cells(row,1).value=Trim(objWorkbook.ActiveSheet.Cells(row,1).value)
			objWorkbook.ActiveSheet.Cells(row,2).value=Replace(objWorkbook.ActiveSheet.Cells(row,2).value, vbCr, " ")
			objWorkbook.ActiveSheet.Cells(row,2).value=Replace(objWorkbook.ActiveSheet.Cells(row,2).value, vbLf, " ")	
			objWorkbook.ActiveSheet.Cells(row,2).value=Replace(objWorkbook.ActiveSheet.Cells(row,2).value, vbCrLf, " ")	
			objWorkbook.ActiveSheet.Cells(row,2).value=Trim(objWorkbook.ActiveSheet.Cells(row,2).value) 
			PartNames2DArray(index,0)= objWorkbook.ActiveSheet.Cells(row,1).value
			PartNames2DArray(index,1)= objWorkbook.ActiveSheet.Cells(row,2).value 
			row = row +1
			index = index +1Loop 
		objWorkbook.Saved=True
        objExcel.Quit()
        objWorkbook =Nothing
        objExcel =Nothing 
 
    lw.Open 
for i =0to4if PartNames2DArray(i,0)<>""thenTry 
			'TRIES TO OPEN THE PART SPECIFIED IN THE ARRAY
			basePart1 = theSession.Parts.OpenActiveDisplay("@DB/"& PartNames2DArray(i,0)&"/"&1, NXOpen.DisplayPartOption.AllowAdditional, partLoadStatus1)
			workPart = theSession.parts.work
			dispPart = thesession.parts.display
			c = dispPart.ComponentAssembly 
		Catch ex As Exception
				lw.WriteLine("Error Trying to Open Part: "& PartNames2DArray(i,0))goto skipforward
			EndTryelsegoto skipforward
	endif 
	ifnot IsNothing(c.RootComponent)then 
			if ArrayIndex =0then
			lw.writeline("Is first part and is an assembly")
				fileNameNoExt = c.RootComponent.DisplayName
				fileNameNoExt = fileNameNoExt.Substring(0, Len(fileNameNoExt)-2)'GETS THE DISPLAYED PART NAME AND TRIMS OFF TWO LETTERS FROM THE STRING IN ORDER TO REMOVE THE FORWARD SLASH AND REVISION NUMBER
				PartNames(ArrayIndex)= FileNameNoExt
				lw.WriteLine("Assembly: "& PartNames(ArrayIndex))for intchecker =0toUBound(PartNames2DArray)if PartNames(ArrayIndex)= PartNames2DArray(intchecker, 0)then
						savename = PartNames2DArray(intchecker, 1)
						part1 = dispPart
						saveas
						exitforendifnext
				ArrayIndex = ArrayIndex +1else
				lw.writeline("Not first part and is an assembly")Redim Preserve PartNames(ArrayIndex)
				fileNameNoExt = c.RootComponent.DisplayName
				fileNameNoExt = fileNameNoExt.Substring(0, Len(fileNameNoExt)-2)'GETS THE DISPLAYED PART NAME AND TRIMS OFF TWO LETTERS FROM THE STRING IN ORDER TO REMOVE THE FORWARD SLASH AND REVISION NUMBERfor j =0toUBound(PartNames)if fileNameNoExt = PartNames(j)then
						match =1endifnextif match <>1then
					PartNames(ArrayIndex)= fileNameNoExt
					for intchecker =0toUBound(PartNames2DArray)if PartNames(ArrayIndex)= PartNames2DArray(intchecker, 0)then
							savename = PartNames2DArray(intchecker, 1)
							part1 = dispPart
							saveas
						exitforendifnext
					ArrayIndex = ArrayIndex +1endif
				match =0 
			endif 
            '*** insert code to process 'root component' (assembly file)'*** end of code to process root component
            ReportComponentChildren(c.RootComponent, 0) 
        else'*** insert code to process piece part 
			lw.writeline("Piece Part")if ArrayIndex =0then 
				lw.writeline("First Part is a Piece Part") 
				dispPart = theSession.Parts.Display
				fileNameNoExt = dispPart.FullPath
				fileNameNoExt = fileNameNoExt.Substring(0, Len(fileNameNoExt)-2)'GETS THE DISPLAYED PART NAME AND TRIMS OFF TWO LETTERS FROM THE STRING IN ORDER TO REMOVE THE FORWARD SLASH AND REVISION NUMBER
				lw.writeline("FileNameNoExt: "& fileNameNoExt)'WRITES THE NAME OF THE OBJECT TO THE LISTING WINDOW
				PartNames(ArrayIndex)= fileNameNoExt
				for intchecker =0toUBound(PartNames2DArray)if PartNames(ArrayIndex)= PartNames2DArray(intchecker, 0)then
						savename = PartNames2DArray(intchecker, 1)
						part1 = dispPart
						saveas
						exitforendifnext
				ArrayIndex = ArrayIndex +1 
			else 
				lw.writeline("Not First part and is Piece Part") 
				dispPart = theSession.Parts.DisplayRedim Preserve PartNames(ArrayIndex)
				fileNameNoExt = dispPart.FullPath
				fileNameNoExt = fileNameNoExt.Substring(0, Len(fileNameNoExt)-2)'GETS THE DISPLAYED PART NAME AND TRIMS OFF TWO LETTERS FROM THE STRING IN ORDER TO REMOVE THE FORWARD SLASH AND REVISION NUMBERfor j =0toUBound(PartNames)if fileNameNoExt = PartNames(j)then
						match =1endifnextif match <>1then
					PartNames(ArrayIndex)= fileNameNoExt
					for intchecker =0toUBound(PartNames2DArray)if PartNames(ArrayIndex)= PartNames2DArray(intchecker, 0)then
						savename = PartNames2DArray(intchecker, 1)
						part1 = dispPart
						saveas
						exitforendifnext
					ArrayIndex = ArrayIndex +1endif
				match =0 
 
			endif 
 
        endif 
	theSession.CleanUpFacetedFacesAndEdges()
	theSession.Parts.Display.Close(BasePart.CloseWholeTree.True, BasePart.CloseModified.UseResponses, Nothing) 
skipforward:
 
next 
	for j =0toUBound(PartNames)
		lw.writeline(PartNames(j))next 
	lw.Close 
    EndSub 
'**********************************************************Sub reportComponentChildren(ByVal comp As Component, _
        ByVal indent AsInteger) 
        ForEach child As Component In comp.GetChildren()'*** insert code to process component or subassembly
				childpart = child.prototype.owningpart
				fileNameNoExt = Child.DisplayName
				fileNameNoExt = fileNameNoExt.Substring(0, Len(fileNameNoExt)-2)'GETS THE DISPLAYED PART NAME AND TRIMS OFF TWO LETTERS FROM THE STRING IN ORDER TO REMOVE THE FORWARD SLASH AND REVISION NUMBERfor j =0toUBound(PartNames)if fileNameNoExt = PartNames(j)then
						match =1endifnextif match <>1thenRedim Preserve PartNames(ArrayIndex)
					PartNames(ArrayIndex)= fileNameNoExt
					lw.writeline("I added at the 3rd bottom most level")for intchecker =0toUBound(PartNames2DArray)if PartNames(ArrayIndex)= PartNames2DArray(intchecker, 0)then
						savename = PartNames2DArray(intchecker, 1)
						part1 = childpart
						saveas
						exitforendifnext
					ArrayIndex = ArrayIndex +1endif
				match =0'*** end of code to process component or subassemblyif child.GetChildren.Length<>0thenforeach children as component in child.getchildren()'*** this is a subassembly, add code specific to subassemblies
				childrenpart = children.prototype.owningpart
                fileNameNoExt = children.DisplayName
				fileNameNoExt = fileNameNoExt.Substring(0, Len(fileNameNoExt)-2)'GETS THE DISPLAYED PART NAME AND TRIMS OFF TWO LETTERS FROM THE STRING IN ORDER TO REMOVE THE FORWARD SLASH AND REVISION NUMBERfor j =0toUBound(PartNames)if fileNameNoExt = PartNames(j)then
						match =1endifnextif match <>1thenRedim Preserve PartNames(ArrayIndex)
					PartNames(ArrayIndex)= fileNameNoExt
					lw.writeline("I added at the 2nd bottom most level")for intchecker =0toUBound(PartNames2DArray)if PartNames(ArrayIndex)= PartNames2DArray(intchecker, 0)then
						savename = PartNames2DArray(intchecker, 1)
						part1 = childrenpart
						saveas
						exitforendifnext
					ArrayIndex = ArrayIndex +1endif
				match =0next'*** end of code to process subassemblyelse'this component has no children (it is a leaf node)
                fileNameNoExt = Child.DisplayName
				fileNameNoExt = fileNameNoExt.Substring(0, Len(fileNameNoExt)-2)'GETS THE DISPLAYED PART NAME AND TRIMS OFF TWO LETTERS FROM THE STRING IN ORDER TO REMOVE THE FORWARD SLASH AND REVISION NUMBERfor j =0toUBound(PartNames)if fileNameNoExt = PartNames(j)then
						match =1endifnextif match <>1thenRedim Preserve PartNames(ArrayIndex)
					PartNames(ArrayIndex)= fileNameNoExt
					lw.writeline("I added at the bottom most level")for intchecker =0toUBound(PartNames2DArray)if PartNames(ArrayIndex)= PartNames2DArray(intchecker, 0)then
						savename = PartNames2DArray(intchecker, 1)
						part1 = childpart
						saveas
						exitforendifnext
					ArrayIndex = ArrayIndex +1endif
				match =0endif
            reportComponentChildren(child, indent +1)Next 
    EndSub'**********************************************************PublicFunction GetUnloadOption(ByVal dummy AsString)AsIntegerReturn Session.LibraryUnloadOption.ImmediatelyEndFunction'********************************************************** 
sub SaveAs() 
		if savename =""then
		theUISession.NXMessageBox.Show("Error", NXMessageBox.DialogType.Error, "The Save-As name is blank or an error")exitsubendif 
 
			readOnly1 = dispPart.IsReadOnly 
			partOperationCopyBuilder1 = theSession.PdmSession.CreateCopyOperationBuilder(NXOpen.PDM.PartOperationBuilder.OperationType.SaveAs) 
			partOperationCopyBuilder1.SetOperationSubType(NXOpen.PDM.PartOperationCopyBuilder.OperationSubType.Default) 
			partOperationCopyBuilder1.DefaultDestinationFolder=":Newstuff" 
			partOperationCopyBuilder1.DependentFilesToCopyOption= NXOpen.PDM.PartOperationCopyBuilder.CopyDependentFiles.All 
			partOperationCopyBuilder1.ReplaceAllComponentsInSession=True 
			partOperationCopyBuilder1.SetDialogOperation(NXOpen.PDM.PartOperationBuilder.OperationType.Revise) 
			selectedparts1(0)= dispPart
 
			partOperationCopyBuilder1.SetSelectedPartsToCopy(selectedparts1, failedparts1) 
			partOperationCopyBuilder1.CreateLogicalObjects(logicalobjects1) 
			sourceobjects1 = logicalobjects1(0).GetUserAttributeSourceObjects() 
			sourceobjects2 = logicalobjects1(0).GetUserAttributeSourceObjects() 
			sourceobjects3 = logicalobjects1(0).GetUserAttributeSourceObjects() 
			sourceobjects4 = logicalobjects1(0).GetUserAttributeSourceObjects() 
			sourceobjects5 = logicalobjects1(0).GetUserAttributeSourceObjects() 
			partOperationCopyBuilder1.SetDialogOperation(NXOpen.PDM.PartOperationBuilder.OperationType.SaveAs) 
			sourceobjects6 = logicalobjects1(0).GetUserAttributeSourceObjects() 
			selectedparts2(0)= dispPart
 
			partOperationCopyBuilder1.SetSelectedPartsToCopy(selectedparts2, failedparts2) 
			partOperationCopyBuilder1.CreateLogicalObjects(logicalobjects2) 
			sourceobjects7 = logicalobjects2(0).GetUserAttributeSourceObjects() 
			sourceobjects8 = logicalobjects2(0).GetUserAttributeSourceObjects() 
			sourceobjects9 = logicalobjects2(0).GetUserAttributeSourceObjects() 
			sourceobjects10 = logicalobjects2(0).GetUserAttributeSourceObjects() 
			attributePropertiesBuilder1 = theSession.AttributeManager.CreateAttributePropertiesBuilder(nullNXOpen_BasePart, objects1, NXOpen.AttributePropertiesBuilder.OperationType.None) 
			objects2(0)= sourceobjects7(0)
			attributePropertiesBuilder1.SetAttributeObjects(objects2) 
			attributePropertiesBuilder1.Title="DB_PART_NO" 
			attributePropertiesBuilder1.Category="N4_NonDesignPart" 
			attributePropertiesBuilder1.StringValue= savename
 
			changed1 = attributePropertiesBuilder1.CreateAttribute() 
			sourceobjects11 = logicalobjects2(0).GetUserAttributeSourceObjects() 
			nXObject1 = partOperationCopyBuilder1.CreateAttributeTitleToNamingPatternMap(attributetitles1, titlepatterns1) 
			objects3(0)= logicalobjects2(0) 
			properties1(0)= nXObject1
 
			errorList1 = partOperationCopyBuilder1.AutoAssignAttributesWithNamingPattern(objects3, properties1) 
			errorList1.Dispose() 
			errorMessageHandler1 = partOperationCopyBuilder1.GetErrorMessageHandler(True) 
			markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Save Parts As") 
			theSession.DeleteUndoMark(markId2, Nothing) 
			markId3 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Save Parts As") 
			partOperationCopyBuilder1.ValidateLogicalObjectsToCommit() 
			errorMessageHandler2 = partOperationCopyBuilder1.GetErrorMessageHandler(True) 
			errorMessageHandler3 = partOperationCopyBuilder1.GetErrorMessageHandler(True) 
			nXObject2 = partOperationCopyBuilder1.Commit() 
			errorMessageHandler4 = partOperationCopyBuilder1.GetErrorMessageHandler(True) 
			theSession.DeleteUndoMark(markId3, Nothing) 
			partOperationCopyBuilder1.Destroy() 
			attributePropertiesBuilder1.Destroy() 
			partstocheckin1(0)= dispPart
 
			operationErrors1 = dispPart.PDMPart.CheckinParts(partstocheckin1, checkininput1) 
			operationErrors1.Dispose() 
			part1 =nothing 
			savename ="" 
endsub 
Function ChooseBomFile()AsString 
        Dim fdlg As OpenFileDialog =New OpenFileDialog()
        fdlg.Title="Select Excel BOM file"Dim dir AsString
        dir = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
        fdlg.InitialDirectory= dir
        fdlg.Filter="Excel Files(*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm"
        fdlg.FilterIndex=2
        fdlg.RestoreDirectory=TrueIf fdlg.ShowDialog()= DialogResult.OKThenReturn fdlg.FileNameElseReturn""EndIf 
    EndFunction 
EndModule

Blockstyler Limiting Vertical length

$
0
0

I am using Blockstyler to create an NX form. But it is getting so tall that user will have trouble getting to their selection in the bottom of the list of the interface. Is there any way to define size of the Blockstyler interface dialog? In my case it is the height?


SpreadsheetManager

$
0
0

Does anyone have experience with SpreadsheetManager in VB? I found an example for Python that works good when ran. When I looked it up in the API doc it appears that should work for opening both Native and Teamcenter Excel files. I can't seem to make it work in VB for either in my testing though.

Original Python Working Example (nx_api6227):

def readFile(self):
        try:
            xlsFile =self.theSession.SpreadsheetManager.OpenFile(self.xlsFileSpec, NXOpen.SpreadsheetManagerOpenMode.Read) 
            self.theLW.Open()self.theLW.WriteLine("Reading: " + self.xlsFileSpec) 
            if xlsFile:
                data =[]#ReadRange(worksheet, rowstart, colstart, rowend, colend)
                data = xlsFile.ReadRange(1,1,1,2,3)
                numData =len(data)self.theLW.WriteLine("Data Entries: " + str(numData))for i inrange(numData):
                    cellType = data[i].Type
                    info ="Data:" + str(i) + ", Type:" + str(cellType) 
                    if cellType == NXOpen.SpreadsheetCellDataTypes.Int:
                        info +=" IntValue = " + str(data[i].IntValue)elif cellType == NXOpen.SpreadsheetCellDataTypes.Double:
                        info +=" DoubleValue = " + str(data[i].DoubleValue)elif cellType == NXOpen.SpreadsheetCellDataTypes.Formula:
                        info +=" FormulaValue = " + str(data[i].FormulaValue)elif cellType == NXOpen.SpreadsheetCellDataTypes.Logical:
                        info +=" LogicalValue = " + str(data[i].LogicalValue)else:
                        info +=" StringValue = " + str(data[i].StringValue) 
                    self.theLW.WriteLine(" " + info) 
        except:
            self.reportException() 
        finally:
            if xlsFile:
                xlsFile.CloseFile(False)

My VB Code:

Dim xlFileLocation AsString="C:\temp\test.xlsx"'xlFileLocation = "@DB/TEST/001" 
                    InfoWindow.WriteLine(xlFileLocation)Dim theSpreadSheetManager As SpreadsheetManager = theSession.SpreadsheetManagerDim xlsFile = theSpreadSheetManager.OpenFile(xlFileLocation, SpreadsheetManager.OpenMode.Read)
                    InfoWindow.WriteLine(xlsFile.GetNumberofsheets&" Sheets found")IfNot IsNothing(xlsFile)ThenDim Data()As SpreadsheetCellData =Nothing'ReadRange(worksheet, rowstart, colstart, rowend, colend) 
                        Dim worksheet = xlsFile.GetWorksheetIndex("INSTRUCTIONS")
                        xlsFile.ReadRange(worksheet, 1, 1, 2, 3, Data)Dim numData = Data.Length 
                        ForEach theData In Data
                            Dim cellType = theData.Type'info = "Data:" + Str(i) + ", Type:" + Str(cellType)
                            InfoWindow.WriteLine("in the data") 
                        NextEndIf

Multiline Note from copied text

$
0
0

I am using following code to read lines from text file and drooping note inside drafting.. not sure what I am doing wrong

       Sub Main()
  Dim path As String = "mypath\file.txt"
                Dim i As Integer = 1
                Dim line(i) As String
                Dim objReader As New System.IO.StreamReader(path)
                Do While objReader.Peek() <> -1
                    line(i) = objReader.ReadLine()
                    i = i + 1
                Loop
                objReader.Close()
                Call Drop_Text(line) ' SHOWING ERROR IN THIS LINE
End Sub
 Public Sub Drop_Text(TextToDrop As String())
        Dim theSession As NXOpen.Session = NXOpen.Session.GetSession()
        Dim workPart As NXOpen.Part = theSession.Parts.Work
        Dim displayPart As NXOpen.Part = theSession.Parts.Display
 
        Dim nullNXOpen_Annotations_SimpleDraftingAid As NXOpen.Annotations.SimpleDraftingAid = Nothing
        Dim draftingNoteBuilder1 As NXOpen.Annotations.DraftingNoteBuilder = Nothing
 
        draftingNoteBuilder1 = workPart.Annotations.CreateDraftingNoteBuilder(nullNXOpen_Annotations_SimpleDraftingAid)
        draftingNoteBuilder1.Origin.SetInferRelativeToGeometry(True)
        draftingNoteBuilder1.Style.LetteringStyle.GeneralTextSize = 0.1
 
        Dim nullNXOpen_View As NXOpen.View = Nothing
        Dim point1 As NXOpen.Point3d = New NXOpen.Point3d(1, 3.5, 0.0)
        Dim nXObject1 As NXOpen.NXObject = Nothing
 
        draftingNoteBuilder1.Text.TextBlock.SetText(TextToDrop)
        draftingNoteBuilder1.Origin.Origin.SetValue(Nothing, nullNXOpen_View, point1)
        nXObject1 = draftingNoteBuilder1.Commit()
        draftingNoteBuilder1.Destroy()
 
 
 
    End Sub
 
<\code>

How to get the Coordinate of a centroid point

$
0
0

Hi there ! First question here. I'm trying to develop APIs for my team. The one that I work on is a making this :

1) The user select parts in an assembly ;
2) Each constraints of each part is removed ;
3) Each part get a Fixed constraint .

It works. But I also want to place the ConstraintReference.HelpPoint . Tho archive this I loop in the part to find bodies and try to average a centroid from them. The problem is :

I have my average centroid Point3d but it is not a coordinate from the CSYS of the parent part. For exemple : centroid of PART1 is (0,0,5) and PART1 is at (50,10,20) in ASSEMBLY1. what I get is an HelpPoint at (0,0,5) but what I need is an HelpPoint at (50,10,25).

I'm looking on the internet for a while without finding my answer. I hope someone can guide me.

Here is my entire script, the centroid part start with the Fonction GetCenter() :

Imports System
Imports System.GlobalizationImports System.Text.RegularExpressionsImports System.IO'Imports System.Collections 
Imports NXOpen
Imports NXOpen.UFImports NXOpen.AssembliesImports NXOpen.UIImports NXOpen.UtilitiesImports NXOpen.Positioning 
Module FixSelectedObj
    Public theSession As Session = Session.GetSession()Public ufs As UFSession = UFSession.GetUFSession() 
	Sub Main() 
		Dim markId1 As NXOpen.Session.UndoMarkId= theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Fixer Composants")Dim MyNXClass AsNew MyClassNXOpen
		MyNXClass.Echo("--------------- START AT "&Date.Now.ToLongTimeString&" ---------------") 
		Dim workPart As Part = theSession.Parts.WorkDim displayPart As Part = theSession.Parts.DisplayDim lw As ListingWindow = theSession.ListingWindowDim mySelectedObjects AsNew List(Of DisplayableObject)Dim theUI As UI = UI.GetUI() 
		TryDim CompList As TaggedObject() 
			CompList = SelectListObjects("Sélectionnez des pièces ") 
			If IsNothing(CompList)Then
				MyNXClass.Echo("Tâche annulée, aucune pièce sélectionnée")ElseForEach item As NXObject In CompList
					'MyNXClass.Echo(item.JournalIdentifier)
					MyNXClass.Echo("Pièce : "& item.GetStringUserAttribute("DB_PART_DESC", -1))'MyNXClass.Echo("Pièce parent : " & item.OwningComponent.GetStringUserAttribute("DB_PART_DESC", -1))
					DeleteConstraint(item)
					FixComponent(item)NextEndIfCatch ex As Exception
			MyNXClass.Echo("Failed: "& ex.ToString)EndTry 
		MyNXClass.Echo("--------------- FINISH AT "&Date.Now.ToLongTimeString&" ---------------")
		theSession.DeleteUndoMark(markId1, Nothing)
		MyNXClass.GetUnloadOption() 
	EndSub 
	Function SelectListObjects(prompt AsString)As TaggedObject() 
		Dim MyClassNX AsNew MyClassNXOpen
 
		Dim selObj As TaggedObject()=NothingDim theUI As UI = UI.GetUIDim title AsString="Select objects"Dim includeFeatures AsBoolean=FalseDim keepHighlighted AsBoolean=FalseDim selAction As Selection.SelectionAction= Selection.SelectionAction.ClearAndEnableSpecificDim scope As Selection.SelectionScope= Selection.SelectionScope.AnyInAssemblyDim selectionMask_array(0)As Selection.MaskTriple 
		With selectionMask_array(0).Type= NXOpen.UF.UFConstants.UF_component_type.SolidBodySubtype= NXOpen.UF.UFConstants.UF_component_subtypeEndWith 
		Dim resp As Selection.Response= theUI.SelectionManager.SelectTaggedObjects(prompt, title, scope, selAction, includeFeatures, keepHighlighted, selectionMask_array, selObj) 
		If resp = Selection.Response.ObjectSelectedOr resp = Selection.Response.ObjectSelectedByNameOr resp = Selection.Response.OkThenReturn selObj
		ElseReturnNothingEndIf 
	EndFunction 
	Sub DeleteConstraint(ByVal CompDel As Component)'.Dim MyNXClass AsNew MyClassNXOpen
		Dim parentPart As Part =CType(CompDel.Parent.Prototype, Part)Dim workPart As Part =CType(CompDel.Prototype, Part)Dim msg As NXMessageBox = UI.GetUI().NXMessageBoxDim tmpName AsString 
		TryDim save_arrangement = parentPart.ComponentAssembly.ActiveArrangement 
			Dim marque As Session.UndoMarkId= theSession.SetUndoMark(Session.MarkVisibility.Visible, "Delete Constraints") 
			ForEach a As Arrangement In parentPart.ComponentAssembly.Arrangements 
				parentPart.ComponentAssembly.ActiveArrangement= a
				Dim RegworkPartID AsNew Regex(workPart.JournalIdentifier.ToString, RegexOptions.IgnoreCase) 
				ForEach c As ComponentConstraint In parentPart.ComponentAssembly.Positioner.Constraints
					tmpName = c.Name.ToStringIf RegworkPartID.IsMatch(tmpName)Then
						theSession.UpdateManager.AddToDeleteList(c)ElseEndIfNext
				theSession.UpdateManager.DoAssemblyConstraintsUpdate(marque) 
			Next
			parentPart.ComponentAssembly.ActiveArrangement= save_arrangement
			MyNXClass.Echo("Toutes les contraintes du composant sont supprimées") 
		Catch ex As Exception
			MyNXClass.Echo("Failed at Del : "& ex.ToString)EndTry 
		ufs.Modl.Update() 
	EndSub 
	Sub FixComponent(ByVal CompFix As Component) 
		Dim MyNXClass AsNew MyClassNXOpen
		Dim tmpParent As Component = CompFix.ParentDim workPart As Part = theSession.Parts.FindObject(tmpParent.DisplayName) 
		TryDim CP As Positioning.ComponentPositioner= workPart.ComponentAssembly.Positioner
			CP.ClearNetwork() 
			Dim activ_arrangement = workPart.ComponentAssembly.ActiveArrangementDim arrangement1 As Assemblies.Arrangement=CType(activ_arrangement, Assemblies.Arrangement)
			CP.PrimaryArrangement= arrangement1
			CP.BeginAssemblyConstraints() 
			Dim allowInterpartPositioning1 AsBoolean
			allowInterpartPositioning1 = theSession.Preferences.Assemblies.InterpartPositioning 
			theSession.Preferences.Assemblies.InterpartPositioning=True 
			Dim Network As Positioning.Network
			Network = CP.EstablishNetwork() 
			Dim CN As Positioning.ComponentNetwork=CType(Network, Positioning.ComponentNetwork)
			CN.DisplayComponent=Nothing
			CN.NetworkArrangementsMode= Positioning.ComponentNetwork.ArrangementsMode.Existing
			CN.MoveObjectsState=True 
			'*** FixDim Constraint1 As Positioning.Constraint= CP.CreateConstraint() 
			Dim CConstraint1 As Positioning.ComponentConstraint=CType(Constraint1, Positioning.ComponentConstraint)
			CConstraint1.ConstraintType= Positioning.Constraint.Type.Fix 
			Dim ConstraintRef1 As Positioning.ConstraintReference= CConstraint1.CreateConstraintReference(CompFix, CompFix, False, False, False) 
			Dim helpPoint1 As NXOpen.Point3d
			helpPoint1 = GetCenter(CompFix)
			ConstraintRef1.HelpPoint= helpPoint1
 
			CN.Solve()
			CN.ApplyToModel() 
			CP.ClearNetwork()
			CP.DeleteNonPersistentConstraints()
			CP.EndAssemblyConstraints() 
			MyNXClass.Echo("Le composant est fixé !")Catch ex As Exception
			MyNXClass.Echo("Failed at Fix : "& ex.ToString)EndTry 
	EndSub 
	Function GetCenter(ByVal CompCenter As Component)As Point3d
 
		Dim MyNXClass AsNew MyClassNXOpen
		Dim nb AsInteger=0Dim tmpX AsInteger=0Dim tmpY AsInteger=0Dim tmpZ AsInteger=0Dim tmpPart As Part = theSession.Parts.FindObject(CompCenter.Name)Dim tmpcomp As Component = CompCenter
		Dim tmpchild As Part
		Dim CG As NXOpen.Point3d=New Point3d(tmpX, tmpY, tmpZ) 
		TryForEach body In tmpPart.Bodies
				nb = nb +1Next body
 
			If nb >0Then 
				ForEach body In tmpPart.BodiesDim theBodies(0)As Body
					theBodies(0)= body
					Dim myMeasure As MeasureManager = theSession.Parts.Display.MeasureManager()Dim massUnits(1)As Unit
					massUnits(0)= theSession.Parts.Display.UnitCollection.GetBase("Volume") 
					Dim mb As MeasureBodies =Nothing'***.NewMassProperties(array of units, accuracy parameter, array of bodies to measure)
					mb = myMeasure.NewMassProperties(massUnits, 0.99, theBodies)
					mb.InformationUnit= MeasureBodies.AnalysisUnit.GramMillimeter 
					CG = mb.Centroid
					tmpX = tmpX + mb.Centroid.X
					tmpY = tmpY + mb.Centroid.Y
					tmpZ = tmpZ + mb.Centroid.Z 
				Next
				tmpX = tmpX / nb
				tmpY = tmpY / nb
				tmpZ = tmpZ / nb
				CG =New Point3d(tmpX, tmpY, tmpZ) 
			Else 
				If tmpcomp.GetChildren.Length<>0ThenForEach child In tmpcomp.GetChildren()
						tmpchild = theSession.Parts.FindObject(child.Name)
						nb =0ForEach body In tmpchild.Bodies
							nb = nb +1Next 
						If nb >0Then 
							ForEach body In tmpchild.BodiesDim theBodies(0)As Body
								theBodies(0)= body
								Dim myMeasure As MeasureManager = theSession.Parts.Display.MeasureManager()Dim massUnits(1)As Unit
								massUnits(0)= theSession.Parts.Display.UnitCollection.GetBase("Volume") 
								Dim mb As MeasureBodies =Nothing'***.NewMassProperties(array of units, accuracy parameter, array of bodies to measure)
								mb = myMeasure.NewMassProperties(massUnits, 0.99, theBodies)
								mb.InformationUnit= MeasureBodies.AnalysisUnit.GramMillimeter 
								CG = mb.Centroid
								tmpX = tmpX + mb.Centroid.X
								tmpY = tmpY + mb.Centroid.Y
								tmpZ = tmpZ + mb.Centroid.Z 
							Next body
							tmpX = tmpX / nb
							tmpY = tmpY / nb
							tmpZ = tmpZ / nb
							CG =New Point3d(tmpX, tmpY, tmpZ) 
						Else'CG = New Point3d(0, 0, 0)EndIfNext child
				Else'CG = New Point3d(0, 0, 0)EndIfEndIfCatch ex As Exception
			MyNXClass.Echo("Failed at GetCenter : "& ex.ToString)'CG = New Point3d(0, 0, 0)EndTryReturn CG
 
	EndFunction 
	PublicFunction GetUnloadOption()AsInteger 
        'Unloads the image when the NX session terminates'GetUnloadOption = NXOpen.Session.LibraryUnloadOption.AtTermination 
        '----Other unload options-------'Unloads the image immediately after execution within NX
        GetUnloadOption = NXOpen.Session.LibraryUnloadOption.Immediately 
        'Unloads the image explicitly, via an unload dialog'GetUnloadOption = NXOpen.Session.LibraryUnloadOption.Explicitly'------------------------------- 
    EndFunction 
EndModule

Get All PMI objects in workPart

$
0
0

Our modeling standard is to have several model views with logical subsets of the PMI. We also include one model view named "ALL" that should have every PMI object.

I am trying to write code to make sure every object is displayed in the ALL view.

the only option I have found so far is to get separate arrays of each specific type of annotation object:

foreach (NXOpen.Annotations.Annotation a in workPart.Annotations.Fcfs)
{//...}
foreach (NXOpen.Annotations.Annotation a in workPart.Annotations.CustomSymbols)
{//...}

etc.

is there any way to get all objects of type NXOpen.Annotations.Annotation ?

read attributes previus versions

$
0
0

Hi All,

I'm new to this forum, and I need help.
I'm use NX integrated in teamcenter and I need read the attributes of previus version of open part. I'm already to read the attributes of open part but not the previus version .... anyone can help me.

Thanks in advance

This is my code.

Option Strict Off
Imports System
Imports NXOpen
Imports NXOpen.UF

Module Module25
Sub Main(ByVal args() As String)

Dim theSession As Session = Session.GetSession()
Dim lw As ListingWindow = theSession.ListingWindow

Dim partNum As String
Dim partId As String
Dim partName As String
Dim partgen As String
Dim partrev As String
Dim partrevid As String
Dim partdesc As String
Dim partdesc2 As String

lw.Open()

lw.WriteLine("Full Path: "& theSession.Parts.Work.FullPath)
lw.WriteLine("Leaf: "& theSession.Parts.Work.Leaf)

Try
partNum = theSession.Parts.Work.GetStringAttribute("DB_PART_NO")
partId = theSession.Parts.Work.GetStringAttribute("PART_ID")
partName = theSession.Parts.Work.GetStringAttribute("DB_PART_NAME")
partgen = theSession.Parts.Work.GetStringAttribute("GENERATO DA")
partrev = theSession.Parts.Work.GetStringAttribute("DB_PART_REV")
partrevid = theSession.Parts.Work.GetStringAttribute("PART_REV_ID")
partdesc = theSession.Parts.Work.GetStringAttribute("DESCRIZIONE")

lw.WriteLine(partNum)
lw.WriteLine(partgen)
lw.WriteLine(partId)
lw.WriteLine(partName)
lw.WriteLine(partrev)
lw.WriteLine(partrevid)
lw.WriteLine(partdesc)

Catch ex As NXException
lw.WriteLine("exception "& ex.ErrorCode.ToString & ": "& ex.Message)
End Try

lw.Close()

End Sub

End Module

Revision Journal - issue with deleting objects

$
0
0

Hello,

I made a journal which displays coordinates of all revision triangles placed on the drawing and change color of triangles on red (for better clarity). User can just copy coordinates and describe purpose of change. Journal works perfect on all sheet sizes (metric and imperial). The only issue is that user cannot delete triangles after running this journal. I was traying to solve it, but I cannot find the solution. I would be grateful for any suggestions :)

P.S. If journal will ask about number of EDO sheets you can type "0".

Option Strict Off
Imports System
Imports System.Collections.Generic
Imports NXOpen
Imports NXOpen.UF
Imports NXOpenUI

Module Module6

Dim theSession As Session = Session.GetSession()
Dim theUfSession As UFSession = UFSession.GetUFSession

Sub Main()

If IsNothing(theSession.Parts.Work) Then
'active part required
Return
End If

Dim workPart As Part = theSession.Parts.Work
Dim lw As ListingWindow = theSession.ListingWindow
Dim theUISession As UI = UI.GetUI
Dim answer As String = ""
Dim myInt As Double
Dim myNumber As Double

Do
answer = NXInputBox.GetInputNumber("Enter number of EDO sheets", "")
'if cancel is pressed, exit sub
If answer = "" Then Exit Sub
Loop Until Integer.TryParse(answer, myInt)

lw.Open()

Dim dicDraftingDatums As New Dictionary(Of String, List(Of String))

For Each temp As Annotations.IdSymbol In workpart.Annotations.IdSymbols

dim myIdBuilder As Annotations.IdSymbolBuilder
myIdBuilder = workPart.Annotations.IdSymbols.CreateIdSymbolBuilder(temp)

If myIdBuilder.Type = Annotations.IdSymbolBuilder.SymbolTypes.TriangleUp Then
Dim myDraftingDatum As Annotations.IdSymbol = temp
Dim myDraftingDatumZone As string
myDraftingDatumZone = ReportAnnotationSheetZone(AskDrawingSheet(myDraftingDatum), myDraftingDatum)

Dim displayModification1 As DisplayModification
displayModification1 = theSession.DisplayManager.NewDisplayModification()
displayModification1.ApplyToAllFaces = True
displayModification1.ApplyToOwningParts = False
displayModification1.NewColor = 186
Dim objects1(0) As DisplayableObject
objects1(0) = temp
displayModification1.Apply(objects1)
displayModification1.Dispose()

If dicDraftingDatums.ContainsKey(myIdBuilder.UpperText) Then
'add zone info to the existing key
dicDraftingDatums.Item(myIdBuilder.UpperText).Add(myDraftingDatumZone)
Else
'add to dictionary
dicDraftingDatums.Add(myIdBuilder.UpperText, New List(Of String)({myDraftingDatumZone}))
End If
End If
Next

For Each pair As KeyValuePair(Of String, List(Of String)) In dicDraftingDatums
'mySheets.Sort(AddressOf CompareSheetNames)
dim finalstring As String

'lw.WriteLine(" Datum label: "& pair.Key & " ["& pair.Value.Count.ToString & " places]")
pair.Value.Sort(AddressOf CompareZones)
For Each temp As String In pair.Value

dim sheetnumber_str As String = mid(temp,1,1)
dim sheetnumber_int As Integer = CDbl(sheetnumber_str) - myInt
dim finalsheetnum As String = sheetnumber_int
if sheetnumber_int > 0 then

finalstring = finalstring + "SH" + finalsheetnum + ", " + "ZONE" + "" + mid(temp,2,3) + ",; "

end if

Next
lw.WriteLine("")
lw.WriteLine(""&finalstring)

Next

lw.Close()

End Sub

Function AskDrawingSheet(ByVal theObject As TaggedObject) As Drawings.DrawingSheet
'Code written by Amy Webster of GTAC
' see nx_api4936 or nx_api4937
' This function will work for:
' an object which "Resides on drawing" or is "View Dependent In" a DraftingView
' a DraftingView
' a DrawingSheet.View
' Returns Nothing for all other (ie. model mode) objects

Dim theView As View = TryCast(theObject, View)
If Not theView Is Nothing Then
Dim sheetTag As Tag = Nothing
Try
theUfSession.Draw.AskDrawingOfView(theView.Tag, sheetTag)
Return Utilities.NXObjectManager.Get(sheetTag) ' the drawing it is on
Catch ex As NXException
Return Nothing ' it is a model view
End Try
End If

Dim viewName As String = Nothing
Dim status As Integer = Nothing
Try
theUfSession.View.AskViewDependentStatus(theObject.Tag, status, viewName)
Catch ex As NXException
Return Nothing
End Try
If status = 0 Then Return Nothing ' it is a model mode object

Dim viewTag As Tag = Nothing
theUfSession.View.AskTagOfViewName(viewName, viewTag)
Dim viewType As Integer = Nothing
Dim viewSubtype As Integer = Nothing
theUfSession.View.AskType(viewTag, viewType, viewSubtype)
If viewType = 0 Then Return Nothing ' it is view dependent in a modeling view

Dim drawingTag As Tag = Nothing
theUfSession.Draw.AskDrawingOfView(viewTag, drawingTag)
Return Utilities.NXObjectManager.Get(drawingTag) ' the drawing it is on!

End Function

Function ReportAnnotationSheetZone(ByVal theSheet As Drawings.DrawingSheet, ByVal theAnnotation As Annotations.Annotation) As String

'sheet number / vertical zone / horizontal zone

Dim borderBuilder As Drawings.BordersAndZonesBuilder

borderBuilder = theSession.Parts.Work.Drafting.BordersAndZonesObjects.CreateBordersAndZonesBuilder(theSheet.BordersAndZones)

dim cell_number_x As Integer = 12
dim cell_number_y As Integer = 8
dim SheetA0 As Integer = 0
dim cord_x As Integer = ((841/25.4)-1) / cell_number_x
dim cord_y As Double = ((594/25.4)-1) / cell_number_y
dim Hcell As Double
dim Vcell As Double
dim const1 As Integer = 0
dim st_cell_size As Double
dim st_cell_size1 As Double
dim cell_size As Double
dim cell_size1 As Double

' A0 size
if theSheet.Length = 1189 then

cell_number_y = 12
cell_number_x = 16
cord_y = ((841/25.4))
cord_x = ((1189/25.4))
st_cell_size = ((cord_x - 1) / cell_number_x) + .5
cell_size = ((cord_x - 1) / cell_number_x)
st_cell_size1 = ((cord_y - 1) / cell_number_y) + .5
cell_size1 = ((cord_y - 1) / cell_number_y)
const1 = 1

end if

' A2 size
if theSheet.Length = 594 then

cell_number_y = 6
cell_number_x = 8
cord_y = (420/25.4)
cord_x = (594/25.4)
st_cell_size = ((cord_x - 1) / cell_number_x) + .5
cell_size = ((cord_x - 1) / cell_number_x)
st_cell_size1 = ((cord_y - 1) / cell_number_y) + .5
cell_size1 = ((cord_y - 1) / cell_number_y)

end if

' A3 size
if theSheet.Length = 420 then

cell_number_y = 4
cell_number_x = 8
cord_y = ((297/25.4))
cord_x = ((420/25.4))
st_cell_size = ((cord_x - 1) / cell_number_x) + .5
cell_size = ((cord_x - 1) / cell_number_x)
st_cell_size1 = ((cord_y - 1) / cell_number_y) + .5
cell_size1 = ((cord_y - 1) / cell_number_y)

end if

' A4 size
if theSheet.Length = 297 then

cell_number_y = 4
cell_number_x = 6
cord_y = ((210/25.4))
cord_x = ((297/25.4))
st_cell_size = ((cord_x - 1) / cell_number_x) + .5
cell_size = ((cord_x - 1) / cell_number_x)
st_cell_size1 = ((cord_y - 1) / cell_number_y) + .5
cell_size1 = ((cord_y - 1) / cell_number_y)

end if

'A1 size
if theSheet.Length = 841 then

cell_number_y = 8
cell_number_x = 12
cord_y = ((594/25.4))
cord_x = ((841/25.4))
st_cell_size = ((cord_x - 1) / cell_number_x) + .5
cell_size = ((cord_x - 1) / cell_number_x)
st_cell_size1 = ((cord_y - 1) / cell_number_y) + .5
cell_size1 = ((cord_y - 1) / cell_number_y)

end if

'D size
if theSheet.Length = 34 then
cell_number_y = 8
cell_number_x = 12
cord_y = 22 / cell_number_y
cord_x = 34 / cell_number_x
st_cell_size = 2.75 + 0.5
cell_size = 2.75
st_cell_size1 = 21/8 + 0.5
cell_size1 = 21/8

end if

'E size
if theSheet.Length = 44 then
cell_number_y = 12
cell_number_x = 16
cord_y = 34 / cell_number_y
cord_x = 44 / cell_number_x
st_cell_size = 3.1875
cell_size = 2.6875
st_cell_size1 = 33/12 + .5
cell_size1 = 33/12
const1=1

end if

'C size
if theSheet.Length = 22 then
cell_number_y = 6
cell_number_x = 8
cord_y = 17 / cell_number_y
cord_x = 22 / cell_number_x
st_cell_size = 2.625 + 0.5
cell_size = 2.625
st_cell_size1 = 16/6 + .5
cell_size1 = 16/6

end if

'B size
if theSheet.Length = 17 then
cell_number_y = 4
cell_number_x = 6
cord_y = 11 / cell_number_y
cord_x = 17 / cell_number_x
st_cell_size = 2.666666666666667 + 0.5
cell_size = 2.666666666666667
st_cell_size1 = 10/4 + .5
cell_size1 = 10/4

end if

'A size
if theSheet.Length = 11 then
cell_number_y = 4
cell_number_x = 6
cord_y = 8.5 / cell_number_y
cord_x = 11 / cell_number_x
st_cell_size = 1.666666666666667 + 0.5
cell_size = 1.666666666666667
st_cell_size1 = 1.875 + .5
cell_size1 = 1.875

end if

if theAnnotation.AnnotationOrigin.X < st_cell_size then
Hcell = 1
end if

if st_cell_size < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*1 then
Hcell = 2
end if

if st_cell_size + cell_size*1 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*2 then
Hcell = 3
end if

if st_cell_size + cell_size*2 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*3 then
Hcell = 4
end if

if st_cell_size + cell_size*3 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*4 then
Hcell = 5
end if

if st_cell_size + cell_size*4 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*5 then
Hcell = 6
end if

if st_cell_size + cell_size*5 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*6 then
Hcell = 7
end if

if st_cell_size + cell_size*6 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*7 then
Hcell = 8
end if

if st_cell_size + cell_size*7 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*8 then
Hcell = 9
end if

if st_cell_size + cell_size*8 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*9 then
Hcell = 10
end if

if st_cell_size + cell_size*9 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*10 then
Hcell = 11
end if

if st_cell_size + cell_size*10 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*11 then
Hcell = 12
end if

if st_cell_size + cell_size*11 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*12 then
Hcell = 13
end if

if st_cell_size + cell_size*12 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*13 then
Hcell = 14
end if

if st_cell_size + cell_size*13 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*14 then
Hcell = 15
end if

if st_cell_size + cell_size*14 < theAnnotation.AnnotationOrigin.X and theAnnotation.AnnotationOrigin.X < st_cell_size + cell_size*15 then
Hcell = 16
end if

'poczatek

if theAnnotation.AnnotationOrigin.Y < st_cell_size1 then
Vcell = 1
end if

if st_cell_size1 < theAnnotation.AnnotationOrigin.Y and theAnnotation.AnnotationOrigin.Y < st_cell_size1 + cell_size1*1 then
Vcell = 2
end if

if st_cell_size1 + cell_size1*1 < theAnnotation.AnnotationOrigin.Y and theAnnotation.AnnotationOrigin.Y < st_cell_size1 + cell_size1*2 then
Vcell = 3
end if

if st_cell_size1 + cell_size1*2 < theAnnotation.AnnotationOrigin.Y and theAnnotation.AnnotationOrigin.Y < st_cell_size1 + cell_size1*3 then
Vcell = 4
end if

if st_cell_size1 + cell_size1*3 < theAnnotation.AnnotationOrigin.Y and theAnnotation.AnnotationOrigin.Y < st_cell_size1 + cell_size1*4 then
Vcell = 5 + const1
end if

if st_cell_size1 + cell_size1*4 < theAnnotation.AnnotationOrigin.Y and theAnnotation.AnnotationOrigin.Y < st_cell_size1 + cell_size1*5 then
Vcell = 6 + const1
end if

if st_cell_size1 + cell_size1*5 < theAnnotation.AnnotationOrigin.Y and theAnnotation.AnnotationOrigin.Y < st_cell_size1 + cell_size1*6 then
Vcell = 7 + const1
end if

if st_cell_size1 + cell_size1*6 < theAnnotation.AnnotationOrigin.Y and theAnnotation.AnnotationOrigin.Y < st_cell_size1 + cell_size1*7 then
Vcell = 8 + const1
end if

if st_cell_size1 + cell_size1*7 < theAnnotation.AnnotationOrigin.Y and theAnnotation.AnnotationOrigin.Y < st_cell_size1 + cell_size1*8 then
Vcell = 9 + const1
end if

if st_cell_size1 + cell_size1*8 < theAnnotation.AnnotationOrigin.Y and theAnnotation.AnnotationOrigin.Y < st_cell_size1 + cell_size1*9 then
Vcell = 10 + const1
end if

if st_cell_size1+ + cell_size1*9 < theAnnotation.AnnotationOrigin.Y and theAnnotation.AnnotationOrigin.Y < st_cell_size1+ + cell_size1*10 then
Vcell = 11 + const1
end if

if st_cell_size1+ + cell_size1*10 < theAnnotation.AnnotationOrigin.Y and theAnnotation.AnnotationOrigin.Y < st_cell_size1+ + cell_size1*11 then
Vcell = 12 + const1
end if

'koniec

Dim verticalLetterNum As Integer
Dim verticalLetter As Char

Dim horizontalNum As Integer

horizontalNum = Hcell
verticalLetterNum = Asc("A") + cell_number_y - Vcell + const1
verticalLetter = Chr(verticalLetterNum)

Dim theSheetNum As String = SheetNumber(theSheet)
Dim theSheetTag As String = SheetTitle(theSheet)

Dim searchChar As String = "EDO"

Dim edo_counter As Integer = 0
dim edo_number As Integer= InStr(1, theSheetTag, SearchChar, CompareMethod.Text)

' if edo_number = 1 then return nothing
Return theSheetNum & verticalLetter & horizontalNum.ToString
End Function

Function SheetNumber(ByVal theSheet As Drawings.DrawingSheet) As String

Dim sheetNum As String
Dim theSheetBuilder As Drawings.DrawingSheetBuilder = theSession.Parts.Work.DrawingSheets.DrawingSheetBuilder(theSheet)
sheetNum = theSheetBuilder.Number

Return sheetNum
theSheetBuilder.Destroy()

End Function

Function SheetTitle(ByVal theSheet As Drawings.DrawingSheet) As String

Dim sheetTag As String
Dim theSheetBuilder As Drawings.DrawingSheetBuilder = theSession.Parts.Work.DrawingSheets.DrawingSheetBuilder(theSheet)
sheetTag = theSheetBuilder.Name

Return sheetTag.ToString
theSheetBuilder.Destroy()

End Function

Private Function CompareZones(ByVal x As String, ByVal y As String) As Integer

'case-insensitive sort
Dim myStringComp As StringComparer = StringComparer.CurrentCultureIgnoreCase

'for a case-sensitive sort (A-Z then a-z), change the above option to:
'Dim myStringComp As StringComparer = StringComparer.CurrentCulture

Return myStringComp.Compare(x, y)

End Function

Public Function GetUnloadOption(ByVal dummy As String) As Integer

'Unloads the image immediately after execution within NX
GetUnloadOption = NXOpen.Session.LibraryUnloadOption.Immediately

End Function

End Module

How to Read Measures from Part with NXOpen

$
0
0

I have a part with several measures (Analysis->Measure). I have renamed them to something descriptive (e.g., CylinderHeight).

Now what I would like to do in the journal is get the value for a specified measure, for instance:

myDouble = GetMeausureValue(measureName as String, measureType as ?)

something like that .....

I tried to reverse engineer a recorded journal but haven't made much progress, any hints or ideas? If I knew how to find the object with the correct measureName that would really help.

Thanks


Collecting projected points on the parts nearest surface (with z-direction)

$
0
0

Hi everyone,

I am quite new at NXOpen. I have some questions to achieve my task.

Lets think there are some points on xy plane.

Example: (0, 0, 0), (0, 10, 0), (10, 10, 0)

I want to collect in z-direction projected points coordinates on the parts nearest surface. As you can imagine results x and y coordinates of points must be the same.

Result could be: (0, 0, 20), (0, 10, 15), (10, 10, 20)

Based on my research I should use origin point, z-unit vector, direction and scalar to achieve my goal. But how?

After collecting projected point. I need to collect surface angle with x-y plane at this point.

In my solution to this task is porbably getting face normal at this point and calculate angle with -z-direction unit vector.

Can you help to discover required functions or methods in NXOpen please?

Updating Point Coordinates in NX With New XYZ Values in JAVA

$
0
0

I am in need of help with a JAVA program.
I did not write this program and could use some help to update one of the 3D points.
I have a program that imports part geometry (A) in another part (B) locating it on 3 points.
Point data is collected per a JAVA program from picking points on a model in an NX part when prompted.
Point1 values are correctly imported into Pdata1 while running the program.
Point2 values are correctly imported into pdata2 while running the program.
Point3 values are correctly created for pdata3 while running the program but are not applied to the point.
The program creates a new point P20 in Expressions and puts the point at 0 on the end of a line.
I need code to update point P20 with the coordinates collected for Pdata3.
It looks like the easiest way to correct the problem will be to update the coordinates at the end of the program by telling P20 to be a 3D point using Point3d(pdata3[0], pdata3[1], pdata3[2]).
Keep in mind the coordinates are collected and not applied in the program.
Can someone please help me write some code that will update point P20 with the coordinates collected for Pdata3 at the end of the program?
The program uses expressions to apply the coordinates.
See the existing code:

nxopen.SelectionIntentRule [] rules1 = new nxopen.SelectionIntentRule[1];
rules1[0] = edgeChainRule1;
nxopen.NXObject nullNXOpen_NXObject = null;
nxopen.Point3d helpPoint1 = new nxopen.Point3d(pdata3[0], pdata3[1], pdata3[2]);
section2.addToSection(rules1, edge1, nullNXOpen_NXObject, nullNXOpen_NXObject, helpPoint1, nxopen.Section.Mode.EDIT, false);

Edit Expressions, Update Model, Export Characteristics

$
0
0

Hello,
I'm exploring the capabilities of NX journals, and to be completely frank, I don't know visual basic or the syntax of journals, but I wanted to see if I could get a general explanation, if not any actual code, to see if what I want to do is even possible before I dive down the rabbit hole. Essentially, I would like to be able to programmatically change expression values in a part within an assembly, update the assembly (including the other parts) to reflect the changes, measure mass, cg, and inertia properties of the assembly, and export those numbers to some sort of file, be it excel or .txt. Is this something NX journals can do with relative ease, can it be done with difficulty, or is it impossible/impractical? Any help you can provide is appreciated, and please forgive my ignorance on the topic.

Export user defined views to an Excel template

$
0
0

Hi all,

I want to export multiple user defined views (03 nos.)to an excel template file.

All the views have their fixed location in that excel template.

Currently we take each views screenshot and paste them in the excel template.

I have made a Block styler which is exporting some point coordinates to the same excel template but without any views.

Any idea how I can export model or camera views to the same excel template at appropriate/defined location.

SpreadsheetManager

$
0
0

Does anyone have experience with SpreadsheetManager in VB? I found an example for Python that works good when ran. When I looked it up in the API doc it appears that should work for opening both Native and Teamcenter Excel files. I can't seem to make it work in VB for either in my testing though.

Original Python Working Example (nx_api6227):

def readFile(self):
        try:
            xlsFile =self.theSession.SpreadsheetManager.OpenFile(self.xlsFileSpec, NXOpen.SpreadsheetManagerOpenMode.Read) 
            self.theLW.Open()self.theLW.WriteLine("Reading: " + self.xlsFileSpec) 
            if xlsFile:
                data =[]#ReadRange(worksheet, rowstart, colstart, rowend, colend)
                data = xlsFile.ReadRange(1,1,1,2,3)
                numData =len(data)self.theLW.WriteLine("Data Entries: " + str(numData))for i inrange(numData):
                    cellType = data[i].Type
                    info ="Data:" + str(i) + ", Type:" + str(cellType) 
                    if cellType == NXOpen.SpreadsheetCellDataTypes.Int:
                        info +=" IntValue = " + str(data[i].IntValue)elif cellType == NXOpen.SpreadsheetCellDataTypes.Double:
                        info +=" DoubleValue = " + str(data[i].DoubleValue)elif cellType == NXOpen.SpreadsheetCellDataTypes.Formula:
                        info +=" FormulaValue = " + str(data[i].FormulaValue)elif cellType == NXOpen.SpreadsheetCellDataTypes.Logical:
                        info +=" LogicalValue = " + str(data[i].LogicalValue)else:
                        info +=" StringValue = " + str(data[i].StringValue) 
                    self.theLW.WriteLine(" " + info) 
        except:
            self.reportException() 
        finally:
            if xlsFile:
                xlsFile.CloseFile(False)

My VB Code:

Dim xlFileLocation AsString="C:\temp\test.xlsx"'xlFileLocation = "@DB/TEST/001" 
                    InfoWindow.WriteLine(xlFileLocation)Dim theSpreadSheetManager As SpreadsheetManager = theSession.SpreadsheetManagerDim xlsFile = theSpreadSheetManager.OpenFile(xlFileLocation, SpreadsheetManager.OpenMode.Read)
                    InfoWindow.WriteLine(xlsFile.GetNumberofsheets&" Sheets found")IfNot IsNothing(xlsFile)ThenDim Data()As SpreadsheetCellData =Nothing'ReadRange(worksheet, rowstart, colstart, rowend, colend) 
                        Dim worksheet = xlsFile.GetWorksheetIndex("INSTRUCTIONS")
                        xlsFile.ReadRange(worksheet, 1, 1, 2, 3, Data)Dim numData = Data.Length 
                        ForEach theData In Data
                            Dim cellType = theData.Type'info = "Data:" + Str(i) + ", Type:" + Str(cellType)
                            InfoWindow.WriteLine("in the data") 
                        NextEndIf
Viewing all 787 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>