Showing posts with label VisualBasic API. Show all posts
Showing posts with label VisualBasic API. Show all posts

Thursday, September 18, 2014

Inserting a UDF (User Defined Feature) programatically in CREO by using a VB Application

In this example we are to use the box of the last exercise, be sure this box has minimum 300mm length, 100mm Depth and 150mm height (or larger for the 3 dimensions)
The UDF we are to create will ask for the user to select a coordinate System  on a surface, and also the user can enter the X and Y distance to this coordinate system. The Reference coordinate system should have the Z vector pointing out normal to the surface. Follow next steps for creating the UDF.
Create a reference coordinate system for the UDF (This CS will not be included in the UDF


Orient with Z axis pointing normal to the surface, X lengthwise and Y crosswise

Create another coordinate system (This CS WILL be included in the UDF definition) referenced on the previous CS and with the offset shown in the image below (20 in X direction and 20 in Y direction)

Now let’s proceed with the creation of the hole feature; select extrude

Select the ‘placement’ tab

Click on ‘Define…’ button

Click on plane textbox

Now we are to create “on the fly” references, click in Model Tab and in “Plane”, as is shown in the image below

Select Z and 0 as the offset direction and dimension, click okay

Now repeat the process for the refernce datum plane, click the “Reference” textbox

And again select Datum plane and click on the CS Select X and 0 as the offset direction and dimension, click okay

Select in the “sketch” dialog box, Right orientation for the reference datum plane and click okay,

Now select the CS as the reference, delete all other references

Make a circle as shown below, the center is constrained in the reference, click okay

Make the extrude a cut and “trough all” option for the depth as shown below, click okay to the extrude creation

Now select the “Tools tab” and “UDF Library”

Next dialog box menu appears in the right top corner

Select “create” and type “Hole01” for the UDF name and click okay


Select Stand alone

And click ‘NO’ to the dialog box asking for including the reference part

Next dialog box appears asking for adding features

Select in the model tree the Coordinate system and the extrude (The last 2 created features)

Click okay and done, then for the prompts type “Reference Coordinate System”

Go to the ‘Var Dims’ Option in the UDF definition dialog and select the Coordinate Sytem (CS1 in this example), all dimensions highlight as shown in the image below

Select the X and Y dimensions that position the CS (CS1) in the surface

The prompt for the values will be X Dimension an Y dimension as shown below, click okay and the definition of our UDF is ready.

Insert the UDF
For testing the previous definition, let’s insert the UDF we have already created.
Select the User-Defined Feature command in the Model tab as shown below

Next dialog box will appear, be sure all options are set as in the image (Advanced reference configuration), and click okay

Next dialog box appears, click on the ‘Reference otf the UDF Features’ textbox, and select the reference coordinate system, remember that the z axis of the CS should be normal to the surface where hol will be inserted, in this case select CS0 as the reference, next picture shows it

Click on the variables tab of the dialog box and type 60 for X dimension and 0 for Y dimension as in next picture and click okay.

The UDF is working so the screen should look similar to this image

Now let’s do this automatically from a VB application
By using MS Visual Studio, add text boxes to the form as is shown below, set the default values also

Create a new class and name it as: “Public Class pfcFeaturesExamples” as shown below


Imports pfcls

Public Class pfcFeaturesExamples
    'Create Hole UDF In Part
    '======================================================================
    'Function   :   createHoleUDFInPart
    'Purpose    :   This function places copies of a node UDF at a
    '               particular coordinate system location in a part. The
    '               node UDF is a cylinder cut centered at the coordinate
    '               system whose diameter is driven by the argument to the
    '               method. The method returns the Feature Group object
    '               created.   
    '======================================================================
    Public Function createHoleUDFInPart(ByVal placementModel As IpfcSolid, _
                                        ByVal Name01 As String, _
                                        ByVal csysName As String, _
                                        ByVal Dim1 As Double, _
                                        ByVal Dim2 As Double) _
                                        As IpfcFeatureGroup

        Dim csys As IpfcCoordSystem = Nothing
        Dim cSystems As IpfcModelItems
        Dim i As Integer
        Dim udfInstructions As IpfcUDFCustomCreateInstructions
        Dim csysSelection As IpfcSelection
        Dim csysReference As IpfcUDFReference
        Dim references As CpfcUDFReferences
        Dim variantDims As IpfcUDFVariantDimension
        Dim variantDims2 As IpfcUDFVariantDimension
        Dim variantVals As IpfcUDFVariantValues
        Dim group As IpfcFeatureGroup

        Try

            cSystems = placementModel.ListItems(EpfcModelItemType.EpfcITEM_COORD_SYS)

            For i = 0 To cSystems.Count - 1
                If (cSystems.Item(i).GetName.ToString = csysName) Then
                    csys = cSystems.Item(i)
                    Exit For
                End If
            Next

            If csys Is Nothing Then
                Throw New Exception("Coordinate System not found in current Solid")
            End If

            '======================================================================
            'Instructions for UDF creation
            '======================================================================
            udfInstructions = (New CCpfcUDFCustomCreateInstructions).Create(Name01)

            '======================================================================
            'Make non variant dimensions blank to disable their display
            '======================================================================
            udfInstructions.DimDisplayType = EpfcUDFDimensionDisplayType.EpfcUDFDISPLAY_BLANK

            '======================================================================
            'Initialize the UDF reference and assign it to the instructions. 
            'The string argument is the reference prompt for the particular
            'reference.
            '======================================================================
            csysSelection = (New CMpfcSelect).CreateModelItemSelection(csys, Nothing)

            csysReference = (New CCpfcUDFReference).Create("Reference Coordinate System", csysSelection)

            references = New CpfcUDFReferences
            references.Set(0, csysReference)

            udfInstructions.References = references

            '======================================================================
            'Initialize the variant dimension and assign it to the instructions.
            'The string argument is the dimension symbol for the variant dimension.
            '======================================================================          
            variantDims = (New CCpfcUDFVariantDimension).Create("d6", Dim1)
            variantDims2 = (New CCpfcUDFVariantDimension).Create("d7", Dim2)
            variantVals = New CpfcUDFVariantValues
            variantVals.Set(0, variantDims)
            variantVals.Set(1, variantDims2)


            udfInstructions.VariantValues = variantVals

            '======================================================================
            'We need the placement model for the UDF for the call to
            'CreateUDFGroup(). If you were placing the UDF in a model other than
            'the owner of the coordinate system, the placement would need to be
            'provided separately.
            '======================================================================

            group = placementModel.CreateUDFGroup(udfInstructions)

            Return group

        Catch ex As Exception
            MsgBox(ex.Message.ToString + Chr(13) + ex.StackTrace.ToString)
            Return Nothing
        End Try
    End Function
End Class

Go back to the form and on the ‘on click’ event of the “Insert UDF” Button add the next code:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim asyncConnection As IpfcAsyncConnection = Nothing
        Dim run As New pfcFeaturesExamples
        Dim Model As IpfcModel
        Dim Solid As IpfcSolid

        Try
            asyncConnection = (New CCpfcAsyncConnection).Connect(Nothing, Nothing, Nothing, Nothing)
            Model = asyncConnection.Session.CurrentModel
            If Model Is Nothing Then
                Throw New Exception("Model not present")

            End If
            If (Not Model.Type = EpfcModelType.EpfcMDL_PART) And _
                (Not Model.Type = EpfcModelType.EpfcMDL_ASSEMBLY) Then
                Throw New Exception("Model is not a solid")
            End If
            Solid = CType(Model, IpfcSolid)
            run.createHoleUDFInPart(Solid, TextBox5.Text, TextBox4.Text, TextBox7.Text, TextBox8.Text)
            MsgBox("Hole Created")
        Catch ex As Exception
            MsgBox(ex.Message.ToString + Chr(13) + ex.StackTrace.ToString)
        End Try
    End Sub

In this case the name of the textboxes is as follow in the picture:


Test the form and the UDF should be inserted in the model.
____________
TRADEMARKS: Creo, Pro/ENGINEER, Pro/Toolkit, J-Link, Pro/Web.Link, Pro/Program and VB API are registered trademarks of PTC (http://www.ptc.com/). All other products or services mentioned in this blog are the trademarks or service marks of their respective companies or organizations.

Monday, February 10, 2014

Controlling a Box in CREO from MSExcel by using the VB API

Once the setup up part was finished, we are ready to test this API. In this simple example we are to use the capabilities for parameters the API has. In other exercise we will show something more sophisticated but based fundamentally in the very same ability of CREO for controlling a model via parameters.

The Box

Let's make in CREO a part with the name "box.prt", in it create a solid box with 3 dimensions (Length, Depth and Height).






Then Create 3 parameters for the 3 dimensions above mentioned. Let's name the variables as: LENGTH, DEPTH and HEIGHT





Now, in the "relations" dialog box, relate each parameter with the dimensions in the box





So we are ready from the side of CREO.

The Excel Side

Now on the side of Excel, let's create a new spreadsheet. and format it as is shown in next picture



Let's take advantage of the validation capabilities of Excel for restricting user inputs and avoid incorrect data to be passed to CREO API. So make the 3 dimensions to be more than 10 units and less than 800 units (let's say mm or inches). Also of course The values should be numeric. Next Image shows how it should look like when trying to enter a vale lower than 10 for HEIGHT Parameter.



Add a Button for connecting to CREO,



and insert the next snippet of code in the on-click event(This code allows for you to update the LENGTH from excel, DEPTH and HEIGHT are not updated as you can see in the code lines):

Private Sub UpdateCreo_Click()

Dim asyncConnection As IpfcAsyncConnection
Dim cAC As CCpfcAsyncConnection
Dim session As IpfcBaseSession
Dim model1 As IpfcModel
Dim px As IpfcParameterOwner
Dim p01, p02 As String
Dim p1 As IpfcParameter
Dim p2 As IpfcBaseParameter
Dim Mitem As CMpfcModelItem
Dim pv1 As IpfcParamValue

p01 = "LENGTH"
Range("D5").Select
p02 = ActiveCell.Text

Set cAC = New CCpfcAsyncConnection
Set asyncConnection = cAC.Connect(dbnull, dbnull, dbnull, dbnull)
Set session = asyncConnection.session
Set model1 = session.GetModel("BOX.PRT", EpfcMDL_PART)
Set px = model1
Set p1 = px.GetParam(p01)
Set p2 = p1
Set Mitem = New CMpfcModelItem
Set pv1 = Mitem.CreateDoubleParamValue(CDbl(p02))
p2.Value = pv1

asyncConnection.Disconnect (1)

End Sub


Test the button and this will allow you to update the box's LENGTH from Excel by using the VB API for PTC's CREO.

Thanks.



Thursday, February 6, 2014

Visual Basic API for PTC's CREO - Setup

In order to use this API (Application Programming Interface) it is necessary first to install this capability and do the proper setup in both Windows and the programming tool. MS Visual Studio can be used for programming and accessing the COM object but also Excel or other COM enabled tool.


Installing VB API


When Installing CREO Parametric be sure you select the VB API as is shown in the next picture:



If all installation process is done successfully then in the installation folder of CREO you´ll find a folder named "[Creo Path]\Common Files\M010\vbapi" [Creo Path] is the path you selected for installing CREO.



Is in this folder where most files related to VB API are located. There are many files inside but one that will be very useful with this API is the "vbug.pdf".


This document is very important and shows most of the contents for this API. Most of the procedures we are to see now are documented there but ours is a practical experiment you can follow.

Connecting MSExcel with CREO via VBAPI

In order to connect any application with CREO Parametric by means of this API, it is necessary to:

1- Set the PRO_COMM_MSG_EXE enviroment variable to the full path of the executable file pro_comm_msg.exe. which is located in:
 <creo_loadpoint>\Common Files\<datecode>\<machine type>\obj\pro_comm_msg.exe, where machine type is i486_nt for 32-bit Windows and x86e_win64 for 64-bit Windows installations.

For doing this, look in MSWindows for the Control Panel, then select System, then Advanced tab, then Environment variables an Add a new one PRO_COMM_MSG_EXE With the path explained before as the contents of the Value text box.

2- Register the COM Server. For doing this just run the "vb_api_register.bat" file located at <creo_loadpoint>/Parametric/bin.

Now each time an application tries to call Creo with the commands of this API, the server will automatically start.

3- Now on the side of the Excel Application, set project references for the VB API, Just select Tools and then References and Check the box for Creo Parametric VB API Type Library for Creo Parametric as shown in the following figure.


4- For Visual Basic .NET Environment, Click Project Properties Add Reference COM. and then, select Creo Parametric VB API Type Library for Creo Parametric as shown in the following figure.



More information on this can be found in the vbug.pdf or in the interactive help whose use is also shown in the vbug.pdf manual.

With this done we are ready for creating our first application.