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

Start a new feature after switching a module (where that feature is compatible)

$
0
0

I was trying to Start a new feature after switching a module. for my case it was to start 'Move Face' after switching to 'Modeling' module. But I wanted the journal to stop after it just start the 'move face' command and stay there (for user to start working). So I recorded the journal for starting 'Move face' command. And added the coded to switch to modeling module. But when I play the edited journal, it just switches module, and does not start the moveface feature. Please suggest where I am doing wrong and what can be the solution. Thanks.

Imports System
Imports NXOpen
Imports NXOpen.UF
 
Module NXJournal
Sub Main (ByVal args() 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
 
        ' ----------------------------------------------
        '   Switch to MODELING Module
        ' ----------------------------------------------
 
 
        Dim theUfSession As UFSession = UFSession.GetUFSession
        ' Dim lw As ListingWindow = theSession.ListingWindow
        Dim theUI As UI = UI.GetUI
        If IsNothing(theSession.Parts.Work) Then
            'active part required
            Return
        End If
 
        Dim currentModuleId As Integer
        theUfSession.UF.AskApplicationModule(currentModuleId)
 
        Select Case currentModuleId
            Case Is = UFConstants.UF_APP_MODELING
                '':::: take no action ::::
            Case Else
                theUI.MenuBarManager.ApplicationSwitchRequest("UG_APP_MODELING")
        End Select
 
 
' ----------------------------------------------
'   Menu: Insert->Synchronous Modeling->Move Face...
' ----------------------------------------------
Dim markId1 As NXOpen.Session.UndoMarkId = Nothing
markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Start")
 
Dim nullNXOpen_Features_AdmMoveFace As NXOpen.Features.AdmMoveFace = Nothing
 
Dim admMoveFaceBuilder1 As NXOpen.Features.AdmMoveFaceBuilder = Nothing
admMoveFaceBuilder1 = workPart.Features.CreateAdmMoveFaceBuilder(nullNXOpen_Features_AdmMoveFace)
 
admMoveFaceBuilder1.FaceToMove.RelationScope = 511
 
admMoveFaceBuilder1.Motion.DistanceAngle.OrientXpress.AxisOption = NXOpen.GeometricUtilities.OrientXpressBuilder.Axis.Passive
 
admMoveFaceBuilder1.Motion.DistanceAngle.OrientXpress.PlaneOption = NXOpen.GeometricUtilities.OrientXpressBuilder.Plane.Passive
 
admMoveFaceBuilder1.Motion.AlongCurveAngle.AlongCurve.IsPercentUsed = True
 
admMoveFaceBuilder1.Motion.AlongCurveAngle.AlongCurve.Expression.RightHandSide = "0"
 
admMoveFaceBuilder1.Motion.AlongCurveAngle.AlongCurve.Expression.RightHandSide = "0"
 
admMoveFaceBuilder1.Motion.OrientXpress.AxisOption = NXOpen.GeometricUtilities.OrientXpressBuilder.Axis.Passive
 
admMoveFaceBuilder1.Motion.OrientXpress.PlaneOption = NXOpen.GeometricUtilities.OrientXpressBuilder.Plane.Passive
 
admMoveFaceBuilder1.FaceToMove.CoplanarEnabled = False
 
admMoveFaceBuilder1.FaceToMove.CoplanarAxesEnabled = False
 
admMoveFaceBuilder1.FaceToMove.CoaxialEnabled = False
 
admMoveFaceBuilder1.FaceToMove.EqualDiameterEnabled = False
 
admMoveFaceBuilder1.FaceToMove.TangentEnabled = False
 
admMoveFaceBuilder1.FaceToMove.SymmetricEnabled = False
 
admMoveFaceBuilder1.FaceToMove.OffsetEnabled = False
 
admMoveFaceBuilder1.FaceToMove.UseFaceBrowse = True
 
admMoveFaceBuilder1.Motion.DeltaEnum = NXOpen.GeometricUtilities.ModlMotion.Delta.ReferenceAcsWorkPart
 
theSession.SetUndoMarkName(markId1, "Move Face Dialog")
 
' ----------------------------------------------
'   Menu: Tools->Journal->Pause Recording
' ----------------------------------------------
 
End Sub
End Module

Get X,Y in pixels for each piece of PMI in a view.

$
0
0

Hello,

I am attempting to get a list of PMI items in a model view and an x,y of those item in pixels.

I have some code that outputs an image for the current model view. I want to be able to write an HTML page with links located on top of that image for things like note call outs and other things. The x,y of the PMI will drive the location of those HTML links.

Open a Spreadsheet

$
0
0

Good Morning

My question is simple.
I have a part with a SpreadSheet in. This SpreadSheet updates the part thanks to the connection between the SpreadSheet and UG Expressions.

I know that is possible to open an external excel file using Open NX but is it possible to open the Part's SpreadSheet with Open NX, execute a macro inside this spreadsheet and close the spreadsheet ?

Thanks in advance

Stopping UnloadLibrary switching to the Gateway application (NX 10)

$
0
0

I am using a VB.Net Windows Forms Application executable that is called from a command button on an NX toolbar, which exits using UF.UnloadLibrary.

This function always switches the application to Gateway, where as I would prefer to stay in the application NX was in when the executable was called.

I can use ApplicationSwitchImmediate to change to an application different to the one NX was in when the executable began but if I try to change to the original workbench then it still ends up in Gateway.

ApplicationSwitch from an original Manufacturing to Modeling shows in the NX title bar upon ending the executable:
Manufacturing -> Modeling -> Gateway -> Modeling (OK but odd.)

ApplicationSwitch from Modeling to Modeling shows in the NX title bar upon ending the executable:
Modeling -> Gateway (Not good)

Multiple ApplicationSwitch commands all show in the NX title bar but if the final application is the same as the original then it always end up in Gateway.
For example an ApplicationSwitch from Modeling to Manufacturing and back to Modeling shows:
Modeling -> Manufacturing -> Modeling -> Gateway (Not good)

This is the only thing tripping me up at the moment, can anybody help?

Arrangement Creation using Sketch Coordinates.

$
0
0

Hi,

Instead of using kinematics, I am trying to create arrangements using move component.
1. I have basic sketch created by expressions. I linked coordinates to the sketch curves.
2. I have to edit the expressions to move the coordinates using the sketch.
3. This expression RHS value I stored in Dwg table.

Step 1: I collect all the coordinates default value to double list (This is where I have issue, after breaking the for loop, In the list all values double(0) is somehow getting modified to the last value of the for loop )
Step 2: Read the table, Create arrangement, Update the sketch, Select the matching coordinate, Move the components.

Option Strict Off
Imports System
Imports System.IOImports System.Windows.FormsImports System.DrawingImports System.Drawing.ImagingImports System.CollectionsImports System.Runtime.InteropServicesImports NXOpen
Imports NXOpen.GeometricUtilitiesImports NXOpen.UFImports NXOpen.AssembliesImports NXOpenUI
Imports System.Collections.GenericImports System.Threading 
Module ArrangementUpdateNew
 
    Dim theSession As Session = Session.GetSession()Dim workPart As Part = theSession.Parts.WorkDim displayPart As Part = theSession.Parts.DisplayDim theUI As UI = UI.GetUIDim ufs As UFSession = UFSession.GetUFSessionDim lw As ListingWindow = theSession.ListingWindow 
 
    Sub Main()
        lw.Open()Dim i AsInteger=NothingDim j AsInteger=NothingDim k AsInteger=NothingDim ii AsInteger=NothingDim ij AsInteger=NothingDim ik AsInteger=NothingDim PrimeCsysList As List(Of CoordinateSystem)=New List(Of CoordinateSystem)Dim SecondaryCsysList As List(Of CoordinateSystem)=New List(Of CoordinateSystem)Dim GroupList As List(Of ComponentGroup)=New List(Of ComponentGroup)Dim FromOrginCollection As List(OfDouble)=New List(OfDouble)Dim FromXAxisCollection As List(OfDouble)=New List(OfDouble)Dim FromYAxisCollection As List(OfDouble)=New List(OfDouble)Dim FromOrigin()AsDouble=NothingDim FromXAxis()AsDouble=NothingDim FromYAxis()AsDouble=NothingDim ArrangementTable As Tag =NothingDim Cellvalue AsString=NothingDim numRows AsInteger=NothingDim numCols AsInteger=NothingDim rowTag As Tag =NothingDim colTag As Tag =NothingDim cellTag As Tag =NothingDim ArrangementName AsString=NothingDim VariablesTitle As List(OfString)=New List(OfString) 
        'ArrangementOptions.IndividuallyPositionedTryDim Mycomponent As ComponentAssembly = workPart.ComponentAssembly
            UpdateArrangementPosition(Mycomponent.RootComponent, 0)Catch e As Exception
            theSession.ListingWindow.WriteLine("Assembly component Individually Postitioned Option failed : "& e.ToString)EndTry 
 
        'Collect all Component group detail and Template coordinate system detailsForEach Mygroup As ComponentGroup In workPart.ComponentGroupsIfTypeOf Mygroup Is ComponentGroup Then
                GroupList.Add(Mygroup)EndIfNext 
        ForEach MyCsys As CoordinateSystem In workPart.CoordinateSystemsIfTypeOf MyCsys Is CoordinateSystem ThenIfNot MyCsys.Name=""Then
                    PrimeCsysList.Add(MyCsys)EndIfEndIfNext 
        'Collect all the Details from Primary CSYS before applying the formula or Else for both Primary and secondary Csys will return the same value'This is where I have the issue the output in the first for loop is reading coorect after collecting the values_'When I read it in next For loop the Fromorgin(0), FromXaxis(0), FromYaxis(0) is got modified for all the items_ 'in the collection to last known value in first for loop' Just create 5 Csys in different locations and run the journal you will have two set of different resultsFor i =0To PrimeCsysList.Count-1
            FromOrigin ={PrimeCsysList(i).Origin.X, PrimeCsysList(i).Origin.Y, PrimeCsysList(i).Origin.Z}
            FromXAxis ={PrimeCsysList(i).Orientation.Element.Xx, PrimeCsysList(i).Orientation.Element.Xy, PrimeCsysList(i).Orientation.Element.Xz}
            FromYAxis ={PrimeCsysList(i).Orientation.Element.Yx, PrimeCsysList(i).Orientation.Element.Yy, PrimeCsysList(i).Orientation.Element.Yz}
            FromOrginCollection.Add(FromOrigin(2))
            FromXAxisCollection.Add(FromXAxis(2))
            FromYAxisCollection.Add(FromYAxis(2))
            lw.WriteLine(PrimeCsysList(i).Name&" : "& FromOrigin(0)&","& FromOrigin(1)&","& FromOrigin(2))
            lw.WriteLine(PrimeCsysList(i).Name&" : "& FromXAxis(0)&","& FromXAxis(1)&","& FromXAxis(2))
            lw.WriteLine(PrimeCsysList(i).Name&" : "& FromYAxis(0)&","& FromYAxis(1)&","& FromYAxis(2))Next 
        For i =0To FromOrginCollection.Count-1
            FromOrigin(2)= FromOrginCollection(i)
            FromXAxis(2)= FromXAxisCollection(i)
            FromYAxis(2)= FromYAxisCollection(i)
            lw.WriteLine(PrimeCsysList(i).Name&" : "& FromOrigin(0)&","& FromOrigin(1)&","& FromOrigin(2))
            lw.WriteLine(PrimeCsysList(i).Name&" : "& FromXAxis(0)&","& FromXAxis(1)&","& FromXAxis(2))
            lw.WriteLine(PrimeCsysList(i).Name&" : "& FromYAxis(0)&","& FromYAxis(1)&","& FromYAxis(2)) 
        Next' Read expression value from table for each arrangement and update the sketch to move the coordinates and update arrangement'Dim myTabularNoteTags As New List(Of Tag)'If FindTabularNotes(myTabularNoteTags, workPart) = 0 Then''no tabular notes to process'    Return'End If 
        '        For Each tableNote As Tag In myTabularNoteTags'            ufs.Tabnot.AskNmRows(tableNote, numRows)'            ufs.Tabnot.AskNmColumns(tableNote, numCols)'            ufs.Tabnot.AskNthRow(tableNote, 0, rowTag)'            ufs.Tabnot.AskNthColumn(tableNote, 0, colTag)'            ufs.Tabnot.AskCellAtRowCol(rowTag, colTag, cellTag)'            ufs.Tabnot.AskCellText(cellTag, Cellvalue) 
        '            If Cellvalue = "Arrangement List" Then'                ufs.Tabnot.AskNthRow(tableNote, 1, rowTag)'                For j = 1 To numCols - 1'                    ufs.Tabnot.AskNthColumn(tableNote, j, colTag)'                    ufs.Tabnot.AskCellAtRowCol(rowTag, colTag, cellTag)'                    ufs.Tabnot.AskCellText(cellTag, Cellvalue)'                    VariablesTitle.Add(Cellvalue)'                Next'                For i = 0 To VariablesTitle.Count - 1'                    lw.WriteLine(VariablesTitle(i).ToString)'                Next'                For i = 2 To numRows - 1 Step 1'                    ufs.Tabnot.AskNthRow(tableNote, i, rowTag)'                    Dim Variables As List(Of String) = New List(Of String)'                    For j = 0 To numCols - 1'                        ufs.Tabnot.AskNthColumn(tableNote, j, colTag)'                        ufs.Tabnot.AskCellAtRowCol(rowTag, colTag, cellTag)'                        ufs.Tabnot.AskCellText(cellTag, Cellvalue)'                        Variables.Add(Cellvalue)'                    Next 
        '                    ArrangementName = Variables(0)'                    Variables.RemoveAt(0)'                    lw.WriteLine(ArrangementName.ToString)'                    Dim DefaultArrangement As Assemblies.Arrangement = CType(workPart.ComponentAssembly.Arrangements.FindObject("Default"), Assemblies.Arrangement)'                    Dim MyArrangement As Assemblies.Arrangement = Nothing'                    Try'                        MyArrangement = workPart.ComponentAssembly.Arrangements.Create(DefaultArrangement, ArrangementName)'                        MyArrangement.IgnoringConstraints = True'                    Catch ex As NXException'                        lw.WriteLine(ex.Message)'                    End Try 
        '                    For iii As Integer = 0 To Variables.Count - 1'                        If Variables(iii).ToString = "NA" Then'                            Variables(iii) = "0"'                        End If'                    Next 
        '                    If VariablesTitle.Count = Variables.Count Then'                        For k = 0 To VariablesTitle.Count - 1''This expression will move the base sketch and move the coordinate system to new location'                            Dim expression1 As Expression = CType(workPart.Expressions.FindObject(VariablesTitle(k)), Expression)'                            expression1.RightHandSide = Variables(k)'                            theSession.Preferences.Modeling.UpdatePending = False'                        Next 
        '                        For Each MyCsys As CoordinateSystem In workPart.CoordinateSystems'                            If TypeOf MyCsys Is CoordinateSystem Then'                                If Not MyCsys.Name = "" Then'                                    SecondaryCsysList.Add(MyCsys)'                                End If'                            End If 
        '                        Next 
        '                        For ii = 0 To PrimeCsysList.Count - 1'                            Dim Movinggroup As ComponentGroup = Nothing'                            Dim fromCsys As CoordinateSystem = PrimeCsysList(ii) 
        '                            FromOrigin(2) = FromOrginCollection(ii)'                            FromXAxis(2) = FromXAxisCollection(ii)'                            FromYAxis(2) = FromYAxisCollection(ii) 
        ''Comparing '                            Dim toCsys As CoordinateSystem = Nothing'                            For ij = 0 To SecondaryCsysList.Count - 1'                                If SecondaryCsysList(ij).Name = fromCsys.Name Then'                                    toCsys = SecondaryCsysList(ij)'                                End If'                            Next 
        '                            Dim toOrigin() As Double = {toCsys.Origin.X, toCsys.Origin.Y, toCsys.Origin.Z}'                            Dim toXAxis() As Double = {toCsys.Orientation.Element.Xx, toCsys.Orientation.Element.Xy, toCsys.Orientation.Element.Xz}'                            Dim toYAxis() As Double = {toCsys.Orientation.Element.Yx, toCsys.Orientation.Element.Yy, toCsys.Orientation.Element.Yz} 
        '                            lw.WriteLine(fromCsys.Name & " : " & FromOrigin(0) & "," & FromOrigin(1) & "," & FromOrigin(2))'                            lw.WriteLine(toCsys.Name & " : " & toOrigin(0) & "," & toOrigin(1) & "," & toOrigin(2)) 
        '                            Dim mtx4Transform(15) As Double 
        '                            ufs.Mtx4.CsysToCsys(FromOrigin, FromXAxis, FromYAxis, toOrigin, toXAxis, toYAxis, mtx4Transform) 
        ''Extract the rotation matrix and the tranlsation vector'                            Dim rotMatrix(8) As Double'                            ufs.Mtx4.AskRotation(mtx4Transform, rotMatrix)'                            Dim transVec(2) As Double'                            ufs.Mtx4.AskTranslation(mtx4Transform, transVec) 
        ''Convert array of doubles to vector 3d'                            Dim translateVector As Vector3d = New Vector3d(transVec(0), transVec(1), transVec(2))''Convert array of doubles to Matrix3x3'                            Dim rotationMatrix As Matrix3x3 = convertToMatrix3x3(rotMatrix) 
        ''Find which component group to move based on Primarycsys'                            Dim Groupobjects() As NXObject = Nothing'                            Try'                                For ik = 1 To GroupList.Count - 1'                                    If GroupList(ik).Name = fromCsys.Name Then'                                        Movinggroup = GroupList(ik)'                                        Groupobjects = Movinggroup.GetComponents'                                        lw.WriteLine(Movinggroup.Name & ": Components Count: " & Groupobjects.Length.ToString)'                                    End If'                                Next'                            Catch ex As Exception'                                lw.WriteLine(ex.Message)'                                GoTo NextGroup'                            End Try 
        ''Move groups for each arrangement as per Primary to Secondary Csys move'                            Dim componentPositioner1 As Positioning.ComponentPositioner'                            componentPositioner1 = workPart.ComponentAssembly.Positioner'                            componentPositioner1.ClearNetwork()'                            MyArrangement = CType(workPart.ComponentAssembly.Arrangements.FindObject(ArrangementName), Assemblies.Arrangement)'                            componentPositioner1.PrimaryArrangement = MyArrangement'                            componentPositioner1.BeginMoveComponent()'                            Dim allowInterpartPositioning1 As Boolean'                            allowInterpartPositioning1 = theSession.Preferences.Assemblies.InterpartPositioning'                            Dim network1 As Positioning.Network'                            network1 = componentPositioner1.EstablishNetwork()'                            Dim componentNetwork1 As Positioning.ComponentNetwork = CType(network1, Positioning.ComponentNetwork)'                            componentNetwork1.MoveObjectsState = True'                            Dim nullAssemblies_Component As Assemblies.Component = Nothing'                            componentNetwork1.DisplayComponent = nullAssemblies_Component'                            componentNetwork1.NetworkArrangementsMode = Positioning.ComponentNetwork.ArrangementsMode.Existing'                            componentNetwork1.NonMovingGroupGrounded = True'                            componentNetwork1.MoveObjectsState = True'                            componentNetwork1.RemoveAllConstraints()'                            componentNetwork1.SetMovingGroup(Groupobjects)'                            Dim loaded1 As Boolean'                            loaded1 = componentNetwork1.IsReferencedGeometryLoaded()'                            componentNetwork1.BeginDrag()'                            componentNetwork1.DragByTransform(translateVector, rotationMatrix)'                            componentNetwork1.EndDrag()'                            componentNetwork1.ResetDisplay()'                            componentNetwork1.ApplyToModel()'                            componentNetwork1.Solve()'                            componentPositioner1.ClearNetwork()'                            Dim nErrs2 As Integer'                            nErrs2 = theSession.UpdateManager.AddToDeleteList(componentNetwork1)'                            componentPositioner1.DeleteNonPersistentConstraints()'                            componentPositioner1.EndMoveComponent()'                            Dim nullAssemblies_Arrangement As Assemblies.Arrangement = Nothing'                            componentPositioner1.PrimaryArrangement = nullAssemblies_Arrangement 
        'NextGroup:'                        Next'                    Else'                        lw.WriteLine("Table has missing Parameters or Parameter Title count and Value count not matching")'                    End If'                Next'            End If'        Next 
 
 
 
    EndSub 
    Function convertToMatrix3x3(ByVal mtx AsDouble())As Matrix3x3
 
        Dim mx As Matrix3x3
        With mx
            .Xx= mtx(0).Xy= mtx(1).Xz= mtx(2).Yx= mtx(3).Yy= mtx(4).Yz= mtx(5).Zx= mtx(6).Zy= mtx(7).Zz= mtx(8)EndWith 
        Return mx
 
    EndFunctionFunction FindTabularNotes(ByRef theTabNotes As List(Of Tag), ByVal Mypart As Part)AsInteger 
        Dim tmpTabNote As NXOpen.Tag= NXOpen.Tag.NullDim type AsIntegerDim subtype AsInteger 
        Do
            ufs.Obj.CycleObjsInPart(Mypart.Tag, UFConstants.UF_tabular_note_type, tmpTabNote)If tmpTabNote = NXOpen.Tag.NullThenContinueDoEndIfIf tmpTabNote <> NXOpen.Tag.NullThen
                ufs.Obj.AskTypeAndSubtype(tmpTabNote, type, subtype)If subtype = UFConstants.UF_tabular_note_subtypeThen
                    theTabNotes.Add(tmpTabNote)EndIfEndIfLoop Until tmpTabNote = NXOpen.Tag.NullReturn theTabNotes.Count 
    EndFunction 
    Sub UpdateArrangementPosition(ByVal comp As Component, ByVal indent AsInteger) 
        ForEach child As Component In comp.GetChildren()If child.GetChildren.Length<>0Then' lw.WriteLine(child.Name)TryDim MyObj(0)As NXObject
                    MyObj(0)= child
                    Dim assembliesParameterPropertiesBuilder1 As AssembliesParameterPropertiesBuilder = workPart.PropertiesManager.CreateAssembliesParameterPropertiesBuilder(MyObj)
                    assembliesParameterPropertiesBuilder1.Arrangements= Assemblies.AssembliesParameterPropertiesBuilder.ArrangementOptions.IndividuallyPositionedDim NxObject1 As NXObject
                    NxObject1 = assembliesParameterPropertiesBuilder1.Commit()
                    assembliesParameterPropertiesBuilder1.Destroy()Catch ex As NXException
                    lw.WriteLine("Failed")EndTryElse'  lw.WriteLine(child.Name)TryDim MyObj(0)As NXObject
                    MyObj(0)= child
                    Dim assembliesParameterPropertiesBuilder1 As AssembliesParameterPropertiesBuilder = workPart.PropertiesManager.CreateAssembliesParameterPropertiesBuilder(MyObj)
                    assembliesParameterPropertiesBuilder1.Arrangements= Assemblies.AssembliesParameterPropertiesBuilder.ArrangementOptions.IndividuallyPositionedDim NxObject1 As NXObject
                    NxObject1 = assembliesParameterPropertiesBuilder1.Commit()
                    assembliesParameterPropertiesBuilder1.Destroy()Catch ex As NXException
                    lw.WriteLine("Failed")EndTryEndIf
            UpdateArrangementPosition(child, indent +1)NextEndSub 
EndModule

Measure distance between 2 csys

$
0
0

Hello

I'm creating 1 journal that create a txt with some values, but now i have 1 problem, there is a way to measure the distance between the active csys and an csys with a default name and measure what is the rotation between the Y csys (because Z csys's have always the same direction on both csys)

