Here is section two of the Inventor API training where you see how the API is used to create and access Inventor documents. This section also covers iProperties, working with units, and parameters. This is the third post with the Inventor API training material. (Section one is here).
Common Document Functionalities
Here is the agenda for this section. Be sure to see the Lab instructions at the end of this section. (completed samples in VB.NET and C# are available)
Document Types
Working with Documents
Document Settings
iProperties
Units of Measure
Parameters
Document Types
Inventor has unique document types for different types of data.
Part Documents (*.ipt)
Assembly Documents (*.iam)
Drawing Documents (*.idw)
Presentation Documents (*.ipn)
The API represents each document type using a different type of object for each type of document.
Accessing Documents
Documents.Add()
To create a new document use the Add method of the Documents collection. This method takes a DocumentTypeEnum which determines which type of document to create. (first argument) You can have a file that you can use as a template. To use that file, you provide a string that is a path to the file. (second argument). The third argument of the Add method is a boolean that determines if the file is opened visible or not. The GetTemplateFile method of the FileManager object allows you to use the default template and change settings for the file that is being created. (You can use this for the second argument of the Add method)
Documents.Open()
The Open method of the documents collection will open existing documents. The first argument is a string with the file path of the document and the second is a boolean that controls the visibility.
Documents.Item()
You use the Item property to access currently open documents. The ActiveDocument property of the Application will get you the current document.
Opening and Creating Documents VB.NET examples
'Opens an existing document.assume part1.ipt exists
Public Sub OpenDoc()
Dim oDoc As Document
oDoc = _InvApplication.Documents.Open _
("C:\Temp\Part1.ipt")
End Sub
'Creates a new document using a specified template.
Public Sub CreateDoc()
Dim oDoc As PartDocument
oDoc = _InvApplication.Documents.Add _
(DocumentTypeEnum.kPartDocumentObject, _
_InvApplication.FileManager.GetTemplateFile _
(DocumentTypeEnum.kPartDocumentObject), True)
End Sub
'Creates a new document using internally
'defined template. (Can be done in the UI by
'using Ctrl-Shift when creating new document.)
Public Sub CreateDoc2()
Dim oDoc As PartDocument
oDoc = _InvApplication.Documents.Add _
(DocumentTypeEnum.kPartDocumentObject, , True)
End Sub
Saving Documents
The first time a new document is saved you should use the SaveAs method with the SaveCopyAs flag set to False.
Dim oDoc As PartDocument
oDoc = _InvApplication.Documents.Add _
(DocumentTypeEnum.kPartDocumentObject)
oDoc.SaveAs("C:\Temp\SaveTest.ipt", False)
For documents that have been saved to disk you can use the Save method or the SaveAs with the SaveCopyAs flag set to True to create a copy. An error will occur if the file name parameter is the same as the open document. (keep in mind that the method will overwrite existing files).
oDoc.Save()
oDoc.SaveAs("C:\Temp\SaveTest2.ipt", True)
You can use the FileSaveCounter property of the document to determine if the document has been saved.
Closing Documents
To close a document call the Close method. You can use the SkipSave parameter to close it without saving.
Document.Close([SkipSave As Boolean = False])
Using the SkipSave argument you can bypass the dialog asking to save the changes and force the document to close without saving. This is useful in cases where you use a file as a template by opening the file, modifying it in some way, and using SaveCopyAs to save it as a new file. Using this you can close the original without saving and without forcing the user to interact with a dialog.
The API has a way to close all documents. Using this method will not save any changes to documents.
Documents.CloseAll([UnreferencedOnly As Boolean = False])
Document Settings
Document settings are exposed from various objects obtained from the document.
In this excerpt from the object model diagram you can see the objects that will allow you to get and update document settings. Notice that these objects are accessed by using properties of the document.
iProperties
iProperties in the User Interface
iProperties are used to associate information with a document. There are a predefined set of properties are available through the iProperties dialog. End-users can create additional properties using the “Custom” tab of the iProperties dialog. These properties are supported by both Inventor and Apprentice.
iProperties – Property Sets
The PropertySets object acts as the container for all of the properties.
The PropertySets object provides access to the individual PropertySet objects using the Item property.
iProperties – Property Set
The PropertySet object contains a group of properties.
Most PropertySet objects roughly correspond to the tabs in the iProperties dialog. PropertySet objects are identified by the following:
InternalName (consistent)
Name (consistent)
DisplayName (may change)
iProperties - Property
Properties are named values and they are identified by:
ID (consistent)
Name (consistent)
DisplayName (may change)
Property values
Property values are stored internally as Variants. The following types are supported: Integer, Long, Double, String, Date, and Boolean. (With the exception of the thumbnail image which is IPictureDisp.)
PropId’s are defined in the various property related enums.
iProperty Names
Name and Internal Name of Inventor defined property sets:
Inventor Summary Information
{F29F85E0-4FF9-1068-AB91-08002B27B3D9}
Inventor Document Summary Information
{D5CDD502-2E9C-101B-9397-08002B2CF9AE}
Design Tracking Properties
{32853F0F-3444-11D1-9E93-0060B03C1CA6}
Inventor User Defined Properties
{D5CDD505-2E9C-101B-9397-08002B2CF9AE}
InternalNames can be found using the Object Browser and in SDK\Include\PropFMTIDs.h
VB.NET Example of changing an iProperty
' Access "Design Tracking Properties"
' "Designer" and change its value
Public Sub iPropAccess()
Dim oDoc As Document
oDoc = _InvApplication.ActiveDocument
' Access a particular property set.
' Design tracking property set.
Dim oDTProps As PropertySet
oDTProps = oDoc.PropertySets.Item _
("{32853F0F-3444-11d1-9E93-0060B03C1CA6}")
' Access the same property set using
' the display name or name.
' DisplayName is not dependable
' because it can be localized, so
'the internal name or name is preferred.
oDTProps = oDoc.PropertySets.Item _
("Design Tracking Properties")
' Get a specific property, in this case
' the designer property.
Dim oDesignerProp As Inventor.Property
oDesignerProp = oDTProps.ItemByPropId( _
PropertiesForDesignTrackingPropertiesEnum _
.kDesignerDesignTrackingProperties)
' You can also use the name or display name
' the display name has the problem that
' it can be changed.
oDesignerProp = oDTProps.Item("Designer")
' Show the display name and value.
Debug.Print(oDesignerProp.DisplayName _
& " = " & oDesignerProp.Value)
' Change the designer name.
oDesignerProp.Value = "Bill & Ted"
End Sub
iProperties - Creation
To create new property set use the Add method of the PropertySets collection. (Name and InternalName must be unique with respect to other property sets in the document).
PropertySets.Add(Name As String, [InternalName]) As PropertySet
To create and add new properties to the PropertySet use the Add method. Keep in mind that properties cannot be added to the predefined sets, except for the custom property set. Also the
name and PropId must be unique with respect to other properties in the property set. The value type can be most Variant types except arrays and objects.
PropertySet.Add(PropValue, [Name], [PropId]) As Property
Note: PropertySets and Properties can be created as hidden by using a name that begins with an underscore. These will not be returned by indexing through a collection. They can only be retrieved by asking for them by name.
Units of Measure
When you use Inventor manually there is a setting that controls the units that are used. When using the API numbers are always in the same internal units and your code needs to convert between units to get the correct behavior. (unless the document settings are using the same internal units).
All Inventor documents use these internal units.
Length: Centimeters
Angle: Radians
Time: Second
Mass: Kilogram
The units specified by the end-user in the Document Settings dialog are used to convert internal units to/from the units the end-user wants to use.
UnitsOfMeasure object
The UnitsOfMeasure object allows you to work with different units. It provides utilities to help with unit handling, primarily the conversion between strings and values. If you are working with numbers you will most likely need to use UnitsOfMeasure to get the results you expect.
A unique UnitsOfMeasure object can be obtained from each document. The UnitsOfMeasure object obtained from a document can be used for unit conversion and also provides a way to control unit settings for the document. The UnitsOfMeasure obtained from the Application object can be used for unit conversion.
Units of Measure - Unit Types
Whenever a unit type is specified within the API, it can be defined in two different ways:
1. As a value from UnitsTypeEnum with a specific unit type such as:
kInchLengthUnits, kMillimeterLengthUnits, kDegreeAngleUnits.
The current default type specified by the end-user: kDefaultDisplayLengthUnits, kDefaultDisplayAngleUnits.
The internal base units: kDatabaseLengthUnits, kDatabaseAngleUnits.
2. As a string, i.e. “in”, “mm mm mm”, “m ^ 3”, “m /(s s)”
Units of Measure – Internal Units
Internally, Inventor uses a consistent set of units regardless of what the user has specified as the document default and the precision is always double-precision floating point,
Internal units used by Inventor for the various types of units
VB.NET - UnitsOfMeasure to get valid input from the user
Private m_oUOM As UnitsOfMeasure
Private Sub UserForm_Initialize()
' get the UnitsOfMeasure of the
' current document
m_oUOM = _InvApplication.
ActiveDocument.UnitsOfMeasure
End Sub
Private Sub TextBox1_Change()
' Check if the input string defines
'a valid length.
If Not m_oUOM.IsExpressionValid _
(TextBox1.Text, _
UnitsTypeEnum.kDefaultDisplayLengthUnits) Then
' The string is not valid so change
' the text color to red.
TextBox1.ForeColor =
Drawing.Color.Red
Else
' The string is valid so change
'the text color to the default color.
TextBox1.ForeColor =
Drawing.Color.Black
End If
End Sub
VB.NET – UnitsOfMeasure - Using user Input
' Get the real value of the input string.
Dim dValue As Double
dValue = m_oUOM.GetValueFromExpression _
(txtInput.Text, _
UnitsTypeEnum.kDefaultDisplayLengthUnits)
' Compare the value with the length of
' a sketch line.
If System.Math.Abs)
(oSketchLine.Length - dValue)_ < 0.00001 Then
MsgBox _
("Line is equal to the input value")
Else
MsgBox _
("Line is not equal to the input value")
End If
VB.NET UnitsOfMeasure - Displaying Values
In this example a double (centimeters) is passed into a function that gets the value of the double in the units that are current and returns it as a string.
Private Sub TestLength()
ShowLength(6.5)
End Sub
Private Sub ShowLength(ByVal dLength As Double)
' Get the string representation of the length.
Dim strLength As String
strLength = m_oUOM.GetStringFromValue _
(dLength, _
UnitsTypeEnum.kDefaultDisplayLengthUnits)
MsgBox("The Length is: " & strLength)
End Sub
Parameters
Component Definition
The Component definition will be discussed in following lessons. However we need to introduce it here because parameters are obtained form properties of the component definition. This excerpt from the Object Model diagram shows the property that will allow you to get the Component Definition of a document. (Drawings don’t have a ComponentDefinition).
Parameters - In the User Interface
Parameters – In the API
Notice how the Parameters collection is obtained from a PartComponentDefinition or AssemblyComponentDefinition
In this VB.NET code snippet the Parameters are accessed.
' Get the Parameters collection object.
Dim oParameters As Parameters = _
_InvApplication.ActiveDocument.
ComponentDefinition.Parameters
Parameters – UI vs. API
On the left in this picture you can see settings from the parameters dialog. The text on the right shows how a similar setting would be made using the API.
VB.NET - Parameters - Setting Values
Public Sub SetParameter()
' Get the Parameters object. Assumes
'a part or assembly document is active.
Dim oParameters As Parameters
oParameters = _InvApplication.
ActiveDocument.ComponentDefinition.Parameters
' Get the parameter named "Length".
Dim oLengthParam As Parameter
oLengthParam = oParameters.Item _
("Length")
' Change the equation of the parameter.
oLengthParam.Expression = "3.5 in"
' Update the document.
_InvApplication.ActiveDocument.Update()
End Sub
Parameters – Units
The Unit property can be set using either a String or a value from UnitsTypeEnum. This enum is an API equivalent to the pre-defined unit types displayed in the Unit Type dialog.
Setting the unit type using a String is the same as defining a unit in the Unit Type dialog and allows you to define custom unit types by combining known unit types.
Parameters – Values
Unlike in the user-interface, the API allows you to directly set the value of a parameter. The Value property sets the actual value of the parameter and will overwrite any existing equation.
Note: In API, Parameter values are always defined using internal units. (use UnitsOfMeasure to convert)
Length – Centimeters
Angle – Radians
π radians = 180 degrees
π = Atn(1) * 4
Parameters - Tolerances
Tolerances can be defined for Model parameters. The Tolerance object exposes functionalities of the Tolerance dialog.
The SetToDefault, SetToDeviation, SetToLimits, etc… methods of the Parameter object allow you to define the parameter’s tolerance.
Call oParam.Tolerance.SetToDeviation("0.125 in", “-0.0625 in")
Call oParam.Tolerance.SetToDeviation(2.54 / 8, -2.54 / 16)
The ModelValueType property sets which tolerance to use when computing the model value.The Precision property sets the number of decimal places to display.
The SetAllToMax, SetAllToMedian, SetAllToMin, SetAllToNominal methods of the Parameters object provides the equivalent of the Parameter dialog’s “Reset Tolerance”.
Parameters – Parameter Types
The Parameters collection returns all Parameter objects regardless of the type. The ModelParameters, ParameterTables, ReferenceParameters, and UserParameters objects provide access to specific types of parameters.
Parameters – Parameter Creation
Parameters are created by using methods on the collection for the specific type of parameter you want to create. In the user-interface you can only create user parameters. All other types are indirectly created as a result of other actions. In the API you can directly create user, model, and reference parameters. TableParameters are created by importing an Excel worksheet. Parameters are created using either the AddByExpression or AddByValue methods
VB.NET - Creating Parameters
' add user parameters
Dim oUserParams As UserParameters
oUserParams = oCompDef.Parameters.
UserParameters
Dim oParam As Parameter
oParam = oUserParams.AddByExpression _
("NewParam1", "3", _
UnitsTypeEnum.kInchLengthUnits)
oParam = oUserParams.AddByExpression _
("NewParam1", "3", "in")
oParam = oUserParams.AddByExpression _
("NewParam2", "3", _
UnitsTypeEnum.kDefaultDisplayLengthUnits)
oParam = oUserParams.AddByExpression _
("NewParam2", "3 in", _
UnitsTypeEnum.kDefaultDisplayLengthUnits)
oParam = oUserParams.AddByValue _
("NewParam3", 3 * 2.54, _
UnitsTypeEnum.kDefaultDisplayLengthUnits)
Parameters – API Only Functionality
Creation of Model and Reference parameters.
Delete unused Model and Referenced Parameters.
DisabledActionTypes – Prohibit deletion of user parameters.
Dependents, DrivenBy – Provides dependency information between parameters.
Creation of custom parameter groups.
Change the type of a parameter.
Model to Reference
Reference to Model
User to Model
User to Reference
Lab: iProperties
Write a .Net program that performs the following steps:
1. Create a new part document.
2. Edit the value of the author property to contain your name.
3. Create a new custom (user-defined) property
4. Save the document
5. Close the document.
Lab: Parameters and UOM
1. Interactively create a simple part that contains a parameter named “Length” to control the size of the part.
2. Create a .Net program that contains a dialog that looks similar to this:
3. The end-user should have created a parameter named “Length” which is a numeric. By this code, he is able to enter any valid expression. The text field should provide feedback when an invalid expression has been defined.
4. When the “Update” button is pressed the entered value should be assigned to the parameter
Here are examples of the completed Labs. (VB.NET and C#) It also contains the ppt we use for the training and another project with some sample code.
Download Inventor_Training_Module_02_Samples
-Wayne