Showing posts with label Pro/ENGINEER. Show all posts
Showing posts with label Pro/ENGINEER. Show all posts

Thursday, October 1, 2009

Pro/WebLink: Replace Drawing Formats

Jürgen from Germany was asking me recently about replacing formats with Pro/WebLink. In the process of providing a solution, I found an interesting combination of disappointments, curiosities, and finally a very nice solution.

SetSheetFormat()

Looking through the API documentation, it's not too hard to find that the method call to replace drawing formats is SetSheetFormat() in the pfcSheetOwner class. One of the primary arguments is the drawing format object in the form of a pfcDrawingFormat object. Unfortunately, this object's class is not obviously documented. The docs say only that its parent class is a pfcModel. So how to you get a drawing format object when it seems to have no methods?

Since it's a subclass of pfcModel, you use pfcBaseSession methods such as OpenFile(), GetModel, and RetrieveModel(). Here's where the J-Link docs are bit better, because they list the methods inherited from parent classes and interfaces, just making it that much more obvious. To use RetrieveModel(), a pfcModelDescriptor object needs to be created which specifies what is to be retrieved and how.

Here is the core sequence of steps, assuming the current model is a drawing:

var session = pfcGetProESession();
var drawing = session.CurrentModel;
var drwSheetNum = drawing.CurrentSheetNumber; // use current sheet

var frmName = "c_size.frm";
var frmSheetNum = 1;
var frmDescr = pfcCreate("pfcModelDescriptor").CreateFromFileName(frmName);
var format = session.RetrieveModel(frmDescr);

var drwModel = null;
drawing.SetSheetFormat(drwSheetNum, format, frmSheetNum, drwModel);
 

Format Folder

You'll notice that the folder where the format is stored was not specified. Why? According to the docs, you can't specify the path to a folder containing a pfcModel when using RetrieveModel(). Although the pfcModelDescriptor object contains a Path property, it is ignored.

How does Pro/Engineer know where to find the format? It just does. Well, if the PRO_FORMAT_DIR config.pro option is set properly, then it just does. Fortunately, this config.pro option can handle folder paths, Intralink 3.x folders, and PDMLink folders. That should cover most scenarios.


Format Sheets

SetSheetFormat() also allows you to specify the sheet number of the format to use (should your format have more than one sheet). Unfortunately, since the pfcDrawing Format object does not implement the pfcSheetOwner interface, the developer has no way to determine how many sheets are in the format. You'll just have to know how many sheet your formats have ahead of time, not a major tragedy.

To be fair this is a Pro/Toolkit limitation first and foremost. The PFC APIs merely inherit Pro/Toolkit's limitations.

Drawings, layouts, and Pro/Report files (who uses these anyway?!) all are defined as pfcModel2D objects, which gives lots of info about sheets, tables, and detail items. Formats, although pretty much the same thing, are not pfcModel2D objects. As a result, we can get none of these things.


Drawing Model

The drawing model is the part or assembly documented on the current sheet. Although this can be specified as the last argument to SetSheetFormat(), we don't have the ability to know what the current model is (at least until WF4). null is used to here to indicate the current drawing model.


Format Tables

Just as with interactive use of Pro/Engineer, when drawing formats are replaced, the drawing tables from the previous format have to be dealt with. Typically, this involves deleting the tables. Since SetSheetFormat() does not provide a mechanism or option for removing the old format tables, this will have to be done with more code.

This is where it gets a little tricky. While there is a CheckIfIsFromFormat() method call that will tell us if a table came from a format, we'll need the table object first. To get the table object, first we'll have to use ListTables() from the pfcTableOwner class to get all of the tables for the entire drawing. ListTables() takes no argument, meaning that we have no way to pre-filter the collection of tables. It really should take a sheet number argument to return only the tables on that sheet. As an alternatives, had the pfcTable class been a pfcDetailItem (in addition to a pfcModelItem), we could have gathered the tables by sheet number using ListDetailItems(), from pfcDetailItemOwner.

var tables = drawing.ListTables();
 
The workflow for CheckIfIsFromFormat() is a bit odd as well. To check if a table is from a format, we need the pfcTableObject, and then we need to specify the sheet number. Now wait a minute, the function returns a boolean so logically the table is from the format or it is not. What does the sheet number have to do with that? Even if the table had been segmented, it's still going to be from the format or not.

if (table.CheckIfIsFromFormat(drwSheetNum) == true) {
// table is from format, delete it
drawing.DeleteTable(table, false);
}
 
This quirkiness turns out to be very useful because it's rather difficult to tell on what sheet the table exists. The pfcTableInfo class does not contain this info. While it's true that the GetSegmentSheet() method can be used for this, we would have to assume that segment zero is the proper segment to use.


Full Example: Replacing Formats

This example shows a complete code set for obtaining the drawing object, the format object, and their related info. It then procedes to call the ReplaceFormat() function, which removes the old format tables prior to replacing the format. The code replaces the format and tables very quickly.

// get current drawing and sheet number
var session = pfcGetProESession();
var drawing = session.CurrentModel;
var drwSheetNum = drawing.CurrentSheetNumber;

// get format name from html text field
var frmName = document.getElementById("frmName").value

// use format sheet 2 if drawing sheet is not sheet 1
var frmSheetNum = 1;
if (drwSheetNum > 1) { frmSheetNum = 2; }

// get the format
var frmDescr = pfcCreate("pfcModelDescriptor").CreateFromFileName(frmName);
var format = session.RetrieveModel(frmDescr);

// replace the format
ReplaceFormat(drawing, drwSheetNum, format, frmSheetNum);

// update the display (optional)
// session.CurrentWindow.Repaint();
// drawing.Regenerate();


function ReplaceFormat ( drawing, drwSheetNum, format, frmSheetNum ) {

var tables = null;

try {
// get sequence of tables in the drawing
tables = drawing.ListTables();
for (var i=0; i<tables.Count; i++) {
var table = tables.Item(i);
if (table.CheckIfIsFromFormat(drwSheetNum) == true) {
// table is from format, delete it
drawing.DeleteTable(table, false);
}
}
}
catch (e) {
// ignore, no tables in drawing
}

drawing.SetSheetFormat(drwSheetNum, format, frmSheetNum, null);

}
 
Another step to perform (marked as optional in the example) is to update the display using either Repaint() or Regenerate(). They both should accomplish the same goal, but one may work better in certain drawings than the other. You can be sure that if a large drawing is slow to repaint when performed in Pro/Engineer interactively, it will be just as slow via Pro/Web.Link.

Wednesday, June 10, 2009

J-Link: Getting Started with Java and Pro/Engineer, Part 2

J-Link Java Code Requirements

J-Link requires that you have static methods with names matching the java_app_start and java_app_stop options from the registry file. Using the example registry file from Part 1, the required signatures for the "start" and "stop" methods would look like this:

    public static void startApp();
public static void stopApp();
 

As you'll see from the code that follows, these static methods don't do much but call other methods where all the important stuff happens. This approach seems to work well, but there are certainly other ways to approach J-Link.

Method Summary:

Here are the other methods used by the program, none of which are static:

Constructor JLinkHelloWorld()

The constructor sets up the needed utility items, such as the program name (based on the class name), a FileWriter object for the log file, and the platform specific newline character.

Method startupApplication()

The startupApplication() method gets the Pro/Engineer session object, defines a UI command, registers the UI command in the GUI (in the 'Tools' menu), and then announces to the user that the program is operational.

Method shutdownApplication()

The shutdownApplication() method closes out the log file's FileWriter object.

Method writeLog(String mesg)

A log file can be used for debugging and reporting purposes. A developer will use it for debugging an application, while an end user will be able to see what the program is doing internally.

Although using the log file is definitely optional, you'll find that there are all sorts of bizarre things in Pro/Engineer models that you will never have anticipated. With the use of proper logging, a developer increases the chances that these anomalies can be reported back by the end user.

Method closeLog()

As you might expect, this closes the log file.

Method DisplayMessage(String mesg)

DisplayMessage() writes an arbitrary message to the Pro/Engineer message area for the user to see. The example uses of DisplayMessage() that I have provided is not really the best approach for internationalization, but it serves the purpose of showing how to write message to the Pro/Engineer GUI. This method also writes the same output to the log file.

UI Command Registration and UI Listeners

A program is not going to be useful to an end user unless they can run the program. The user is not going to be able to run a J-Link program unless it registers itself with the Pro/Engineer GUI via a new menu or new menu option.

UI command registration is a multistep action requiring a couple of different pieces. The pieces required are a UICommandActionListener and a callback method, while the actions involve creating a command using UICreateCommand() and adding the command to the GUI using UIAddButton(). The text strings used as arguments to the UI methods are either found in the application's text message file (i.e. "JLHW Btn1 Label") or are known by Pro/Engineer (i.e. "Utilities" which represents the "Tools" menu).