I'm using NX10

How to initialize UGMGR in command line?

$
0
0

Hello All,
My task is to initialize managed NX(UGMGR.initialize), open the given part, do some operations in NX, save back to teamcenter and terminate the connection. I have a sample code to initialize ugmgr and terminate. I'm well aware of the ugmgr API's. The issue I'm facing it is to set the required environmental variables. Can anyone let me know what are the variables I need to set for a 2 Tier teamcenter and command line arguments I need to pass to the EXE to successfully run the application in batch mode. I'm using NX8.5 and TC 2T 10. Thanks in advance.

Part Getting corrupted

$
0
0

Running this code more than onetime makes something corrupt in the assembly. After this I am unable to create arrangements, Not able to save or not able to part cleanup (Actually this is part of big script which I shared earlier for creating arrangement from sketch and table, But this causes issue in the file). First time it is running perfectly on new assembly without any issues, but whenever I am running this next the assembly is getting corrupt, throws "A dimension subscript for an array attribute was out of range or invalid" message.

Option Strict Off
Imports System
Imports NXOpen
Imports NXOpen.GeometricUtilitiesImports NXOpen.UFImports NXOpen.AssembliesImports NXOpenUI
Imports System.Collections.Generic 
 
Module PositionOverRide
 
    Dim theSession As Session = Session.GetSession()Dim workPart As Part = theSession.Parts.WorkDim displayPart As Part = theSession.Parts.DisplayDim theUI As UI = UI.GetUIDim ufs As UFSession = UFSession.GetUFSessionDim lw As ListingWindow = theSession.ListingWindow 
 
    Sub Main() 
        'ArrangementOptions.IndividuallyPositioned and Position override for each assembliesTryDim Mycomponent As ComponentAssembly = workPart.ComponentAssembly
            UpdateArrangementPosition(Mycomponent.RootComponent, 0)Catch e As Exception
            lw.WriteLine("Assembly component Individually Postitioned Option failed : "& e.ToString)EndTry 
 
    EndSub 
    Sub UpdateArrangementPosition(ByVal comp As Component, ByVal indent AsInteger) 
        ForEach child As Component In comp.GetChildren()If child.GetChildren.Length<>0Then' lw.WriteLine(child.Name)Try
                    child.EstablishPositionOverride(comp)
                    lw.WriteLine(child.Name&"-"& child.GetPositionOverrideType.ToString())Catch ex As NXException
                    lw.WriteLine("Failed To Position Override")EndTryElseTry
                    child.EstablishPositionOverride(comp)
                    lw.WriteLine(child.Name&"-"& child.GetPositionOverrideType.ToString())Catch ex As NXException
                    lw.WriteLine("Failed To Position Override")EndTryEndIf
            UpdateArrangementPosition(child, indent +1)NextEndSub 
    PublicFunction GetUnloadOption(ByVal dummy AsString)AsInteger 
        'Unloads the image immediately after execution within NX
        GetUnloadOption = NXOpen.Session.LibraryUnloadOption.Immediately 
    EndFunctionEndModule

