Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations IDS on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

vb system.nullreferenceexception object reference not set to an instance

Status
Not open for further replies.

Kenja824

Automotive
Nov 5, 2014
949
Cowski had created this code for me. As he mentioned in that thread, the arrows were not connecting to the edge right. I told him what he had was awesome for now and I was hoping in my head I could figure it out from there.

I one time found another code where it created Symbol IDs with balloons (which I needed notes associated to components) but this one the leaders connected perfect.

I saw this as a good challenge for me to try and steal the functions I needed from the Symbol code and use them in cowski's code and see if I could get it working. I have to say, trying this and needing to start from scratch several times, I have learned a lot. I still suck at code but I am understanding it a little more and that was the main focus of trying this myself.

At one point I had the arrows connecting exactly where my cursor picked but not attaching to the edge of the component. Looking at it, I realized I needed to use the "get_position_on_object" function from the other code. Unfortunately that has led me into a corner I cant figure out. A stupid null reference error.

With the understanding I have very little idea what I am doing, I would ask you not to laugh too hard if this code is all screwed up looking. But can someone tell me why I am getting this error on line 55?

image_m5bgm7.png


Code:
Option Strict Off
Imports System
Imports NXOpen
'Imports NXOpen.UI
Imports NXOpen.UF
Imports NXOpen.Drawings
Imports System.Collections.Generic

