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

Execute code via comand prompt

$
0
0

Execute code via comand prompt raises those errors below:

I tried to run the code that is in the link below.
http://nxjournaling.com/content/using-message-boxes
It is normaly working by running in NX Journal editor window.

The error text that I got when I run this on command prompt:

The MSVCDir environment variable is not defined
This variable is necessary only when using uflink or starting up Studio
from this window. You must modify the ufvars.bat file to define this.

C:\Program Files\Siemens\NX 8.0\UGII>"%UGII_ROOT_DIR%\run_journal.exe""D:\journ
als\jr3.vb"
Line 16: Type 'UI' is not defined.
Line 37: 'NXMessageBox' is not declared. It may be inaccessible due to its prote
ction level.
Line 46: 'NXMessageBox' is not declared. It may be inaccessible due to its prote
ction level.
Line 48: 'NXMessageBox' is not declared. It may be inaccessible due to its prote
ction level.
Line 50: 'NXMessageBox' is not declared. It may be inaccessible due to its prote
ction level.
Line 54: 'NXMessageBox' is not declared. It may be inaccessible due to its prote
ction level.
Compilation failed

C:\Program Files\Siemens\NX 8.0\UGII>

I could not realise why this happen
Thanks


Exporting Screenshot to PowerPoint

$
0
0

Hi I am taking NX standard views and export to them to a PPT in standard format, I am facing problem with the scale. The view scale is not aligned to each other due to the capture size and fit view (Width and Height is not same when the image is compressed to standard size, View fit is also causing the issue). Is that possible to Make the capture area square and Properly fit, so the views will look aligned. Will this one will help me to define the frame "ufs.Disp.CreateFramedImage"? for this what has to be the upleftcorner value

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.ThreadingImports Microsoft.OfficeImports Microsoft.Office.Interop.PowerPointImports Microsoft.Office.InteropImports Microsoft.Office.Interop.Excel 
 
