Tuesday, November 11, 2008

Intralink SQL: User and Group Folder Authorizations

Intralink stores folder authorizations in four Oracle tables. Two for user authorizations (PDM_USERFOLAUTH and PDM_USERFOLRLAUTH) and two for group authorizations (PDM_USERGRFOLAUTH and PDM_USERGRFOLRLAUTH).

The PDM_USERFOLAUTH and PDM_USERGRFOLAUTH tables contain folder role authorizations. The PDM_USERFOLRLAUTH and PDM_USERGRFOLRLAUTH tables contain folder authorizations by release level.


Query for user folder role authorizations:

-- user folder auth
--
set linesize 135
col folpath format a60
col userexpname format a12
col rolename format a15
--
select
FOLPATH,
USEREXPNAME,
ROLENAME
from
pdm.PDM_USERFOLAUTH ufa,
pdm.PDM_ROLE role,
pdm.PDM_FOLDER fol,
pdm.PDM_USER usr
where
role.ROLEID=ufa.ROLEID and
ufa.FOLID=fol.FOLID and
ufa.USERID=usr.USERID
;
 


Query for user folder/releaselevel role authorizations:

-- user folder/releaselevel auth
--
set linesize 135
col folpath format a60
col userexpname format a12
col rlname format a15
col rolename format a15
--
select
FOLPATH,
USEREXPNAME,
RLNAME,
ROLENAME
from
pdm.PDM_USERFOLRLAUTH ufrla,
pdm.PDM_RELEASELEVEL rl,
pdm.PDM_ROLE role,
pdm.PDM_FOLDER fol,
pdm.PDM_USER usr
where
role.ROLEID=ufrla.ROLEID and
ufrla.RLID=rl.RLID and
ufrla.FOLID=fol.FOLID and
ufrla.USERID=usr.USERID
;
 


Query for group folder role authorizations:

-- group folder auth
--
set linesize 135
col folpath format a60
col rolename format a15
col grexpname format a25
--
select
FOLPATH,
GREXPNAME
ROLENAME,
from
pdm.PDM_USERGRFOLAUTH gfa,
pdm.PDM_ROLE role,
pdm.PDM_FOLDER fol,
pdm.PDM_USERGROUP grp
where
role.ROLEID=gfa.ROLEID and
gfa.FOLID=fol.FOLID and
gfa.GRID=grp.GRID
;
 


Query for group folder/releaselevel role authorizations:

-- group folder/releaselevel auth
--
set linesize 135
col folpath format a60
col grexpname format a25
col rlname format a15
col rolename format a15
--
select
FOLPATH,
GREXPNAME,
RLNAME,
ROLENAME
from
pdm.PDM_USERGRFOLRLAUTH gfrla,
pdm.PDM_RELEASELEVEL rl,
pdm.PDM_ROLE role,
pdm.PDM_FOLDER fol,
pdm.PDM_USERGROUP grp
where
role.ROLEID=gfrla.ROLEID and
gfrla.RLID=rl.RLID and
gfrla.FOLID=fol.FOLID and
gfrla.GRID=grp.GRID
;
 


Putting it all together

To streamline these queries, unions can be used to combine the output into one report. In the following example, user and group names are reported under the 'ID' column. The final where clause can be used to filter for a specific user or group. Leave it out to report authorizations for everyone.

The report is also enhanced in that the order of the release levels in the output matches the output one would see in the folder authorization window in Intralink Admin.

The syntax is somewhat inefficient because it is setup to allow outer joins based on folders (see end of article). However, even for very large numbers of folders, user, and groups, the combined query is still pretty fast.


-- user & group auth
--
set linesize 200
column folpath format a70
column rolename format a20
column rlname format a15
column id format a25
--
select FOLPATH,id,rlname,rolename,rlseqnum
from
(
select
folpath,
(select userexpname from pdm.pdm_user where userid=ufa.userid) as id,
'' as rlname,
to_number('') as rlseqnum,
(select rolename from pdm.pdm_role where roleid=ufa.roleid) as rolename
from
pdm.pdm_userfolauth ufa,
pdm.pdm_folder fol
where
ufa.folid=fol.folid
UNION
select
FOLPATH,
(select userexpname from pdm.pdm_user where userid=ufrla.userid) as id,
(select rlname from pdm.pdm_releaselevel where rlid=ufrla.rlid) as rlname,
(select rlseqnum from pdm.pdm_releaselevel where rlid=ufrla.rlid) as rlseqnum,
(select rolename from pdm.pdm_role where roleid=ufrla.roleid) as rolename
from
pdm.PDM_USERFOLRLAUTH ufrla,
pdm.PDM_FOLDER fol
where
ufrla.FOLID=fol.FOLID
UNION
select
folpath,
(select grexpname from pdm.pdm_usergroup where grid=ugfa.grid) as id,
'' as rlname,
to_number('') as rlseqnum,
(select rolename from pdm.pdm_role where roleid=ugfa.roleid) as rolename
from
pdm.pdm_usergrfolauth ugfa,
pdm.pdm_folder fol
where
ugfa.folid=fol.folid
UNION
select
FOLPATH,
(select grexpname from pdm.pdm_usergroup where grid=gfrla.grid) as id,
(select rlname from pdm.pdm_releaselevel where rlid=gfrla.rlid) as rlname,
(select rlseqnum from pdm.pdm_releaselevel where rlid=gfrla.rlid) as rlseqnum,
(select rolename from pdm.pdm_role where roleid=gfrla.roleid) as rolename
from
pdm.PDM_USERGRFOLRLAUTH gfrla,
pdm.PDM_FOLDER fol
where
gfrla.FOLID=fol.FOLID
)
where
id like '%smith%'
order by folpath,id,rlseqnum
;
 


Outer Joins for More Information

To show all folders, regardless of whether they contain any authorization settings, add the following outer join syntax to the above:
      ...folid(+)=fol.folid
 

There will be some minor duplications, but it does give a good sense of where the authorizations are set in your folder hierarchy.

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

Intralink SQL: Searching Based on Attribute Values

Searching based on attribute values can be performed using Oracle SQL, but a little investigation work needs to be done beforehand.

Attributes and their characteristics are contained in the pdm.PDM_CLASSATTR table in the Oracle database. The first step that needs to be done is to identify the 'id' number of the attribute.

The following query shows, for the "file based" attributes, the 'id', the name, and the 'type'. Also included is the CLADEFVALU column which would show any default values for the attributes.



-- show file based attributes
--
select CLAID,CLANAME,CLADEFVALUE,CLATYPE
from pdm.PDM_CLASSATTR
where CLAUSERDEF=1 and CLAFILEBASED=1
order by CLANAME;

CLAID CLANAME CLADEFVALU CLATYPE
---------- -------------------- ---------- ----------
123 Desc 5
234 Matl 5
345 Mc_Config 5
456 Mc_Errors 2
567 Mc_Mode 5
678 Model_Check 5
789 Weight 3
 

The CLATYPE numbers correspond to these data types:

  • 2: Integer
  • 3: Real
  • 4: Boolean
  • 5: String

If the 'Desc' attribute is needed, we take the CLAID value and prepend "UDA" to form the column name in the pdm.PDM_PRODUCTITEM_VUDA1 table. In this example, the Desc attribute corresponds to the "UDA123" column.


Putting this into an example, the following query searches for Intralink PIV's with the Desc attribute matching "...some string...".

-- search based on attribute values 
--
column piname format a35
column UDA123 format a40
column REVVER format a7

SELECT
piv.pivid, PINAME, PIVREV'.'PIVVER as REVVER, UDA123
FROM
PDM.PDM_PRODUCTITEM pi,
PDM.PDM_BRANCH br,
PDM.PDM_PRODUCTITEMVERSION piv,
pdm.PDM_PRODUCTITEM_VUDA1 vuda
WHERE
pi.PIID = br.PIID
AND br.BRID = piv.BRID
AND piv.pivid = vuda.pivid
AND UDA123 like '%some string%'
;
 


For an exact match, use this as the last condition in the "WHERE" clause instead:

AND UDA123 = 'some string'
 

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.

Tuesday, May 20, 2008

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

Trail File Basics

Despite a diverse set of API's, Pro/ENGINEER trail files represent a reliable and robust method of automating Pro/ENGINEER activities. They are not the perfect fit for every application, but for many needs they work great.

Trail files are best used after recording specific actions, then combining the resulting content to create the finished trail file. In order to edit trail files it is important to understand their content.

Here is an example of a trail file header. These entries are generated by Pro/E upon startup without any action from the user. The first line is always present and always required in your trail files. Some other lines that stand out indicate that Wildfire 2 was used and the ProE to JT Translator is started via a protk.dat file. Both of these are status messages and are not required.

!trail file version No. 1301
!Pro/ENGINEER TM Wildfire 2.0 (c) 2004 by Parametric Technology Corporation All Rights Reserved.
< 0 1.135407
< 0 0.964741
< 0 0.879000
< 0 0.842000
!Application (VisProducts): started via registry.
! exec path: /opt/UGS_JtTranslators/ProE/EAI_Proe/proe/sun/proclientWF2
! type: synchronous Pro/TOOLKIT EXE
< 0 0.846000
~ Move `splash_dlg` `splash_dlg` \
2 7.472141 6.432063
 

I have never needed to keep lines that start with the 'less than' symbol and typically always remove them if piecing together a trail file:

< 0 1.135407
< 0 0.964741
< 0 0.879000
< 0 0.842000
 

As the lines relative to the 'splash_dlg' are unnecessary, all that is needed from the above is this:

!trail file version No. 1301
 

Although we don't need the lines associated with the 'splash_dlg', the syntax is important to understand as it is used throughout trail files. The trail file 'interpreter' sees the backslash continuation character (\) as an instruction to treat the following as a single line:

~ Move `splash_dlg` `splash_dlg` \
2 7.472141 6.432063
 
If the entry is to be removed, both lines should be removed, or the trail file will not work. Don't try to combine the lines. That won't work either. If you need the entry, leave it as is. The interpreter can handle it, and you shouldn't worry about it consuming more than one line.


Another note in the JT Translator startup messages is that they start with an exclamation point. This is the 'comment' indicator, instructing the interpreter to ignore the line. All lines starting with an exclamation point are not needed and can be removed, if desired. In some cases, I'll leave a comment in place to help identify the end of an action, but typically they are removed.

To assist in editing trail files, I usually add comment lines before and after sections. This makes it very easy to copy or move sections within the file.

!!!
!!! Run massprop calculation
!!!
~ Select `main_dlg_cur` `MenuBar1` \
1 `Analysis`
~ Close `main_dlg_cur` `MenuBar1`
~ Activate `main_dlg_cur` `Analysis.psh_analysis_modelanl`
~ Activate `modelprop` `Compute`
!%CIMass Properties calculation completed.
~ Activate `modelprop` `Close`
!!!
!!! Exit session
!!!
~ Select `main_dlg_cur` `MenuBar1` \
1 `File`
~ Close `main_dlg_cur` `MenuBar1`
~ Activate `main_dlg_cur` `File.psh_exit`
! Message Dialog: Warning
! : Do you really want to exit?
~ Move `UI Message Dialog` `UI Message Dialog` \
2 14.561095 12.836755
~ FocusIn `UI Message Dialog` `no`
~ FocusIn `UI Message Dialog` `yes`
~ Activate `UI Message Dialog` `yes`
!End of Trail File
 

Part 2: Recording robust trail files

Thursday, May 1, 2008

Pro/Toolkit: Simplifying Your protk.dat File with Environment Variables

If you find yourself editing your protk.dat files because you are changing the location of the application or you are using multiple hardware architectures (i.e. Unix and Windows, Win32 and Win64, etc), STOP! Put down the mouse, and slowly step away from the keyboard.

If you use environment variable creatively, you will need one protk.dat file for all of your installations. That's it, just one. Unix and Windows you ask? YES! 32 bit and 64 bit Windows? YES!

The first thing you need to do is to setup an environment variable for the install folder of your application. Call it what you want, but be consistent. I am going to give examples here about the open source Pro/ENGINEER to BRL CAD converter. I'll use the environment variable PROE2BRL_INSTALL for the install folder.

The resulting protk.dat file looks like this:

name PROE2BRL
startup dll
exec_file $PROE2BRL_INSTALL/proe2brl.dll
text_dir $PROE2BRL_INSTALL/text
allow_stop TRUE
end

 
I know what you're thinking, you think you'll have to change those paths for Windows machines. WRONG! It's a little known secret that Pro/ENGINEER on Windows can handle unix style pathing and environment variable syntax, and not just in protk.dat files. This includes the config.pro file. It may seem strange to those die-hard Windows guys, but it works.