Module Module2

    Dim ufs As UFSession = UFSession.GetUFSession()
    Dim theSession As Session = Session.GetSession()
    Dim theUfSession As UFSession = UFSession.GetUFSession
    'Dim theUI As UI = UI.GetUI()

    Dim workPart As Part = theSession.Parts.Work
    Dim displayPart As Part = theSession.Parts.Display
    Dim lw As ListingWindow = theSession.ListingWindow
    Dim lg As LogFile = theSession.LogFile

    Sub Main()

        'lg.WriteLine("~~ NXJ label component ~~")
        'lg.WriteLine("800c0a41-139c-4682-b37f-cfd398de402c")
        'lg.WriteLine("  timestamp: " & Now)

        If IsNothing(theSession.Parts.Work) Then
            'active part required
            lg.WriteLine("  no active part, exiting journal")
            Return
        End If

        lw.Open()

        Const undoMarkName As String = "create component labels"
        Dim markId1 As Session.UndoMarkId
        markId1 = theSession.SetUndoMark(Session.MarkVisibility.Visible, undoMarkName)

        Dim myDraftingCurve As Drawings.DraftingCurve = Nothing
        Dim myPickPt As Point3d
        Dim myView As View = Nothing
        Dim obj_coords As Point3d = Nothing '---------------------------------------------------------------------FROM IDSYMBOL
        Dim edge1 As DisplayableObject = Nothing '----------------------------------------------------------------FROM IDSYMBOL
        Dim view1 As DraftingView = Nothing '---------------------------------------------------------------------FROM IDSYMBOL
        Dim cursor As Point3d = Nothing '-------------------------------------------------------------------------FROM IDSYMBOL
        Dim vwname As String = Nothing '--------------------------------------------------------------------------FROM IDSYMBOL
        '   Dim coords As Point3d = Nothing '--------------------------------------------------------------------------FROM IDSYMBOL

        While SelectDraftingCurve(edge1, myPickPt, view1) <> Selection.Response.Cancel '-----------------------------

            Dim parentCount As Integer
            Dim parents() As Tag = Nothing
            theUfSession.Draw.AskDraftingCurveParents(myDraftingCurve.Tag, parentCount, parents)
            Dim someComp As Assemblies.Component = Nothing
            '  lw.WriteLine("parent count: " & parentCount.ToString)


            '-----------------------------------------------------------------------------------------------------FROM IDSYMBOL
            ufs.Ui.AskLastPickedView(vwname)
            view1 = CType(workPart.DraftingViews.FindObject(vwname), Drawings.DraftingView)
            obj_coords = get_position_on_object(edge1, view1, cursor)
            '-----------------------------------------------------------------------------------------------------

            For Each temp As Tag In parents
                Dim tempObj As NXObject = Utilities.NXObjectManager.Get(temp)

                If tempObj.IsOccurrence Then
                    'lw.WriteLine("owning component: " & tempObj.OwningComponent.DisplayName)
                    someComp = tempObj.OwningComponent
                Else
                    'lw.WriteLine("owning part: " & tempObj.OwningPart.Leaf)
                End If
            Next

            If IsNothing(someComp) Then
                lw.WriteLine("no component selected")
                Return
            End If

            'select point for label
            Dim labelPosition As Point3d = SelectScreenPoint()

            'lw.WriteLine("label position: " & labelPosition.ToString)

            'UF_DRF_create_label

            Dim curLetterPrefs As Annotations.LetteringPreferences = theSession.Parts.Work.Annotations.Preferences.GetLetteringPreferences
            Dim userSymbolPreferences1 As Annotations.UserSymbolPreferences
            userSymbolPreferences1 = theSession.Parts.Work.Annotations.NewUserSymbolPreferences(Annotations.UserSymbolPreferences.SizeType.ScaleAspectRatio, 1, 1)
            Dim curDimPrefs As Annotations.LineAndArrowPreferences = theSession.Parts.Work.Annotations.Preferences.GetLineAndArrowPreferences

            '     AddComponentLabel(someComp, edge1, myView, myPickPt, labelPosition, MakeLabelText(someComp))
            AddComponentLabel(someComp, edge1, myView, obj_coords, labelPosition, MakeLabelText(someComp))

        End While

        lw.Close()

    End Sub


    Function MapView2Abs(ByVal aView As View, ByVal coords As Point3d)
        Dim vmx As Matrix3x3 = aView.Matrix
        Dim vw() As Double = {0, 0, 0, vmx.Xx, vmx.Xy, vmx.Xz, vmx.Yx, vmx.Yy, vmx.Yz}
        Dim abs() As Double = {0, 0, 0, 1, 0, 0, 0, 1, 0}
        Dim mx(11) As Double
        Dim irc As Integer
        Dim c() As Double = {coords.X, coords.Y, coords.Z}

        ufs.Trns.CreateCsysMappingMatrix(vw, abs, mx, irc)
        ufs.Trns.MapPosition(c, mx)

        MapView2Abs = New Point3d(c(0), c(1), c(2))
    End Function

    Function MapAbs2View(ByVal aView As View, ByVal coords As Point3d)
        Dim vmx As Matrix3x3 = aView.Matrix
        Dim vw() As Double = {0, 0, 0, vmx.Xx, vmx.Xy, vmx.Xz, vmx.Yx, vmx.Yy, vmx.Yz}
        Dim abs() As Double = {0, 0, 0, 1, 0, 0, 0, 1, 0}
        Dim mx(11) As Double
        Dim irc As Integer
        Dim c() As Double = {coords.X, coords.Y, coords.Z}

        ufs.Trns.CreateCsysMappingMatrix(abs, vw, mx, irc)
        ufs.Trns.MapPosition(c, mx)

        MapAbs2View = New Point3d(c(0), c(1), c(2))
    End Function


    '---------FROM IDSYMBOL
    Function get_position_on_object(ByVal obj As DisplayableObject, ByVal aView As View, ByRef coords As Point3d)

        Dim guess1 As Double() = New Double(2) {}
        Dim pt1 As Double() = New Double(2) {}
        Dim pt2 As Double() = New Double(2) {}
        Dim min_dist As Double

        Dim loc_view As Point3d = MapAbs2View(aView, coords)

        Dim sp_view As New Point3d(loc_view.X, loc_view.Y, loc_view.Z + 1000)
        Dim ep_view As New Point3d(loc_view.X, loc_view.Y, loc_view.Z - 1000)
        Dim sp_abs As Point3d = MapView2Abs(aView, sp_view)
        Dim ep_abs As Point3d = MapView2Abs(aView, ep_view)

        Dim line1 As Line = theSession.Parts.Work.Curves.CreateLine(sp_abs, ep_abs)
        line1.SetVisibility(NXOpen.SmartObject.VisibilityOption.Visible)
        line1.RedisplayObject()

        ufs.Modl.AskMinimumDist(obj.Tag, line1.Tag, 0, guess1, 0, guess1, min_dist, pt1, pt2)

        Dim markId2 As Session.UndoMarkId = theSession.SetUndoMark(Session.MarkVisibility.Visible, "Delete")
        theSession.UpdateManager.AddToDeleteList(line1)
        theSession.UpdateManager.DoUpdate(markId2)

        get_position_on_object = New Point3d(pt1(0), pt1(1), pt1(2))
    End Function


    Function SelectDraftingCurve(ByRef theDraftingCurve As Drawings.DraftingCurve,
                                 ByRef pickPt As Point3d,
                                 ByRef selView As View) As Selection.Response

        Dim message As String = "Drafting Curve:"
        Dim title As String = "Select a drafting curve"
        Dim scope As Integer = UFConstants.UF_UI_SEL_SCOPE_ANY_IN_ASSEMBLY
        Dim response As Integer
        Dim draftingCurveTag As Tag = Tag.Null
        Dim view As NXOpen.Tag
        Dim cursor(2) As Double
        Dim ip As UFUi.SelInitFnT = AddressOf mask_for_curves

        Dim cursorView As Integer
        theUfSession.Ui.AskCursorView(cursorView)

        theUfSession.Ui.SetCursorView(0)

        theUfSession.Ui.LockUgAccess(UFConstants.UF_UI_FROM_CUSTOM)

        Try
            theUfSession.Ui.SelectWithSingleDialog(message, title, scope, ip,
                         Nothing, response, draftingCurveTag, cursor, view)
            theDraftingCurve = Utilities.NXObjectManager.Get(draftingCurveTag)
            selView = Utilities.NXObjectManager.Get(view)
            pickPt.X = cursor(0)
            pickPt.Y = cursor(1)
            pickPt.Z = cursor(2)
            If draftingCurveTag <> Tag.Null Then
                theUfSession.Disp.SetHighlight(draftingCurveTag, 0)
            End If
        Finally
            theUfSession.Ui.UnlockUgAccess(UFConstants.UF_UI_FROM_CUSTOM)
            theUfSession.Ui.SetCursorView(cursorView)
        End Try

        If response <> UFConstants.UF_UI_OBJECT_SELECTED And
           response <> UFConstants.UF_UI_OBJECT_SELECTED_BY_NAME Then
            Return Selection.Response.Cancel
        Else
            Return Selection.Response.Ok
        End If

    End Function

    Function mask_for_curves(ByVal select_ As IntPtr, ByVal userdata As IntPtr) As Integer

        Dim num_triples As Integer = 4
        Dim mask_triples(3) As UFUi.Mask

        mask_triples(0).object_type = UFConstants.UF_line_type
        mask_triples(0).object_subtype = 0
        mask_triples(0).solid_type = 0

        mask_triples(1).object_type = UFConstants.UF_circle_type
        mask_triples(1).object_subtype = 0
        mask_triples(1).solid_type = 0

        mask_triples(2).object_type = UFConstants.UF_conic_type
        mask_triples(2).object_subtype = 0
        mask_triples(2).solid_type = 0

        mask_triples(3).object_type = UFConstants.UF_spline_type
        mask_triples(3).object_subtype = 0
        mask_triples(3).solid_type = 0

        theUfSession.Ui.SetSelMask(select_,
                UFUi.SelMaskAction.SelMaskClearAndEnableSpecific,
                                          num_triples, mask_triples)

        Return UFConstants.UF_UI_SEL_SUCCESS

    End Function

    Function GetComponentAttribute(ByVal theComp As Assemblies.Component, ByVal attributeTitle As String) As String

        If theComp.HasUserAttribute(attributeTitle, NXObject.AttributeType.String, -1) Then
            Return theComp.GetUserAttributeAsString(attributeTitle, NXObject.AttributeType.String, -1)
        Else
            Return Nothing
        End If

    End Function

    Function SelectScreenPoint() As Point3d

        'Allow user to interactively pick the point where the annotation
        'will be placed.

        'This Function needs Sub MotionCallback() to work properly.

        Dim myScreenPos(2) As Double
        Dim theViewTag As Tag = theSession.Parts.Display.Views.WorkView.Tag
        Dim theResponse As Integer

        theUfSession.Ui.LockUgAccess(UFConstants.UF_UI_FROM_CUSTOM)

        theUfSession.Ui.SpecifyScreenPosition("pick a point", AddressOf MotionCallback, Nothing, myScreenPos, theViewTag, theResponse)

        theUfSession.Ui.UnlockUgAccess(UFConstants.UF_UI_FROM_CUSTOM)

        If theResponse = UFConstants.UF_UI_PICK_RESPONSE Then
            Return New Point3d(myScreenPos(0), myScreenPos(1), myScreenPos(2))
        Else
            Return Nothing
        End If

    End Function

    Sub MotionCallback(ByVal pos() As Double,
                   ByRef motion_cb_data As UFUi.MotionCbData,
                   ByVal client_data As System.IntPtr)

        'This sub will be called every time a cursor move is detected during the
        'SpecifyScreenPosition function.

        'The parameters motion_cb_data and client_data are not used in this implementation,
        'but the Sub must have the same signature as UFUI.MotionFnT to work properly.

        'disable (for now)
        Return

        Dim wView As NXOpen.View = theSession.Parts.Display.Views.WorkView
        Dim topLeft(2) As Double
        Dim topRight(2) As Double
        Dim botLeft(2) As Double
        Dim botRight(2) As Double

        Dim labelWidth As Double = 20
        Dim labelHeight As Double = 5

        'draw rectangle(s) to represent tabular note boundary
        Select Case 1
            Case Is = 1     'top left
                'draw rectangle to the right and down
                'pos = top left corner
                topLeft(0) = pos(0)
                topLeft(1) = pos(1)
                topRight(0) = pos(0) + labelWidth
                topRight(1) = pos(1)
                botLeft(0) = pos(0)
                botLeft(1) = pos(1) - labelHeight
                botRight(0) = topRight(0)
                botRight(1) = botLeft(1)
            Case Is = 2     'top right
                'draw rectangle to the left and down
                'pos = top right corner
                topRight(0) = pos(0)
                topRight(1) = pos(1)
                topLeft(0) = topRight(0) - labelWidth
                topLeft(1) = topRight(1)
                botLeft(0) = topLeft(0)
                botLeft(1) = topLeft(1) - labelHeight
                botRight(0) = topRight(0)
                botRight(1) = botLeft(1)
            Case Else       'shouldn't happen


        End Select

        'for other temp graphics commands, see:
        '  DisplayOgpArc
        '  DisplayOgpCircle
        '  DisplayOgpLine
        '  DisplayOgpPolyline

        theUfSession.Disp.DisplayOgpLine(wView.Tag, topLeft, topRight)
        theUfSession.Disp.DisplayOgpLine(wView.Tag, topLeft, botLeft)
        theUfSession.Disp.DisplayOgpLine(wView.Tag, botLeft, botRight)
        theUfSession.Disp.DisplayOgpLine(wView.Tag, topRight, botRight)

    End Sub

    Sub AddComponentLabel(ByVal theComponent As Assemblies.Component,
                          ByVal theDraftingCurve As Drawings.DraftingCurve,
                          ByVal theView As View,
                          ByVal leaderPt As Point3d,
                          ByVal originPt As Point3d,
                          ByVal theText() As String)


        Dim markId1 As NXOpen.Session.UndoMarkId = Nothing
        markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Note")

        Dim nullNXOpen_Annotations_SimpleDraftingAid As NXOpen.Annotations.SimpleDraftingAid = Nothing

        Dim draftingNoteBuilder1 As NXOpen.Annotations.DraftingNoteBuilder = Nothing
        draftingNoteBuilder1 = workPart.Annotations.CreateDraftingNoteBuilder(nullNXOpen_Annotations_SimpleDraftingAid)

        draftingNoteBuilder1.Origin.Anchor = NXOpen.Annotations.OriginBuilder.AlignmentPosition.MidCenter

        draftingNoteBuilder1.Origin.Plane.PlaneMethod = NXOpen.Annotations.PlaneBuilder.PlaneMethodType.XyPlane

        Dim leaderData1 As NXOpen.Annotations.LeaderData = Nothing
        leaderData1 = workPart.Annotations.CreateLeaderData()
        leaderData1.StubSize = theSession.Parts.Work.Annotations.Preferences.GetLineAndArrowPreferences.StubLength
        'leaderData1.Arrowhead = theSession.Parts.Work.Annotations.Preferences.GetLineAndArrowPreferences.FirstArrowType
        'lw.WriteLine("first arrow type: " & theSession.Parts.Work.Annotations.Preferences.GetLineAndArrowPreferences.FirstArrowType.ToString)
        leaderData1.VerticalAttachment = NXOpen.Annotations.LeaderVerticalAttachment.Center
        leaderData1.StubSide = NXOpen.Annotations.LeaderSide.Inferred
        leaderData1.Arrowhead = NXOpen.Annotations.LeaderData.ArrowheadType.ClosedArrow
        draftingNoteBuilder1.Leader.Leaders.Append(leaderData1)

        draftingNoteBuilder1.Text.TextBlock.SetText(theText)

        ' Jog position relocated or jog removed
        leaderData1.Jogs.Clear()

        Dim assocOrigin1 As NXOpen.Annotations.Annotation.AssociativeOriginData = Nothing
        assocOrigin1.OriginType = NXOpen.Annotations.AssociativeOriginType.Drag
        Dim nullNXOpen_View As NXOpen.View = Nothing

        draftingNoteBuilder1.Origin.SetAssociativeOrigin(assocOrigin1)

        draftingNoteBuilder1.Origin.Origin.SetValue(Nothing, nullNXOpen_View, originPt)

        draftingNoteBuilder1.Origin.SetInferRelativeToGeometry(False)

        leaderData1.Leader.SetValue(theDraftingCurve, theView, leaderPt)

        Dim nXObject1 As NXOpen.NXObject = Nothing
        nXObject1 = draftingNoteBuilder1.Commit()

        draftingNoteBuilder1.Destroy()

    End Sub

    Function MakeLabelText(ByVal theComponent As Assemblies.Component) As String()

        Dim labelText As New List(Of String)

        If theComponent.HasUserAttribute("TOOL_ID", NXObject.AttributeType.String, -1) Then
            Dim associativeText1 As Annotations.AssociativeText
            associativeText1 = workPart.Annotations.CreateAssociativeText()

            labelText.Add(associativeText1.GetObjectAttributeText(theComponent, "TOOL_ID"))

            associativeText1.Dispose()
        End If

        If GetComponentAttribute(theComponent, "TOOL_CLASS").ToUpper = "COMM" Then
            Dim associativeText1 As Annotations.AssociativeText
            associativeText1 = workPart.Annotations.CreateAssociativeText()

            labelText.Add(associativeText1.GetObjectAttributeText(theComponent, "DB_PART_NAME"))

            associativeText1.Dispose()

        End If

        Return labelText.ToArray

    End Function

    Function MeasureNoteLength(ByVal theNote As Annotations.Note) As Double

        Dim tempLetteringPref As Annotations.LetteringPreferences
        tempLetteringPref = theNote.GetLetteringPreferences
        tempLetteringPref.AlignmentPosition = Annotations.AlignmentPosition.MidLeft
        theNote.SetLetteringPreferences(tempLetteringPref)

        Dim noteStart As Point3d = theNote.AnnotationOrigin

        tempLetteringPref.AlignmentPosition = Annotations.AlignmentPosition.MidRight
        theNote.SetLetteringPreferences(tempLetteringPref)

        Dim noteEnd As Point3d = theNote.AnnotationOrigin

        theNote.SetLetteringPreferences(tempLetteringPref)

        Return noteEnd.X - noteStart.X

    End Function

    Public Function GetUnloadOption(ByVal dummy As String) As Integer

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

    End Function

End Module
 
Replies continue below

Recommended for you

I had a strong sense of deja vu when I posted the component label code. I was almost sure that I had run into the issue with the leaders not pointing to the correct locations before... Looks like you found it - the ID symbol program.

Check out thread561-457883 for the latest code update.

www.nxjournaling.com
 
I was looking at them and comparing them. It kind of looks like I was on the right track of what it needed and had absolutely no idea how to add it. lol

I have a loooooong road ahead of me with this stuff. [sadeyes]



Thanks Cowski For all the times you have helped me, I cant even imagine how much I would owe if you charged. lol
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor