My First Plug-in Training

Lesson 5: Adding Attributes

In Lesson 4, you created a button on the form to hide selected components in the active Inventor assembly. Along the way you learned how to use Inventor objects along with how to control code execution using “If Then” and “For Next” statements. Instead of directly hiding the selected components, you’ll now modify the code to “tag” your components for later hiding or display. Attaching attributes provided by the Inventor API will allow you to identify and perform different operations on your tagged components.

Provide Feedback: Please provide feedback about this Inventor Training or this lesson via email: myfirstplugin@autodesk.com
Lesson Downloads
lesson5_vb-net.zip (zip - 26Kb)
lesson5_c-sharp.zip (zip - 40Kb)
  1. Open the project from the previous lesson and open the Code Window for Form1.  Or if the plug-in is already running stop it by selecting Stop Debugging on the Debug menu in VB Express. You can also close the plug-in’s form by clicking the x in its upper right corner. If the Designer is active, right click on Form1.vb in the Solution Explorer and select View Code.

    In the For Next loop within the Button1_Click event, you are currently hiding each of the selected components by setting its Visible property to False. Comment out the line of code that sets the Visible property by inserting an apostrophe/single quote (') at the beginning of the line.

           For Each obj In selSet
                compOcc = obj
                Debug.Print(compOcc.Name)
                'compOcc.Visible = False
           Next

  2. There are three Inventor API classes that are used to add an Attribute to entities, one of which is the AttributeSets collection. Add a line of code which uses the Dim statement to declare a variable named attbSets of type AttributeSets. You’ll assign this variable directly to contain the value of your component occurrence’s AttributeSets property.

    Dim attbSets As AttributeSets = compOcc.AttributeSets

  3. You only want to add your attribute once to each tagged component. You can use the NameIsUsed() method of the AttributeSets collection to check whether an AttributeSet of a particular name has already been created.  Add the below code just after the code you added in step 2.


    ' Add the attributes to the ComponentOccurrence
    If Not attbSets.NameIsUsed("myPartGroup") Then
     
    End If

  4. You’ll now create and assign a variable named attbSet of type AttributeSet, once again using the combination of the Dim statement and the equals sign. The string “myPartGroup” specifies the name of the AttributeSet in the AttributeSets collection .  Add this in the body of the If Then statement you created in step 3.


    Dim attbSet As AttributeSet = attbSets.Add("myPartGroup")

  5. The third class you use to add the attribute is the Attribute itself.  You use the Add() method on your AttributeSet to create an Attribute object and add it to the set. You can assign the results of the Add() method directly to a variable named attb of type Inventor.Attribute. This is another case where we specify the Inventor namespace explicitly to prevent a name clash: this time with another Attribute class.


    Dim attb As Inventor.Attribute = _
                 attbSet.Add( _
                   "PartGroup1", ValueTypeEnum.kStringType, "Group1")

  6. Build the project using the Build item on the Debug menu. This will let you know if the project contains any errors: its good practice to build regularly both to fix issues as they get introduced and to save your work.

Use the Watch Window

  1. Place a break point on the line that adds the attribute. You can do this by putting the cursor on the line and then using the F9 key. Another way is to click on the bar to the left of the code window:



  2. Run the project by selecting Start Debugging from the Debug menu (or using the F5 key).



  3. In the Inventor session, select a couple of components and then click the button on your form. Visual Basic Express – and the code window showing this code – should become active when the line that adds the attribute is about to be executed. The execution will stop here, waiting for you to perform some action to advance it.




  4. When execution has been paused via a breakpoint, you can examine the values of the variables in your code using the Watch window. You do this by right-clicking on the variable name and selecting Add Watch.



    You can see in the Watch window that the values for the AttributeSet’s properties include the name you assigned it during the previous line of code.



    To make the code execution proceed, use the Debug pull-down menu and select Continue (or use the F5 key).



  5. Stop debugging by closing the form or selecting Stop Debugging on the Debug menu.

Add Another Button to the Form and use the AttributeManager to get the Components

  1. Let’s now add another button to the form that will make use of the attributes you’ve used to tag your components. Display the Designer by right-clicking on Form1.vb and selecting View Designer (or using the Shift+F7 keys). Display the Toolbox using the View Menu > Other Windows then ToolBox (or using the Ctrl+Alt+X keys). Click and drag to place the button.



  2. By default, the text displayed on the buttons are Button1, Button2 and so on. In most cases you will want to have more descriptive names for them. You can do this by using the Properties Window. You can display the Properties window by right-clicking on the button and selecting Properties. Change the Text property of the button to Hide or Show Group: this changes the text shown inside the button but does not change the internal name of the button.

     

  3. Using the same approach as step 2 and change the text on Button1 to Add to group.

  4. Make the code window active. Double-click on the button in the Designer to switch to the code window and create the click event handler. In Lesson 4, you used dropdowns from the code window to add the Sub Button1_Click event handler: the two approaches have similar results.

  5. When the user clicks on Button2 you want to get the AttributeManager from the active document after making sure the active document is an assembly. You already have some code that does this in the Button1_Click Sub. Copy this code into the Button2_Click Sub.

       If _invApp.Documents.Count = 0 Then
          MsgBox("Need to open an Assembly document")
          Return
        End If
     
        If _invApp.ActiveDocument.DocumentType <> _
             DocumentTypeEnum.kAssemblyDocumentObject Then
          MsgBox("Need to have an Assembly document active")
          Return
        End If
     
        Dim asmDoc As AssemblyDocument
        asmDoc = _invApp.ActiveDocumen

  6. You will now use the AttributeManager to find the various objects tagged with your attribute. To do so, add these lines of code after the code you added in step 5.


    Try
         Dim attbMan As AttributeManager = asmDoc.AttributeManager
     
          Dim objsCol As ObjectCollection
          objsCol = _
            attbMan.FindObjects("myPartGroup", "PartGroup1", "Group1")
     
         Catch ex As Exception
              MsgBox("Problem hiding component")
    End Try

  7. The components that were tagged by the code behind Button1 will be contained in the ObjectCollection after the call to FindObjects. You will now go through each of the items in this collection and toggle their visibility (setting the visible ones to be invisible and the invisible ones to be visible). Do so by adding the below code between the call to FindObjects and the Catch statement added in step 6.

    Dim compOcc As ComponentOccurrence
    For Each obj As Object In objsCol
        compOcc = obj
     ' Toggle the visibility of the Component Occurrence
       compOcc.Visible = Not compOcc.Visible
    Next

  8. Build the project and fix any errors that get reported. You can test (and, if necessary, debug) the project by using the Debug pulldown menu and selecting Start Debugging (or using the F5 key).  Select a couple of components and click Button1 to add the attribute. When you click Button2, the display of the components should toggle between visible and invisible.

A Closer Look at the Code for Button1

As you now know, using the Inventor API you can use custom attribute values to tag entities such as components. You can then use this attribute to find the tagged entities and do something with them. In this example, you used a custom attribute value to locate certain components and then hide or displayed them. There are three Inventor API classes that are used to add an Attribute to entities: AttributeSets, AttributeSet and Attribute. Many types of an Inventor entity – including ComponentOccurrence – have an AttributesSets property. Notice in this example that the name of the variable you used to store the contents of the AttributeSets property is attbSets, a shorthand version of AttributeSets. Any naming convention can be used; however it is helpful if the chosen names are descriptive and consistent with either the type or the purpose of the variable.

Dim attbSets As AttributeSets = compOcc.AttributeSets

As mentioned, the second class you used when adding attributes was AttributeSet. From the name of this class, you can guess that the AttributeSets object is a collection of AttributeSet objects. Each AttributeSet associated with an object needs to have a unique name. If an AttributeSet with the name you want to use has already been added to the component, you should not try to add another with that name. You can use the NameIsUsed() method of the AttributeSets class to check if an AttributeSet with a particular name has already been added to that object. The name of the AttributeSet you created in this example, myPartGroup, is passed into the NameIsUsed() method. The If Not Then statement caused the code between the If and End If to be processed if the name myPartGroup had not already been given to an AttributeSet in the AttributesSets of the component.

' Add the attributes to the ComponentOccurrence
If Not attbSets.NameIsUsed("myPartGroup") Then
 
End If

You used the Add() method of the AttributeSets object to create an AttributeSet. (Remember that you got the AttributeSets property from the component). The AttributeSets.Add() method took a String that will be the name of the AttributeSet. There you are using the name myPartGroup, which needed to be passed in as a string of characters. To create a String, you simply need to enclose the text – the contents of the string – in double quotes. It is a good idea to use a descriptive value in this string, which will essentially be the name of your AttributeSet. You also used this text to test for the existence of your AttributeSet via the NameIsUsed method.

     Dim attbSet As AttributeSet = attbSets.Add("myPartGroup")

The third object you needed to add to the attribute is the Attribute itself. You used the Add() method of the AttributeSet to create the Attribute.

Dim attb As Inventor.Attribute = _
             attbSet.Add( _
               "PartGroup1", ValueTypeEnum.kStringType, "Group1")
The AttributeSet.Add() method took three arguments. Notice how IntelliSense is very helpful for knowing the types of the various arguments:

The first argument was a String, the name of the Attribute. The second argument specified the type of the attribute value and was one of the types listed in Inventor.ValueTypeEnum. The third argument was the value itself, which needed to be of the type specified by the second argument.

A Closer Look at the Code for Button2

The code in Button2 searched for entities tagged with the attributes added by the code behind Button1: it used the FindObjects() method of the AttributeManager, which you accessed via the assembly document (asmDoc) and assigned to a variable (attbMan). To catch any errors you enclosed these operations in a Try Catch block.

Try
     Dim attbMan As AttributeManager = asmDoc.AttributeManager
 
      Dim objsCol As ObjectCollection
      objsCol = _
        attbMan.FindObjects("myPartGroup", "PartGroup1", "Group1")
 
     Catch ex As Exception
          MsgBox("Problem hiding component")
End Try

The FindObjects() method populated an ObjectCollection with each of the objects it found with your custom attribute attached. FindObjects() took three arguments to locate objects (Inventor entities) with attributes. Although you used all three arguments in your project – to look for attributes with a specific AttributeSetName, AttributeName and AttributeValue – they were all not required: in other situations you might have chosen to look only for attributes belonging to a set with a particular name, for instance.  In this example you passed in “myPartGroup” (as the AttributeSetName), “PartGroup1” (as the AttributeName) and “Group1” (as the AttributeValue). IntelliSense, as we see below, helps us understand the meaning of the arguments to the FindObjects() method. Notice the square brackets, which indicate that each of the arguments is optional.

You should now have the tagged components in the ObjectCollection returned by the call to FindObjects. To hide or show the components you needed to loop through each object in the collection and change its Visible property. The natural way to loop through a collection is using a “For Each Next” loop: other types of loop would also work, but would require you to maintain a counter which acts as an index into the collection to select items from it. For Each Next loops provided us with the current object in the collection at each pass through the code.

The next line is very simple: you are toggling the Visible property of each ComponentOccurrence object: if the value is True it gets set to False and if it’s False it gets set to True. The Not operator let us do this very succinctly, without the need for an If Then Else conditional statement.

Dim compOcc As ComponentOccurrence
For Each obj As Object In objsCol
     compOcc = obj
     ' Toggle the visibility of the Component Occurrence
     compOcc.Visible = Not compOcc.Visible
Next

This wraps up the coding part of Lesson 5.