Now the 64 bit Windows guy in the audience (I'll call him Dustin), shouts out "What if we have 32 bit and 64 bit DLL's?!" Well Dustin, no problem there either because Pro/ENGINEER sets some platform specific environment variables that we can use.

We can separate the 32 bit and 64 bit DLL's into two folders. For Windows, this would be "i486_nt" for 32 bit DLL's and "x86e_win64" for 64 bit DLL's. If we plug in the MC environment variable, Pro/ENGINEER uses the correct DLL based on the current architecture.

The resulting protk.dat file looks like this:

name PROE2BRL
startup dll
exec_file $PROE2BRL_INSTALL/$mc/proe2brl.dll
text_dir $PROE2BRL_INSTALL/text
allow_stop TRUE
end

 
Now the Unix guys, bored with talk of mere a 32 bit application, rant "On Unix, our DLL's are called shared objects and have a .so extension and ... blah blah blah ...". Again, not a problem. If that's a concern, setup another environment variable, let's call it PROE2BRL_EXEC. On Unix this can be set to "proe2brl.so" and on Windows "proe2brl.dll". (Or, just call it "proe2brl.dll" and skip this step)

The resulting protk.dat file looks like this:

name PROE2BRL
startup dll
exec_file $PROE2BRL_INSTALL/$mc/$PROE2BRL_EXEC
text_dir $PROE2BRL_INSTALL/text
allow_stop TRUE
end

 

In the config.pro, we can use this:

protkdat $PROE2BRL_INSTALL/protk.dat

 

These techniques get us much closer to the mythical "one install" for all platforms. Also be sure to check out my previous article on how to conditionally load your Pro/Toollkit applications.


Questions and comments are always welcome, either here on my blog or at MarcMettes@InversionConsulting.com.

Tuesday, April 29, 2008

WebLink: Sending Pro/ENGINEER Point Data to Excel

Extracting point data from your Pro/ENGINEER models can be a cumbersome task, especially if you follow the suggested PTC export/import process. This can be streamlined significantly using Pro/WebLink, but also with J-Link and Pro/Toolkit.

I've discussed, in previous articles, obtaining lists of features and recursing through assemblies. What's different here is that a transformation matrix will be used to obtain the XYZ position of the point with respect to the default coordinate system of the assembly. This is the position data that will be output to Excel.


The HTML page has a single button, which initiates the point data extraction, and a single div field for some results. Library files pfcUtils.js and pnts2excel.js contain Javascript code. pfcUtils.js is a utility library provided by PTC. The code discuss in this article would be contained in the pnts2excel.js file.

<HTML>
<SCRIPT LANGUAGE="JavaScript" type=text/javascript src="pfcUtils.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript" type=text/javascript src="pnts2excel.js"></SCRIPT>
<BODY>
<form name="f">
<INPUT name="a" type=button value="Get Point Data!" onclick="GetPoints()">
<br><div id="mesg"></div><br>
</form>
</BODY>
</HTML>

 

After the GetPoints() function has obtained the session object and verified that a model is active, it sets up an object used for some persistent data and for returning an array of points.

The object has the following properties: modelsFound (array), points (array), root (top-level model object), comppath_seq (intseq object) and transform (assembly tranformation matrix). GetPointData() is called using the current model and appdata object to obtain the point data. Then PntArrayToExcel() is used to send the data to Excel.

function GetPoints () {

if (!pfcIsWindows())
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

var elem = document.getElementById("mesg");

var modelname = "no model";
var session = null;
var model = null;

try {
session = pfcGetProESession();
}
catch (e) {
elem.innerHTML = "ERROR: Cannot connect to Pro/Engineer session!";
return;
}

try {
model = session.CurrentModel;
}
catch (e) {
// probably no model
elem.innerHTML = "Problem getting current model info.";
return;
}

elem.innerHTML = "<br>" + "Top Level Model: " + model.FileName;

// Create appdata object
//
var appdata = new Object();
appdata.modelsFound = new Array();
appdata.points = new Array();
appdata.root = model;
appdata.comppath_seq = new pfcCreate("intseq"); // need 'new', this is an instance object
appdata.transform = null;

GetPointData(model, appdata);
PntArrayToExcel(appdata.points);
}

 

There are two main actions in the GetPointData() function: point extraction, and recursing (for subassemblies). The modelsFound array is used in both actions, and helps to avoid extracting data from a model more than once. In the assignment statement, it is flagging the currently encountered model as having been processed, so that it will not get processed again.

After that, a sequence of points is obtained using the current model and the ListItem() method specifying ITEM_POINT. This will return all points in the model, not just a single feature, which is important if point array features are present in the model. Using the 'Point' property of the point, we can get a Point3D object which has the XYZ info. If there is a transform matrix available, it is applied to the point data first. The model name and XYZ data of the point are assigned to an object, which is then push into the 'points' array property of the appdata object.

In the recursing action, if the encountered model is a subassembly, the code iterates over the component features, if any. If the component is active, the feature id is appended to the comppath_seq sequence, which is used to get the model object from the feature object and the transformation matrix from the root assembly's default coordinate system. The matrix is saved into the appdata object.

If the component has not been encountered already, GetPointData() is called recursively with the component model info. After the function returns, the last element of the comppath_seq is removed.

function GetPointData ( model, appdata ) {

var elem = document.getElementById("mesg");
appdata.modelsFound[model.FileName] = 1;


// Get points in current model
//
var points = model.ListItems( pfcCreate("pfcModelItemType").ITEM_POINT );

for (var i = 0; i < points.Count; i++) {
var point = points.Item(i);
var pnt3d = null;

if (appdata.transform == null) {
pnt3d = point.Point;
}
else {
pnt3d = appdata.transform.TransformPoint(point.Point);
}

// send pnt data to the browser
elem.innerHTML += "<br> " + model.FileName + ": "
+ point.GetName() + " (Id " + point.Id + ")"
+ ", XYZ= ( "
+ pnt3d.Item(0) + ", "
+ pnt3d.Item(1) + ", "
+ pnt3d.Item(2) + " )"
;

var object = new Object();
object.Owner = model;
object.Point = pnt3d;

appdata.points.push(object);
}


// Recurse into components, if model is an assembly
//
if ( model.Type == pfcCreate("pfcModelType").MDL_ASSEMBLY ) {

var components = model.ListFeaturesByType( false, pfcCreate("pfcFeatureType").FEATTYPE_COMPONENT );

for (var i = 0; i < components.Count; i++) {

var compFeat = components.Item(i);

if (compFeat.Status != pfcCreate("pfcFeatureStatus").FEAT_ACTIVE) {
continue;
}

// Append id for use in building comppath
appdata.comppath_seq.Append(compFeat.Id);

try {
// Create ComponentPath object to get pfcModel object of component and transform
var cp = pfcCreate("MpfcAssembly").CreateComponentPath( appdata.root, appdata.comppath_seq );
var compMdl = cp.Leaf;
appdata.transform = cp.GetTransform(true);
} catch (e) {
elem.innerHTML += "<br> CreateComponentPath() exception: " + pfcGetExceptionType(e);
}

// Descend into subassembly
if ( !(compMdl.FileName in appdata.modelsFound) ) {
GetPointData(compMdl, appdata);
}

// Remove id (last in seq), not needed anymore
try {
appdata.comppath_seq.Remove( (appdata.comppath_seq.Count-1), (appdata.comppath_seq.Count) );
} catch (e) {
elem.innerHTML += "<br> comppath_seq.Remove exception: " + pfcGetExceptionType(e);
}

} // Loop: components

} // model.Type
}

 

The PntArrayToExcel() function sends the data to Excel. The code first tries to use an existing Excel session, but will start a new one if necessary. Certain IE security settings may result in a new session being started every time.

Once an Excel session is available and a new workbook has been created, the code iterates over the 'points' array property of the appdata object to write the data into the active sheet. Four columns are used in the output, which include the model name, X position, Y position, and Z position. Since a particular coordinate system was not referenced, the default coordinate system of the top-level assembly is used.

function PntArrayToExcel ( array ) {

var oXL;
var elem = document.getElementById("mesg");

// Get/Create Excel Object Reference
try {
oXL = GetObject("","Excel.Application"); // Use current Excel session
}
catch (e) {
// couldn't get an excel session, try starting a new one
try {
oXL = new ActiveXObject("Excel.Application"); // Open new Excel session
}
catch (e) {
// couldn't start a new excel session either
}
}

if (oXL == null) {
elem.innerHTML = "Could not get or start Excel session!";
return;
}

try {
oXL.Visible = true;
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
}
catch (e) {
elem.innerHTML = "Problem creating new workbook.";
return;
}

for (var i=0; i < array.length; i++ ) {
var pnt3d = array[i].Point;
var ownerMdl = array[i].Owner;

oSheet.Cells(i+1, 1).Value = ownerMdl.FileName;
oSheet.Cells(i+1, 2).Value = "" + pnt3d.Item(0);
oSheet.Cells(i+1, 3).Value = "" + pnt3d.Item(1);
oSheet.Cells(i+1, 4).Value = "" + pnt3d.Item(2);
}
}

 

Other than the transformation matrix, the code is pretty straightforward and easily adaptable to other data sets (i.e. parameters, layers, feature lists, etc).


Questions and comments are always welcome, either here on my blog or at MarcMettes@InversionConsulting.com.