The example program implements the listener by defining an inner class that extends the DefaultUICommandActionListener class. The inner class has a single method OnCommand() that is triggered when the user clicks on the command in the GUI. OnCommand() calls Btn1_callback() which is in the main class. Btn1_callback() then gets the current model object, if any, and displays the name in the message window using DisplayMessage().


The J-Link "Hello World" Java Code:

// JLinkHelloWorld.java
// Copyright 2009, MarcMettes@InversionConsulting.com

// imports required
import com.ptc.cipjava.*;
import com.ptc.pfc.pfcCommand.*;
import com.ptc.pfc.pfcGlobal.*;
import com.ptc.pfc.pfcModel.*;
import com.ptc.pfc.pfcSession.*;
import java.io.*;

public class JLinkHelloWorld {

static JLinkHelloWorld App = null;
String programName = null;
Session session = null;
FileWriter log = null;
String msgFile = "msg_jlinkhelloworld.txt";
String newline = null;

// constructor
//
public JLinkHelloWorld () {
programName = this.getClass().getName();
try {
log = new FileWriter(programName + ".log");
newline = System.getProperty("line.separator");
}
catch (Exception e) {
// couldn't create log file, ignore
}
}

// Display message in Pro/Engineer
//
public void DisplayMessage ( String mesg ) throws Exception {
stringseq seq = stringseq.create();
seq.set(0, mesg);
session.UIDisplayMessage(msgFile, "JLHW %s", seq);
seq.clear();
writeLog(mesg);
}

// Write text to log file
//
public void writeLog ( String mesg ) {
try {
if (log == null) { return; }
log.write(mesg + newline);
log.flush();
}
catch (Exception e) {
// ignore
}
}

// Close log file
//
public void closeLog () {
try {
if (log == null) { return; }
log.close();
}
catch (Exception e) {
// ignore
}
}

// Called by Pro/Engineer when starting the application
//
public static void startApp () {
try {
App = new JLinkHelloWorld();
App.startupApplication();
}
catch (Exception e) {
App.writeLog("Problem running startupApplication method" + e.toString());
return;
}
}

// Called by Pro/Engineer when stopping the application
//
public static void stopApp () {
try {
App.shutdownApplication();
}
catch (Exception e) {
App.writeLog("Problem running shutdownApplication method" + e.toString());
return;
}
}

// Perform some steps when shutting down the application
//
public void shutdownApplication () throws Exception {
writeLog("Application '" + programName + "' stopped");
closeLog();
}

// Perform some steps when starting the application
//
public void startupApplication () throws Exception {

try {
writeLog("Application '" + programName + "' started.");
session = pfcGlobal.GetProESession();
}
catch (jxthrowable x) {
writeLog("ERROR: Problem getting session object.");
return;
}

UICommand btn1_cmd = null;

try {
// Define a UI command
btn1_cmd = session.UICreateCommand(
"JLHW Btn1 Cmd", new JLHW_Btn1_CmdListener()
);
}
catch (jxthrowable x) {
writeLog("ERROR: Problem creating uicmd.");
return;
}

try {
// Add UI command to 'Tools' menu
session.UIAddButton(
btn1_cmd, "Utilities", null,
"JLHW Btn1 Label", "JLHW Btn1 Help",
"msg_jlinkhelloworld.txt"
);
}
catch (jxthrowable x) {
writeLog("ERROR: Problem creating menu: " + x.toString());
return;
}

DisplayMessage(programName + " application started.");

}

// Callback for the 'Tools' menu button
//
public void Btn1_callback ( ) throws Exception {

String mesg = null;
Model model = session.GetCurrentModel();

if (model == null) {
mesg = "Hello!";
}
else {
mesg = "Hello! The model is: " + model.GetFileName();
}

DisplayMessage(mesg);

}

// Inner class for UI Command Listener
//
public class JLHW_Btn1_CmdListener extends DefaultUICommandActionListener {

// Handler for button push
//
public void OnCommand () {
try {
Btn1_callback();
}
catch (Exception e) {
writeLog("Exception thrown by Btn1_callback method: " + e.toString());
}
}

}

}
 


As you can see, there are a number of non-trivial steps involved in creating J-Link applications. However, creating simple programs is really easy.

If you need a J-Link program written for you, please contact me at MarcMettes@InversionConsulting.com to discuss your requirements.

Friday, June 5, 2009

J-Link: Getting Started with Java and Pro/Engineer, Part 1

J-Link can seem intimidating at first, but once you have all the little pieces in hand to get started, it's actually pretty simple. In this article, I'll walk you through all the pieces that you need to create a basic J-Link application.

Even a simplistic J-Link program requires several files, including your Java code compiled to class file(s), a text-based "message file", and an auxiliary application "registry file". I'll explain the required content of each file and how to put them all together.

The Registry File

The registry file is used to instruct Pro/Engineer on how to load an auxiliary application, such as a Pro/Toolkit or J-Link program. Pro/Engineer uses this to find all of the program's pieces. The actual name of the file is not that important, but "protk.dat" will be used as the filename in this example.

An auxiliary application can be started by Pro/Engineer automatically by using the PROTKDAT config.pro option, or by placing the registry file in certain special locations (i.e. the working directory, within the Pro/Engineer install, etc). Auxiliary applications can also be started manually.

Here is an example registry file for the J-Link "Hello World" application:

name               JLinkHelloWorld-App
startup java
java_app_class JLinkHelloWorld
java_app_start startApp
java_app_stop stopApp
allow_stop true
delay_start false
text_dir M:/apps/JLinkHelloWorld/text
java_app_classpath M:/apps/JLinkHelloWorld
end
 

The "name" will appear in the auxiliary application dialog to aid in identifying the program and can be as descriptive (or cryptic) as you need. The "startup java" entry is required for J-Link apps.

"java_app_class" indentifies the primary class of the application where the "java_app_start" and "java_app_stop" methods are contained. The program is required to have static "stop" and "start" methods matching the names given in the registry file (more on that later).

The "allow_stop" option allows the user to stop the program if it is running. The "delay_start" option (if set to "true") can disable automatic startup allowing the user to do this later, manually, if desired.

The "text_dir" option identifies the folder hierarchy containing your application's message files. Although the inclusion of the "text" folder in the path is not always required, it doesn't cause any problems. Unix style paths work just fine here, as they do with config.pro files. Consult my other articles about cool stuff with registry files.

"java_app_classpath" is generally used to find other class and jar files that you may use in your application. It's like having a private CLASSPATH environment variable for each program. As an alternative, this option can be replaced by using the ADD_JAVA_CLASS_PATH config.pro option, using the same value. However, keeping the option in the registry file is generally the simpler approach.

Not every entry is required, but it's usually a good idea to use the above set for greater flexibility.


The config.pro File

To initiate the program upon startup of Pro/Engineer, you can use a PROTKDAT config.pro option. The value of this option is the full path to the registry file.

Using the above example, the option might look like this:

PROTKDAT M:/apps/JLinkHelloWorld/protk.dat
 

The Text Message File

The text message file is used primarily to support internationalization. However, it also enables "code vs data" separation by relocating static text to standalone files. A text message file is needed for even the most basic J-Link program.

Each "entry" in a text message file is comprised of four lines. Typically only the first two are used, the last two are placeholders. The first line is the "message id" that you use in your code, and the second line is the text that will generally appear for that message id.

In this example, the text message file msg_jlinkhelloworld.txt will contain three entries as follows:

JLHW Btn1 Label
JLink Hello World
#
#
JLHW Btn1 Help
Run the JLink Hello World Application
#
#
JLHW %s
%0s
#
#
 

Be sure to leave an extra blank line at the end of the file to avoid one of the many strange problems with text message files.

The text message file must be placed within the folder structure specified by "text_dir" in the registry file. In this example application, the text message file will be placed in:
    M:/apps/JLinkHelloWorld/text/usascii
 

Proper location of the text message file is very critical. Putting the file in the wrong folder is the source of confusion and frustation to new Pro/Engineer API developers.


Read Part 2 for the Java code

Tuesday, August 19, 2008

Pro/ENGINEER: Anatomy of a Trail File, Part 3

Read Part 2

In my experience, there are three main uses for trail files: Recovery, Benchmarking, and Templating. Generally speaking this series of articles is about templating trail files. Templating is the modification of trail files to perform actions that are not specific to a particular model.

In more complex trail files, selection of items eventually becomes a necessity. Doing this in a repeatable way can become very challenging, especially if working with different models or models that are changing often.

Selections of models, features, annotations, and notes can be accomplished in various ways, but selections of geometry items such as surfaces and edges are very difficult in such a manner that it works for different models. Trail file selections using the graphics window are almost never transferable for use with other models.

Model Tree

When you click on an item in the model tree, you'll see, for example, "node4" or "node31" appear. Here is an example of a trail file entry caused by selecting 'Note_1'.

~ Select `main_dlg_cur` `PHTLeft.AssyTree` \
1 `node6`
!Note_1
 
These node numbers are assigned by Pro/ENGINEER on a first come, first served basis. When the model is first opened the node numbers are assigned in a bottom first, upwardly increasing sequence, based on what is displayed at that time.

For example, if the model tree of a part is shown with features and annotations when the model is opened, the following table reflects the node number assignments. The top level item (the part itself) is node 0 (zero), then working up from the bottom the node numbers increase. As you can see, even the 'Insert Here' pointer has a node number.

 Item        Node #
ABC.PRT 0
Note_0 8
Note_1 7
Note_2 6
Feat1 5
Feat2 4
Feat3 3
Feat4 2
Insert Here 1
 
The tricky part comes when new nodes are shown either through expansion of existing nodes (i.e. to show features of a component) or modification of the model tree filters. Regardless of where in the model tree they appear, the new nodes are given new node numbers based on the previous largest value.

As an example, if your model tree initially shows nothing, then annotations are added, then features are added, you might get a result like this:

 Item        Node #
ABC.PRT 0
Note_0 3
Note_1 2
Note_2 1
Feat1 8
Feat2 7
Feat3 6
Feat4 5
Insert Here 4
 
The node numbers for a complex assembly might even appear to be randomly assigned. Disappointingly, use of 'Expand All' doesn't produce very orderly node number assignments.

Beyond the top level nodes, use of the model tree can be very complicated. It is definitely something that can be done, but requires some preprocessing to generate a trail file programmatically before it is run. Most likely, trail files making more than trivial use of the Model Tree will not be usable for other models.


Search Tool

Another approach to selections with trail files is the "Search" tool (i.e. Edit -> Find). The Search tool works very well when selecting items with a trail file. Selections of specific models, features, or numerous other entities can be accomplished easily.

The downside to this approach is that you lose some control over where in an assembly hierarchy objects can be located. An option exists to search only in the top level, but an 'All Levels' search will return results from any level.

Another difficulty is that multiple results will be obtained when searching for common objects, such as hardware parts, shared subassemblies, and models with standard features, etc. There is a mechanism to select specific items, but this requires a great deal of information that has to be provided ahead of time.


Defaults

Another thing to keep in mind is that the last option you use in the Search Tool may be the default option when the Search Tool is used a second time. A recommendation is always to set explicitly every option (even if it is the default) every time the Search Tool is used with a trail file. This will produce more robust trail files.

It may be extra work to click on other options that you don't want in order to record the selection that you do want, however it's worth the effort. Extra baggage code in the trail file can usually be removed, if that is desirable.


Example

A typical scenario is the need to select an item such as a component, a feature, or a note using its name. Here is an example of using the Search tool to search an assembly for a subassembly called 'A.ASM'. I have added comments to indicate the major sections.

!! Start the Search tool
!!
~ Select `main_dlg_cur` `MenuBar1` \
1 `Edit`
~ Close `main_dlg_cur` `MenuBar1`
~ Activate `main_dlg_cur` `Edit.Find`
!!
!! Select entity type to be searched for
!!
~ Open `selspecdlg0` `SelOptionRadio`
~ Close `selspecdlg0` `SelOptionRadio`
~ Select `selspecdlg0` `SelOptionRadio` \
1 `Prt_or_Asm`
!!
!! Limit search to top level
!!
~ Activate `selspecdlg0` `SelScopeCheck` \
0
!!
!! Enter name
!!
~ Update `selspecdlg0` `ExtRulesLayout.ExtBasicNameLayout.BasicNameList` \
`A.ASM`
!!
!! Perform search by clicking 'Find Now' button
!!
~ Activate `selspecdlg0` `EvaluateBtn`
!!
!! Selecting item(s) in results
!!
~ Select `selspecdlg0` `ResultList` \
1 `-1:69:[39]`
!!
!! Hit 'Close' in Search dialog (even though it says 'CancelButton')
!!
~ Activate `selspecdlg0` `CancelButton`
 
If you follow along in your trail file while performing the search, you can see that each action produces a certain output, which is mostly self explanatory. What is not so obvious is the syntax of the output when items are selected in the search results.


Selections

The syntax used for selection of components differs from the selection of other types of entities, but it is similar. The `-1:69:[39]` specifier is a colon separated list of three fields: ID, Type, Component Path.

The first field is an item ID field (i.e. feature id, note id, etc), except for components where it always shows -1. The second field is a numeric code corresponding to the type of entity in the search, whether that be 'Feature', 'Annotation', 'Component', etc. The third field specifies a "Component Path" which is a list of component feature IDs from a top level to a subassembly or component. The "[39]" indicates that the selected component is feature ID 39 in the top level assembly.

A selected item generating this syntax `2:147:[40][40][41][61]`, is a note (or some other annotation) with id 2 and found through the component id sequence of 40 (level 1 component id), 40 (level 2 component id), 41 (level 3 component id), 61 (level 4 component id).


Select All

The "Select All" action (Ctrl-A) can be used at any time and generates the following trail code. Even if a selection of an item is required for an interactive user prior to using "Select All", this can be used without it in a trail file.

~ Select `selspecdlg0` `ResultList` \
-1
 

Depth

The depth of the search is controlled by the "Include submodels" option in the Search Tool dialog. Checking or unchecking this option adds one of the following code sequences to the trail file.

!! Limit search to top level ('Include submodels' is not checked)
!!
~ Activate `selspecdlg0` `SelScopeCheck` \
0
 

!! Search all levels ('Include submodels' is checked)
!!
~ Activate `selspecdlg0` `SelScopeCheck` \
1
 

Closing The Dialog

As you can see from my comment, hitting Close in the dialog adds a curiously named "CancelButton" entry. Just remember if you're editing the trail file, that this means "Close".

!! Hit 'Close' in Search dialog (even though it says 'CancelButton')
!!
~ Activate `selspecdlg0` `CancelButton`
 

Types

One of the first things typically done when using the Search Tool is the choice of entity type. If you're familiar with the tool, you know that there is a very wide range of type options to choose from.

Type selection generates code such as this:

~ Open `selspecdlg0` `SelOptionRadio`
~ Close `selspecdlg0` `SelOptionRadio`
~ Select `selspecdlg0` `SelOptionRadio` \
1 `TYPENAME`
 
Some examples of `TYPENAME` are `Prt_or_Asm`, `Component`, `Feature`, `Annotation`, `Note`, `Location`, `Datum`, `3D Curve`.

As discussed earlier, the numeric code for the type is reflected in the code generated when selecting items in the search results. The type code for `Annotation` and `Note` are both 147, while `Prt_or_Asm` ("Solid Model" from the GUI) and `Component` are both 69.


By Name

The Search Tool allows case-insensitive name searches, and wildcards can be used to make the search criteria more generic. The basic syntax is as follows:

~ Select `selspecdlg0` `RuleTab` \
1 `Attributes`
~ Update `selspecdlg0` `ExtRulesLayout.ExtBasicNameLayout.BasicNameList` \
`NAME`
 
Examples of `NAME` with and without wildcards might be `12345678_OBSOLETE.PRT`, `DEFAULT`, `ASM_TOP`, `ASM_*`, `*65-5*`, `*side*`.


By ID

If a specific feature ID or note ID is known, this can be searched for as well. This appears in the GUI under the "History" tab and generates the following entry:

~ Select `selspecdlg0` `RuleTab` \
1 `Misc`
~ Select `selspecdlg0` `RuleTypes` \
1 `ID`
~ Update `selspecdlg0` `ExtRulesLayout.ExtBasicIDLayout.InputIDPanel` \
`IDENT`
 
Where `IDENT` is an integer number such as `1`, `2`, `3`, etc. Note that the History tab goes by the name of Misc in the trail file. All other tabs follow their name in the trail file more directly.


By Parameter Value

In addition to entity name searches, the Search Tool can perform searches based on parameter values, using the "Expression" radio option in the "Attributes" tab. Keep in mind that there are differences in the behavior of "Component" searches versus "Solid Model" searches. Testing will ensure your searches produce the desired results.

This sequences will prep the dialog box for searches based on parameter values:

~ Select `selspecdlg0` `RuleTab` \
1 `Attributes`
~ Select `selspecdlg0` `RuleTypes` \
1 `Expression`
 
The type must be selected first (real number, string, integer, yes/no), then the name of the parameter. Be careful when selecting the parameter name from the drop down list, because only a sequence number will be recorded. For a different set of models, the sequence number may not correspond to the same parameter name as when you recorded the trail files.

This results from choosing a parameter from the list:

~ Open `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprTypesList`
~ Close `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprTypesList`
~ Select `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprTypesList` \
1 `51`
 
This results from typing in a parameter name:

~ Open `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprParamsList`
~ Close `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprParamsList`
~ Input `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprParamsList` \
`DES`
~ Input `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprParamsList` \
`DESC`
~ Update `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprParamsList` \
`DESC`
 
The typed syntax can be simplified, by removing the 'Input' entries and leaving the 'Update' entry, to this:

~ Open `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprParamsList`
~ Close `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprParamsList`
~ Update `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprParamsList` \
`DESC`
 
The 'Value' field in the dialog box corresponds to the 'ExprValuesList'. Any value can be entered, and wildcards can be used as well. Note that string searches seem to be case insensitive only when used with wildcards.

~ Update `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprValuesList` \
`brack*`
 
The "Comparison" can be changed from the default of "is equal to". There are seven operators available, with this being an example of greater than (more useful for numeric comparisons):

~ Open `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprOperandLabel`
~ Close `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprOperandLabel`
~ Select `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprOperandLabel` \
1 ` > `
 
The list of comparisons (for ExprOperandLabel) is:

` == `   is equal to
` != ` is not equal to
` < ` is less than
` > ` is greater than
` <= ` is less than or equal to
` >= ` is greater than or equal to
` * ` exists
` !* ` does not exist
 
When searching by parameter, the parameter type must be selected first.

~ Open `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprTypesList`
~ Close `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprTypesList`
~ Select `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprTypesList` \
1 `TYPEID`
 
Where `TYPEID` is 50, 51, 52, or 53 for Real Number, String, Integer, and Yes/No, respectively.


Look In

The 'Look In' drop down list allows for user control of the model (or hierarchy) to be searched. Here are some examples of selections made from the drop down list.

Top level selected:

~ Input `selspecdlg0` `LookInDrop` \
`12345678.ASM`
 
Component selected:

~ Select `selspecdlg0` `LookInDrop` \
1 `12345678_SKEL.PRT (12345678, id 43) (43)`
 
It is also an editable field in which you can attempt to enter model names. Unfortunately, the rather strong autocomplete nature may prevent entering the correct model name, or stop at another model, or result in garbage entered. None of this will produce a useful trail file.

The good news is that the syntax used for top level example can be used for any model at any level:

~ Input `selspecdlg0` `LookInDrop` \
`23456789.ASM`
 
This differs from other trail file entries in that typically the "Update" statement is kept while the "Input" entries are eliminated, because they are typically redundant. It is most likely the autocomplete functionality that makes this necessary.

When using this syntax, which lacks the component path (list of component ids), you'll lose some control if the model is used multiple times in an assembly hierarchy. Not a major problem, just something to be aware of. Based on my testing, the Search Tool uses the model that appears last in the model tree, if multiples exist.


Tabs

A specific tab in the Search Tool dialog can be selected using the following example:

~ Select `selspecdlg0` `RuleTab` \
1 `TABNAME`
 
Where `TABNAME` is `Attributes` for the Attribute tab, `Misc` for the History tab, `Status` for the Status tab, and `Geometry` for the Geometry tab.


Another Example

Combining several of these elements, here is an example that searches for parts and assemblies within all levels of ASM0002.ASM that for parameter DESC have a value matching "brack*", selects all found, and closes the dialog:

!!
!! Start the Search tool (via Ctrl+F)
!!
~ Activate `main_dlg_cur` `ProCmdMdlTreeSearch.edit_t`
!!
!! Select "Solid Model" as entity type to be searched for
!!
~ Open `selspecdlg0` `SelOptionRadio`
~ Close `selspecdlg0` `SelOptionRadio`
~ Select `selspecdlg0` `SelOptionRadio` \
1 `Prt_or_Asm`
!!
!! Restrict search to a subassembly
!!
~ Input `selspecdlg0` `LookInDrop` \
`ASM0002.ASM`
!!
!! Search all levels ('Include submodels' is checked)
!!
~ Activate `selspecdlg0` `SelScopeCheck` \
1
!!
!! Go to "Attributes" tab, select "Expression" radio button
!!
~ Select `selspecdlg0` `RuleTab` \
1 `Attributes`
~ Activate `selspecdlg0` `selspecdlg0`
~ Select `selspecdlg0` `RuleTypes` \
1 `Expression`
!!
!! Select "String" from parameter value type pull down
!!
~ Open `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprTypesList`
~ Close `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprTypesList`
~ Select `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprTypesList` \
1 `51`
!!
!! Enter parameter name
!!
~ Update `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprParamsList` \
`DESC`
!!
!! Enter parameter value search string
!!
~ Update `selspecdlg0` `ExtRulesLayout.ExtExprLayout.ExprValuesList` \
`brack*`
!!
!! Perform search by clicking 'Find Now' button
!!
~ Activate `selspecdlg0` `EvaluateBtn`
!!
!! Select all in search results
!!
~ Select `selspecdlg0` `ResultList` \
-1
!!
!! Hit 'Close' in Search dialog (even though it says 'CancelButton')
!!
~ Activate `selspecdlg0` `CancelButton`
 

Both the Model Tree and Search Tool are useful when used in trail files. Use of the Model Tree is more limited because it requires knowledge of its contents before the trail file is generated. The Search Tool, when used properly, provides one of the most robust methods of performing selecting with trail files. With minor editing, trail files utilizing the Search Tool can be generated quickly, easily and can be applied to a wide range of models.


Next time: Mapkeys and Trail Files

Wednesday, July 2, 2008

Pro/WebLink: Tips On Getting Started

Pro/WebLink is one of the free PFC based API's available for automating Pro/Engineer. Although the documentation and marketing literature is focused on using Javascript with Pro/WebLink, VBScript can be used if that is more to your taste.

Developers interested in writing Pro/WebLink application have to overcome a number of hurdles. Most of these are related to the Internet Explorer and Mozilla security models, because Pro/WebLink applications typically must run within the context of the Pro/Engineer embedded web browser. This differs from the VB API (new with Wildfire 4.0), which runs outside of the Pro/Engineer process and has far fewer security issues to worry about.

While security is not the only problem facing Pro/WebLink developers, it is the most common problem in my experience. In this article I'll discuss the necessary steps in setting up your environment to run Pro/WebLink applications.

Pro/ENGINEER Configuration

Use of Pro/WebLink requires that the config.pro option WEB_ENABLE_JAVASCRIPT be set to ON (the default is OFF). In Windows, if this option is set to ON when Pro/ENGINEER is started, pfcscom.dll will be registered as a COM server. This contains all of the Pro/WebLink functionality.

Generally this works very well, but I have seen problems where the DLL doesn't get registered, or some other similar problem occurs preventing the Pro/WebLink application from functioning. The workaround is to run the application as an administrative user first, then the program works for everyone. Fortunately, I have only seen one user affected like this, otherwise the workaround would get really annoying.

None of that is relevant in Unix, as the required XPCOM technology is already present in the embedded Mozilla browser. However, I have seen rare instances where the Mozilla profile in the user's unix home directory has become corrupted. The resolution is to delete the profile. Pro/Engineer will recreate it upon startup.

HTML SCRIPT Tag

When setting up your Pro/WebLink programs, you are likely to include one or more files containing your Javascript code. A common one to use, although it is not absolutely necessary, is the PTC supplied pfcUtils.js file. If you are going to use such functions as pfcCreate() and pfcGetProESession(), you need to make sure you include pfcUtils.js correctly to avoid confusing errors, such as "Object Expected".

You also need to ensure that the SCRIPT tag entry in your HTML code correctly locates the pfcUtils.js file. For example, this entry will find the bom2excel.js file if it is placed in the same folder as the HTML file, and the pfcUtils.js file if it is in the parent folder:

<SCRIPT LANGUAGE="JavaScript" type=text/javascript src="../pfcUtils.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript" type=text/javascript src="bom2excel.js"></SCRIPT>
 

Your web browser may not complain in an obvious way if it cannot find one of your Javascript programs, making the resulting errors hard to diagnose. If using a web server, make sure that the web server process has sufficient permissions to read the HTML and JS files, otherwise you'll wind up with the same problems, but it will that much harder to diagnose.

Web Browser Security Models

Overcoming the security requirements of Wildfire's various supported web browsers is often frustrating because the requirements are not inherently obvious and the documentation can be hard to find. With Wildfire 4.0, Mozilla is the supported browser on Unix platforms and Internet Explorer is the browser for Windows. Both have different mechanisms and rules concerning security.

Using digitally signed applications allow the developer to bypass some security roadblocks by requesting enhanced functionality based on the user's "trust" of the developer. Digital signatures are far beyond the scope of this article however.

Internet Explorer Security

Internet Explorer security is based on zones: Internet, Local intranet, Trusted sites, and Restricted sites. Each zone has it own security settings enabling or disabling certain functionalities. Using the "Custom Level" button, each option can be enabled or disabled selectively. If you change any of the security options, you may need to restart Pro/Engineer for the changes to take effect in the embedded web browser.
It is recommended that you do not reduce security for the Internet zone. It would be better to add the web site to the Trusted sites zone, then adjust the security for that zone.

Internet Explorer will decide to which zone your application applies depending on how you access it. If you access your program from a web server using a fully qualified domain name (i.e. www.yahoo.com) for a site that is not in your Trusted sites list, Internet Explorer will consider it part of the Internet zone. Using an internal web server (i.e. without top level domain: .com, .org, .co.uk, etc) or accessing the program from your hard drive or a network hard drive, will cause Internet Explorer to use the Local intranet zone. Not surprisingly, the Trusted sites zone will apply to a site that is in the Trusted sites list, even if it is an internal web server.

Pro/WebLink applications need a couple of settings defined for the zone that will be used by your application. Some of these may already be the default for you. As PTC recommends in the documentation, the option "Initialize and script ActiveX controls not marked safe for scripting" should be set to "Prompt". If you are interacting with Excel from Pro/WebLink, this option may need to be set to "Enable".


Ensure that the option "Active Scripting" is set to "Enable".

Mozilla Security

Mozilla has some good security functionality in which a script can request enhanced functionality allowing the user to accept or deny the request. That's why you see some UniversalXPConnect requests in Pro/WebLink examples. The code has to ask for enhanced privileges to connect to Pro/Engineer and do something useful.

When the Pro/WebLink application is served from a web server, the code and HTML must be digitally signed (together) for this request process to work. To make matters worse, a very unusual jar:http: URL must be used to interact with the resulting JAR file that contains the code and HTML.

A workaround is not to use a web server, but instead access the code and HTML from the file system using a file: type URL. For Pro/WebLink applications, the user is generally prompted only once for enhanced privileges, then is good to from then on.

Review

Keeping some of these issues in mind will help you get up and running with Pro/WebLink avoiding many of the pitfalls and frustrations.

  • Set WEB_ENABLE_JAVASCRIPT to ON in your config.pro file
  • Ensure that HTML and JS files are located correctly
  • Make sure that the web browser security requirements are satisfied

Wednesday, June 18, 2008

Pro/E VB API: Not Just for Visual Basic Anymore

In a previous article entitled "WebLink: What is it anyway?", I discussed Pro/WebLink and how it's not exactly a Javascript interface. Now it's the VB API's turn. The VB API is newly released by PTC with Wildfire 4. It is billed as a Visual Basic interface to PTC's PFC libraries, which is the same core that J-Link and Pro/WebLink are built upon.

While this is true, it's not that limited. Don't let the name scare you away from using your favorite COM accessible programming or scripting language to write Pro/Engineer applications. This is a good thing because it opens the API to a much wider range of applications.

In this article, I'll walk through sample applications written in Visual Basic, VBScript (using Windows Script Host), Perl, and Javascript (in a HyperText Application), all using the VB API. The sample application will connect to a Pro/Engineer session, obtain the session object, display the name of the current model, then disconnect from the Pro/Engineer session. Each program will display the model name in a different way.

Suggested reading is the section on the importance of disconnecting from Pro/Engineer in Pro/E VB API: A First Look.

Excel Macro

This is the standard and documented approach to the sample program. Objects are declared up front, the connection to Pro/Engineer is made, then the session object is obtained. The model name is displayed both in cell A1 and in a MsgBox.

Sub Macro1()

Dim asynconn As New pfcls.CCpfcAsyncConnection
Dim conn As pfcls.IpfcAsyncConnection
Dim session As pfcls.IpfcBaseSession
Dim mdlname

Set conn = asynconn.Connect("", "", ".", 5)
Set session = conn.session

mdlname = session.CurrentModel.Filename
Range("A1").Select
ActiveCell.FormulaR1C1 = mdlname
MsgBox ("Name: " & mdlname)
conn.Disconnect(2)

End Sub
 

VBScript

The VBScript code is almost identical except that VBScript doesn't seem to allow for the type declaration of the objects. As a result, the CreateObject() call is used to instantiate a pfcAsyncConnection object.

The program is executed using the following command line:
  cscript vbapi_script.vbs
 

Dim asynconn
Dim conn
Dim session
Dim mdlname

Set asynconn = CreateObject("pfcls.pfcAsyncConnection")
Set conn = asynconn.Connect("", "", ".", 5)
Set session = conn.session

mdlname = session.CurrentModel.Filename
MsgBox ("Name: " & mdlname)
conn.Disconnect(2)
 

Perl

As with most COM applications, the Perl syntax is also very similar to the VBScript code, but with Perl's own syntactical flavor. Win32::OLE->new() is the Perl equivalent to VBScript's CreateObject(). The Perl program outputs the model name to the command prompt (or standard output).

use Win32::OLE;
$asynconn = Win32::OLE->new("pfcls.pfcAsyncConnection");
$conn = $asynconn->Connect( "", "", ".", 5 );
$session = $conn->Session;
$mdlName = $session->CurrentModel->FileName;

print "mdlName: $mdlName", "\n";
$conn->Disconnect(2);
 

Javascript

Pro/WebLink applications can finally break out of the embedded browser jail using the VB API. This example uses a "Hypertext Application", which is a web page with a special HTA tag and with a file extension of ".hta" instead of ".htm". The pfcUtils.js file cannot be used as-is because it tries to use COM objects with "pfc." prefixes, instead of those associated with VB API which have "pfcls." prefixes.

Other than those differences, it's essentially a Pro/WebLink application. As with the other examples, because it's an asynchronous application, the code must connect to the Pro/Engineer session. This is a step that embedded browser based Pro/WebLink applications don't have to worry about.

<html>
<head>
<title>VB API Test</title>

<HTA:APPLICATION
ID="vbapi-test"
APPLICATIONNAME="VB API Test"
SCROLL="auto"
SINGLEINSTANCE="yes"
>
</head>

<body>

<SCRIPT LANGUAGE="JavaScript">

function HitMe ( ) {
var obj = null;
var elem = document.getElementById("mesg");

if (obj == null) {
try {
obj = new ActiveXObject("pfcls.pfcAsyncConnection");
}
catch (e) {
elem.innerHTML = "Failed to create object";
return;
}
}

var conn = obj.Connect( "", "", ".", 5 );
var session = conn.Session;
var mdlName = session.CurrentModel.FileName;

elem.innerHTML = "mdlName: " + mdlName;
conn.Disconnect(2);
}

</SCRIPT>

<form name="f">
<INPUT name="a" type=button value="Hit me!" onclick="HitMe()">
<br><a id="mesg"></a><br>
</form>

</body>
</html>
 

These are just a few of the possibilities. As you can see, there is nothing really Visual Basic specific about the VB API. It's just an API.

Tuesday, June 17, 2008

Pro/WebLink: Send Excel Data To Pro/ENGINEER Drawing Tables, and Back Again - Part 2

In part 1, the transfering of data from Excel to Pro/ENGINEER drawing tables was discussed. In this second part, the discussion will focus on the other direction, sending Pro/ENGINEER drawing table data to an Excel workbook.

TableToExcel Function

The TableToExcel() function is also pretty simple. After resetting the status fields, it uses ArrayFromProETable() to obtain an array of data from a user selected drawing table, then uses ArrayToExcel() to populate a new Excel workbook with the data from the array.

function TableToExcel ( ) {

var mesg = document.getElementById("mesg");
var errmesg = document.getElementById("errmesg");
mesg.innerHTML = "";
errmesg.innerHTML = "";

var array = ArrayFromProETable();
if (array == null) {
mesg.innerHTML = "null array";
return;
}

if (array != null) { ArrayToExcel(array); }
}
 

ArrayFromProETable Function

The ArrayFromProETable() function gathers drawing table data into an array. It's main steps are: Get the Pro/Engineer session object, obtaining the current model object and ensure a drawing is active, request a drawing table selection from the user, and iterate through the table cells to populate the array elements. After the table is selected by the user, UnHighlight() is used to repaint the table with its normal colors.

The table cell iteration code cycles first through the table rows, then the columns of each row, then through the lines of text in each cell. When there is more than one line of text in a table cell, a linefeed character is added as a line separator. This is correctly interpreted by Excel as multi-line data.

It's important to note that while in Javascript (as in many programming languages) arrays are indexed starting with zero, both drawing tables and Excel cells are indexed starting with one.

Once the iteration of the table cells has completed and the array has been populated, the array is returned.

function ArrayFromProETable ( ) {

var mesg = document.getElementById("mesg");
var errmesg = document.getElementById("errmesg");
var session = null;
var drawing = null;


// Get ProE session object
//
try {
session = pfcGetProESession();
}
catch (e) {
errmesg.innerHTML = "Unable to connect to Pro/Engineer";
return null;
}


// Get model object and ensure it's a drawing
//
try {
drawing = session.CurrentModel;

if (drawing == null || drawing.Type != pfcCreate("pfcModelType").MDL_DRAWING) {
errmesg.innerHTML = "A drawing must be active!";
return null;
}
}
catch (e) {
errmesg.innerHTML = "A drawing must be active.";
return null;
}


// Prompt user to select an existing table
//
var selections = null;
var table = null;

try {
selections = selectItems("dwg_table", 1);
var tabnum = selections.Item(0).SelItem;
table = drawing.GetTable(tabnum.Id);
}
catch (e) { // nothing selected
errmesg.innerHTML = "A drawing table was not selected.";
return null;
}

selections.Item(0).UnHighlight();


mesg.innerHTML = "Selected Table: "
+ table.GetRowCount() + " rows, "
+ table.GetColumnCount() + " columns";


// Gather data from table and populate into array
//

var array = new Array();

for (var i=0; i<table.GetRowCount(); i++) {

array[i] = new Array();

for (var j=0; j<table.GetColumnCount(); j++) {

// Table cell indexes start with one, arrays with zero
var cell = pfcCreate("pfcTableCell").Create(i+1,j+1);
var mode = pfcCreate("pfcParamMode").DWGTABLE_NORMAL;
array[i][j] = "";

try {
var textseq = table.GetText(cell, mode);

for (var k=0; k<textseq.Count; k++) {
var textitem = textseq.Item(k);
if (k > 0) { array[i][j] += "\n"; }
array[i][j] += textitem;
}
}
catch (e) { // cell has no value
// ignore
}

}

}

return array;
}
 

ArrayToExcel Function

The ArrayToExcel() function takes the two dimensional array and populates cells in a new Excel workbook. There are only three steps in this function: Get the Excel session object, Create a new workbook and get the active sheet object, Populate cells of the active sheet from data in the array.

As an alternative, a new Excel session could be started if an existing one can not be found.

function ArrayToExcel ( array ) {

var oXL;
var errmesg = document.getElementById("errmesg");


// Try to access Excel and get Application object.
//
try {
oXL = GetObject("","Excel.Application");
if (oXL == null) {
errmesg.innerHTML = "Failed to get Excel session object.";
return null;
}
}
catch (e) {
// oXL = new ActiveXObject("Excel.Application");
errmesg.innerHTML = "Excel must be running!";
return;
}


// Make session visible, get Sheet object
//
try {
oXL.Visible = true;
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
}
catch (e) {
errmesg.innerHTML = "Problem creating new workbook.";
return;
}


// Put the array data into the cells of the active sheet
//
for (var i=0; i < array.length; i++ ) {
for (var j=0; j < array[i].length; j++ ) {
// Excel cell indexes start with one, arrays with zero
oSheet.Cells(i+1, j+1).Value = array[i][j];
}
}

}
 

selectItems Function

The selectItems() function is largely based on selectItems() from an example in the Pro/WebLink documentation. It is changed here to be slightly more generic. The function builds a pfcSelectionOptions object that defines the type and number of allowable items that can be selected. It also minimizes the browser window during the selection process.

A sequence of selections (or null if nothing was selected) is returned.

function selectItems ( options, max ) {

// Setup options object
selOptions = pfcCreate("pfcSelectionOptions").Create(options);
selOptions.MaxNumSels = parseInt(max);


var session = pfcGetProESession();
var browserSize = session.CurrentWindow.GetBrowserSize();
session.CurrentWindow.SetBrowserSize(0.0);


var selections = null;

try {
selections = session.Select(selOptions, null);
session.CurrentWindow.SetBrowserSize(browserSize);
}
catch (err) {
session.CurrentWindow.SetBrowserSize(browserSize);
// In case user didn't select expected item
var errstr = pfcGetExceptionType(err);
if (errstr == "pfcXToolkitUserAbort" || errstr == "pfcXToolkitPickAbove") {
return null;
}
}

if (selections == null || selections.Count == 0)
return null;


return selections;
}
 


As I've mentioned, interaction with Excel is easy and straightforward. Although the Pro/Engineer interaction code is much more complex, the PFC API's contain a rich set a classes and methods making automation, such as I have shown here, possible. It's a quantum leap beyond relying upon mapkeys.

Wednesday, June 11, 2008

Pro/E VB API: A First Look

A peek under the hood of the new API for Wildfire 4

In case you didn't know about it, PTC introduced a new PFC based API for Pro/Engineer, starting with Wildfire 4. It's called the VB API and it allows code to be written in Visual Basic that can communicate with Pro/Engineer. (For the curious, it does not work with older versions of Pro/Engineer, sorry)

Unlike Pro/WebLink, it is not limited to running in the embedded web browser. Applications written with the VB API can be run almost anywhere that supports a Visual Basic environment (i.e. in an Excel macro). It's important to understand how this new API works in order to understand some of its limitations and to write robust applications.

The API is an asynchronous PFC API, which means that it shares a set of core classes and methods which are mostly identical to Pro/WebLink and J-Link. It is asynchronous in that VB API applications run outside of the Pro/Engineer process (i.e. in Excel, Word, etc), but still can communicate and control the Pro/Engineer session.

EXE COM Server?

Similar to Pro/WebLink, it is implemented as a COM server, but (interestingly) not as a DLL. While a VB API application is running, an executable called "pfclscom.exe" starts and runs in the background. This introduces a major limitation.

Only one VB API program can run at a time, even if there are multiple Pro/Engineer sessions. If a second VB API application tries to start, it won't be able to connect to any Pro/Engineer session if the first one is still connected. As long as the first application has disconnected, the second connection will be successful.

This is a little disappointing, because one can have several asynchronous Pro/Toolkit applications connected to a single Pro/Engineer process at the same time. In fact, there could be any number of Pro/Toolkit applications connecting to any number of Pro/Engineer sessions. There is really no underlying technical restriction causing this limitation.

You had me at goodbye

Those familiar with asynchronous Pro/Toolkit and J-Link applications probably already know that the main steps in an asynchronous application are: 1) Connect to the Pro/Engineer session, 2) Do some stuff, 3) Disconnect. While step 2 is somewhat optional, step 3 is absolutely critical.

The primary reason is that Pro/Engineer keeps track of all asynchronous connections, and considers connections that have not disconnected as "open". Unfortunately, there is a limit to the number of "open" connections, and that limit is surpisingly low.

If you have an asynchronous application that connects over and over with no disconnect, Pro/Engineer will eventually refuse any further connections. It doesn't matter if it's a Pro/Toolkit, J-Link, or VB API application. The limit is around 58-60 connections. That might sound a little high, but if you run VB API programs from an Excel macro over and over again, you might hit that limit pretty quick. If you disconnect properly, there should be no limit to the number of times you can connect to a Pro/Engineer session.

You'd think that with disconnecting being so important for asynchronous applications, it would deserve some special mention in the documentation. Well, you'd be wrong. Sure, the Disconnect() method is mentioned along with the various flavors of the Connect() method, but there is no mention of the importance of disconnecting. You have been warned.

It it weren't broke, they wouldn't have fixed it

All is not perfect in Pro/Engineer VB land however. Don't waste your time with the C000 build of Wildfire 4. The COM server that comes with the install won't allow any connections.

Another more minor issue has to do with "text message" files that nearly all Pro/Engineer API's use. The "text" directory containing these files would normally be defined in a protk.dat file. This is not used for asynchronous applications. Instead, it is specified as part of the connection process. All of the Connect() methods have an argument that is supposed to identify the "text" directory.

For some reason, this argument is ignored by the VB API. As a result, only files in subdirectories of the Pro/Engineer install can be used (Proe/text/usascii if your language is english). It's not a major problem, but definitely an inconvenience if distributing your code to other users and/or companies.

"Happiness equals reality minus expectations" -Tom Magliozzi

Although I question the choice of an EXE based COM server, on the whole, PTC did a great job making the VB API fully functional and very consistent with its sibling API's (Pro/WebLink and J-Link). While I find that Visual Basic has a kludgey syntax and a somewhat broken object model, the API itself gets the job done.

Monday, June 9, 2008

Pro/WebLink: Send Excel Data To Pro/ENGINEER Drawing Tables and Back Again - Part 1

In previous articles (BOM Data to Excel, Point Data to Excel), I've discussed the transfer of data from Pro/ENGINEER to Excel. Of course, transfering the data in the other direction, from Excel to Pro/Engineer, is not only possible, but it's just as easy.

In this two part article series, I will be discussing how to take data from a selected range in Excel and transfer that into a new table in a Pro/ENGINEER drawing, and vice versa. Part 1 concerns the Excel to Pro/Engineer transfer, and part 2 concerns the Pro/Engineer to Excel transfer.

HTML Page

The HTML page for this application is very simple: two javascript files, two buttons, and two status fields. pfcUtils.js is provided by PTC (see my pfcCreate optimization article).

All remaining code from this article is in the excel2table.js file. One of the buttons allows transfer from Excel to ProEngineer using the ExcelToTable() function, while the other allows transfer in the other direction using the TableToExcel() function. The two div fields allow for the display of error and general status information.

<HTML>
<SCRIPT LANGUAGE="JavaScript" type=text/javascript src="pfcUtils.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript" type=text/javascript src="excel2table.js"></SCRIPT>
<BODY>

<form name="f">
<table border=1>
<tr>
<td>Excel</td>
<td>
<INPUT name="button1" type=button value=">>" onclick="ExcelToTable()">
<br>
<INPUT name="button2" type=button value="<<" onclick="TableToExcel()">
</td>
<td>Drawing Table</td>
</tr>
</table>

<br><font color='red'><a id="errmesg"></a></font>
<br><a id="mesg"></a><br>
</form>