Export spreadsheet containing certain expressions and in a certain format

$
0
0

Hello,

I've been struggling with recording and coding a journal in VB that will export an entire assembly's expressions to an excel spreadsheet in a certain format.

The expressions are scattered across the assembly structure and describe hole location and diameter, but they are all unique and numbered sequentially: H1, D1, X1, Y1, Z1, H2, D2, X2, Y2, Z2, H3, ... and so forth.

H1 is a string value of either "L" or "R"
X1, Y1, Z1 and D1 are all integer of measurement length

For the time being, I'd like to create a journal that can export the expressions to a spreadsheet grouping the numbers sequentially in rows top-to-bottom. The columns should contain from left to right X, Y, Z, H, D - values.

I've only gotten as far as figuring out recursive functions to run through the assembly before realising this is a bit larger than anticipated.

Can anyone help me, please?

Cheers.

Changing Arrangement

$
0
0

What demand/function should one use to change the arrangements of children in an assembly. I am thinking of using "setUsedArrangement", any examples of code that will walk through all the children and change the active arrangement to a specific arrangement. Thanks

Creating A Bounding Box Around A Solid: Assembly Mode

$
0
0

The code I copied from http://www.nxjournaling.com/content/creating-bounding-box-arround-solid is very good but it is accurate when applied to the displayed part only. In the assembly mode, it is not accurate as it does not create box around the correct directions.In other words, the box dimensions reported in displayed-part mode and assembly mode are not the same. How should the code be adjusted so the dimensions in assembly mode is the same as the displayed part mode?

Option Strict Off
 
Imports System
 
Imports NXOpen
Imports NXOpen.UI
Imports NXOpen.Utilities
Imports NXOpen.UF
 
Module make_bounding_block_of_selected_body_relative_to_wcs
 
    Dim s As Session = Session.GetSession()
    Dim ufs As UFSession = UFSession.GetUFSession()
    Dim lw As ListingWindow = s.ListingWindow()
 
    Sub Main()
 
        Dim a_body As NXOpen.Tag = NXOpen.Tag.Null
        Dim csys As NXOpen.Tag = NXOpen.Tag.Null
        Dim target As NXOpen.Tag = NXOpen.Tag.Null
        Dim blockFeature As NXOpen.Tag = NXOpen.Tag.Null
 
        Dim min_corner(2) As Double
        Dim directions(2, 2) As Double
        Dim distances(2) As Double
        Dim edge_len(2) As String
 
        While select_a_body(a_body) = Selection.Response.Ok
 
            ufs.Csys.AskWcs(csys)
 
            ufs.Modl.AskBoundingBoxExact(a_body, csys, min_corner, directions, _
                distances)
 
            lw.Open()
 
            lw.WriteLine("Min_corner: " & _
                min_corner(0).ToString & ", " & _
                min_corner(1).ToString & ", " & _
                min_corner(2).ToString & ", ")
 
            lw.WriteLine("X direction: " & _
                directions(0, 0).ToString & ", " & _
                directions(0, 1).ToString & ", " & _
                directions(0, 2).ToString & ", ")
            lw.WriteLine("X distance: " & _
                distances(0).ToString)
 
            lw.WriteLine("Y direction: " & _
                directions(1, 0).ToString & ", " & _
                directions(1, 1).ToString & ", " & _
                directions(1, 2).ToString & ", ")
            lw.WriteLine("Y distance: " & _
                distances(1).ToString)
 
            lw.WriteLine("Z direction: " & _
                directions(2, 0).ToString & ", " & _
                directions(2, 1).ToString & ", " & _
                directions(2, 2).ToString & ", ")
            lw.WriteLine("Z distance: " & _
                distances(2).ToString)
 
            edge_len(0) = distances(0).ToString()
            edge_len(1) = distances(1).ToString()
            edge_len(2) = distances(2).ToString()
 
            ufs.Modl.CreateBlock(FeatureSigns.Nullsign, _
                                 target, min_corner, edge_len, blockFeature)
        End While
 
    End Sub
 
    Function select_a_body(ByRef a_body As NXOpen.Tag) As Selection.Response
 
        Dim message As String = "Select a body"
        Dim title As String = "Select a body"
        Dim scope As Integer = UFConstants.UF_UI_SEL_SCOPE_ANY_IN_ASSEMBLY
        Dim response As Integer
 
        Dim view As NXOpen.Tag
        Dim cursor(2) As Double
        Dim ip As UFUi.SelInitFnT = AddressOf body_init_proc
 
        ufs.Ui.LockUgAccess(UFConstants.UF_UI_FROM_CUSTOM)
 
        Try
            ufs.Ui.SelectWithSingleDialog(message, title, scope, ip, _
                         Nothing, response, a_body, cursor, view)
        Finally
            ufs.Ui.UnlockUgAccess(UFConstants.UF_UI_FROM_CUSTOM)
        End Try
 
        If response <> UFConstants.UF_UI_OBJECT_SELECTED And _
           response <> UFConstants.UF_UI_OBJECT_SELECTED_BY_NAME Then
            Return Selection.Response.Cancel
        Else
            ufs.Disp.SetHighlight(a_body, 0)
            Return Selection.Response.Ok
        End If
 
    End Function
 
    Function body_init_proc(ByVal select_ As IntPtr, _
                           ByVal userdata As IntPtr) As Integer
 
        Dim num_triples As Integer = 1
        Dim mask_triples(0) As UFUi.Mask
        mask_triples(0).object_type = UFConstants.UF_solid_type
        mask_triples(0).object_subtype = UFConstants.UF_solid_body_subtype
        mask_triples(0).solid_type = UFConstants.UF_UI_SEL_FEATURE_BODY
 
        ufs.Ui.SetSelMask(select_, _
                           UFUi.SelMaskAction.SelMaskClearAndEnableSpecific, _
                           num_triples, mask_triples)
        Return UFConstants.UF_UI_SEL_SUCCESS
 
    End Function
 
    Public Function GetUnloadOption(ByVal dummy As String) As Integer
 
        GetUnloadOption = UFConstants.UF_UNLOAD_IMMEDIATELY
 
    End Function

