Rule to create view reps

Rule to create view reps

Shag_Bore
Advocate Advocate
339 Views
2 Replies
Message 1 of 3

Rule to create view reps

Shag_Bore
Advocate
Advocate

Hello All,

 

I have been working on this rule and it works for the most part. there is one spot that I am hung up on. I lost the links but this is concatenated from a bunch of previous posts on this forum. The rule is setup to:


-create view rep for each unique part in the assembly (filter out the phantom parts)

 

-scan each part for the custom iproperty "PART DESCRIPTION", if one exists then name the view rep that, if not then name the view rep the same as the part file name

 

-scan each part for the custom iproperty "CATEGORY", if the iprop exist, group the parts that share the same "CATEGORY" value (ex. WELDMENT), create and name the new view rep WELDMENT.  there will be maybe 6 different "CATEGORY" groups eventually. 

 

The first two sections work perfectly, and the third section partially works, the rule runs and creates the "CATEGORY" view rep, but there is only one visible part in the view rep, there should be more visible parts. I have tripled checked that the custom iprop does exist in the part files. 

 

Any ideas? thanks!

 

' Define current document
Dim openDoc As Document
openDoc = ThisDoc.Document

Dim oTrans As Transaction
oTrans = ThisApplication.TransactionManager.StartTransaction(openDoc, "Create View Rep's")

On Error Goto ErrorHandler

' Set a reference to the assembly component definition.
' This assumes an assembly document is open.
Dim oAsmCompDef As AssemblyComponentDefinition
oAsmCompDef = ThisApplication.ActiveDocument.ComponentDefinition

' Look at all of the components in the assembly
Dim oCompDef As Inventor.ComponentDefinition
oCompDef = openDoc.ComponentDefinition

' Define the first level components collection
Dim oCompOcc As Inventor.ComponentOccurrence

' Define view rep 
Dim oViewRep As DesignViewRepresentation

' Define an arraylist to hold the list of view rep names
Dim NameList As New Collection

' Look at the view reps in the assembly
For Each oViewRep In oAsmCompDef.RepresentationsManager.DesignViewRepresentations
    ' Set the list of names to the array list
    NameList.Add (oViewRep.Name)
Next

' Check for a Default view rep and create it if not found
If Not NameList.Contains("FULL ASSEMBLY") Then
    ' Create Default view rep 
    oViewRep = oAsmCompDef.RepresentationsManager.DesignViewRepresentations.Add("FULL ASSEMBLY")
    oViewRep.ShowAll
    oViewRep.Activate
End If

' Zoom all
ThisApplication.CommandManager.ControlDefinitions.Item("AppIsometricViewCmd").Execute

' Dictionary to store parts by category
Dim CategoryParts As Object
CategoryParts = CreateObject("Scripting.Dictionary")