</BODY>
</HTML>
 

ExcelToTable Function

The core of ExcelToTable() is pretty basic. Other than resetting the status fields, it uses ArrayFromExcel() to obtain an array of Excel data and ArrayToProETable() to create a drawing table from the array.

function ExcelToTable ( ) {
var mesg = document.getElementById("mesg");
var errmesg = document.getElementById("errmesg");
mesg.innerHTML = "";
errmesg.innerHTML = "";

var array = ArrayFromExcel();

if (array == null) {
mesg.innerHTML = "null array";
return;
}

if (array != null) { ArrayToProETable(array); }
}
 

ArrayFromExcel Function

The ArrayFromExcel() function has three main tasks: get the Excel session object using GetObject(), get the current range selection object, then loop through the rows and columns of the selection and extract the cell values.

Looping through the selection is done using Enumerator objects, one for rows and one for columns. The rows Enumerator is created using the 'rows' property of the selection object, then a for loop is used to iterate over the rows. For each row, a columns Enumerator is created using the 'columns' property, which references the selected columns of the row. The second for loop iterates over those columns, which in this case are cells.

The Enumerator has an item() method which is used to obtain the row object from the row Enumerator and the cell object from the column Enumerator. The 'value' property returns the cell value, which would usually be of type 'Number' or 'String'. Regardless of the type, the value is coerced into a String for ease of processing later. Pro/ENGINEER treats all table cell values as strings anyway, so it doesn't really matter too much what the type is.

The array used is two dimensional, populated in the iteration of the selection. A two dimensional array is created by first constructing an Array object, then populating it with array objects. The elements of the internal arrays contain the cell values. In the iteration, as a new row is processed, a new Array object is created and then assigned to the top level array. In Javascript, elements can be added to an Array object by a simple assignment statement, almost endlessly.

Once the iteration of the selection via Enumerator's has completed and the array has been populated, the array is returned.

function ArrayFromExcel ( ) {

var oXL = null;
var mesg = document.getElementById("mesg");
var errmesg = document.getElementById("errmesg");


// Try to access Excel and get Application object.
//
try {
oXL = GetObject("","Excel.Application");
if (oXL == null) {
errmesg.innerHTML = "Failed to get Excel session object.";
return null;
}
}
catch (e) {
errmesg.innerHTML = "Excel must be running!";
return null;
}


// Get Selection object
var sel = null;

try {
sel = oXL.ActiveWindow.Selection;
}
catch (e) {
errmesg.innerHTML = "Could not get Selection object.";
return null;
}

if (sel.columns.count <= 1 && sel.rows.count <= 1) {
errmesg.innerHTML = "A range of cells must be selected in Excel.";
return null;
}

mesg.innerHTML = "Selection: " + sel.rows.count + " rows, " + sel.columns.count + " columns";


var i_row = 0;
var e_rows = new Enumerator(sel.rows);
var array = new Array();


// Loop through each row of the selection
//
for ( ; !e_rows.atEnd(); e_rows.moveNext() ) {

var i_col = 0;
var row = e_rows.item();
var e_cols = new Enumerator(row.columns);

array[i_row] = new Array();

// Within the row, loop through each column
//
for ( ; !e_cols.atEnd(); e_cols.moveNext() ) {

var cell = e_cols.item();
var val = cell.value;

if (val == null) { val = "-"; }
array[i_row][i_col] = "" + val;
i_col++;
}

i_row++;
}

return array;
}
 

ArrayToProETable Function

The ArrayToProETable() function takes an array and creates a drawing table. Its main steps are: get the ProE session object, prompt the user for the table location, create the table creation instructions object, create the row and column specification objects, create the table, add content to the table cells, and display the table. As you can see, the ProE portion is quite a bit more complicated than the Excel part.

Included in the function, part of the row and column specs, are calculations to auto-size the rows and columns to fit the data in Excel. This is primarily for readability of the resulting table making it optional, but very helpful.

Also included is a workaround for a table creation bug that limits the size of a table to no more than 50 rows and/or no more than 50 columns. This is a bug in all Pro/Engineer API's, even Pro/Toolkit and J-Link. It doesn't mean that a huge table can't be created, just that it can't be created in one shot.

The workaround in the function is to create the table with a single row or column then add more rows or columns as necessary to get the table to the requested size. With the adjustment step (adding rows and/or columns) coming after the table creation step, but before the table display step, the time required by the workaround is hardly noticable, except with huge tables.

function ArrayToProETable ( array ) {

var errmesg = document.getElementById("errmesg");
var session = null;
var drawing = null;


// Get ProE session object
//
try {
session = pfcGetProESession();
}
catch (e) {
errmesg.innerHTML = "Unable to connect to Pro/Engineer";
return null;
}


// Get model object and ensure it's a drawing
//
try {
drawing = session.CurrentModel;

if (drawing == null || drawing.Type != pfcCreate("pfcModelType").MDL_DRAWING) {
errmesg.innerHTML = "A drawing must be active!";
return null;
}
}
catch (e) {
errmesg.innerHTML = "A drawing must be active.";
return null;
}


// Get location for new table by mouse click
//
var location = getMousePickPosition("Select location for table", true);
if (location == null) { return null; }


// Setup the table creation instructions object
//
var instrs = new pfcCreate("pfcTableCreateInstructions").Create(location);
instrs.SizeType = pfcCreate("pfcTableSizeType").TABLESIZE_BY_NUM_CHARS;


// Figure out max sizes to auto-expand the table
var ArrayMaxData = getArrayMaxData(array);


// Generate column data (for table creation instructions object)
// API Bug: Can't create table with more than 50 columns
// Workaround: Create with one column, add more later
//

var column_just = pfcCreate("pfcColumnJustification").COL_JUSTIFY_LEFT;
var columnData = pfcCreate("pfcColumnCreateOptions");
var columnOption = pfcCreate("pfcColumnCreateOption");
var maxOneShotCols = 50; // Most columns that can be created without workaround

if (ArrayMaxData.cols < maxOneShotCols) {
// Number of columns is ok, setup instructions to create table as-is.
// Use max column widths to auto-size columns
for (var i=0; i < ArrayMaxData.max_col_width.length; i++ ) {
var column = columnOption.Create(column_just, ArrayMaxData.max_col_width[i]);
columnData.Append(column);
}
}
else {
// Too many columns to create table as-is, setup instructions
// to create table with one column, expand after creation
var column = columnOption.Create(column_just, ArrayMaxData.max_col_width[0]);
columnData.Append(column);
}

// Add column data object to table creation instructions
instrs.ColumnData = columnData;


// Generate row data (for table creation instructions object)
// API Bug: Can't create table with more than 50 rows
// Workaround: Create with one row, add more later
//

var rowData = pfcCreate("realseq");
var maxOneShotRows = 50; // Most rows that can be created without workaround

if (ArrayMaxData.rows < maxOneShotRows) {
// Number of rows is ok, setup instructions to create table as-is.
// Use max row heights to auto-size rows
for (var i = 0; i < array.length; i++) {
rowData.Append(ArrayMaxData.max_row_height[i]);
}
}
else {
// Too many rows to create table as-is, setup instructions
// to create table with one row, expand after creation
rowData.Append(ArrayMaxData.max_row_height[0]);
}

// Add row data object to table creation instructions
instrs.RowHeights = rowData;


// Create the table (no contents yet, and won't be visible yet)
//
var dwgTable = null;

try {
dwgTable = drawing.CreateTable(instrs);
}
catch (e) {
errmesg.innerHTML += "Cannot create table: " + e.message;
return;
}


// Add rows if data had more than allowed to create in one shot
//
try {
if (ArrayMaxData.rows >= maxOneShotRows) {
for (var i=1; i < array.length; i++ ) {
// Add remaining rows needed. Index starts
// at 1 because one row already exists
dwgTable.InsertRow(ArrayMaxData.max_row_height[i], null, false)
}
}
}
catch (e) {
errmesg.innerHTML += "Cannot add rows: " + e.message;
return;
}


// Add columns if data had more than allowed to create in one shot
//
try {
if (ArrayMaxData.cols >= maxOneShotCols) {
for (var i=1; i < ArrayMaxData.max_col_width.length; i++ ) {
// Add remaining columns needed. Index starts
// at 1 because one column already exists
dwgTable.InsertColumn(ArrayMaxData.max_col_width[i], null, false);
}
}
}
catch (e) {
errmesg.innerHTML += "Cannot add columns: " + e.message;
return;
}


// Fill in each cell with data
//
for (var i=0; i < array.length; i++ ) {
for (var j=0; j < array[i].length; j++ ) {
// Table cell indexes start with one, arrays with zero
writeTextInCell(dwgTable, i+1, j+1, array[i][j]);
}
}


// Display the table
dwgTable.Display ();
}
 

getMousePickPosition Function