Module OnePagerToolNX
 
    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'Dim AppPowerPoint As PowerPoint.Application = Nothing'Dim ActiveSlide As PowerPoint.Slide = Nothing'Dim ActivePresentation As PowerPoint.Presentation = NothingDim AppPowerPoint AsObject=Nothing' NX Doesnot support Powerpoint or Office ObjectsDim ActiveSlide AsObject=NothingDim ActivePresentation AsObject=NothingDim RefFileName AsString=NothingDim RefPresentation AsObject=NothingDim RefSlide AsObject=NothingDim ModelParts AsNew ArrayList
    Dim AssyParts AsNew ArrayList
    Dim MyPart As Part =NothingDim PowerpointFileName AsString=NothingDim PowerpointFileExists AsBoolean=FalseDim basePart1 As BasePart =NothingDim allParts()As Part =Nothing 
 
    Sub Main() 
        lw.Open() 
        Dim ParentPartNo AsString=NothingDim ParentPartRev AsString=NothingDim ParentPartName AsString=NothingDim CurrentDate AsString= System.DateTime.Today
        ParentPartNo ="X"'workPart.GetStringAttribute("DB_PART_NO")
        ParentPartRev ="Y"'workPart.GetStringAttribute("DB_PART_REV")
        ParentPartName ="Z"'workPart.GetStringAttribute("DB_PART_NAME") 
        'Create Powerpoint File and Save it in user defined locationDim SaveFileDialog1 AsNew SaveFileDialog
        With SaveFileDialog1
            .Title="Save OnePager to Presentation File".InitialDirectory="C:\".Filter="PowerpointFiles (*.pptx)|*.pptx|Macro enabled Powerpoint files (*.pptm)|*.pptm|All files (*.*)|*.*".FilterIndex=1.RestoreDirectory=True.OverwritePrompt=False.FileName= ParentPartNo &"- One Pager Presentation"If.ShowDialog()= DialogResult.OKThen
                PowerpointFileName =.FileNameElseExitSubEndIfEndWith 
        If AppPowerPoint IsNothingThen
            AppPowerPoint =CreateObject("PowerPoint.Application") 
            If AppPowerPoint IsNothingThen
                theUI.NXMessageBox.Show("Error", NXMessageBox.DialogType.Error, "Could not start Powerpoint, journal exiting")ExitSubEndIfEndIf 
        AppPowerPoint.Visible=True 
        If File.Exists(PowerpointFileName)Then
            PowerpointFileExists =True
            ActiveSlide = AppPowerPoint.Presentations.Open(PowerpointFileName)Else
            ActivePresentation = AppPowerPoint.Presentations.Add()
            ActivePresentation.SaveAs(PowerpointFileName)EndIf 
        If ActivePresentation IsNothingThen
            theUI.NXMessageBox.Show("Error", NXMessageBox.DialogType.Error, "Could not open Powerpoint file: "& PowerpointFileName & ControlChars.NewLine&"journal exiting.")ExitSubEndIf 
        RefPresentation = AppPowerPoint.Presentations.Open("C:\MyTemplate.pptx") 
        For i AsInteger=1To RefPresentation.Slides.Count
            RefPresentation.Slides.Item(i).Copy()
            ActivePresentation.Slides.Paste()'ActivePresentation.Slides.Item(i).Design = RefPresentation.Slides.Item(i).Design()Next i
        RefPresentation.Close() 
        Dim Titlebox AsObject=NothingDim DateBox AsObject=Nothing 
        Titlebox = ActivePresentation.slides(1).Shapes.AddTextbox(1, 20, 150, 400, 30)With Titlebox.TextFrame.TextRange.Text= ParentPartNo &"/"& ParentPartRev &" : "& ParentPartName
            .Font.Bold=True.Font.Name="Times New Roman".Font.Size=15EndWith 
        DateBox = ActivePresentation.slides(1).Shapes.AddTextbox(1, 20, 260, 150, 15)With DateBox.TextFrame.TextRange.Text= CurrentDate.ToString.Font.Bold=False.Font.Name="Times New Roman".Font.Size=11EndWith 
 
        'Categorize Assembly and Parts in the current session
        allParts = theSession.Parts.ToArray()ForEach Part1 As Part In allParts
            Dim thisTag As NXOpen.Tag= ufs.Assem.AskRootPartOcc(Part1.Tag)If thisTag = NXOpen.Tag.NullThen
                ModelParts.Add(Part1)Else
                AssyParts.Add(Part1)EndIfNext 
        'Export all Parts Detail to Powerpoint 
        ForEach Part2 As Part In AssyParts
            MyPart = Part2
            Call CreatePPT()Next 
        ForEach Part3 As Part In ModelParts
            MyPart = Part3
            Call CreatePPT()Next 
        'ActivePresentation.Slides(2).Delete()
        ActivePresentation.Save()
        ActivePresentation.Close()
        AppPowerPoint.Quit()
        AppPowerPoint =Nothing
        ActivePresentation =Nothing
        ActiveSlide =Nothing 
 
    EndSubSub CreatePPT() 
        Dim Partno AsString=Nothing 
        Dim MyPartLoadStatus As PartLoadStatus =NothingDim SDPSstatus As PartCollection.SdpsStatus=Nothing
        SDPSstatus = theSession.Parts.SetDisplay(MyPart, False, False, MyPartLoadStatus)Dim tempScreenshot AsStringDim tempLocation AsString="C:\Temp" 
        'Getting Part AttributesTry
            Partno = MyPart.GetStringAttribute("DB_PART_NO")Catch ex As NXException
            lw.WriteLine("Partno Not found"& ex.ErrorCode&":"& ex.Message.ToString)
            Partno ="Not Found"EndTry 
 
        'Capture ViewsDim Mylayout As Layout =Nothing'Hide unwanted Items in ViewDim visibleObjects()As DisplayableObject =NothingTry
            Mylayout =CType(MyPart.Layouts.FindObject("L1"), Layout)Const OtheritemLayer AsInteger=6'Const Solidlayer As Integer = 1Dim Isoview As ModelingView =CType(MyPart.ModelingViews.FindObject("Isometric"), ModelingView)
            Mylayout.ReplaceView(MyPart.ModelingViews.WorkView, Isoview, True)
            visibleObjects = MyPart.ModelingViews.WorkView.AskVisibleObjects()ForEach Obj As DisplayableObject In visibleObjects
                IfTypeOf(Obj)Is DatumPlane Then
                    Obj.Layer= OtheritemLayer
                    Obj.RedisplayObject()EndIfIfTypeOf(Obj)Is CoordinateSystem Then
                    Obj.Layer= OtheritemLayer
                    Obj.RedisplayObject()EndIfIfTypeOf(Obj)Is DatumAxis Then
                    Obj.Layer= OtheritemLayer
                    Obj.RedisplayObject()EndIfIfTypeOf(Obj)Is Curve Then
                    Obj.Layer= OtheritemLayer
                    Obj.RedisplayObject()EndIf 
                IfTypeOf(Obj)Is Sketch Then
                    Obj.Layer= OtheritemLayer
                    Obj.RedisplayObject()EndIf 
            Next
            MyPart.Layers.SetState(1, Layer.State.WorkLayer)
            MyPart.Layers.SetState(6, Layer.State.Hidden)Catch ex As NXException
            lw.WriteLine(Partno &": Layers are not correct Please Check Image-"& ex.ErrorCode&":"& ex.Message.ToString)EndTry 
 
        TryDim currentScale AsDouble= workPart.ModelingViews.WorkView.Scale
            workPart.ModelingViews.WorkView.Fit()
            workPart.ModelingViews.WorkView.SetScale(currentScale)Catch ex As Exception
            lw.WriteLine(Partno & ex.Message.ToString&"View Scale failed")EndTryTryDim Isoview As ModelingView =CType(MyPart.ModelingViews.FindObject("Isometric"), ModelingView)
            Mylayout.ReplaceView(MyPart.ModelingViews.WorkView, Isoview, True)
            MyPart.ModelingViews.WorkView.RenderingStyle= NXOpen.View.RenderingStyleType.ShadedWithEdges
            tempScreenshot = IO.Path.Combine(tempLocation, Partno &"- ISO.jpg")
            ExportScreenshot(tempScreenshot) 
        Catch ex As NXException
            lw.WriteLine(Partno &": ISO View Not Generated-"& ex.ErrorCode&":"& ex.Message.ToString)EndTry'Capture Front ViewTryDim Frontview As ModelingView =CType(MyPart.ModelingViews.FindObject("Front"), ModelingView)
            Mylayout.ReplaceView(MyPart.ModelingViews.WorkView, Frontview, True)
            MyPart.ModelingViews.WorkView.RenderingStyle= NXOpen.View.RenderingStyleType.ShadedWithEdges
            tempScreenshot = IO.Path.Combine(tempLocation, Partno &"- Front.jpg")
            ExportScreenshot(tempScreenshot) 
        Catch ex As NXException
            lw.WriteLine(Partno &": Front View Not Generated-"& ex.ErrorCode&":"& ex.Message.ToString)EndTry 
        'Capture Left ViewTryDim Leftview As ModelingView =CType(MyPart.ModelingViews.FindObject("Left"), ModelingView)
            Mylayout.ReplaceView(MyPart.ModelingViews.WorkView, Leftview, True)
            MyPart.ModelingViews.WorkView.RenderingStyle= NXOpen.View.RenderingStyleType.ShadedWithEdges
            tempScreenshot = IO.Path.Combine(tempLocation, Partno &"- Left.jpg")
            ExportScreenshot(tempScreenshot) 
        Catch ex As NXException
            lw.WriteLine(Partno &": Left View Not Generated-"& ex.ErrorCode&":"& ex.Message.ToString)EndTry 
        'Capture Top ViewTryDim Topview As ModelingView =CType(MyPart.ModelingViews.FindObject("Top"), ModelingView)
            Mylayout.ReplaceView(MyPart.ModelingViews.WorkView, Topview, True)
            MyPart.ModelingViews.WorkView.RenderingStyle= NXOpen.View.RenderingStyleType.ShadedWithEdges
            tempScreenshot = IO.Path.Combine(tempLocation, Partno &"- Top.jpg")
            ExportScreenshot(tempScreenshot) 
        Catch ex As NXException
            lw.WriteLine(Partno &": Top View Not Generated-"& ex.ErrorCode&":"& ex.Message.ToString)EndTry 
 
        AppPowerPoint.ActivePresentation.Slides.AddSlide(AppPowerPoint.ActivePresentation.Slides.Count+1, AppPowerPoint.ActivePresentation.SlideMaster.CustomLayouts(7))
        AppPowerPoint.ActiveWindow.View.GotoSlide(AppPowerPoint.ActivePresentation.Slides.Count)
        ActiveSlide = AppPowerPoint.ActivePresentation.Slides(AppPowerPoint.ActivePresentation.Slides.Count)'Adding Images from Temporary LocationTry
            ActiveSlide.Shapes.AddPicture(tempLocation &"\"& Partno &"- ISO.jpg", False, True, 40, 60, 200, 200)
            ActiveSlide.Shapes.AddPicture(tempLocation &"\"& Partno &"- Left.jpg", False, True, 40, 280, 200, 200)
            ActiveSlide.Shapes.AddPicture(tempLocation &"\"& Partno &"- Top.jpg", False, True, 280, 60, 200, 200)
            ActiveSlide.Shapes.AddPicture(tempLocation &"\"& Partno &"- Front.jpg", False, True, 280, 280, 200, 200)Catch ex As Exception
            lw.WriteLine(Partno &": Image Not added-"& ex.Message.ToString)EndTry 
        ForEach Myshape AsObjectIn ActiveSlide.Shapes
            Myshape.Select()
            Myshape.Line.Transparency=1
            Myshape.Line.Weight=1
            Myshape.Line.Visible=1Next 
 
    EndSub 
 
    Sub ExportScreenshot(ByVal filename AsString) 
        'save user preference for visibility of WCS, triad, view name, and view borderDim wcsVisible AsBoolean= theSession.Parts.BaseDisplay.WCS.VisibilityDim triadVisible AsInteger= theSession.Preferences.ScreenVisualization.TriadVisibilityDim displayModelViewNames AsBoolean= theSession.Parts.BaseDisplay.Preferences.NamesBorderVisualization.ShowModelViewNamesDim displayModelViewBorders AsBoolean= theSession.Parts.BaseDisplay.Preferences.NamesBorderVisualization.ShowModelViewBorders 
        'turn off the WCS, triad, view name, and view border
        theSession.Parts.BaseDisplay.WCS.Visibility=False
        theSession.Preferences.ScreenVisualization.TriadVisibility=True
        theSession.Parts.BaseDisplay.Preferences.NamesBorderVisualization.ShowModelViewBorders=False
        theSession.Parts.BaseDisplay.Preferences.NamesBorderVisualization.ShowModelViewNames=False 
        Try
            ufs.Disp.CreateImage(filename, UFDisp.ImageFormat.Jpeg, UFDisp.BackgroundColor.White)'Dim Upleftcorner() As Integer = Nothing'Upleftcorner(0) = 0'Upleftcorner(1) = 0'ufs.Disp.CreateFramedImage(filename, UFDisp.ImageFormat.Jpeg, UFDisp.BackgroundColor.White, Upleftcorner, 200, 200)Catch ex As Exception
            MsgBox(ex.Message& ControlChars.NewLine& _
                   "'"& filename &"' could not be created")ThrowNew Exception("Screenshot could not be created")Finally'reset visibility of WCS, triad, view name, and view border to user's preference
            theSession.Parts.BaseDisplay.WCS.Visibility= wcsVisible
            theSession.Preferences.ScreenVisualization.TriadVisibility= triadVisible
            theSession.Parts.BaseDisplay.Preferences.NamesBorderVisualization.ShowModelViewBorders= displayModelViewBorders
            theSession.Parts.BaseDisplay.Preferences.NamesBorderVisualization.ShowModelViewNames= displayModelViewNames
        EndTry 
    EndSub 
    PublicFunction GetUnloadOption(ByVal dummy AsString)AsInteger'Unloads the image immediately after execution within NX
        GetUnloadOption = NXOpen.Session.LibraryUnloadOption.Immediately 
    EndFunction 
EndModule 
 
 

Updating Cylinder Block Assemblies

$
0
0

Hello,

I am very new to Journaling. I kindly request your help with my below problem.

I have an assembly with first level sub-assemblies made up of cylinder blocks in Teamcenter. Basically each cylinder block is placed on to another, creating a tower-like structure. And this structure has a drawing.

I wonder if it is possible to add another cylinder block between any of the existing blocks and the drawing will update along with it. The same applies for removal of any of the cylinder blocks.

Is that possible in teamcenter?

Setting "Move Component" dialog window options with NX Open

$
0
0

Hello,
I want to set "Move Component" dialog window options by journal.
"Move Selected Components Only" box has to be always unticked and the collision action has to be set to "Highlight collision".
The journal can be triggered by some other action.
I tried to record a journal but these options seem to be not settable with NX Open.
Is there any way to do this?
I currently use NX 8.5 but I have also tried it in NX 11 and apparently not much changed in handling these options.
I will appreciate all the help you can give.

Changing Character Font Size in Titleblock - With user Input

$
0
0

I am looking to have an adjustable drawing template that adjusted with the size of the sheet size. I have created this successfully but when creating large sheet sizes the title block and revision block become illegible due to size.

I have created the blocks in a way that the font size determines the scale of the block size. All I need to do is have a journal file that selects the tables and changes the font size based on a user input.

If anyone could help it would be much appreciated.

Create RBE Spider from Point

$
0
0

Hi together :)
My problem can be described as follows:
I have a cross-section of my component. In this cross-section, there are several points called GUYAN_points from now on.
The desired output shall be a 3D-Meshed (most desirable a axisymmetric mesh -> 3D-Swept mesh through body or Revolve 2D Mesh n times) with implemented RBE spiders starting from the GUYAN_point and the corresponding center point.

My problem now is:
I only have one point per RBE. There is no possibility to "revolve" the single RBE element to generate the desired RBE spider.
How can i connect the RBE center point to all corresponding nodes along the circumference with the single Guyan point serving as reference?

So my first approach in mind was to create a curve based on centerpoint and the Guyan point. Then select all related nodes to that curve. Unfortunately, the RBE element does not offer that option.
My next approach was to do a pattern feature(circular) to the single Guyan point to get all corresponding points along the circumference. Next step:
How can I connect these pattern points to the mesh and get the RBE element?

I would be really thankful for help

Regards
Benny

Running OK_CB immediately if preselection

$
0
0

I am using the Block UI styler dialog to create a simple feature selection dialog. I want the code to execute immediately if the user has preselected features prior to running the journal without waiting for the user to select OK. Can anyone offer any help?

Creating a screenshot for each tool movement while machining simulation

$
0
0

I'm currently working on creating a journal which will batch screenshots into folder for each movement of the tool, for all operations (ultimately to create work instructions without using "work instructions authoring" which I don't have).
I am very new to both journaling and visual basic programming, and following code is as far as I could get: (it does limited amount of screenshots for first several movements, thanks for the guy who posted screenshot journal before).

Anyone knows how to add/fix etc. this code so it could work on any part and do the screenshot for all tool movements? I am guessing I will have to loop somehow, but I don't have enough knowledge of this. Thanks.

Option Strict Off
Imports System
Imports System.Drawing
Imports System.Windows.Forms
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
 
' ----------------------------------------------
'   Menu: Tools->Operation Navigator->Tool Path->Simulate...
' ----------------------------------------------
Dim markId1 As NXOpen.Session.UndoMarkId
markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Start")
 
Dim kinematicConfigurator1 As NXOpen.SIM.KinematicConfigurator
kinematicConfigurator1 = workPart.KinematicConfigurator
 
Dim objects1(0) As NXOpen.CAM.CAMObject
Dim nCGroup1 As NXOpen.CAM.NCGroup = CType(workPart.CAMSetup.CAMGroupCollection.FindObject("NC_PROGRAM"), NXOpen.CAM.NCGroup)
 
objects1(0) = nCGroup1
Dim isvControlPanelBuilder1 As NXOpen.SIM.IsvControlPanelBuilder
isvControlPanelBuilder1 = kinematicConfigurator1.CreateIsvControlPanelBuilder(NXOpen.SIM.IsvControlPanelBuilder.VisualizationType.ToolPathSimulation, objects1)
 
isvControlPanelBuilder1.SetSingleStep(NXOpen.SIM.IsvControlPanelBuilder.SingleStepType.Block)
 
isvControlPanelBuilder1.SetSpeed(10)
 
theSession.SetUndoMarkName(markId1, "Simulation Control Panel Dialog")
 
theSession.SetUndoMarkVisibility(markId1, Nothing, NXOpen.Session.MarkVisibility.Invisible)
 
Dim simulationOptionsBuilder1 As NXOpen.CAM.SimulationOptionsBuilder
simulationOptionsBuilder1 = isvControlPanelBuilder1.SimulationOptionsBuilder
 
Dim response1 As Integer
response1 = isvControlPanelBuilder1.SetShow3dMaterialRemoval(True)
 
isvControlPanelBuilder1.SingleStepForward()
 ExportScreenshot("''''destination folder''''\Nx_screenshot0001.png")
isvControlPanelBuilder1.SingleStepForward()
 ExportScreenshot("''''destination folder''''\NX_screenshot0002.png")
isvControlPanelBuilder1.SingleStepForward()
 ExportScreenshot("''''destination folder''''\NX_screenshot0003.png")
isvControlPanelBuilder1.SingleStepForward()
 ExportScreenshot("''''destination folder''''\NX_screenshot0004.png")
isvControlPanelBuilder1.SingleStepForward()
 ExportScreenshot("''''destination folder''''\NX_screenshot0005.png")
isvControlPanelBuilder1.SingleStepForward()
 ExportScreenshot("''''destination folder''''\NX_screenshot0006.png")
isvControlPanelBuilder1.SingleStepForward()
 
isvControlPanelBuilder1.SingleStepForward()
 
isvControlPanelBuilder1.SingleStepForward()
 
isvControlPanelBuilder1.SingleStepForward()
 
isvControlPanelBuilder1.SingleStepForward()
 
isvControlPanelBuilder1.SingleStepForward()
 
 
' ----------------------------------------------
'   Menu: Tools->Journal->Stop Recording
' ----------------------------------------------
 
End Sub
 
Dim theSession As Session = Session.GetSession()
Dim theUfSession As UFSession = UFSession.GetUFSession()
 
Sub submain()
 
        If IsNothing(theSession.Parts.BaseWork) Then
            'active part required
            Return
        End If
 
        Dim workPart As Part = theSession.Parts.Work
        Dim lw As ListingWindow = theSession.ListingWindow
        lw.Open()
 
        'change export location as needed
        'ExportScreenshot("\\myhome.itap.purdue.edu\myhome\kbernadi\ecn.data\Desktop\testfolder\NX_screenshot.png")
 
        'optional, delete the image file
        'DeleteFile("\\myhome.itap.purdue.edu\myhome\kbernadi\ecn.data\Desktop\testfolder\NX_screenshot.png")
 
        lw.Close()
 
    End Sub
 
Sub ExportScreenshot(ByVal filename As String)
 
        Dim wcsVisible As Boolean = theSession.Parts.Display.WCS.Visibility
        Dim triadVisible As Integer = theSession.Preferences.ScreenVisualization.TriadVisibility
 
 
        Try
            DeleteFile(filename)
 
            theSession.Parts.Display.WCS.Visibility = False
            theSession.Preferences.ScreenVisualization.TriadVisibility = 0
 
            theUfSession.Disp.CreateImage(filename, UFDisp.ImageFormat.Png, UFDisp.BackgroundColor.White)
        Catch ex As Exception
            MsgBox(ex.Message & ControlChars.NewLine & _
                   "'" & filename & "' could not be created")
            'Return
 
        Finally
            theSession.Parts.Display.WCS.Visibility = wcsVisible
            theSession.Preferences.ScreenVisualization.TriadVisibility = triadVisible
 
        End Try
 
        'copy image to clipboard
        Dim theImage As Bitmap = CType(Image.FromFile(filename), Bitmap)
        Clipboard.SetImage(theImage)
 
    End Sub
 
Sub DeleteFile(ByVal filePath As String)
 
        'does file exist? if so, try to delete it (overwrite)
        If IO.File.Exists(filePath) Then
            IO.File.Delete(filePath)
        End If
 
    End Sub
 
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

Removing selection stickness from CAM object

$
0
0

Trying to remove selection stickiness from the journal which simulates machine in NX CAM. Anyone knows how to deal with it? I read through tutorial for but I wasn't able to apply it to cam.object.

here is the code,

Option Strict Off
Imports System
Imports System.Drawing
Imports System.Windows.Forms
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
 
 
Dim markId1 As NXOpen.Session.UndoMarkId
markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Start")
 
Dim kinematicConfigurator1 As NXOpen.SIM.KinematicConfigurator
kinematicConfigurator1 = workPart.KinematicConfigurator
 
Dim objects1(0) As NXOpen.CAM.CAMObject
Dim nCGroup1 As NXOpen.CAM.NCGroup = CType(workPart.CAMSetup.CAMGroupCollection.FindObject("NC_PROGRAM"), NXOpen.CAM.NCGroup)
 
objects1(0) = nCGroup1
Dim isvControlPanelBuilder1 As NXOpen.SIM.IsvControlPanelBuilder
isvControlPanelBuilder1 = kinematicConfigurator1.CreateIsvControlPanelBuilder(NXOpen.SIM.IsvControlPanelBuilder.VisualizationType.ToolPathSimulation, objects1)
 
isvControlPanelBuilder1.SetSingleStep(NXOpen.SIM.IsvControlPanelBuilder.SingleStepType.Block)
 
isvControlPanelBuilder1.SetSpeed(10)
 
theSession.SetUndoMarkName(markId1, "Simulation Control Panel Dialog")
 
theSession.SetUndoMarkVisibility(markId1, Nothing, NXOpen.Session.MarkVisibility.Invisible)
 
Dim simulationOptionsBuilder1 As NXOpen.CAM.SimulationOptionsBuilder
simulationOptionsBuilder1 = isvControlPanelBuilder1.SimulationOptionsBuilder
 
Dim response1 As Integer
response1 = isvControlPanelBuilder1.SetShow3dMaterialRemoval(True)
 
isvControlPanelBuilder1.SingleStepForward()
 
End Sub
 
End Module

Save Assembly File to new file name (SaveAs) in NXOpen (Python)

$
0
0

Hello all,

I'm looking for a way to save my NX assembly file to a new name. I can currently save the modifications I make in my journal using:

theSession = NXOpen.Session.GetSession()
theSession.Parts.SaveAll()

I've tried using the following,

import NXOpen.UF
theUFSession = NXOpen.UF.UFSession.GetUFSession()
 
theUFSession.Part.SaveAs('newFileName')

but I received the following error: "NXOpen.NXException: No write access"

Does anyone have any insight on this? Thanks for any help in advance!

-Sam

Python: What is important to know to get started?

$
0
0

Hello everyone!
After having written some small NX Journals in .vb during the past years, I've now come to the conclusion that it might be a good move to give Python a try. So I've started to learn Python (looks quite sympathetic to me!) and then I took one of the simpler .vb Journals of mine as an example to try and create the same functionality using Python. After some hours I managed to arrange the 30 lines of code in the proper order and it's working as expected.

Next, I'd like to see wheter I can use simple dialogue boxes as I used to in .vb utilizing System.Windows.Forms or NXOpenUI. I don't wish to go for BlockStyler right now because I am afraid to run into comlicated requirements - I'd prefer to keep things easy and straightforward - at least for a start.

System.Windows.Forms seems to be impossible as it is .NET related and there are quite a few GUI packages for Python like wxPython which does not yet fully support Python 3.3. Do I get that correct? Or is there a tweak?

So I thought NXOpenUI would rescue me and I tried:
import NXOpenUI
but that give an ImportError: No module named 'NXOpenUI'.
OK, next I tried:
import NXOpen.UI
which raises a weird error message referring to a line number which doesn't exist, still the sum of it is "ImporError: NXOpen.UI".
Feels as if there is no such thing as NXOpenUI ?

Well, I thought, it's about time for RTFM, so I went into NX Help / Programming tools, where an internet based page opens up "Accessing the Programming Tools help", telling me to "click here". Next, I can click Product area NX Open / NX Open for Python / NX Open Python Reference Guide.

My naive expectation was to get a .chm file for download, instead I am led to a web based page with API reference for NXOpen Python. This looks very pleasing at the 1st glance, but if I try to use the index, it becomes quite confusing being displayed in two columns, and it displays very slow.
To speed up things, I tried using the "quick search" feature feeding it some simple phrases like "OpenUI" or "Input" but after some minutes waiting for results, all I get for results are hundreds of lines saying
"blabla Class: {"timestamp":1491981571724,"status":404,"error":"Not Found","message":"No message available","path":"/data_services//resources/nx/11/nx_api/custom/en_US/nxopen_python_ref/_sources/NXOpen.Features.MapleBuilder.txt"}...

So now here come a few newbee questions:
- Is it possible at all to use either NXOpenUI or System.Windows.Forms dialogue boxes for Python in NX? And if so: how can this be done?
- What is your experience in making use of the NX Open Python API Reference 11.0 documentation? What is the best practice to cope with it?
- What other sources of information and orientation would you recommend to get things running?

Thank for your support & my best Regards to everyone,
UdoMM

Feature Group vs Brep

$
0
0

Hi,

I have bodies grouped together in a part. I want to generate a excel report with each group mass properties. While compile I got error saying feature group cannot be cast into Brep, If I use Brep it is selecting all the individual bodies inside group not considering the group.

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.ThreadingImports Microsoft.OfficeImports Microsoft.Office.Interop.ExcelImports Microsoft.Office.Interop 
 
Module MassandCG
 
    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() 
        Dim MyExcel AsObject=NothingDim MyBook AsObject=NothingDim Mysheet AsObject=NothingDim RefBook AsObject=NothingDim RefSheet AsObject=NothingDim ExcelFileName AsString="C:\Users\t5371pa\Desktop\Checklist.xlsx"Dim ExcelNewFileName AsString="C:\Users\t5371pa\Desktop\Myexcel.xlsx"Dim ExcelFileExists AsBoolean=FalseDim NewExcel AsString=Nothing'Dim MyExcel As Excel.Application = Nothing'Dim MyBook As Workbook = Nothing'Dim Mysheet As Worksheet = Nothing'Dim RefBook As Workbook = Nothing'Dim RefSheet As Worksheet = Nothing 
 
        Dim Partno AsString=NothingDim tempScreenshot AsString=NothingDim tempLocation AsString="C:\Temp"Try
            Partno = workPart.GetStringAttribute("DB_PART_NO")Catch ex As NXException
            lw.WriteLine("Partno Not found"& ex.ErrorCode&":"& ex.Message.ToString)
            Partno ="Not Found"EndTry 
        'Create Excel File and Save it in user defined locationDim Savechecklist AsNew SaveFileDialog
        With Savechecklist
            .Title="Saving Standard DP Check File".InitialDirectory="C:\Users\t5371pa\Desktop".Filter="ExcelFiles (*.xlsx)|*.xlsx|Macro enabled Powerpoint files (*.xlsm)|*.xlsm|All files (*.*)|*.*".FilterIndex=1.RestoreDirectory=True.FileName= ExcelNewFileName
            If.ShowDialog= DialogResult.OKThen
                NewExcel =.FileNameEndIfEndWith 
        If MyExcel IsNothingThen
            MyExcel =CreateObject("Excel.Application")If MyExcel IsNothingThen
                theUI.NXMessageBox.Show("Error", NXMessageBox.DialogType.Error, "Could not start Excel, journal exiting")ExitSubEndIfEndIf 
        MyExcel.Visible=False 
        If File.Exists(ExcelNewFileName)Then'Open the Excel file
            ExcelFileExists =True
            MyBook = MyExcel.Workbooks.Open(ExcelNewFileName)Else'Create the Excel file
            MyBook = MyExcel.Workbooks.Add
            MyBook.SaveAs(ExcelNewFileName)EndIfIf MyBook IsNothingThen
            theUI.NXMessageBox.Show("Error", NXMessageBox.DialogType.Error, "Could not open Excel file: "& ExcelFileName & ControlChars.NewLine&"journal exiting.")ExitSubEndIf 
        Mysheet = MyBook.Worksheets.Add()
        Mysheet.Activate() 
        Dim Row AsInteger=NothingDim i AsInteger=NothingDim MyGroupRep As NXObject =NothingDim MyGroup As Features.Brep=NothingDim Replist As ArrayList =New ArrayList
        Dim Mylist As ArrayList =New ArrayList
 
        ForEach MyGroupRep In workPart.FeaturesIfTypeOf MyGroupRep Is Features.BrepThen
                Replist.Add(MyGroupRep)EndIfNext 
        ForEach MyGroup In Replist
            Mylist.Add(MyGroup)NextMsgBox(Mylist.Count.ToString) 
 
        For Row =1To Mylist.Count-1Dim Thegroup As Features.Brep= Mylist(Row)Dim GruopName AsString= Thegroup.Name
            Thegroup.ShowBody(False)Dim BodyList()As Body =NothingDim MYSolidBodies As List(Of Body)=NothingDim MYSheetBodies As List(Of Body)=Nothing
            BodyList = Thegroup.GetBodies() 
            For j =1To BodyList.Length-1If BodyList(j).IsSolidBodyThen
                    MYSolidBodies.Add(BodyList(i))ElseIf BodyList(j).IsSheetBodyThen
                    MYSheetBodies.Add(BodyList(i))EndIfNextMsgBox(MYSolidBodies.Count.ToString)Dim thebodies()As Body = MYSolidBodies.ToArrayDim Partvolume AsString=NothingDim PartDen AsString=NothingDim PartMass AsString=NothingDim CGValue As Point3d =NothingDim CGX AsString=NothingDim CGY AsString=NothingDim CGZ AsString=Nothing 
            Dim myMeasure As MeasureManager = theSession.Parts.Display.MeasureManager()Dim massUnits(4)As Unit
            massUnits(0)= theSession.Parts.Display.UnitCollection.GetBase("Area")
            massUnits(1)= theSession.Parts.Display.UnitCollection.GetBase("Volume")
            massUnits(2)= theSession.Parts.Display.UnitCollection.GetBase("Mass")
            massUnits(3)= theSession.Parts.Display.UnitCollection.GetBase("Length") 
            Dim MyNewmeasure As MeasureBodies =NothingTry
                MyNewmeasure = myMeasure.NewMassProperties(massUnits, 0.99, thebodies)
                MyNewmeasure.InformationUnit= MeasureBodies.AnalysisUnit.KilogramMillimeterTry
                    Partvolume = MyNewmeasure.Volume.ToString("#.0")Catch ex As NXException
                    Partvolume = MyNewmeasure.Volume.ToString("#.0")EndTryTry
                    PartMass = MyNewmeasure.Mass.ToString("#.0")Catch ex As NXException
                    PartMass = MyNewmeasure.Mass.ToString("#.0")EndTryTry
                    CGValue = MyNewmeasure.Centroid
                    CGX = CGValue.X.ToString("#.0")
                    CGY = CGValue.Y.ToString("#.0")
                    CGZ = CGValue.Z.ToString("#.0")Catch ex As NXException
                    CGX =0
                    CGY =0
                    CGZ =0EndTryTryDim DenFor AsInteger=(MyNewmeasure.Mass.ToString/ MyNewmeasure.Volume.ToString)
                    PartDen = DenFor.ToString("#.0")Catch ex As NXException
                    PartDen =(MyNewmeasure.Mass.ToString/ MyNewmeasure.Volume.ToString).ToString("#.0")EndTryCatch ex As Exception
                lw.WriteLine(Partno &": MassProperties error-"& ex.Message.ToString)EndTry 
            Try
                tempScreenshot = IO.Path.Combine(tempLocation, Partno &"-"& Row.ToString&".jpg")
                ExportScreenshot(tempScreenshot) 
            Catch ex As NXException
                lw.WriteLine(Partno & Row.ToString&": View Not Generated-"& ex.ErrorCode&":"& ex.Message.ToString)EndTry
            Mysheet.cells(Row, 1).value()= GruopName
            Dim Piccommant AsObject= Mysheet.Cells(Row, 2).AddComment()
            Mysheet.cells(Row, 3).value()= Partvolume
            Mysheet.cells(Row, 4).value()= PartMass
            Mysheet.cells(Row, 5).value()= PartDen
            Mysheet.cells(Row, 6).value()= CGX
            Mysheet.cells(Row, 7).value()= CGY
            Mysheet.cells(Row, 8).value()= CGZ
 
            'Dim Piccommant As Excel.Comment = Mysheet.Cells(Row, 3).AddComment()With Piccommant.Shape.Fill.UserPicture(tempLocation &"\"& Partno &"-"& Row.ToString&".jpg").Height=600.Width=600EndWith 
            Thegroup.HideBody()Next 
 
        MyBook.Save()
        MyBook.Close()
        MyBook =Nothing
        MyExcel.Quit() 
    EndSub 
 
 
    Sub ExportScreenshot(ByVal filename AsString) 
        'save user preference for visibility of WCS, triad, view name, and view borderDim wcsVisible AsBoolean= theSession.Parts.BaseDisplay.WCS.VisibilityDim triadVisible AsInteger= theSession.Preferences.ScreenVisualization.TriadVisibilityDim displayModelViewNames AsBoolean= theSession.Parts.BaseDisplay.Preferences.NamesBorderVisualization.ShowModelViewNamesDim displayModelViewBorders AsBoolean= theSession.Parts.BaseDisplay.Preferences.NamesBorderVisualization.ShowModelViewBorders 
        'turn off the WCS, triad, view name, and view border
        theSession.Parts.BaseDisplay.WCS.Visibility=False
        theSession.Preferences.ScreenVisualization.TriadVisibility=False
        theSession.Parts.BaseDisplay.Preferences.NamesBorderVisualization.ShowModelViewBorders=False
        theSession.Parts.BaseDisplay.Preferences.NamesBorderVisualization.ShowModelViewNames=False 
        Try
            ufs.Disp.CreateImage(filename, UFDisp.ImageFormat.Jpeg, UFDisp.BackgroundColor.White)Catch ex As Exception
            MsgBox(ex.Message& ControlChars.NewLine& _
                   "'"& filename &"' could not be created")ThrowNew Exception("Screenshot could not be created")Finally'reset visibility of WCS, triad, view name, and view border to user's preference
            theSession.Parts.BaseDisplay.WCS.Visibility= wcsVisible
            theSession.Preferences.ScreenVisualization.TriadVisibility= triadVisible
            theSession.Parts.BaseDisplay.Preferences.NamesBorderVisualization.ShowModelViewBorders= displayModelViewBorders
            theSession.Parts.BaseDisplay.Preferences.NamesBorderVisualization.ShowModelViewNames= displayModelViewNames
        EndTry 
    EndSubEndModule

Create Parts List

$
0
0

I couldn't record the Parts List button, but found something on GTAC coded for C# (search nx_api4978 on GTAC to find it).

I put together something in VB.NET that imitates the function of the Parts List button. Hopefully it helps saves someone the trouble I went through!

Option Strict Off
Imports System
Imports NXOpen
Imports NXOpen.UFImports NXOpen.UI 
Module NXJournal
 
    Dim ufs As UFSession = UFSession.GetUFSession() 
    Sub Main()
        CreatePartsList()EndSub 
    Function CreatePartsList()Dim origin AsDouble()=NewDouble(2){0.0, 0.0, 0.0} 
        Dim partsListTag As Tag = NXOpen.Tag.Null 
        Dim partUnits AsInteger=0 
        Dim prefs As UFPlist.Prefs=Nothing 
        ufs.Plist.AskDefaultPrefs(prefs) 
        SelectPoint("Parts List Position", origin) 
        ufs.Plist.Create(prefs, origin, partsListTag) 
    EndFunction 
    Function SelectPoint(cue AsString, ByRef base_pt AsDouble())AsIntegerDim point_tag As NXOpen.Tag= NXOpen.Tag.Null 
        Dim response AsInteger=0 
        Dim base_method As UFUi.PointBaseMethod= UFUi.PointBaseMethod.PointInferred 
        ufs.Ui.LockUgAccess(NXOpen.UF.UFConstants.UF_UI_FROM_CUSTOM)
        ufs.Ui.PointConstruct(cue, base_method, point_tag, base_pt, response)
        ufs.Ui.UnlockUgAccess(NXOpen.UF.UFConstants.UF_UI_FROM_CUSTOM) 
        Return response
 
    EndFunction 
EndModule

Best,
Craptor

Display Move Component Dialog

$
0
0

Hello,
I am working on a program that will select a component and start the move component dialog based on previous used selections. I have recorded a few journals using the move component command but I can't seem to find a way to actually display the move component dialog when the journal runs. The user will need to specify the motion, the program is just to insure that the correct program is selected (It's a large assembly with similarly named components).

I have everything working up to actually displaying the move component dialog. Any hep or suggestions would be greatly appreciated.

Thanks,
-Mike

Detecting & Cleaning broken dimensions/Symbols

$
0
0

Hello,

I have an assembly drawing, and when I remove some components from the assembly, some dimensions/symbols/notes defining these components get broken as expected.

I want to find&delete whatever is broken in this multi sheet drawing automatically.

Is that possible?

Thanks,
Onur.


Face selection problem in NX11 Nxopen

$
0
0

Below code is just for converting solid to sheetmetal by letting user select the face to do the operation. Having the following error on my code. Using NX11 with TC11

Error 1 Overload resolution failed because no accessible 'SelectObject' accepts this number of arguments.

I tried to replace 'SelectObject' with 'SelectTaggedObject' but still don't work. Please suggest what can I do?

Imports System
Imports NXOpen
Imports NXOpen.UF
Imports NXOpenUI
 
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
theSession.ApplicationSwitchImmediate("UG_APP_SBSM")
 
Dim markId1 As NXOpen.Session.UndoMarkId = Nothing
markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Enter Sheet Metal")
Dim markId2 As NXOpen.Session.UndoMarkId = Nothing
markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Start")
 
Dim nullNXOpen_Features_Feature As NXOpen.Features.Feature = Nothing
 
Dim convertToSheetmetalBuilder1 As NXOpen.Features.SheetMetal.ConvertToSheetmetalBuilder = Nothing
convertToSheetmetalBuilder1 = workPart.Features.SheetmetalManager.CreateConvertToSheetmetalFeatureBuilder(nullNXOpen_Features_Feature)
 
convertToSheetmetalBuilder1.SetApplicationContext(NXOpen.Features.SheetMetal.ApplicationContext.NxSheetMetal)
 
Dim expression1 As NXOpen.Expression = Nothing
expression1 = workPart.Preferences.PartSheetmetal.GetBendReliefDepth()
 
Dim expression2 As NXOpen.Expression = Nothing
expression2 = workPart.Preferences.PartSheetmetal.GetBendReliefWidth()
 
Dim nullNXOpen_Features_SketchFeature As NXOpen.Features.SketchFeature = Nothing
 
convertToSheetmetalBuilder1.Sketch = nullNXOpen_Features_SketchFeature
 
Dim nullNXOpen_Face As NXOpen.Face = Nothing
 
convertToSheetmetalBuilder1.BaseFace = nullNXOpen_Face
 
Dim nullNXOpen_Section As NXOpen.Section = Nothing
 
convertToSheetmetalBuilder1.RipSection = nullNXOpen_Section
 
Dim scCollector1 As NXOpen.ScCollector = Nothing
scCollector1 = convertToSheetmetalBuilder1.AdditionalFacesToConvert
 
Dim expression3 As NXOpen.Expression = Nothing
expression3 = workPart.Preferences.PartSheetmetal.GetBendReliefDepth()
 
Dim expression4 As NXOpen.Expression = Nothing
expression4 = workPart.Preferences.PartSheetmetal.GetBendReliefWidth()
 
convertToSheetmetalBuilder1.BendReliefType = NXOpen.Features.SheetMetal.ConvertToSheetmetalBuilder.BendReliefTypeOptions.None
 
Dim expression5 As NXOpen.Expression = Nothing
expression5 = convertToSheetmetalBuilder1.BendReliefDepth
 
Dim expression6 As NXOpen.Expression = Nothing
expression6 = workPart.Preferences.PartSheetmetal.GetBendReliefDepth()
 
Dim name1 As String = Nothing
name1 = expression6.Name
 
expression5.RightHandSide = name1
 
Dim expression7 As NXOpen.Expression = Nothing
expression7 = convertToSheetmetalBuilder1.BendReliefWidth
 
Dim expression8 As NXOpen.Expression = Nothing
expression8 = workPart.Preferences.PartSheetmetal.GetBendReliefWidth()
 
Dim name2 As String = Nothing
name2 = expression8.Name
 
expression7.RightHandSide = name2
 
convertToSheetmetalBuilder1.MaintainZeroBendRadius = False
 
theSession.SetUndoMarkName(markId2, "Convert to Sheet Metal Dialog")
 
Dim section1 As NXOpen.Section = Nothing
section1 = workPart.Sections.CreateSection(0.00095, 0.001, 0.01)
 
Dim markId3 As NXOpen.Session.UndoMarkId = Nothing
markId3 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Convert to Sheet Metal")
 
theSession.DeleteUndoMark(markId3, Nothing)
 
Dim markId4 As NXOpen.Session.UndoMarkId = Nothing
markId4 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Convert to Sheet Metal")
 
        'Dim brep1 As NXOpen.Features.Brep = CType(workPart.Features.FindObject("UNPARAMETERIZED_FEATURE(14)"), NXOpen.Features.Brep)
 
        'Dim face1 As NXOpen.Face = CType(brep1.FindObject("FACE 3 {(0.75,17.65125,8.6937488451453) UNPARAMETERIZED_FEATURE(14)}"), NXOpen.Face)
        Dim face1 As NXopen.face = SelectPlanarFace()
 
 
convertToSheetmetalBuilder1.BaseFace = face1
 
Dim ripEdges1(-1) As NXOpen.Edge
convertToSheetmetalBuilder1.SetRipEdges(ripEdges1)
 
convertToSheetmetalBuilder1.Sketch = nullNXOpen_Features_SketchFeature
 
convertToSheetmetalBuilder1.RipSection = section1
 
convertToSheetmetalBuilder1.MaintainZeroBendRadius = False
 
Dim builderDataValidity1 As Integer = Nothing
builderDataValidity1 = convertToSheetmetalBuilder1.ValidateBuilderData()
 
Dim feature1 As NXOpen.Features.Feature = Nothing
feature1 = convertToSheetmetalBuilder1.CommitFeature()
 
theSession.DeleteUndoMark(markId4, Nothing)
 
theSession.SetUndoMarkName(markId2, "Convert to Sheet Metal")
 
convertToSheetmetalBuilder1.Destroy()
 
section1.Destroy()
 
    End Sub
 
    Function SelectPlanarFace() As Face
 
        Dim ui As UI = ui.GetUI
        Dim title As String = "Select a planar face"
        Dim message As String = "Selection"
        Dim includeFeatures As Boolean = False
        Dim keepHighlighted As Boolean = False
        Dim selAction As Selection.SelectionAction = Selection.SelectionAction.ClearAndEnableSpecific
        Dim cursor As Point3d
        Dim scope As Selection.SelectionScope = Selection.SelectionScope.WorkPart
        Dim selectionMask_array(0) As Selection.MaskTriple
 
        With selectionMask_array(0)
            .Type = UFConstants.UF_solid_type
            .SolidBodySubtype = UFConstants.UF_UI_SEL_FEATURE_PLANAR_FACE
        End With
 
'Problem in this line below 
 
        Dim resp As Face = ui.SelectionManager.SelectObject(message, title, scope, selAction, includeFeatures, keepHighlighted, selectionMask_array, cursor)
 
        If resp Is Nothing Then
            Return Nothing
        End If
 
    End Function
 
 
    Public Function GetUnloadOption(ByVal dummy As String) As Integer
 
        'Unloads the image when the NX session terminates
        GetUnloadOption = NXOpen.Session.LibraryUnloadOption.AtTermination
 
    End Function
 
End Module

Can this be extended to all the sub level components of current assembly

$
0
0
Option Strict Off
Imports System
Imports NXOpen
Imports NXOpen.Assemblies 
Module ArrangementUpdateNew
 
    Dim theSession As Session = Session.GetSession()Dim workPart As Part = theSession.Parts.WorkDim lw As ListingWindow = theSession.ListingWindow 
    Sub Main()
        lw.Open() 
        'ArrangementOptions.IndividuallyPositionedDim Mycomponent As Assemblies.Component=NothingForEach Mycomponent In workPart.ComponentAssembly.RootComponent.GetChildren()
            lw.WriteLine(Mycomponent.Name)TryDim MyObj(0)As NXObject
                MyObj(0)= Mycomponent
                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")EndTry 
        Next 
    EndSub 
EndModule

Open/Edit Multiplt NX Files Inside Same "run_journal" Script

$
0
0

Hello all,

I'm currently working to automate some NX tasks but I need to work in multiple assemblies/file parts. I could do this by running multiple scripts using "run_journal()" multiple times, but this is not efficient and would take some time to run. Does anyone know if there is a way to open a separate NX part file while inside a session?

Currently I am using the following code.

theSession   = NXOpen.Session.GetSession()
 
    #Opens assembly part desired to modify
    #Try to open Part; throw an error upon failure
    try:
        basepart1, partLoadStatus1 = theSession.Parts.OpenBaseDisplay(assemblyFile)
        partLoadStatus1.Dispose()
    except Exception:
        msg.error(fullLogFile,' The specified file could not be opened.'
                                 +' Ensure that the file name and path are correct.')
 
#get work part of assembly
workPart = theSession.Parts.Work
 
##------------------------------------------------------------
##------------------------------------------------------------
## CODE MODIFICATIONS GO HERE (not relevant to problem at hand)
##------------------------------------------------------------
##------------------------------------------------------------
 
#try to open new part file to edit (different than assemblyFile)
newPart = 'C:/my/directory/to/newPart/' 
#use class method to open new session/workPart
newWorkPart,newDisplayPart = ModMass.SetNXFile(newPart,logFile)
 
##------------------------------------------------------------
##------------------------------------------------------------
## NEW PART MODIFICATIONS GO HERE
##------------------------------------------------------------
##------------------------------------------------------------
 
#now we need to get back to original assembly file.
workPart,displayPart = ModMass.SetNXFile(assemblyFile,logFile)

The class method is shown here: (this opens a new file)

import NXOpen
import MsgAppend as msg
 
#Configure message appending
msg    = msg.MsgAppend()
 
class ModMassIndex():
 
    def __init__(self):
        super(ModMassIndex, self).__init__()
 
    def SetNXFile(self,NXFile,logFile):
        theSession   = NXOpen.Session.GetSession()
        #Opens assembly part desired to modify
        #Try to open Part; throw an error upon failure
        try:
            basepart1, partLoadStatus1 = theSession.Parts.OpenBaseDisplay(NXFile)
            partLoadStatus1.Dispose()
        except Exception:
            msg.error(logFile,' The specified file could not be opened.'
                                     +' Ensure that the file name and path are correct.')
 
        #Obtains needed NXOpen work class that give access to other objects
        if theSession.Parts.Work == None:
            msg.error(logFile,' NXOpen.Session.GetSession().Parts.Work is Null.')
        else:
            workPart    = theSession.Parts.Work
            displayPart = theSession.Parts.Display
 
        return workPart, displayPart

This code successfully opens the new desired part, but when I need to access components of the original part later on, it cannot locate the assembly. If anyone has any insight on this issue, it would be greatly appreciated!

Thank you!
Sam

Implementing .MakeUptoDate method

$
0
0

Hi All,

Can anyone please provide me an example for implementing '.MakeUptoDate()' method(which is equivalent to 'Update for external changes option ' in UG NX)

Edit NX expressions Through NX Journal Userform

$
0
0

Hi all,

I want to create an userform in NX, which is showing existing Expressions and their values in Textboxes, and asks user to edit it. When user edits the values and hit OK , it edits the values in expressions.

Thanks & Regards,
Vivek

Viewing all 787 articles
Browse latest View live


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