Information of selected object on the status bar

$
0
0

Hi guys,

Imagine you want to insert a point feature in NX. When you select the appropriate command and move your cursor in the graphics window, you will notice the status bar changes with the info of the object you're on. For example "Midpoint - Edge of Extrude(4)". It also displays the same in a balloon tip close to your cursor.

This is what I want to mimic with a journal (output of that info to listing window for example.

Unfortunately journal recorder does not help much on that situation

Any ideas ?

Create points on the faces and get coordinates and normal

$
0
0

Hello

I'm trying create a few points on my body and i wanna get x,y,z and the normal of the face on that point i,j,k. I followed this code NX Journaling but now i have 1 problem, when i click on a face, this create a point behind the face and not on the face, can you see what is wrong with this code? And how can i get the i,j,k of that point?

Option Strict Off
Imports System
Imports NXOpen
Imports NXOpen.UF 
Module Module1
 
    Dim theSession As Session = Session.GetSession()Dim theUfSession As UFSession = UFSession.GetUFSession() 
    Sub Main() 
        Dim workPart As Part = theSession.Parts.WorkDim lw As ListingWindow = theSession.ListingWindow
        lw.Open() 
        Const undoMarkName AsString="create endpoint"Dim markId1 As Session.UndoMarkId
        markId1 = theSession.SetUndoMark(Session.MarkVisibility.Visible, undoMarkName) 
        Dim selectedFace As Face
        Dim selectedPoint As Point3d
        Dim count AsInteger 
        for count =0to15 
            If SelectAnFace("Select an Face", selectedFace, selectedPoint)= Selection.Response.CancelThenexitforEndIf 
            Dim scalar1 As Scalar
            scalar1 = workPart.Scalars.CreateScalar(1, Scalar.DimensionalityType.None, SmartObject.UpdateOption.WithinModeling) 
            'create pointDim Point_Face As Point
            Point_Face = workPart.Points.CreatePoint(selectedPoint)
            Point_Face.SetVisibility(SmartObject.VisibilityOption.Visible) 
            lw.WriteLine("")
            lw.WriteLine("x= "& selectedPoint.x)
            lw.WriteLine("y= "& selectedPoint.y)
            lw.WriteLine("z= "& selectedPoint.z)
            lw.WriteLine("i= ")
            lw.WriteLine("j= ")
            lw.WriteLine("k= ") 
        Next 
        lw.Close() 
    EndSub 
    Function SelectAnFace(prompt AsString, ByRef selFace As Face, ByRef selPos As Point3d)As Selection.Response 
        Dim selObj As NXObject
        Dim theUI As UI = UI.GetUIDim cursor As Point3d
        Dim typeArray()As Selection.SelectionType={Selection.SelectionType.Faces} 
        Dim resp As Selection.Response= theUI.SelectionManager.SelectObject( prompt, "Select a Point in a Face", _
                Selection.SelectionScope.AnyInAssembly, False, typeArray, selObj, cursor) 
        If resp = Selection.Response.ObjectSelectedOr resp = Selection.Response.ObjectSelectedByNameThen
            selFace = selObj
            selPos = cursor
            Return Selection.Response.OkElseReturn Selection.Response.CancelEndIf 
    EndFunction 
    PublicFunction GetUnloadOption(ByVal dummy AsString)AsInteger
        GetUnloadOption = NXOpen.Session.LibraryUnloadOption.ImmediatelyEndFunction 
EndModule

Delete unused groups - please help

$
0
0

Hi everyone.

I am struggling with something and I hoped someone here could help.

I have a program that takes requests (in the form of car areas like "front wing") and makes groups for them in a hierarchy and then queries a server for data for the areas and makes splines (CFD streamlines). However, as a CFD run might not have data for all the areas requested, some groups can be left empty which I don't like.

I need a way to find all of the empty groups so that I can delete them before the program finishes. I can't just make a list of groups I used and delete the others because the user could use the button twice to get different car areas and I don't want the second attempt deleting the stuff from the first. Also I prefer to make the groups at the start rather than after successfully getting data back from the server because it is easier to do the hierarchy.

Can anyone think of a way to help me go through my groups and delete ones with nothing in them (other than another group (which could be done with a dictionary of groups to parent groups))

Thanks

Nick

How to get a surface normal in the assembly context ? - user selected surface.

$
0
0

I am making a journal that orients a modeling view in an assembly when a user clicks on a planar surface - just one click operation -, but I'm stuck.
I used the following code to get a surface, which was on this site in VB and I converted to c#.
Although I can get a surface, it is NOT an occurrence but a prototype since its IsOccurrence property is "false" and, when I get the normal of the surface, it's not in the assembly context.
How can I get a surface occurrence without any additional user's operations ?
Any advice will be appreciated.

publicstatic Selection.Response SelectPlanarFace(string prompt, out Face myPlanarFace,out Point3d cursor){
        UI theUI  = UI.GetUI();string title  ="Select a planar face";
        Selection.SelectionScope scope = Selection.SelectionScope.WorkPartAndOccurrence;
        Selection.SelectionAction selAction = Selection.SelectionAction.ClearAndEnableSpecific;bool includeFeatures =false;bool keepHighlighted  =false;
        Selection.MaskTriple[] selectionMask_array=new Selection.MaskTriple[1];
        selectionMask_array[0].Type= UFConstants.UF_solid_type;
        selectionMask_array[0].SolidBodySubtype= UFConstants.UF_UI_SEL_FEATURE_PLANAR_FACE;
        TaggedObject selObj;
        Selection.Response resp = theUI.SelectionManager.SelectTaggedObject(prompt, title, scope, selAction,includeFeatures, keepHighlighted, selectionMask_array, out selObj, out cursor);if(resp == Selection.Response.ObjectSelected|| resp == Selection.Response.ObjectSelectedByName){
            myPlanarFace =(Face)selObj;return Selection.Response.Ok;}else{
            myPlanarFace=null;return Selection.Response.Cancel;}}

Dimensions. Load settings from customer defaults.

$
0
0

Hello

Here’s the code that applies customer defaults settings to the angular dimensions. The code acts weirdly. The dimension tolerance disappears, but when I open dimension settings the tolerance is still there. The other thing is that the tolerance text settings (color, font and height) is not inherited form customer defaults but from part drafting preferences.

Option Strict Off
Imports System
Imports NXOpen
Imports NXOpen.UF
Imports NXOpen.UI
Imports NXOpen.Annotations
 
Module NX_cd
 
    Dim s As Session = Session.GetSession()
    Dim ui As UI = UI.GetUI()
    Dim ufs As UFSession = UFSession.GetUFSession()
    Dim workPart As Part = s.Parts.Work
    Dim myDim As Annotations.Dimension
    Dim lw As ListingWindow = s.ListingWindow
 
    Sub Main()
 
        For Each myDim As Annotations.Dimension In workPart.Dimensions
 
            Dim dimname1 As String = Nothing
 
            dimname1 = myDim.ToString()
            lw.Open()
            If dimname1.Contains("Angular") = True Then
 
                Dim AngularDimension1 As Annotations.AngularDimension = myDim
                Dim angularTolerance1 As Annotations.AngularTolerance
                Dim upperToleranceDEG As Annotations.Value
                Dim lowerToleranceDEG As Annotations.Value
                Dim upItemValue As Double
                Dim lowItemValue As Double
                Dim toltype As Annotations.ToleranceType
 
                angularTolerance1 = AngularDimension1.GetTolerance()
 
                toltype = angularTolerance1.ToleranceType
 
                upItemValue = angularTolerance1.GetUpperToleranceDegrees.ItemValue
                lowItemValue = angularTolerance1.GetLowerToleranceDegrees.ItemValue
 
                Dim objects1(0) As NXOpen.DisplayableObject
                objects1(0) = myDim
                Dim linearDimensionBuilder1 As Annotations.AngularDimensionBuilder
                linearDimensionBuilder1 = workPart.Dimensions.CreateAngularDimensionBuilder(objects1(0))
                linearDimensionBuilder1.Style.InheritSettingsFromPreferences()
                linearDimensionBuilder1.Style.InheritSettingsFromCustomerDefault()
                linearDimensionBuilder1.Style.InheritSettingsFromPreferences()
                linearDimensionBuilder1.Style.InheritSettingsFromCustomerDefault()
                Dim nXObject1 As NXObject
                nXObject1 = linearDimensionBuilder1.Commit()
                linearDimensionBuilder1.Destroy()
 
                angularTolerance1.ToleranceType = Annotations.ToleranceType.None
                angularTolerance1.ToleranceType = toltype
 
                upperToleranceDEG.ItemValue = upItemValue
                upperToleranceDEG.ValuePrecision = 2
                angularTolerance1.SetUpperToleranceDegrees(upperToleranceDEG)
 
                lowerToleranceDEG.ItemValue = lowItemValue
                lowerToleranceDEG.ValuePrecision = 2
                angularTolerance1.SetLowerToleranceDegrees(lowerToleranceDEG)
 
                AngularDimension1.SetTolerance(angularTolerance1)
            End If
        Next
    End Sub
 
    Public Function GetUnloadOption(ByVal dummy As String) As Integer
        GetUnloadOption = NXOpen.Session.LibraryUnloadOption.Immediately
    End Function
End Module 
 

SelectObjects: Warning if range is smaller then given one

$
0
0

Hello at all,

I have a problem with my SelectObjects function. I want to select various drilling holes, but if I the distance between the centre of the holes are smaller than a given a range, I want to get a warning. Important is that we select the circle of the holes and not the centre.
For example:
Hole1 have to be minimum 100 mm away from Hole2
Hole2 have to be minimum 100 mm away from Hole3
But it isn't important which distance is between Hole1 and Hole3

I didn't found anything by now for putting conditions in the SelectObjects function and also having a problem in getting the distance between two centres by only choosing the holes.

If SelectObjects("Select holes",
                       mySelectedObjects) = Selection.Response.Ok Then
 
'...
 
    Function SelectObjects(prompt As String,
               ByRef selObj As NXObject()) As Selection.Response
 
        Dim theUI As UI = UI.GetUI
 
        'only choose edges
 
        Dim typeArray() As Selection.SelectionType =
            {Selection.SelectionType.Edges}
 
        Dim resp As Selection.Response = theUI.SelectionManager.SelectTaggedObjects(
                prompt, "Selection",
                Selection.SelectionScope.AnyInAssembly,
                False, typeArray, selObj)
 
        If resp = Selection.Response.ObjectSelected Or
                resp = Selection.Response.ObjectSelectedByName Or
                resp = Selection.Response.OK Then
            Return Selection.Response.Ok
        Else
            Return Selection.Response.Cancel
        End If
 
    End Function

Thanks already for any help

Create Assembly sequence to get motion Envelope_NX 9

$
0
0

I have the following requirement. create a sweep envelop of the assembly items based on movement. (Example a rack and pinon is there I want to have maximum and minimum limits as a body or facet). In NX9 I believe there is no direct NX open methods for sequencing, I have to go with UF only.

1. Create sequence.

2. Start sequence motion based on CSYS to CSYS component move or each arrangement as a motion from default position.

3. Measure the sweep volume for all the motions to find the complete volume of all mechanism.

Here create step throwing Fatal Error (I don't understand the concepts of MyT and MyC). Also I want to know after creating step how to move components and create motion envelope.

Option Strict Off
Imports System
Imports System.CollectionsImports System.Collections.GenericImports NXOpen
Imports NXOpen.UFImports NXOpen.FeaturesImports NXOpen.Utilities 
Module Sequence
 
    Dim theSession As Session = Session.GetSession()Dim workPart As Part = theSession.Parts.WorkDim displayPart As Part = theSession.Parts.DisplayDim theUI As UI = UI.GetUIDim ufs As UFSession = UFSession.GetUFSessionDim lw As ListingWindow = theSession.ListingWindow 
    Sub Main() 
        lw.Open() 
        ufs.Assem.InitializeSequencing()Dim SeqName AsString="Motion Envelope Sequence"Dim Mysequence As NXOpen.Tag=Nothing
        ufs.Assem.CreateSequence(SeqName, workPart.Tag, Mysequence)'ufs.Assem.AskSequenceName(Mysequence, SeqName)'MsgBox(SeqName)' ufs.Assem.ActivateSequence(Mysequence)TryDim MyT AsDouble=10Dim MyC AsDouble=5Dim Desc AsString="Motion_1"Dim MyStep As NXOpen.Tag=Nothing
            ufs.Assem.CreateStep(Mysequence, workPart.Tag, 1, MyT, MyC, Desc, Tag.Null, MyStep)Catch ex As Exception
            lw.WriteLine(ex.Message)EndTry 
 
    EndSubEndModule

Drawing sheet annotation search

$
0
0

Hello All,

I have found a way to isolate a single drawing sheet:

    Sub Main()
        Dim s As Session = Session.GetSession()
        Dim dp As Part = s.Parts.Display
        Dim dsc As DrawingSheetCollection = dp.DrawingSheets
        Dim dsca As Array = dsc.ToArray()
        Dim ds As DrawingSheet = dsca(0)
    End Sub

I have been trying to find a way to search through the notes on this sheet, but I cant find a method or a property to call which shows the annotation. I want to search through them for a specific string of text. For Example "10 K". I have found a way to search the whole drawing for it, but I dont want to search the whole drawing as it seems inefficient and for larger drawing packs (10+sheets) the process will be slower. Does anyone know of a way to search through a specific drawing sheet for notes/annotations?

Get Bodies from component groups

$
0
0

Hi,
I want to collect bodies from each component group individually to create wrap geometry, But this is collecting all the bodies in the workpart. Is there anyway to change it only the component from group.

'Collect all Component group detail and Template coordinate system detailsDim GroupList As List(Of ComponentGroup)=New List(Of ComponentGroup)Dim BodyList As List(Of Body)=New List(Of Body)Dim PartsList As List(Of Part)=New List(Of Part)ForEach Mygroup As ComponentGroup In workPart.ComponentGroupsIfTypeOf Mygroup Is ComponentGroup Then
                    GroupList.Add(Mygroup)EndIfNextForEach MyG As ComponentGroup In GroupList
                ForEach Mycomp As Component In MyG.GetComponents
                    PartsList.Add(Mycomp.OwningPart)Next 
                ForEach MyP As Part In PartsList
                    ForEach MyB As Body In AskAllBodies(MyP).ToArray
                        BodyList.Add(MyB)NextNext
                lw.WriteLine("Count: "& BodyList.Count.ToString) 
                'Create Wrap gemotry with bodyList and move to next groupDim nullFeatures_WrapGeometry As WrapGeometry =NothingDim WrapBuild As Features.WrapGeometryBuilder
                WrapBuild = workPart.Features.CreateWrapGeometryBuilder(nullFeatures_WrapGeometry)
                WrapBuild.CloseGaps= Features.WrapGeometryBuilder.CloseGapType.NoOffset
                WrapBuild.AddOffset.RightHandSide="0"
                WrapBuild.SplitOffset.RightHandSide="0"
                WrapBuild.IsInterpart=True
                WrapBuild.DistTol=0.01
                WrapBuild.Associative=FalseDim AddBodies AsBoolean=Nothing
                AddBodies = WrapBuild.Geometry.Add(BodyList.ToArray)
                WrapBuild.PlanesList.Clear(ObjectList.DeleteOption.NoDelete)Dim NxObj As NXObject
                NxObj = WrapBuild.Commit()Dim MyBrep As Brep = Utilities.NXObjectManager.Get(NxObj.Tag)
                MyBrep.SetName("Group_"& MyG.Name)Dim HideObj()As DisplayableObject =Nothing
                HideObj = MyBrep.GetBodies()
                theSession.DisplayManager.BlankObjects(HideObj)
                workPart.ModelingViews.WorkView.FitAfterShowOrHide(NXOpen.View.ShowOrHideType.HideOnly)
                WrapBuild.Destroy()Next 
 
    Function AskAllBodies(ByVal thePart As Part)As List(Of Body)Dim thebodies AsNew List(Of Body)TryDim BodyTag As Tag = Tag.NullDo
                ufs.Obj.CycleObjsInPart(thePart.Tag, UFConstants.UF_solid_type, BodyTag)If BodyTag = Tag.NullThenExitDoEndIfDim theType AsInteger, theSubtype AsInteger
                ufs.Obj.AskTypeAndSubtype(BodyTag, theType, theSubtype)If theSubtype = UFConstants.UF_solid_body_subtypeThen
                    thebodies.Add(Utilities.NXObjectManager.Get(BodyTag))EndIfLoopWhileTrueCatch ex As NXException
            lw.WriteLine(ex.ErrorCode& ex.Message)EndTryReturn thebodies
    EndFunction
Viewing all 783 articles
Browse latest View live