' Look at all of the unique parts in the assembly
For Each docFile In openDoc.AllReferencedDocuments
    If oCompDef.Occurrences.AllReferencedOccurrences(docFile).Count > 0 Then ' Avoid to create a view rep for base part of derived parts
        If Not docFile.ComponentDefinition.BOMStructure = BOMStructureEnum.kPhantomBOMStructure Then
            If docFile.DocumentType = 12290 Then ' 12290 is the part document enumerator
                ' Locate the last backslash position in the full file name
                Dim FNamePos As Long
                FNamePos = InStrRev(docFile.FullFileName, "\", -1)
                ' Remove path from part file name     
                Dim docFName As String
                docFName = Right(docFile.FullFileName, Len(docFile.FullFileName) - FNamePos)
                ' Remove extension from part file name 
                Dim ShortName As String
                ShortName = Left(docFName, Len(docFName) - 4)

                ' Check for the custom iProperty "PART DESCRIPTION"
                Dim partDescription As String
                partDescription = ""
                On Error Resume Next
                partDescription = docFile.PropertySets.Item("Inventor User Defined Properties").Item("PART DESCRIPTION").Value
                On Error Goto 0

                ' Determine view representation name
                Dim viewRepName As String
                If partDescription <> "" Then
                    viewRepName = partDescription
                Else
                    viewRepName = ShortName
                End If

                ' Check to see if the arraylist contains the desired view rep
                If Not NameList.Contains(viewRepName) Then
                    ' Create new View Rep 
                    oViewRep = oAsmCompDef.RepresentationsManager.DesignViewRepresentations.Add(viewRepName)
                    oViewRep.Activate
                    oViewRep.Locked = False
                Else
                    ' Reference existing View Rep 
                    oViewRep = oAsmCompDef.RepresentationsManager.DesignViewRepresentations.Item(viewRepName)
                    oViewRep.Activate
                    oViewRep.Locked = False
                End If

                Dim bSkip As Boolean
                bSkip = False
                ' Look at all of the occurrences
                For Each oCompOcc In oCompDef.Occurrences.AllLeafOccurrences
                    ' Locate the colon position in the occurrence name
                    Dim oCompOccPos As Long
                    oCompOccPos = InStrRev(oCompOcc.Name, ":")
                    If oCompOccPos < 2 Then oCompOccPos = Len(oCompOcc.Name)
                    ' Set occurrence name to everything left of the colon
                    Dim oOccName As String
                    oOccName = Left(oCompOcc.Name, oCompOccPos - 1)
                    ' Set visible if name matches first occurrence
                    If System.IO.Path.GetFileNameWithoutExtension(oCompOcc.ReferencedDocumentDescriptor.ReferencedFileDescriptor.FullFileName) = ShortName And bSkip = False Then
                        oCompOcc.Visible = True
                        ThisApplication.ActiveView.Update
                        bSkip = True ' Even if there is more than one occurrence named "xyz:1" in different sub-assemblies, we want only one occurrence in our view rep
                    Else
                        oCompOcc.Visible = False
                        ThisApplication.ActiveView.Update
                    End If
                Next

                ' Lock view rep
                oViewRep.Locked = True

                ' Check for the custom iProperty "CATEGORY"
                Dim category As String
                category = ""
                On Error Resume Next
                category = docFile.PropertySets.Item("Inventor User Defined Properties").Item("CATEGORY").Value
                On Error Goto 0

                ' Add part to the corresponding category list
                If category <> "" Then
                    If Not CategoryParts.Exists(category) Then
                        CategoryParts.Add (category, New Collection)
                    End If
                    CategoryParts(category).Add (docFile)
                End If
            End If
        End If
    End If
Next

' Create view representations for each category
For Each category In CategoryParts.Keys
    ' Check to see if the arraylist contains the desired view rep
    If Not NameList.Contains(category) Then
        ' Create new View Rep 
        oViewRep = oAsmCompDef.RepresentationsManager.DesignViewRepresentations.Add(category)
        oViewRep.Activate
        oViewRep.Locked = False
    Else
        ' Reference existing View Rep 
        oViewRep = oAsmCompDef.RepresentationsManager.DesignViewRepresentations.Item(category)
        oViewRep.Activate
        oViewRep.Locked = False
    End If

    ' Set visibility for parts in the category
    For Each docFile In CategoryParts(category)
        Dim bSkip As Boolean
        bSkip = False
        For Each oCompOcc In oCompDef.Occurrences.AllLeafOccurrences
            ' Locate the colon position in the occurrence name
            Dim oCompOccPos As Long
            oCompOccPos = InStrRev(oCompOcc.Name, ":")
            If oCompOccPos < 2 Then oCompOccPos = Len(oCompOcc.Name)
            ' Set occurrence name to everything left of the colon
            Dim oOccName As String
            oOccName = Left(oCompOcc.Name, oCompOccPos - 1)
            ' Set visible if name matches first occurrence
            If System.IO.Path.GetFileNameWithoutExtension(oCompOcc.ReferencedDocumentDescriptor.ReferencedFileDescriptor.FullFileName) = _
                    System.IO.Path.GetFileNameWithoutExtension(docFile.FullFileName) And bSkip = False Then
                oCompOcc.Visible = True
                ThisApplication.ActiveView.Update
                bSkip = True ' Even if there is more than one occurrence named "xyz:1" in different sub-assemblies, we want only one occurrence in our view rep
            Else
                oCompOcc.Visible = False
                ThisApplication.ActiveView.Update
            End If
        Next
    Next

    ' Lock view rep
    oViewRep.Locked = True
Next

' Set Default View Rep active
oAsmCompDef.RepresentationsManager.DesignViewRepresentations.Item("FULL ASSEMBLY").Activate

oTrans.End
Exit Sub

ErrorHandler:
MsgBox (Err.Description)
oTrans.Abort
Sean Farr
Product Designer at Teksign Inc.
Inventor 2016 SP1
Dell Precision 3660
i7-12700 @ 2.40GHz-4.90GHz
32GB DDR5 4400MHz RAM
NIVDIA RTX A2000 6GB
0 Likes
340 Views
2 Replies
Replies (2)
Message 2 of 3

A.Acheson
Mentor
Mentor

Hi @Shag_Bore 

I quickly reviewed the code and couldn't really see the issue, so I can only offer a little advice having done this process before. 

  • If you have narrowed your problem area set up some logger statements and check the occurrence name is being logically reached based on needing to be visible or not.
  • I would suggest to use Try Catch Statements over On Error Resume Next. You really have no indication of what is happening with the On Error methods.
  • I see two leaf occurrences loops are they both needed or could you put it in a function or to store the occurrences as a list of occurrences? 
  • i see you create weekly typed Collections rather than to explicitly declare the type. Example for string. this can help narrow down issues if the wrong object type gets added into the collection. 
Dim list as New List  (Of String)

Dim occList as New List  (Of ComponentOccurrence)

 

  • If this section of code is designed to get the filename without extension  then I would suggest to change it to System IO method as it has less lines. The method here looks more like old VBA methods. 
' Locate the last backslash position in the full file name
                Dim FNamePos As Long
                FNamePos = InStrRev(docFile.FullFileName, "\", -1)
                ' Remove path from part file name     
                Dim docFName As String
                docFName = Right(docFile.FullFileName, Len(docFile.FullFileName) - FNamePos)
                ' Remove extension from part file name 
                Dim ShortName As String
                ShortName = Left(docFName, Len(docFName) - 4)

 

You actually use it further down the code.

ShortName = System.IO.Path.GetFileNameWithoutExtension(oCompOcc.ReferencedDocumentDescriptor.ReferencedFileDescriptor.FullFileName)

 

 

  • In this section there is a good lot of code duplication with the same definition variables used in different places all the way through the code. It will work but it could lead to issues identifying what is going on especially when trying to target sub assemblies etc. 
' Define current document
Dim openDoc As Document
openDoc = ThisDoc.Document

Dim oTrans As Transaction
oTrans = ThisApplication.TransactionManager.StartTransaction(openDoc, "Create View Rep's")

On Error Goto ErrorHandler

' Set a reference to the assembly component definition.
' This assumes an assembly document is open.
Dim oAsmCompDef As AssemblyComponentDefinition
oAsmCompDef = ThisApplication.ActiveDocument.ComponentDefinition

' Look at all of the components in the assembly
Dim oCompDef As Inventor.ComponentDefinition
oCompDef = openDoc.ComponentDefinition

 

If this solved a problem, please click (accept) as solution.‌‌‌‌
Or if this helped you, please, click (like)‌‌
Regards
Alan
0 Likes
Message 3 of 3

nstevelmans
Advocate
Advocate

Hi, try this code it has a recursive function so it will find every Occurrence in the assembly tree.

 

Sub main
	 Dim CATEGORYVALUE As String = "ex.WELDMENT"
        ' Get the active assembly.
        Dim oAsmDoc As AssemblyDocument = ThisApplication.ActiveDocument
        Dim oAssyCompdef As ComponentDefinition = oAsmDoc.ComponentDefinition
        Dim ViewRep As DesignViewRepresentation = SetDesignview(oAssyCompdef, CATEGORYVALUE)

        ' Call the function that does the recursion.
        TraverseAssembly(oAsmDoc.ComponentDefinition.Occurrences, 1, CATEGORYVALUE)

        ViewRep.Locked = True
	
End Sub


Private Sub TraverseAssembly(Occurrences As ComponentOccurrences, Level As Integer, PropValue As String)
        ' Iterate through all of the occurrence in this collection.  This
        ' represents the occurrences at the top level of an assembly.
        Dim oOcc As ComponentOccurrence
        Dim value As String = Nothing
        For Each oOcc In Occurrences
            ' Print the name of the current occurrence.
            Dim oCompdef As ComponentDefinition = oOcc.Definition
            Dim oDoc As Document = oCompdef.Document
            Dim oCustomprop As Inventor.Property = Getproperty(oDoc, "CATEGORY")
            oOcc.Visible = False
            If oCustomprop IsNot Nothing Then
                If oCustomprop.Value = PropValue Then
                    oOcc.Visible = True
                End If
            End If
            ' Check to see if this occurrence represents a subassembly
            ' and recursively call this function to traverse through it.
            If oOcc.DefinitionDocumentType = DocumentTypeEnum.kAssemblyDocumentObject Then
                TraverseAssembly(oOcc.SubOccurrences, Level + 1, PropValue)
            End If
        Next
    End Sub

Private Function Getproperty(ByVal oDoc As Document, ByVal Prop As String)
        Dim result As Inventor.Property = Nothing
        Try
            Dim oPropertyset As PropertySet = oDoc.PropertySets("Inventor User Defined Properties")
            Dim oProperty As Inventor.Property = Nothing
            Try
                oProperty = oPropertyset.Item(Prop)
            Catch ex As Exception
            End Try
            result = oProperty
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical, "Getproperty")
        End Try
        Return result
    End Function
	
	 Private Function SetDesignview(ByVal oAssyCompDef As AssemblyComponentDefinition, ViewRepName As String) As DesignViewRepresentation
        Dim result As DesignViewRepresentation = Nothing
        Dim ViewRep As DesignViewRepresentation = Nothing
        Dim ViewReps As DesignViewRepresentations = oAssyCompDef.RepresentationsManager.DesignViewRepresentations
        Try
            Dim ViewRepExist As Boolean = False
            For Each ViewRep In ViewReps
                If ViewRep.Name = ViewRepName Then
                    ViewRep.Activate()
                    ViewRepExist = True
                    Exit For
                End If
            Next
            If ViewRepExist = False Then
                ViewRep = oAssyCompDef.RepresentationsManager.DesignViewRepresentations.Add(ViewRepName)
                ViewRep.Activate()
            End If
        Catch ex As Exception
        End Try
        result = ViewRep
        Return result
    End Function
	
	

 

0 Likes