The getMousePickPosition() function is used to prompt the user for a position by using the left mouse button. It uses the UIGetNextMousePick() method of the pfcSession object to accomplish this. The function also hides the browser window, displays an alert dialog to prompt the user, and then restores the browser window to its previous size.

function getMousePickPosition ( prompt, hideBrowser ) {

var browserSize = null;
var session = pfcGetProESession();

if (hideBrowser) {
// Minimize browser, remember browser size for later restoration
browserSize = session.CurrentWindow.GetBrowserSize();
session.CurrentWindow.SetBrowserSize(0.0);
}

// Prompt user and get user specified location
alert(prompt);
var mouseButton = pfcCreate("pfcMouseButton");
var mouseClick = session.UIGetNextMousePick(mouseButton.MOUSE_BTN_LEFT);

if (hideBrowser) {
// Restore browser window
session.CurrentWindow.SetBrowserSize(browserSize);
}

return mouseClick.Position;
}
 

getArrayMaxData Function

The getArrayMaxData function analyzes an array and returns an object containing four properties. Two properties are the number of rows and columns in the array, which is expected to be two dimensional. The other two properties are maximum column widths for each column and maximum row heights for each row.

If a row in excel contains a cell with a single linefeed character, that row will have a maximum row height of at least two characters. Similarly, if a column contains a cell with 50 characters, the maximum column width for that column will be at least 50 characters.

Once these values are populated, the object is returned to the calling function.

function getArrayMaxData ( array ) {

var obj = new Object();

// Figure out max size for each row and column to auto-expand
//
obj.max_col_width = new Array();
obj.max_row_height = new Array();

for (var i=0; i < array.length; i++ ) {
obj.max_row_height[i] = 0;
}

for (var i=0; i < array[0].length; i++ ) {
obj.max_col_width[i] = 0;
}

obj.rows = array.length;
obj.cols = 0;

// populate arrays of max column widths and max row heights
//
for (var i=0; i < array.length; i++) {

for (var j=0; j < array[i].length; j++) {

if (obj.cols < array[i].length) { obj.cols = array[i].length; }

var lines = array[i][j].split("\n");

if (lines.length > obj.max_row_height[i]) {
obj.max_row_height[i] = lines.length;
}

for (var k=0; k < lines.length; k++ ) {
if (lines[k].length > obj.max_col_width[j]) {
obj.max_col_width[j] = lines[k].length;
}
}

}

}

return obj;
}
 

writeTextInCell Function

The writeTextInCell() function writes text to a specific table cell. If the cell data in Excel contains linefeeds, the result will be a table cell that matches with the same number of lines of text.

function writeTextInCell ( table, row, col, text ) {

var cell = pfcCreate("pfcTableCell").Create(row, col);
var lines = pfcCreate("stringseq");

var cell_lines = text.split("\n");

for (var i=0; i < cell_lines.length; i++ ) {
lines.Append(cell_lines[i]);
}

table.SetText(cell, lines);
}
 


There may be strange issues if "zombie" or multiple Excel sessions are running. If Excel is clearly running, but unexpected error messages are received, it may be best to kill all Excel sessions, then start it over again.

Part 2: Sending drawing table data to Excel

Wednesday, May 28, 2008

Pro/ENGINEER: Anatomy of a Trail File, Part 2

Read Part 1

Recording/Editing Techniques

Trail files are often touted as a crash recovery mechanism. While they can serve this function in very limited circumstances, they are usually not that helpful for this activity. For repetitive tasks, however, trail files are extraordinarily helpful.

To make them extraordinarily helpful, trail files must be recorded and edited very carefully. Right out of the box, Pro/ENGINEER doesn't record very efficient trail files. They will function, but can be excessively verbose and difficult to edit.

Here is an example of a trail file segment that opens a part file. It's a good example of how not to record trail files. Generally speaking, avoid typing in names when you can select them.

~ Select `main_dlg_cur` `MenuBar1` \
1 `File`
~ Close `main_dlg_cur` `MenuBar1`
~ Activate `main_dlg_cur` `File.psh_open`
< 2 0.256000
~ Input `file_open` `Inputname` \
`a`
~ Input `file_open` `Inputname` \
`ab`
~ Input `file_open` `Inputname` \
`abc`
~ Input `file_open` `Inputname` \
`abc.`
~ Input `file_open` `Inputname` \
`abc.p`
~ Input `file_open` `Inputname` \
`abc.pr`
~ Input `file_open` `Inputname` \
`abc.prt`
~ Update `file_open` `Inputname` \
`abc.prt`
~ Activate `file_open` `Inputname`
!Command ProCmdModelOpenExe was pushed from the software.
!15-May-08 17:39:09 Start ./abc.prt.2
!15-May-08 17:39:11 End ./abc.prt.2
 
Compare this against a trail recorded by selecting (not typing) the name of the model to open, and using the config.pro option CMDMGR_TRAIL_OUTPUT set to YES. This option is meant to simplify trail file output and make the menu picks less dependent on the menus. If Tools / Customize Screen is used to move menus around, this mapkey will continue to work, but the previous one might fail.

~ Command `ProCmdModelOpen` 
< 2 0.256000
~ Select `file_open` `Ph_list.Filelist` \
1 `abc.prt`
~ Activate `file_open` `Open`
!Command ProCmdModelOpenExe was pushed from the software.
!15-May-08 17:36:11 Start ./abc.prt.2
!15-May-08 17:36:16 End ./abc.prt.2
 
As you can see the results are much simpler. In fact, following the rules from Part 1, four of the eight lines can additionally be reduced:

~ Command `ProCmdModelOpen` 
~ Select `file_open` `Ph_list.Filelist` \
1 `abc.prt`
~ Activate `file_open` `Open`
 

There will be times when you need to automate something using an existing trail file but you either don't have the luxury or the desire to re-record the trail file. In this case you want to eliminate the fluff, but keep the necessary elements. From the verbosely recorded sequence, the following can be completely eliminated:

~ Input `file_open` `Inputname` \
`a`
~ Input `file_open` `Inputname` \
`ab`
~ Input `file_open` `Inputname` \
`abc`
~ Input `file_open` `Inputname` \
`abc.`
~ Input `file_open` `Inputname` \
`abc.p`
~ Input `file_open` `Inputname` \
`abc.pr`
 

Of the remaining lines, the first two can typically be eliminated.

~ Input `file_open` `Inputname` \
`abc.prt`
~ Update `file_open` `Inputname` \
`abc.prt`
 

Which leaves this as a result:

~ Update `file_open` `Inputname` \
`abc.prt`
 

When you are replaying a trail file without changing the model used (i.e. for running a benchmark), a lot of these edits are not required. When you are using the trail file as a template for different models, these type of edits are very important, making it much easier to adapt the trail file.


Next time: Robust selection techniques with trail files

Thursday, May 22, 2008

Pro/WebLink: Changing Model Relations Quickly with Wildfire 4

Changing relations is often a frustratingly difficult task to perform in a Pro/ENGINEER model. This is especially true for assemblies, even ones with only a few dozen parts.

Up until Wildfire 4, there were many ways to accomplish this involving some kind of file export/import process. These include mapkeys, J-Link, and Pro/WebLink, each having its own complications.

Starting with Wildfire 4, the PFC API's (Pro/WebLink, J-Link, VB API) have been enhanced to allow more direct access to relations. Relations can be read into a string sequence (a form of dynamic array), modified within the sequence, then re-applied to the model very quickly. This makes programmatic editing of relations very simple, fast, and easy.

While using the PFC API's to perform this action on a single part model may seem overkill compared to using mapkeys, consider that mapkeys don't scale well. If you're doing a one-off task, mapkeys work great. When you need to perform the task for all components of an assembly, whether large or small, the API's can accomplish the task much more quickly and reliably. For assemblies with thousands of components, mapkeys just won't get the job done.

What follows is an example of a Pro/WebLink function to add relations to a model from an array. First, existing relations are obtained from the model using the "Relations" property (a stringseq object), then elements of the array are appended to the stringseq using the Append() method. Finally, the modified stringseq is reassociated to the model. The change is immediate and does not require a regeneration.

function addRelations ( model, array ) {

// get relations as stringseq object
var rel_seq = model.Relations;

// append array elements to stringseq
for (var i=0; i<array.length; i++) {
rel_seq.Append(array[i]);
}

// assign modified stringseq to model relations
model.Relations = rel_seq;

}
 
Code to call the function is also pretty basic. Using the CurrentModel property of the session object, the model object can is obtained. Here an array is defined, but even better would be to pull the values from an HTML TextArea or some other data source. Lastly, the addRelations() function is called with the model object and the relations array.

// get current model
var session = pfcGetProESession();
var model = session.CurrentModel;

// define new relations as array
var array = new Array( "abc=123", "def=456" );

// add relations
addRelations(model, array);
 
A recursive procedure to apply relations to assembly components is only moderately more complicated. See my other examples only how to rcursively process assembly components with Pro/WebLink.




Comments and questions are always welcome, either here on my blog or via email at MarcMettes@InversionConsulting.com.