Download as pdf or txt
Download as pdf or txt
You are on page 1of 221

API Fundamentals of

SOLIDWORKS PDM Professional


SOLIDWORKS 2016 TRAINING

ENG

SYSPRICE - REVENDA SOLIDWORKS


+55 112165.6900
www.sysprice.com.br
SOLIDWORKS
PDM Professional

API Fundamentals of
SOLIDWORKS PDM Professional

Dassault Systèmes SolidWorks Corporation


175 Wyman Street
Waltham, MA 02451 U.S.A.
© 1995-2015, Dassault Systemes SolidWorks Corporation, a Copyright Notices for SOLIDWORKS Standard, Premium,
Dassault Systèmes SE company, 175 Wyman Street, Waltham, Professional, and Education Products
Mass. 02451 USA. All Rights Reserved. Portions of this software © 1986-2015 Siemens Product
The information and the software discussed in this document are Lifecycle Management Software Inc. All rights reserved.
subject to change without notice and are not commitments by This work contains the following software owned by Siemens
Dassault Systemes SolidWorks Corporation (DS SolidWorks). Industry Software Limited:
No material may be reproduced or transmitted in any form or by D-Cubed™ 2D DCM © 2015. Siemens Industry Software
any means, electronically or manually, for any purpose without Limited. All Rights Reserved.
the express written permission of DS SolidWorks.
D-Cubed™ 3D DCM © 2015. Siemens Industry Software
The software discussed in this document is furnished under a Limited. All Rights Reserved.
license and may be used or copied only in accordance with the
terms of the license. All warranties given by DS SolidWorks as D-Cubed™ PGM © 2015. Siemens Industry Software Limited.
to the software and documentation are set forth in the license All Rights Reserved.
agreement, and nothing stated in, or implied by, this document or D-Cubed™ CDM © 2015. Siemens Industry Software Limited.
its contents shall be considered or deemed a modification or All Rights Reserved.
amendment of any terms, including warranties, in the license D-Cubed™ AEM © 2015. Siemens Industry Software Limited.
agreement. All Rights Reserved.
Patent Notices Portions of this software © 1998-2015 Geometric Ltd.
SOLIDWORKS® 3D mechanical CAD and/or Simulation Portions of this software incorporate PhysX™ by NVIDIA 2006-
software is protected by U.S. Patents 5,815,154; 6,219,049; 2010.
6,219,055; 6,611,725; 6,844,877; 6,898,560; 6,906,712; Portions of this software © 2001-2015 Luxology, LLC. All
7,079,990; 7,477,262; 7,558,705; 7,571,079; 7,590,497; rights reserved, patents pending.
7,643,027; 7,672,822; 7,688,318; 7,694,238; 7,853,940;
8,305,376; 8,581,902; 8,817,028, 8,910,078, 9,129,083, Portions of this software © 2007-2015 DriveWorks Ltd.
9,153,072 and foreign patents, (e.g., EP 1,116,190 B1 and JP Copyright 1984-2010 Adobe Systems Inc. and its licensors. All
3,517,643). rights reserved. Protected by U.S. Patents 5,929,866; 5,943,063;
eDrawings® software is protected by U.S. Patent 7,184,044; 6,289,364; 6,563,502; 6,639,593; 6,754,382; Patents Pending.
U.S. Patent 7,502,027; and Canadian Patent 2,318,706. Adobe, the Adobe logo, Acrobat, the Adobe PDF logo, Distiller
U.S. and foreign patents pending. and Reader are registered trademarks or trademarks of Adobe
Systems Inc. in the U.S. and other countries.
Trademarks and Product Names for SOLIDWORKS For more DS SolidWorks copyright information, see Help >
Products and Services About SOLIDWORKS.
SOLIDWORKS, 3D ContentCentral, 3D PartStream.NET,
eDrawings, and the eDrawings logo are registered trademarks Copyright Notices for SOLIDWORKS Simulation Products
and FeatureManager is a jointly owned registered trademark of Portions of this software © 2008 Solversoft Corporation.
DS SolidWorks.
PCGLSS © 1992-2014 Computational Applications and System
CircuitWorks, FloXpress, PhotoView 360, and TolAnalyst are Integration, Inc. All rights reserved.
trademarks of DS SolidWorks.
FeatureWorks is a registered trademark of Geometric Ltd. Copyright Notices for SOLIDWORKS Standard Product
SOLIDWORKS 2016, SOLIDWORKS Standard, © 2011, Microsoft Corporation. All rights reserved.
SOLIDWORKS Professional, SOLIDWORKS Premium,
SOLIDWORKS PDM Professional, SOLIDWORKS PDM Copyright Notices for SOLIDWORKS PDM Professional
Standard, SOLIDWORKS Workgroup PDM, SOLIDWORKS Product
Simulation, SOLIDWORKS Flow Simulation, eDrawings, Outside In® Viewer Technology, © 1992-2012 Oracle
eDrawings Professional, SOLIDWORKS Sustainability, © 2011, Microsoft Corporation. All rights reserved.
SOLIDWORKS Plastics, SOLIDWORKS Electrical,
SOLIDWORKS Composer, and SOLIDWORKS MBD are Copyright Notices for eDrawings Products
product names of DS SolidWorks.
Portions of this software © 2000-2014 Tech Soft 3D.
Other brand or product names are trademarks or registered
trademarks of their respective holders. Portions of this software © 1995-1998 Jean-Loup Gailly and
Mark Adler.
COMMERCIAL COMPUTER SOFTWARE - PROPRIETARY
Portions of this software © 1998-2001 3Dconnexion.
The Software is a "commercial item" as that term is defined at 48
C.F.R. 2.101 (OCT 1995), consisting of "commercial computer Portions of this software © 1998-2014 Open Design Alliance.
software" and "commercial software documentation" as such All rights reserved.
terms are used in 48 C.F.R. 12.212 (SEPT 1995) and is provided Portions of this software © 1995-2012 Spatial Corporation.
to the U.S. Government (a) for acquisition by or on behalf of The eDrawings® for Windows® software is based in part on the
civilian agencies, consistent with the policy set forth in 48 C.F.R. work of the Independent JPEG Group.
12.212; or (b) for acquisition by or on behalf of units of the
Department of Defense, consistent with the policies set forth in Portions of eDrawings® for iPad® copyright © 1996-1999
48 C.F.R. 227.7202-1 (JUN 1995) and 227.7202-4 (JUN 1995). Silicon Graphics Systems, Inc.
In the event that you receive a request from any agency of the Portions of eDrawings® for iPad® copyright © 2003 - 2005
U.S. Government to provide Software with rights beyond those Apple Computer Inc.
set forth above, you will notify DS SolidWorks of the scope of
the request and DS SolidWorks will have five (5) business days
to, in its sole discretion, accept or reject such request. Contractor/
Manufacturer: Dassault Systemes SolidWorks Corporation, 175
Wyman Street, Waltham, Massachusetts 02451 USA. Document Number: PMT1633-ENG
Contents

Introduction
About This Course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Course Design Philosophy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Using this Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
About the Training Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Conventions Used in this Book . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Windows® 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
More SOLIDWORKS Training Resources. . . . . . . . . . . . . . . . . . . . . . 4
Local User Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Lesson 1:
Connecting to a Vault
COM Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
API Object Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
SOLIDWORKS PDM Professional Type Library . . . . . . . . . . . . . 6
Application Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Case Study: Creating a VB.NET Stand Alone Application . . . . . . 8
Namespaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Importing Namespace Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
The IEdmVault Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Stand-alone Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Add-in Programs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Debugger feedback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Data Tips. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Watch Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Message Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Debug Output Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

i
Contents SOLIDWORKS PDM Professional

Case Study:List Vault Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15


Logging into a Vault . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
LoginAuto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
LoginEx. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Handling HRESULT Return Codes . . . . . . . . . . . . . . . . . . . . . . . . . . 19
C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Visual Basic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
EPDMResultCode Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
VerifyVersion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
SOLIDWORKS PDM Professional API Help . . . . . . . . . . . . . . . . . . 25
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Favorites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Understanding API Interface Member Descriptions. . . . . . . . . . . 27
Interface Versioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Assigning Interfaces of Different Types. . . . . . . . . . . . . . . . . . . . 34
Exercise 1: Connecting to a Vault . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Lesson 2:
Files, Folders, Items and References
The IEdmObject Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
The IEdmFile Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
The IEdmFolder Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
The IEdmPos Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Case Study:File Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Case Study:Folder Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Recursive Folder Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
File References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
The IEdmReference Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
The IEdmBatch-Listing Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
The IEdmClear-LocalCache Interface . . . . . . . . . . . . . . . . . . . . . . . . 49
Case Study:Reference Tree Traversal . . . . . . . . . . . . . . . . . . . . . . . . . 50
Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
The IEdmBatchItem-Generation Interface . . . . . . . . . . . . . . . . . . 60
Case Study:Create Items from Imported Data . . . . . . . . . . . . . . . 60
Exercise 2: Traverse Files and Folders . . . . . . . . . . . . . . . . . . . . . . . . 69

ii
SOLIDWORKS PDM Professional Contents

Lesson 3:
Users and Groups
The IEdmUser Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
The IEdmUserGroup Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
The IEdmUserMgr Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Case Study:User Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Case Study:Group Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Case Study:Group Member Traversal . . . . . . . . . . . . . . . . . . . . . 76
Case Study:Using IEdmUser Properties to Search for Users . . . . 78
Case Study:Adding New Users. . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Exercise 3: Find Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Lesson 4:
Card Variables, Versions and Revisions
Card Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
IEdmEnumerator-Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
GetVar and SetVar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
CloseFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
File Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
File Revisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Case Study:Set Revisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
The IEdmDictionary Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Case Study:Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Exercise 4: Find Cards where a Variable is Used. . . . . . . . . . . . . . . 112
Exercise 5: Find Revisions That Use a Component . . . . . . . . . . . . . 116
Lesson 5:
Add-In Applications
SOLIDWORKS PDM Professional Add-Ins . . . . . . . . . . . . . . . . . . 120
The IEdmAddIn Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Case Study:Creating an Add-In . . . . . . . . . . . . . . . . . . . . . . . . . 120
The Implements Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Simple Implementation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
COM Registration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
GetAddInInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Minimum Version Required . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Additional Add-In Information. . . . . . . . . . . . . . . . . . . . . . . . . . 129
Installing an Add-In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Debugging a DLL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
The IEdmVault Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
The IEdmCmdMgr Argument. . . . . . . . . . . . . . . . . . . . . . . . . . . 137
The IEdmAddIn5. OnCmd Method . . . . . . . . . . . . . . . . . . . . . . 138
Case Study:Changing Card Variable Values . . . . . . . . . . . . . . . 141
EdmCmdData Members for EdmCmd_CardInput . . . . . . . . . . . 143
Case Study:Generating Serial Numbers . . . . . . . . . . . . . . . . . . . 147
EdmCmdData Members for EdmCmd_SerialNo . . . . . . . . . . . . 148
Exercise 6: State Change . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

iii
Contents SOLIDWORKS PDM Professional

Lesson 6:
Task Add-In Applications
SOLIDWORKS PDM Professional Task Add-Ins . . . . . . . . . . . . . . 170
Task Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Case Study:Simple Task Add-In. . . . . . . . . . . . . . . . . . . . . . . . . 173
Task Hooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Case Study:Check Number of Days in State . . . . . . . . . . . . . . . 183
The IEdmSearch Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
The IEdmWorkflowMgr Interface . . . . . . . . . . . . . . . . . . . . . . . 193
The IEdmWorkflow Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Exercise 7: Scheduled Tasks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
Appendix A:
C# Examples
Connecting to a Vault Using C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210

iv
Introduction

1
Introduction SOLIDWORKS PDM Professional

About This The goal of this course is to introduce you to the SOLIDWORKS PDM
Course Professional Application Programming Interface (API). The API can
be used to automate redundant and lengthy tasks using SOLIDWORKS
PDM Professional. It can also be used to expand and build on the
capabilities of SOLIDWORKS PDM Professional. Most of the
capabilities that the user leverages through the SOLIDWORKS PDM
Professional user interface can be automated by programming it
through the API.
The SOLIDWORKS PDM Professional API is so robust and feature
rich that it is impractical to cover every detail and still have the course
be a reasonable length. Therefore, the focus of this course is on the
fundamental skills and concepts central to successfully building
automation tools. You should view the training course manual as a
supplement to, not a replacement for, the system documentation and
on-line help. Once you have developed a good foundation in basic
skills, you can refer to the on-line help for information on more
functionality available in the API.
Prerequisites Students attending this course are expected to have:
 completed the course Administering SOLIDWORKS PDM
Professional.
 experience with the Windows™ operating system.
 experience with Visual Basic.
Course Length The recommended minimum length of this course is 2 days.
Course Design This course is designed around a process- or task-based approach to
Philosophy training. Rather than focus on individual features and functions, a
process-based training course emphasizes the process and procedures
you follow to complete a particular task. By utilizing case studies to
illustrate these processes, you learn the necessary skills in the context
of completing a programming task.
Using this Book This training manual is intended to be used in a classroom environment
under the guidance of an experienced SOLIDWORKS PDM
Professional API instructor. It is not intended to be a self-paced tutorial.
The examples and case studies are designed to be demonstrated “live”
by the instructor.
Laboratory Laboratory exercises give you the opportunity to apply and practice the
Exercises material covered during the lecture/demonstration portion of the
course. They are designed to represent typical programming and
automation situations while being modest enough to be completed
during class time. However, many students work at different paces.
Therefore, we have included more lab exercises than you can
reasonably expect to complete during the course. This ensures that even
the fastest student will not run out of exercises.

2
SOLIDWORKS PDM Professional Introduction

About the A complete set of the various files used throughout this course can be
Training Files downloaded from the SolidWorks website, www.solidworks.com.
Click on the link for Support, then SOLIDWORKS Training, then
Training Files, SOLIDWORKS PDM. Select the link for the desired
file set. There may be more than one version of each file set available.
Direct URL:
www.solidworks.com/trainingfilespdm

The files are supplied in signed, self-extracting executable packages.


The files are organized by lesson number. The Case Study folder
within each lesson contains the files your instructor uses while
presenting the lessons. The Exercises folder contains any files that are
required for doing the laboratory exercises.
Conventions Used This manual uses the following typographic conventions:
in this Book
Convention Meaning
Bold Sans Serif SOLIDWORKS PDM Professional
commands and options appear in this style.
For example, Change State, Passed
approval means choose the Passed
approval option from the Change State
menu.
Typewriter Project names and file names appear in this
style. For example, Block.SLDPRT. Names
that you type appear in this style.
Double lines precede and follow sections of
17 Do this step the procedures. This provides separation
between the steps of the procedure and large
blocks of explanatory text. The steps
themselves are numbered in sans serif bold.

Windows® 7 The screen shots in this manual were made using SOLIDWORKS
PDM Professional running on Windows® 7. You may notice
differences in the appearance of the menus and windows. These
differences do not affect the performance of the software.

3
Introduction SOLIDWORKS PDM Professional

User Interface Throughout the development of the software, there have been some
Appearance cosmetic User Interface changes, intended to improve visibility, that do
not affect the function of the software. As a policy, dialog images in the
manuals which exhibit no functional change from the previous version
are not replaced. As such, you may see a mixture of current and “old”
UI dialogs and color schemes.
More MySolidWorks.com enables you to be more productive by connecting
SOLIDWORKS you with relevant SOLIDWORKS content and services - anytime,
Training anywhere, on any device.
Resources Plus, with MySolidWorks Training you can enhance your
SOLIDWORKS skills on your own schedule, at your own pace.
Just go to My.SolidWorks.com/training.
Local User Groups Discover the benefits of the SOLIDWORKS User Group Network
(SWUGN). Attend local meetings to hear technical presentations on
SOLIDWORKS and related engineering topics, learn about additional
SOLIDWORKS products, and network with other users. Groups are
led by SOLIDWORKS users just like you. Check out SWUGN.org for
more information, including how to find a group in your area.

4
Lesson 1
Connecting to a Vault

Upon successful completion of this lesson, you will be able to:


 Understand the role of COM in the API.
 Understand the types of API applications available.
 Understand the API Object Model.
 Create a stand-alone API application.
 Use IEdmVault properties and methods that don’t require login.
 Login to a vault.
 Use IEdmVault properties and methods that do require login.
 Debug a stand-alone application.
 Handle error codes.
 Understand and use the SOLIDWORKS PDM Professional
API Help.

5
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

COM COM programming is an extremely broad topic and is, for the most
Programming part, beyond the scope of this book. However, the SOLIDWORKS
PDM Professional API is based on COM in order to be able to
accommodate various programming languages. COM is an acronym
for Component Object Model, which is a standard that allows software
components written in different programing languages to interact with
one another. COM programming allows SOLIDWORKS PDM
Professional to expose selected functionality of actual SOLIDWORKS
PDM Professional objects to the outside world.
API Object The SOLIDWORKS PDM Professional API is made up of a group of
Interfaces COM interfaces that are organized into an interface object model.
Interface is the term used to describe the COM mechanism used to
“wrap” the actual class object that is used in the software. Object model
is the term used to describe how the COM interfaces relate to one
another. SOLIDWORKS PDM Professional was designed using object-
oriented programming techniques. Under the hood of SOLIDWORKS
PDM Professional is a vast object model that represents every aspect of
the software. An instance of an interface is referred to as an object and
often the terms interface and object are used synonymously. When you
are using an API interface object you are really working with interface
pointers to the objects that they represent in the SOLIDWORKS PDM
Professional software.
SOLIDWORKS COM utilizes a file called a type library to communicate to other
PDM Professional programs the definitions of the API objects exposed by a software
Type Library application. By referencing a type library within a software
development project, the project’s development environment is made
aware of all the details of the API that are exposed by the type library.
A reference to the current SOLIDWORKS PDM Professional Type
Library should be added to applications that use the API. This type
library contains the definitions for all the functionality supported by the
SOLIDWORKS PDM Professional API including:
 Interfaces
 Members (Properties and Methods)
 Arguments and their types
 Structures
 Enums

6
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

Once a type library is referenced by a Visual Studio project, its contents


can be examined using the Object Browser tool. In addition,
IntelliSense becomes aware of the contents of the type library and
makes it available in the auto-completion tool within the project editor.
The type library is located in the EdmInterface.dll file in the
installation folder. The definitions of all the interfaces and their
members are in the EdmLib namespace defined in the type library.
These COM interfaces that are defined in the type library also happen
to be implemented in the EdmInterface.dll file, although they could
have been placed in separate files and been just as valid.
When a COM type library is referenced by a Visual Studio.NET
project, an Interop Assembly is automatically created. The interop
assembly reproduces, in a .NET way, all the information contained in
the COM type library and acts as a kind of bridge between COM and
the .NET programming environment. Your project is actually
referencing the new interop assembly which will act as a conduit to the
COM API. Some COM server software comes provided with an interop
assembly that is pre-built and ready for use with .NET API programs.
This type of interop assembly is called a Primary Interop Assembly
(PIA). When possible, it is better to reference the pre-built PIA in .NET
API programs rather than reference the type library and then create an
ad-hoc interop assembly as needed. The SOLIDWORKS PDM
Professional software does come provided with a PIA, which is located
in the installation folder and is named EPDM.Interop.epdm.dll. When
distributing your program, the interop assembly needs to be included
along with your other project executables in order for it to run properly.

Application There are two types of applications that can use the SOLIDWORKS
Types PDM Professional API. They are called stand-alone and add-in
applications.
Stand alone applications are typically executable (EXE) files that can
be run independent of SOLIDWORKS PDM Professional and add-ins
are dynamic link library (DLL) files that are loaded by SOLIDWORKS
PDM Professional and can respond to events such as user actions and
menu selections within SOLIDWORKS PDM Professional. Both types
of applications use the same type library, interfaces, structures and
enums with the exception that add-in applications need to implement
the IEdmAddIn5 interface and make use of methods, structures and
enums related to that interface.

7
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

Case Study: Now that you understand the relationship between COM, .NET, the
Creating a VB.NET SOLIDWORKS PDM Professional API, the type library and your
Stand Alone project, you can create a simple application that utilizes the API. Since
Application a stand alone application is easier to create and debug, we’ll start with a
stand alone application and explore add-in applications in later lessons.

1 Create a new SOLIDWORKS PDM Professional stand alone API


application with Visual Basic.
Open Visual Studio. Click File, New, Project from the menu.
From the Installed, Templates list, choose Visual Basic.
Select Windows Forms Application from the Templates list.
In the Name text box, type EpdmStandAlone.
Browse to a suitable folder location for the project and click OK.

2 Add a reference to the project.


To add the SOLIDWORKS PDM
Professional Type Library reference to
the project, navigate to the Solution
Explorer.

Double-click on the My Project node.


In the Project Designer click the References tab.

8
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

Click the Add button and choose Reference from the drop-down list.

3 Add the SOLIDWORKS PDM Professional PIA.


From the Reference Manager dialog box, click the Browse button.
In the file browser dialog, navigate to the SOLIDWORKS PDM
installation folder. This is typically located in the C:\Program Files\
SolidWorks Corp\SOLIDWORKS PDM folder. Scroll down the list
of components and click EPDM.Interop.epdm.dll to select it.
Click Add, then click OK to add the reference to your project.

Note This adds a reference in your project to the Primary Interop Assembly
(PIA) that is provided with SOLIDWORKS PDM Professional. This
.NET assembly wraps the SOLIDWORKS PDM Professional COM
type library and exposes it for native use with .NET projects.

9
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

4 Review the Enums, Structures and Interfaces that are now


available to your project.
Click View, Object Browser from the menu. The external components
that are available to your project are listed in the browser window.
Expand the assembly name EPDM.Interop.epdm and the namespace
name EPDM.Interop.epdm. All the information, including the
Enums, Structures and Interfaces that are contained in the
SOLIDWORKS PDM Professional Type Library are listed.
Click on a listed item to see its members listed in the adjacent window.
Click on a listed member to see details about that member.

Namespaces At this point Visual Studio is aware of the various components


contained within the EdmLib type library because of the reference to it
that has been added to your project through the PIA. Since all the
interfaces, structures and enums in the type library are exposed through
the EPDM.Interop.epdm namespace, your code will need to
somehow include the namespace name when you use them in Visual
Studio.
Importing There are three ways that you can do this.
Namespace  Use fully qualified names by prefixing each name with the
Names namespace name EPDM.Interop.epdm followed by a dot wherever
they are used in your code. For example:
Dim vault As EPDM.Interop.epdm.IEdmVault5
 Add the following statement to the namespace declarations section
at the top of your code.
Imports EPDM.Interop.epdm
This will allow you to refer to the names contained within the type
library without fully qualifying them. For example:
Dim vault As IEdmVault5

10
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

 Check the check box beside EPDM.Interop.epdm in the


Imported namespaces window on the References tab of the
project properties. This has the same effect as adding an Imports
statement.

Using fully qualified names would produce unnecessarily long names


and result in a lot of typing. Since we will be using names from the
EdmLib type library frequently, we will use the Imports statement
method in the examples in this book in order to keep the code more
compact.

5 Add Imports statement to code.


Add the following statement at the top of the Form code:
Imports EPDM.Interop.epdm
Public Class Form1

End Class

6 Edit the form.


Name the form StandAloneForm and assign its Text property the
value Stand Alone.
Add a button control, name it VaultButton, and
assign its Text property the value Vault.

7 Add a click event to VaultButton.


Double-click VaultButton on the form to set up a button click event
handler. When you double-click the button, Visual Studio
automatically adds a stub event handler to the source code. The code
that you will add to the event handler will run when the user clicks the
button while your application is running.
Private Sub VaultButton_Click(ByVal sender As System. _
Object, ByVal e As System.EventArgs) Handles _
VaultButton.Click

End Sub

11
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

The IEdmVault The IEdmVault interface represents a SOLIDWORKS PDM


Interface Professional file vault. It is the highest level interface within the API
and most of the other interfaces are retrieved from it either directly or
indirectly.
Stand-alone Stand-alone programs will use the API by first declaring and creating
Programs an instance of this interface. Since interfaces are abstract definitions
and not implementations, they cannot be created directly using the New
keyword. The type library includes a creatable class called EdmVault5
which implements the IEdmVault5 interface. You can create an
instance of the EdmVault5 class with the New keyword and since this
class implements the IEdmVault5 interface, you can reference it with
the variable declared as IEdmVault5 interface type. By convention,
interface names begin with an upper case “I”
'Declare an IEdmVault5 interface object
Dim vault As IEdmVault5
'Create an instance of IEdmVault5 interface object
vault = New EdmVault5()

Once the IEdmVault5 interface object is created, most of the other


interface objects within the API will be returned either directly or
indirectly by methods and properties of the IEdmVault5 object or
some other API object that originated from it. Some of the IEdmVault
members may be used without first logging into a vault. IEdmVault
has some members for logging into a vault and still other members that
can only be used after logging into a file vault and establishing a
connection with it. Consult the SOLIDWORKS PDM Professional API
Help to learn which members require being logged in to a vault in order
to use them.
Add-in Programs Add-in programs will be passed an IEdmVault5 object when the add-
in is loaded and at other times when needed. No explicit login is
required because the interactive user must already be logged into a
vault when the add-in is launched.

8 Add code to the VaultButton click event handler.


Declare and create an instance of an IEdmVault5 interface object.
Private Sub VaultButton_Click(ByVal sender As System. _
Object, ByVal e As System.EventArgs) Handles _
VaultButton.Click

'Declare an IEdmVault5 interface object


Dim vault As IEdmVault5
'Create an instance of IEdmVault5 interface object
vault = New EdmVault5()
End Sub

12
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

After the instance of IEdmVault5 is created in the code above, the


object vault will represent an instance of a file vault, but is not yet
logged in.

Debugger While debugging, there is frequently a need to display the values of


Feedback variables while the program is executing.
Data Tips The easiest way to display the value of a variable is to hover over the
variable name in the debugger window while execution is paused
within the variable’s scope. A small data tip window will pop up
displaying its value.
Watch Windows There are several watch windows available in the debugger that let you
view the values of variables that you specify or that update depending
on the current scope of the application being debugged.
Message Boxes One technique commonly used is to display information in a message
box using the MsgBox function. This method also stops execution of
the program until the user dismisses the dialog. The MsgBox function
can also be used to display information to the user during normal
program execution; when not debugging. Variations of this technique
include the use of the MessageBox.Show method, which depends on
the System.Windows.Forms type library being referenced and the
use of the IEdmVault5.MsgBox method.
Debug Output Another technique to display variable values while debugging is to use
Window the Debug.Print method to display information in the Output debug
window. In order to see the output of this function, the Output window
needs to be visible in Visual Studio while debugging. If it isn’t visible,
click on the Debug menu, Windows, Output. The Debug.Print
method prints information and continues running so it is useful when it
is necessary to display large amounts of information. The information
remains in the Output window even after the program being debugged
has stopped executing, so it is useful if you want to be able to go back
and refer to it later or even copy and paste any information from it.

Note The Debug.Print method can send its output to the Immediate
window instead of the Output window, depending upon the checked
status of the option Redirect all Output Window text to the
Immediate Window. This option can be set in the Visual Studio Tools,
Options, Debugging, General menu item dialog.

13
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

9 Add code that doesn’t require login.


Some IEdmVault methods and properties don’t require login. For
example, we can call the IsLoggedIn property whether or not we are
logged in. The GetVersion method will return the version information
of the currently installed version of SOLIDWORKS PDM
Professional. Add the following lines of code.
Private Sub VaultButton_Click(ByVal sender As System. _
Object, ByVal e As System.EventArgs) Handles _
VaultButton.Click

'Declare an IEdmVault5 interface object


Dim vault As IEdmVault5
'Create an instance of IEdmVault5 interface object
vault = New EdmVault5()

'Check to see if we're logged into a vault


Debug.Print("We are" + IIf(vault.IsLoggedIn, "", _
" not") + " logged into a vault.")

'Display the SOLIDWORKS PDM Professional version


Dim VerMajor As Integer
Dim VerMinor As Integer
vault.GetVersion(VerMajor, VerMinor)
MsgBox("SOLIDWORKS PDM Professional version is " + _
VerMajor.ToString() + "." + VerMinor.ToString())
End Sub

10 Build and debug the application.


From the Build menu, click Build EpdmStandAlone to build and save
the application then press F5 to run it in the debugger environment.
While simply pressing F5 will cause your project to rebuild if
necessary, it is good to recognize that there are actually two steps
taking place; rebuilding and debugging.
Click the Vault button.
The output showing the current login status using the Debug.Print
method will display first in the Output window.

14
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

Then the MsgBox function will


display a message box showing
the version of SOLIDWORKS
PDM Professional that is
currently installed.
Click the OK button.
11 Stop the application.
Click the close icon in the upper right corner of the Stand Alone form.

Case Study: Without being logged into a vault, the IEdmVault interface can be
List Vault Views used to find and get information about all the vault views that are
currently set on the client computer. This information can be used, for
example, to allow the user to select which vault view they would like to
log in to.
The IEdmVault8.GetVaultViews method has as an output value an
array of EdmViewInfo structures that contain information about the
available vault views. This array needs to be declared before it is
passed as an argument to the IEdmVault8.GetVaultViews method.
Another boolean input argument determines whether all the vault views
are returned or only those that the user is currently logged into.
1 Add a ComboBox control.
Add a ComboBox control and name it
VaultsComboBox. Add a Label control,
name it VaultsLabel and assign its Text
property the value Select Preferred Vault
View.

2 Add a load event handler to the form.


Double-click on the form to set up a load event handler.
Private Sub StandAloneForm_Load(ByVal sender As System. _
Object, ByVal e As System.EventArgs) Handles MyBase. _
Load

End Sub

15
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

3 Add code to the form load event handler.


Add code to declare and create an instance of an IEdmVault8 interface
object.
Declare an initially empty array of EdmViewInfo structures to hold
the vault view information that will be output from the
IEdmVault8.GetVaultViews method.
Add the name of each output vault view to VaultsComboBox.
The user will now be able to select their preferred vault view to be used
in subsequent code.
Private Sub StandAloneForm_Load(ByVal sender As System. _
Object, ByVal e As System.EventArgs) Handles MyBase. _
Load

Dim vault As IEdmVault8 = New EdmVault5


Dim Views() As EdmViewInfo = {}
vault.GetVaultViews(Views, False)
VaultsComboBox.Items.Clear()
For Each View As EdmViewInfo In Views
VaultsComboBox.Items.Add(View.mbsVaultName)
Next
If VaultsComboBox.Items.Count > 0 Then
VaultsComboBox.Text = VaultsComboBox.Items(0)
End If
End Sub

Logging into a There is only so much that can be done using the SOLIDWORKS PDM
Vault Professional API without being logged into a vault. There are two
recommended methods that allow the API user to log into a vault.
These methods are IEdmVault5.LoginAuto and
IEdmVault13.LoginEx. Once logged into a vault there are many more
API methods that are available for your application to use.
LoginAuto The LoginAuto method will log in to the file vault whose name is
passed in as an argument using the same user identity as used in the
SOLIDWORKS PDM Professional client. If no user is currently logged
in on the specified vault, a log-in dialog box will be displayed. If the
window handle of your application is passed in as an argument to
LoginAuto, the log-in dialog box will be kept on top of your
application window. In Visual Basic, you can obtain a window handle
from your form class using the ToInt32() method of the Handle
property of the form class, for example: Me.Handle.ToInt32().

16
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

LoginEx The LoginEx method provides user name and password arguments in
addition to a vault name. This allows your application to login as a
specific user other than the one currently logged in. In case there isn’t a
user logged in already, the LoginEx method will allow an API program
to log in without relying on user intervention. The LoginEx method
will allow your application to properly consume licenses in compliance
with the SOLIDWORKS End User License Agreement.

4 Add a Button control.


Add a second button control, name it
LoginButton, and assign its Text property the
value Login.
5 Add a click event to LoginButton and add
code.
Double-click LoginButton on the form to set up
a button click event handler.
Add the following lines of code.
Private Sub LoginButton_Click(ByVal sender As System. _
Object, ByVal e As System.EventArgs) Handles _
LoginButton.Click

'Declare and create an instance of IEdmVault5 object


Dim vault As IEdmVault5 = New EdmVault5()
'Log into the selected Vault as the current user
vault.LoginAuto(VaultsComboBox.Text, Me.Handle. _
ToInt32())
'Check to see if we're logged into a vault
MsgBox("We are" + IIf(vault.IsLoggedIn, "", " not") + _
" logged into a vault.")
End Sub

6 Build and run the application.


From the Build menu, click Build EpdmStandAlone to build and save
the application then press F5 to run it in the debugger environment.
Since there is no user logged into the
file vault, the LoginAuto method will
cause a login dialog to pop up on top
of your form.
Enter a valid user name and password
and click the Log In button.

17
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

The vault’s IsLoggedIn property should now


confirm that we are logged in.
Click OK.
Now that there is a user logged into the vault, if you
click on the Login button on your form again, you
will not be presented with the login dialog.
7 Stop the application.
Click the close icon in the upper right corner of the form.
8 Add code that requires login.
Once the vault object in our application has been logged in, more
IEdmVault5 members are available for use. Add the following lines of
code.
Private Sub LoginButton_Click(ByVal sender As System. _
Object, ByVal e As System.EventArgs) Handles _
LoginButton.Click

'Declare and create an instance of IEdmVault5 object


Dim vault As IEdmVault5 = New EdmVault5()
'Log into the selected Vault as the current user
vault.LoginAuto(VaultsComboBox.Text, Me.Handle. _
ToInt32())
'Check to see if we're logged into a vault
MsgBox("We are" + IIf(vault.IsLoggedIn, "", " not") + _
" logged into a vault.")
'Display the vault name
MsgBox("The vault name is """ + vault.Name + """.")
'Display the path of the vault view folder
MsgBox("The path of the vault view folder is """ + _
vault.RootFolderPath + """.")
End Sub

9 Build and run the application.


Press F5 to build and save the application and run it in the debugger
environment.
Click the Login button.
The vault’s IsLoggedIn property should confirm
that we are logged in.
Click OK.

18
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

The vault name will display in a message box.


Click OK.

The vault view folder name will


display in another message box.
Click OK.

10 Stop the application.


Click the close icon in the upper right corner of the form.

Handling COM interface methods return a value of the type HRESULT, which is
HRESULT a 32 bit value indicating the status of the method call. Its value
Return Codes indicates success, failure or may indicate warnings. Many HRESULT
constants are pre-defined by the system for indicating typical status
codes specific to the COM runtime.
The SOLIDWORKS PDM Professional API also uses some custom
HRESULT return codes to indicate the result of certain API method
calls.
For example, the VerifyVersion method of the IEdmVault5 interface
will return an HRESULT indicating whether the installed
SOLIDWORKS PDM Professional software is at the specified version
level. If the HRESULT value returned by the VerifyVersion method
call is S_OK, it means that the method successfully executed. If it
returns the HRESULT value
E_EDM_UNSUPPORTED_PROGRAM_VERSION, it means that the
installed program is at a version level that is lower than the specified
version.
C++ Variables in a native C++ API program can be declared as the COM
type HRESULT. These variables can have values assigned to them and
be used directly in C++ code. For instance, the HRESULT returned in
C++ when a COM call has completed successfully is the COM defined
constant S_OK and C++ code can compare a return value from a COM
interface method to the value S_OK to check whether a COM call had
completed successfully. There are many other HRESULT codes
defined that could be returned from methods as well. These codes
inform the program of the status of the COM call.

19
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

.NET In .NET languages such as Visual Basic and C#, the COM HRESULT
code doesn’t get returned directly from a method call as a return value.
Instead, if COM returns any HRESULT value other than S_OK, an
exception is thrown.
Many of the SOLIDWORKS PDM Professional API methods will only
return HRESULT values of S_OK. For these methods, no special
coding is necessary, since when a COM method returns S_OK, normal
program execution continues. However, if any return value other than
S_OK is anticipated, your code will need to include some form of
exception handling because .NET will translate the returned COM
HRESULT code to an exception that needs to be properly handled in
order to prevent the code execution from halting when the exception is
thrown.
You will need to check the SOLIDWORKS PDM Professional API
Help for each method that your API program uses to see which
HRESULT codes they return. The return codes that a method will
return can be found in the Remarks section of the method’s
documentation page.
Visual Basic Visual Basic has a special object variable named Err whose members
will hold the details of an exception after one has been thrown. The
Err.Number member will hold the numeric HRESULT value. This
value can be passed in as an argument to the
IEdmVault5.GetErrorString method to get the error code and
description of the error as defined by the SOLIDWORKS PDM
Professional API.
The Err object is for the most part a legacy object that was used in
Visual Basic prior to .NET but was retained for compatibility.
C# C# doesn’t have an Err object, so applications written in C# need to
use try/catch blocks to handle exceptions that are a result of a COM
HRESULT.
A .NET program can retrieve the return code that was contained in the
HRESULT by enclosing the code in a try statement containing a catch
block based on the COMException type. Since many of the API
methods return values other than S_OK to indicate the status of the call,
try/catch blocks should routinely be used not only to examine the
returned value but also to avoid having an unhandled exception error
during program execution.
Since using try/catch blocks to handle COM exceptions works with
both Visual Basic and C#, code written using this technique is more
portable than that using the Err object.

20
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

EPDMResultCode In order to make handling HRESULT values more intuitive, the


Namespace EPDM.Interop.EPDMResultCode namespace has two enumerations
which contain values for error codes and for success codes. These two
enumerations are named EdmResultErrorCodes_e and
EdmResultSuccessCodes_e. These pneumonic values have names that
are more meaningful than their equivalent eight hexadecimal digit
values. To use these enumerations, the project needs to reference the
EPDM.Interop.EPDMResultCode primary interop assembly, which
contains the EPDM.Interop.EPDMResultCode namespace.
VerifyVersion The IEdmVault5.VerifyVersion method checks to see whether the
currently installed version of SOLIDWORKS PDM Professional is at
the specified version level or later. If it is, then the method returns
S_OK, which in .NET code means the code continues to execute
normally. If the installed version of SOLIDWORKS PDM Professional
is older than that specified, the HRESULT code
E_EDM_UNSUPPORTED_PROGRAM_VERSION is returned. Since
the returned code isn’t S_OK, an exception will be thrown and
execution will stop with an unhandled exception error unless the
exception is caught.

11 Add a Button control.


Add another button control, name it
HresultButton, and assign its Text property the
value HRESULT.
12 Add a click event to HresultButton and add
code.
Double-click HresultButton on the form to set
up a button click event handler.

Add the following lines of code:


Private Sub HresultButton_Click(ByVal sender As System. _
Object, ByVal e As System.EventArgs) Handles _
HresultButton.Click

'Declare and create an instance of IEdmVault5 object


Dim vault As IEdmVault5 = New EdmVault5()
'Verify that the installed version of SOLIDWORKS
'PDM Professional meets our minimum needs
vault.VerifyVersion(20, 0)
End Sub

21
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

13 Build and run the application.


Press F5 to build and save the application and run it in the debugger
environment.
Click the HRESULT button.
Since the VerifyVersion method is asking for a newer version of
SOLIDWORKS PDM Professional than we have installed, the value of
the HRESULT returned will be
E_EDM_UNSUPPORTED_PROGRAM_VERSION. Since our code
currently doesn’t have an exception handler, the program execution
will halt with an unhandled exception error.

14 Stop the application.


From the Debug menu, click Stop Debugging.
15 Add a reference to the EPDM.Interop.EPDMResultCode PIA.
From the Solution Explorer, double-click on the My Project node.
In the Project Designer click the References tab.
Click the Add button and choose Reference from the drop-down list.
From the Reference Manager dialog box, click the Browse button.
In the file browser dialog, navigate to the SOLIDWORKS PDM
installation folder.
Scroll down the list of components and click
EPDM.Interop.EPDMResultCode.dll to select it.

22
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

Click Add, then click OK to add the reference to your project.

16 Add Imports statement to code.


Add the following statement at the top of the Form code:
Imports EPDM.Interop.epdm
Imports EPDM.Interop.EPDMResultCode

Public Class StandAloneForm


17 Add exception handler code.
If an exception is thrown while executing code within a Try statement,
instead of causing the program to halt, the exception is handled by
passing control to the code within the corresponding Catch block and
the program resumes normal execution from there.
Add the following lines of code.
Private Sub HresultButton_Click(ByVal sender As System. _
Object, ByVal e As System.EventArgs) Handles _
HresultButton.Click

'Declare and create an instance of IEdmVault5 object


Dim vault As IEdmVault5 = New EdmVault5()

23
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

Try
'Verify that the installed version of SOLIDWORKS
'PDM Professional meets our minimum needs
vault.VerifyVersion(20, 0)
Catch ex As Runtime.InteropServices.COMException
'We will get here if VerifyVersion
'doesn't return S_OK
Select Case ex.ErrorCode
Case EdmResultErrorCodes_e. _
E_EDM_UNSUPPORTED_PROGRAM_VERSION
MessageBox.Show("The installed program is at " + _
"a version level that is lower than the " + _
"specified version.")
Case Else
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
End Select
End Try
End Sub
18Build and run the application.
Press F5 to build and save the application and run it in the debugger
environment.
Click the HRESULT button.
The message box will display the text message that is associated with
the numeric value of the HRESULT that was returned by
VerifyVersion.

Click OK to dismiss the dialog. The application will resume normal


execution of the code following Catch block.
19 Stop the application.
Click the close icon in the upper right corner of the form.

24
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

SOLIDWORKS The SOLIDWORKS PDM Professional API Help is designed for


PDM programmers and end users who want to research information specific
Professional to API interfaces, methods, properties, events, structures and constants.
API Help The API Help can be accessed from the Windows Explorer menu by
clicking Help, SOLIDWORKS PDM Programmer’s Reference
Guide.

Note The API Help may also be opened by double clicking on the
API_GB.chm file, which is located in the SOLIDWORKS PDM
Professional installation folder and is also on the installation media in
the Support\API folder.
Contents The Contents tab of the
SOLIDWORKS PDM Professional
API Help contains the following
sections:
 Welcome - This section contains
an overview with general
information about SOLIDWORKS PDM Professional, the API and
the documentation.
 Release Notes - This section provides information about what’s
new in the API as of this release and previous releases of the
SOLIDWORKS PDM Professional software.
 Getting Started - Information to get you started writing API
applications with links to the various functional areas.
 Stand-alone Applications - This section describes how to create
stand-alone applications in C++ and VB.NET as well as related
topics.
 Add-in Applications - This section describes how to create add-in
applications in C++ and VB.NET as well as related topics.

25
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

 EPDM.Interop.epdm Namespace - Contains sections describing:


Interfaces - This section lists all the interfaces supported by the
API, descriptions of their properties and methods, how they are
used, arguments, return values and types.
Enumerations - This section lists all the enumerations used
throughout the API, their values, where they are used and their
meanings.
Structures - All the structures used in the API are listed in this
section. Information is provided about which interfaces and
members they are used with and the structure members are listed
and how they are used is described.
 EPDM.Interop.EPDMResultCode Namespace - Contains a
section describing:
Enumerations - This section lists the enumerations used by API
methods that return HRESULT values. It lists the enumeration
values, their corresponding hexadecimal values and their meanings.
Index The Index tab of the SOLIDWORKS PDM Professional API Help
allows you to quickly locate API topics through its alphabetically
ordered list of keywords. Typing into the text box at the top of the
window takes you quickly to the part of the keyword list that matches
what you’ve typed.
Search The Search tab of the SOLIDWORKS PDM Professional API Help
allows you to search throughout the Reference Guide for text that may
not be in the index.
Favorites The Favorites tab of the SOLIDWORKS PDM Professional API Help
allows you to keep a list of topics for easy access. When you are
viewing a page that you would like to be able to quickly return to, click
Add at the bottom of the tab and the current topic will be added to your
favorites list.

26
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

Understanding API
Interface Member 1
Descriptions
3
2
4

1. API Member and Interface Names - Used to describe the API


interface and member. The member name (a method in this case) is
LoginAuto, and the interface to which it belongs (IEdmVault5) is
shown in parentheses.
2. Expand All / Collapse All - Toggles all the regions within the body
of the help topic between fully expanded and fully collapsed states.
3. Language Filter - Allows display of member syntax information to
be filtered according to programming language:

Visual Basic
C#
C++/CLI
4. Topic Path - Displays the full path of the selected topic within the
API Help file, starting from the namespace name.
5. API Description - This is an explanation of the API interface or the
selected member’s functionality.
6. Help Topic Body - This section will display a combination of
regions depending on applicability within the topic:

Syntax
Example
Accessors
Remarks
See Also
Availability

27
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

For example: Expanding the Syntax region with the Visual Basic
checkbox checked in the Language Filter, the following syntax
information will be displayed:

Visual Basic - The Visual Basic section shows the prototype for the
member. If there is a return value, the member is declared as a Function
and a return type is declared. If there is no return value, as in this
example, the member is declared as a Sub.
The parameters that are passed to the API member are declared within
the member prototype with their data types. Parameters are declared
ByVal if they are inputs to the member and they are declared ByRef if
they are used for output.
The Parameters section describes the meanings of the parameters. In
this case, a description of the parameters bsVaultName and
hParentWnd and their usage is given.
The Return Value section describes the meaning of the return value, if
there is one. Since LoginAuto is declared as a Sub, there is no return
value in this example.
Example Region - This region, when available, provides links to code
examples illustrating the usage of the selected member.
Accessors Region - This region is available on interface pages and
contains links to members that can return an instance of the interface.
Remarks Region - Contains notes to the programmer about using the
member. This is also where any Return codes for this member are listed
and described. Before using any member, spend time reading the
Remarks section if there is information available.
See Also Region - Contains links to additional related information.

28
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

Availability Region - Contains information about when the interface or


member became available for use. Your code should check the running
instance of the SOLIDWORKS PDM Professional software for
compatibility.
Interface By now you’ve probably noticed that many of the SOLIDWORKS
Versioning PDM Professional API interface names end with numeric digits.
For example: IEdmVault5, IEdmVault6, IEdmVault7, etc.
The numeric suffix in the interface name indicates the version of the
interface. As new functionality in the form of new members is added to
the API, the new members are added to a new interface in order to
maintain the integrity of the original interface for backward
compatibility to existing applications. Each version of a particular
interface is implemented by the same underlying class so, for example,
in Visual Basic a variable of type IEdmVault5 can be assigned to a
variable of type IEdmVault10 and vice versa as long as the installed
version of SOLIDWORKS PDM Professional supports the interface
version being assigned.

20 Add a Button control.


Add another button control, name it
VersionButton, and assign its Text
property the value Version.

29
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

21 Add a click event to VersionButton and add code.


Double-click VersionButton on the form to set up a button click event
handler.
Add the following lines of code.
Private Sub VersionButton_Click(ByVal sender As System. _
Object, ByVal e As System.EventArgs) Handles _
VersionButton.Click

'Declare an IEdmVault5 interface object


Dim vault5 As IEdmVault5
'Create an instance of IEdmVault5 interface object
vault5 = New EdmVault5()

'ClientType is a member of the IEdmVault8 interface


Dim ClientType As EdmClientType
ClientType = vault5.
End Sub

Notice that after typing the period after vault5, the IntelliSense pop-
up list displays the members of the IEdmVault5 interface. The
ClientType property is a member of the IEdmVault8 interface so it
doesn’t appear in the list.

Manually type in the IEdmVault8 property ClientType after the


period.

30
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

22 Add code to call an IEdmVault5 member from an IEdmVault8


object.
Add the following lines of code:
Private Sub VersionButton_Click(ByVal sender As System. _
Object, ByVal e As System.EventArgs) Handles _
VersionButton.Click

'Declare an IEdmVault5 interface object


Dim vault5 As IEdmVault5
'Create an instance of IEdmVault5 interface object
vault5 = New EdmVault5()

'ClientType is a member of the IEdmVault8 interface


Dim ClientType As EdmClientType
ClientType = vault5.clienttype

'IsLoggedIn is a member of the IEdmVault5 interface


Dim vault8 As IEdmVault8
vault8 = vault5
Dim IsLoggedIn As Boolean
IsLoggedIn = vault8.IsLoggedIn
End Sub
Notice that after typing the period after vault8, the IntelliSense pop-
up list displays the members of the IEdmVault8 interface. The
IsLoggedIn property is a member of the IEdmVault5 interface but it
still appears in the list. SOLIDWORKS PDM Professional API
interfaces include the members of any interfaces that they inherit from.

31
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

23 Add a break point.


Click in the gray vertical bar to the left of your code next to the line of
code that creates a new IEdmVault5 object. A red dot will appear in
the bar and the corresponding line of code is highlighted. By clicking in
the gray bar you added a break point to the debugger. When run in the
debugger, execution will stop whenever a break point is reached.
Variable values can be checked at this point and execution can be
resumed normally be pressing F5 or execution can proceed one line of
code at a time by pressing F10. You may add as many break points as
you wish.

32
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

24 Build and run the application.


Press F5 to build and save the application and run it in the debugger
environment.
Click the Version button.
Execution will stop at the break point and the next line to be executed
will highlight in yellow.
Continue single step execution by pressing F10 until the yellow
highlight is past the ClientType property assignment.

Hover over the variable ClientType with the mouse cursor. The
current value of ClientType will appear in a pop-up window and
confirm that we were able to call a IEdmVault8 member on a variable
declared as type IEdmVault5. This is because Visual Basic knows that
the interfaces IEdmVault5 and IEdmVault8 are implemented by the
same class so it takes care of any necessary type casting for you
“behind the scenes”. Some stricter programming languages would not
compile properly and would require that you use the interface that is
appropriate for the member being called.

33
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

25 Observe the IEdmVault5 member called from an IEdmVault8


object.
Continue single stepping by pressing F10 until the yellow highlight is
on the End Sub statement. Hovering over the IsLoggedIn variable
with the mouse cursor will display its value and confirm that we were
able to call an IEdmVault5 property from an IEdmVault8 object.
Resume normal execution by pressing F5.
26 Stop the application.
Click the close icon in the upper right corner of the form.

Assigning In addition to versioned interfaces existing on the same underlying


Interfaces of class, it is possible for unrelated or loosely related interfaces to be
Different Types implemented by the same class.
Whenever interfaces are implemented by the same class, they can be
assigned from one type of object variable to another in VB, assigned to
another object variable with an explicit cast in C# and retrieved from
one type of interface pointer to another in C++ using the COM
QueryInterface method.
Below are some of the SOLIDWORKS PDM Professional API
interfaces that are implemented by the same class.
Note - some interface assignments may only be valid under certain
circumstances. See specific interface details in the SOLIDWORKS
PDM Professional API Help.

34
SOLIDWORKS PDM Professional Lesson 1
Connecting to a Vault

In addition, all of the SOLIDWORKS PDM Professional API


interfaces that have a corresponding EdmObjectType value defined
inherit from IEdmObject5.

IEdmVault5
IEdmVault6
IEdmVault7
IEdmVault8
IEdmVault9
IEdmVault10
IEdmVault11
IEdmVault12
IEdmUserMgr5
IEdmUserMgr6
IEdmUserMgr7
IEdmCategoryMgr6
IEdmVariableMgr5
IEdmVariableMgr6
IEdmVariableMgr7
IEdmWorkflow5
IEdmWorkflow6
IEdmWorkflowMgr6

IEdmUser5
IEdmUser6
IEdmUser7
IEdmUser8
IEdmInbox5

IEdmBatchUnlock
IEdmRefItemContainer

35
Lesson 1 SOLIDWORKS PDM Professional
Connecting to a Vault

IEdmFile5
IEdmFile6
IEdmFile7
IEdmFile8
IEdmEnumeratorCustomReference5
IEdmEnumeratorVersion5
IEdmSearchResult5
IEdmItem

IEdmFolder5
IEdmFolder6
IEdmEnumeratorVariable5
IEdmEnumeratorVariable6
IEdmEnumeratorVariable7
IEdmEnumeratorVariable8
IEdmSearchResult5

IEdmTemplate5
IEdmTemplate53

IEdmBom
IEdmBomView

36
SOLIDWORKS PDM Professional Exercise 1
Connecting to a Vault

Exercise 1:
Connecting to a
Vault

Create a stand-alone application that will:


 Find all the vault views on the computer.
 Add the name of each vault view to a ComboBox.
 Let the user press a button to:
Log in to the vault whose name is displayed in the ComboBox.
Display the EPDM version.
Display the path of the vault view folder.
 Handle any COM exceptions.
 Handle any other exceptions.

Imports EPDM.Interop.epdm
Public Class FormExercise1
Private Sub FormExercise1_Load(ByVal sender As System. _
Object, ByVal e As System.EventArgs) Handles MyBase. _
Load

Try
Dim vault As IEdmVault8 = New EdmVault5
Dim Views() As EdmViewInfo = {}
vault.GetVaultViews(Views, False)
VaultsComboBox.Items.Clear()
For Each View As EdmViewInfo In Views
VaultsComboBox.Items.Add(View.mbsVaultName)
Next
If VaultsComboBox.Items.Count > 0 Then
VaultsComboBox.Text = VaultsComboBox.Items(0)
End If
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + ex.ErrorCode. _
ToString("X") + vbCrLf + ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

37
Exercise 1 SOLIDWORKS PDM Professional
Connecting to a Vault

Private Sub LoginButton_Click(ByVal sender As System. _


Object, ByVal e As System.EventArgs) Handles _
LoginButton.Click

Try
'Declare and create an instance of
'IEdmVault5 object
Dim vault As IEdmVault5 = New EdmVault5()
'Log into the selected Vault as the current user
vault.LoginAuto(VaultsComboBox.Text, Me.Handle. _
ToInt32())

'Display the SOLIDWORKS PDM Professional version


Dim VerMajor As Integer
Dim VerMinor As Integer
vault.GetVersion(VerMajor, VerMinor)
MessageBox.Show("SOLIDWORKS PDM Professional " + _
"version is " + VerMajor.ToString() + "." + _
VerMinor.ToString())

'Display the path of the vault view folder


MessageBox.Show("The path of the vault view " + _
"folder is """ + vault.RootFolderPath + """.")
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + ex.ErrorCode. _
ToString("X") + vbCrLf + ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class

38
Lesson 2
Files, Folders, Items and
References

Upon successful completion of this lesson, you will be able to:


 Understand the use of IEdmObject interface.
 Understand the use of the IEdmPos interface.
 Traverse all files in a folder.
 Traverse all sub-folders in a folder.
 Recursively traverse sub-folders.
 Understand the IEdmReference interface.
 Understand the IEdmBatchListing interface.
 Recursively traverse a file reference tree.
 Save file reference tree information to an XML file.
 Understand the IEdmBatchItemGeneration interface.
 Use data from an XML file to create stand-alone Items.

39
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

The IEdmObject Many of the SOLIDWORKS PDM Professional API objects are
Interface derived from the IEdmObject interface. This interface has members
that are common to all the derived interfaces.
Some of its properties are:
 ID - uniquely identifies each object in the database
 Name - holds the name associated with the object
 ObjectType - the type of the object
 Vault - the file vault to which this object belongs

This means that even though an object doesn’t explicitly have a Name
property, for example, its name can still be obtained from the object’s
parent IEdmObject interface’s Name property. We will make use of
this property to get the file and folder names in the examples below.
The IEdmFile The IEdmFile interface represents a single file in SOLIDWORKS
Interface PDM Professional. It has members that allow access to the
SOLIDWORKS PDM Professional file properties, status and
functionality.
For example, the IEdmFile interface has members that can get and
change the current version, revision, workflow state and its checked out
status.
The IEdmFolder The IEdmFolder interface represents a file system folder that has been
Interface added to a file vault. It has members that allow access to the
SOLIDWORKS PDM Professional folder properties, status and
functionality.
For example, the IEdmFolder interface has members that can add, get
and delete files, get subfolder and the related folder data card
information.
The IEdmPos The IEdmPos interface is used throughout the SOLIDWORKS PDM
Interface Professional API to traverse the various lists that hold information
about a file vault. It is used to represent the current position during an
enumeration of a list of elements.
For example, it is used to traverse:
 Controls in a card
 Versions of a file
 Revisions of a file
 Sub folders in a folder
 Files in a folder
 Users in a vault
 States in a workflow

40
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

A typical enumeration begins with a call to a GetFirst member that


returns an IEdmPos object which represents the position of the first
element in the list. The IEdmPos object is then passed as an argument
to a GetNext member which returns the corresponding list element and
also positions the IEdmPos object to reference the next element in the
list. The GetNext member can then be called repeatedly to enumerate
all the elements in the list while the IsNull property of the IEdmPos
object is False.
Case Study: File traversal is commonly needed to get information about all the files
File Traversal in a folder. It begins with a call to the GetFirstFilePosition method of
the IEdmFolder object of the file system folder that will be traversed.
The returned IEdmPos object doesn’t represent the first file in the
folder, but the position of the first file in the list. Passing it as an
argument to the GetNextFile method of the IEdmFolder object will
return the IEdmFile object that does represent the first file in the list.
At the same time, the IEdmPos object is incremented to point to the
next file in the list.

1 Open project and add code.


Open the project Traversal and add the
following code to the click event handler of
the TraversFilesButton control.

Private Sub TraversFilesButton_Click(ByVal sender As _


System.Object, ByVal e As System.EventArgs) Handles _
TraversFilesButton.Click

'Declare and create an instance of IEdmVault5 object


Dim vault As IEdmVault5 = New EdmVault5()
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, Me.Handle. _
ToInt32())

'Get the IEdmFolder5 object of the root folder


Dim RootFolder As IEdmFolder5
RootFolder = vault.RootFolder

41
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

'Get the path of the root folder


Dim FolderPath As String
FolderPath = RootFolder.LocalPath
Debug.Print(vbCrLf + vbCrLf + FolderPath + vbCrLf)

'Get the name of the root folder


'from the IEdmObject interface
Dim FolderName As String
FolderName = RootFolder.Name
Debug.Print("+" + FolderName)

'Get the IEdmPos object for


'the first file in the folder
Dim FilePos As IEdmPos5
FilePos = RootFolder.GetFirstFilePosition

'Enumerate the files in the folder.


Dim file As IEdmFile5
While Not FilePos.IsNull
file = RootFolder.GetNextFile(FilePos)
'Get the name of each file
'from the IEdmObject interface
Dim FileName As String = file.Name
'Get its checked out status
Dim CheckedOutStatus As String
CheckedOutStatus = IIf(file.IsLocked, "", " not")
Debug.Print(" " + FileName + " -" + _
CheckedOutStatus + " checked out")
End While
End Sub

2 Build and run the application.


Press F5 to build and save the application and run it in the debugger
environment.
Click the Traverse Files button.
The application will log into the selected vault and print the path and
the name of the root folder in the Output window. It will then traverse
all the files in the root folder and print the name of each file and its
checked out status in the Output window.
3 Stop the application.
Click the close icon in the upper right corner of the form.

42
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

Case Study: In addition to files, folders can hold any number of sub-folders. Each of
Folder those sub-folders may themselves also hold any number of sub-folders.
Traversal To enumerate the sub-folders contained in a folder, begin by calling the
GetFirstSubFolderPosition method of the IEdmFolder object of the
file system folder that is to be traversed. The returned IEdmPos object
can then be passed as an argument to the GetNextSubFolder method
of the IEdmFolder object being traversed. This method will return the
IEdmFolder object that represents the first sub-folder in the list. At the
same time, the IEdmPos object is incremented to point to the next sub-
folder in the list. The GetNextSubFolder method can then be called
repeatedly to enumerate all the sub-folders in the list while the IsNull
property of the IEdmPos object is False.

4 Add a new button and copy code.


Add a new button to the form.
Name it TraverseFoldersButton and set its Text property value to
Traverse Folders.
Double click the TraverseFoldersButton control to create a click
event handler.
Copy and paste all the code from the TraversFilesButton click event
handler and add the following code at the end of the subroutine.
Private Sub TraverseFoldersButton_Click(ByVal sender _
As System.Object, ByVal e As System.EventArgs) _
Handles TraverseFoldersButton.Click

. . .

'Get the name of each file


'from the IEdmObject interface
Dim FileName As String = file.Name
'Get its checked out status
Dim CheckedOutStatus As String
CheckedOutStatus = IIf(file.IsLocked, "", " not")
Debug.Print(" " + FileName + " -" + _
CheckedOutStatus + " checked out")
End While

'Enumerate the sub-folders in the root folder


Dim FolderPos As IEdmPos5
FolderPos = RootFolder.GetFirstSubFolderPosition
While Not FolderPos.IsNull
Dim SubFolder As IEdmFolder5
SubFolder = RootFolder.GetNextSubFolder _
(FolderPos)

43
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

Debug.Print("+" + SubFolder.Name)
End While
End Sub

5 Build and run the application.


Press F5 to build and save the application and run it in the debugger
environment.
Click the Traverse Folders button.
After the application traverses all the files in the root folder and prints
their names and checked out status in the Output window as it did in
the previous example, it will then traverse the sub-folders in the root
folder and print their names too.
6 Stop the application.
Click the close icon in the upper right corner of the form.

Recursive Folder Since any sub-folder may itself contain any number of sub-folders,
Traversal those sub-folders can in turn be traversed in the same way as we
traversed the root folder in the example above. Since those sub-folders
may in turn contain further sub-folders down to an unknown depth, the
easiest way to traverse them all is to use recursive calls to a general
folder traversal routine.

7 Create a new recursive subroutine.


Create a new subroutine that will recursively call itself to traverse sub-
folders down to any depth. Name it TraverseFolder. We will pass in
as arguments to the subroutine the current IEdmFolder object to
traverse and the current depth level of the IEdmFolder object. The
depth level argument is only used to make it easier to format the output
an appropriate indent amount. Each folder’s name will be indented two
spaces more than that of the parent folder.
Private Sub TraverseFolder(ByVal CurFolder As _
IEdmFolder5, ByVal Level As Integer)

Dim FolderName As String = CurFolder.Name


Dim Indent As String = New String(" ", Level * 2)

Debug.Print(Indent + "+" + FolderName)

End Sub

44
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

8 Cut and paste code from the TraverseFoldersButton click event


handler.
Cut code from the TraverseFoldersButton click event handler
starting with the comment “Get the IEdmPos object for the first file in
the folder” and continuing to the end of the subroutine.
Paste the code into the TraverseFolder subroutine.
Private Sub TraverseFolder(ByVal CurFolder As _
IEdmFolder5, ByVal Level As Integer)
Dim FolderName As String = CurFolder.Name
Dim Indent As String = New String(" ", Level * 2)

Debug.Print(Indent + "+" + FolderName)

'Get the IEdmPos object for


'the first file in the folder
Dim FilePos As IEdmPos5
FilePos = RootFolder.GetFirstFilePosition

'Enumerate the files in the folder.


Dim file As IEdmFile5
While Not FilePos.IsNull
file = RootFolder.GetNextFile(FilePos)
'Get the name of each file
'from the IEdmObject interface
Dim FileName As String = file.Name
'Get its checked out status
Dim CheckedOutStatus As String
CheckedOutStatus = IIf(file.IsLocked, "", " not")
Debug.Print(" " + FileName + " -" + _
CheckedOutStatus + " checked out")
End While

'Enumerate the sub-folders in the root folder


Dim FolderPos As IEdmPos5
FolderPos = RootFolder.GetFirstSubFolderPosition
While Not FolderPos.IsNull
Dim SubFolder As IEdmFolder5
SubFolder = RootFolder.GetNextSubFolder _
(FolderPos)
Debug.Print("+" + SubFolder.Name)
End While
End Sub

45
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

9 Rename RootFolder variable.


Rename the RootFolder variable to CurFolder, indent the file output
with the appropriate number of spaces and recursively call
TraverseFolder instead of simply printing the folder name. The folder
name will be printed by the TraverseFolder subroutine.
Private Sub TraverseFolder(ByVal CurFolder As _
IEdmFolder5, ByVal Level As Integer)
Dim FolderName As String = CurFolder.Name
Dim Indent As String = New String(" ", Level * 2)

Debug.Print(Indent + "+" + FolderName)

'Get the IEdmPos object for


'the first file in the folder
Dim FilePos As IEdmPos5
FilePos = CurFolder.GetFirstFilePosition

'Enumerate the files in the folder.


Dim file As IEdmFile5
While Not FilePos.IsNull
file = CurFolder.GetNextFile(FilePos)
'Get the name of each file
'from the IEdmObject interface
Dim FileName As String = file.Name
'Get its checked out status
Dim CheckedOutStatus As String
CheckedOutStatus = IIf(file.IsLocked, "", " not")
Debug.Print(Indent + " " + FileName + " -" + _
CheckedOutStatus + " checked out")
End While

'Enumerate the sub-folders in the root folder


Dim FolderPos As IEdmPos5
FolderPos = CurFolder.GetFirstSubFolderPosition
While Not FolderPos.IsNull
Dim SubFolder As IEdmFolder5
SubFolder = CurFolder.GetNextSubFolder _
(FolderPos)
'Debug.Print("+" + SubFolder.Name)
TraverseFolder(SubFolder, Level + 1)
End While
End Sub

46
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

10 Make the initial call to TraverseFolder.


Delete or comment out the code in the TraversFoldersButton click
event handler that gets and prints the root folder name.
Start the recursive folder traversal by making the initial call to the
TraverseFolder subroutine.
Private Sub TraverseFoldersButton_Click(ByVal sender _
As System.Object, ByVal e As System.EventArgs) _
Handles TraverseFoldersButton.Click

'Declare and create an instance of IEdmVault5 object


Dim vault As IEdmVault5 = New EdmVault5()
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, Me.Handle. _
ToInt32())

'Get the IEdmFolder5 object of the root folder


Dim RootFolder As IEdmFolder5
RootFolder = vault.RootFolder

'Get the path of the root folder


Dim FolderPath As String
FolderPath = RootFolder.LocalPath
Debug.Print(vbCrLf + vbCrLf + FolderPath + vbCrLf)

'Get the name of the root folder


'from the IEdmObject interface
'Dim FolderName As String
'FolderName = RootFolder.Name
'Debug.Print("+" + FolderName)

TraverseFolder(RootFolder, 0)
End Sub

47
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

11 Build and run the application.


Press F5 to build and save the application and run it in the debugger
environment.
Click the Traverse Folders button.
After the application logs in to the file vault and prints the path of the
root folder, it calls the TraverseFolder subroutine which will print the
name of the current folder and traverse the files in it printing their
names and checked out status in the Output window as it did in the
previous example.
It will then traverse the sub-folders in the current folder, but instead of
simply printing their names, it will then recursively call the
TraverseFolder subroutine for each sub-folder, passing in its
IEdmFolder object and incremented level as arguments.
12 Stop the application.
Click the close icon in the upper right corner of the form.

File References Some file types can contain references to other


files. SOLIDWORKS PDM Professional will
display these file references as a reference tree for
example, in the check in dialog box in the User
Interface.
The SOLIDWORKS PDM Professional API
provides interfaces, methods and properties to
handle file references programmatically.

The The IEdmReference interface has most of the methods and properties
IEdmReference you will need to retrieve information about a particular reference as
Interface well as to traverse the reference tree of a given file. When interrogating
a file for its reference tree, the traversal begins with a call to
IEdmFile5.GetReferenceTree. The returned IEdmReference5
interface allows traversal of the file’s reference tree for all the files
referenced by the file with its GetFirstChildPosition and
GetNextChild methods. Using the methods GetFirstParentPosition
and GetNextParent, you can also traverse the files that a given file is
referenced by. As when traversing files and folders, the IEdmPos5
interface is used to aid in the traversal.
Similar to the way that a file folder structure can contain arbitrarily
deep levels of sub folders, so can file references themselves contain
child reference trees as well. When traversing the reference tree,
recursively calling the IEdmFile5.GetReferenceTree method on
each child or parent reference will allow you to retrieve information
about all the references in the complete reference tree.

48
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

The IEdmBatch- The IEdmBatchListing interface allows you to retrieve information


Listing Interface related to a file without the need to retrieve the file’s IEdmFile
interface or its IEdmEnumeratorVariable interface. While this gain
in efficiency may not be important when dealing with only a handful of
files, when a large number of files is involved the reduced overhead of
not needing to make many COM calls to retrieve the individual
interfaces, the performance gain may be significant.
The IEdmBatchListing interface is created using the
IEdmVault7.CreateUtility method and passing in the enumeration
value EdmUtil_BatchList as an argument. The information desired is
specified by calling the IEdmBatchListing2.AddFileCfg method and
passing in the specifics of the desired information as arguments.
Once the files have been added, a call to
IEdmBatchListing2.CreateListEx will generate the file
information. In order to retrieve the generated file information,
IEdmBatchListing.GetFiles can be called, which will return an array
of EdmListFile structures, one structure for each file that was added to
the IEdmBatchListing object. The EdmListFile structure members
will hold the various file information values. Most of the members of
the EdmListFile structure hold system defined values. There are
however, two members whose values are defined by the API
programmer.
 mlParam - Holds a value of type long that is assigned for the
associated file by passing it as an argument to the AddFile method
when this file was added to the IEdmBatchListing object.
 moColumnData - Holds a value of type Object that will hold the
array of file data card variables associated with this file that were
requested by the IEdmBatchListing2.CreateListEx method.
The IEdmClear- The IEdmClearLocalCache interface can be used to remove files
LocalCache from the local cache. It is created using the
Interface IEdmVault7.CreateUtility method by passing in the enumeration
value EdmUtil_ClearLocalCache as an argument. Files and folders
that you would like to clear can then be added by calling the
AddFileByPath and the AddFolder methods. A call to the
CommitClear method will then perform the clearing.

49
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

Case Study: In this case study, we will create an application that retrieves the
Reference Tree reference tree for a file or group of files and some file data card
Traversal variable values and then outputs information about the reference tree
and associated data to an XML file.
In order to keep the file selection process simple, we will allow the user
to interactively select one or more files. We will then recursively
traverse the reference trees of the selected files and store the path
names and recursion levels of all the files that they reference in a
Dictionary collection object.
As a side-effect of being selected by the user in the file open dialog, the
selected files and all the files that they reference are loaded into the
local cache. We will clear the selected files and any files that are
referenced by them from the local cache.
All the filenames from the reference trees that were stored in the
Dictionary collection will be used to clear the local cache and also to
get the information about the files in a batch operation.
Once all the information is collected, we will store all the relevant
information in a List collection of FileRef objects.
FileRef is a class that is defined within the case study application to
make it convenient for creating the file reference output XML file. It
has Public properties for getting and setting the data values that we
want to output.

1 Open project and review code.


Open the project
BatchRefTreeInfo and open the
FileRef.vb file. Look at the
definition of the FileRef class.
The Public properties of this
class will be used for writing the
information about each file in the
reference tree to the XML file.
Notice that the property FileRefs
is used for storing a list of
FileRefs. This property will be
used to store any child references that a file may have. This can be done
to whatever depth is needed. With this property we can re-create the
tree structure within the output XML file.

50
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

Public Class FileRef


Private mFileName As String
Private mLatestVersion As String
Private mLatestRevision As String
Private mNumber As String
Private mDescription As String
Private mCurrentState As String
Private mCheckedOutBy As String
Private mFileRefs As List(Of FileRef)

Public Sub New()

End Sub

Public Property FileName() As String


Get
Return mFileName
End Get
Set(ByVal value As String)
mFileName = value
End Set
End Property

Public Property LatestVersion() As String


Get
Return mLatestVersion
End Get
Set(ByVal value As String)
mLatestVersion = value
End Set
End Property

Public Property LatestRevision() As String


Get
Return mLatestRevision
End Get
Set(ByVal value As String)
mLatestRevision = value
End Set
End Property

51
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

Public Property Number() As String


Get
Return mNumber
End Get
Set(ByVal value As String)
mNumber = value
End Set
End Property

Public Property Description() As String


Get
Return mDescription
End Get
Set(ByVal value As String)
mDescription = value
End Set
End Property

Public Property CurrentState() As String


Get
Return mCurrentState
End Get
Set(ByVal value As String)
mCurrentState = value
End Set
End Property

Public Property CheckedOutBy() As String


Get
Return mCheckedOutBy
End Get
Set(ByVal value As String)
mCheckedOutBy = value
End Set
End Property

Public Property FileRefs() As List(Of FileRef)


Get
Return mFileRefs
End Get
Set(ByVal value As List(Of FileRef))
mFileRefs = value
End Set
End Property
End Class

52
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

2 Add code to get file references.


Add code to the recursive GetReferencedFiles subroutine that will
traverse the reference tree and store the referenced file names and the
level in the hierarchy that they were found at in a Dictionary
collection.
The first time the GetReferencedFiles subroutine is called for a given
file, 0 is passed to it in the Level argument and Nothing is passed to it
in the Reference argument, which will trigger the subroutine to call
IEdmFile5.GetReferenceTree and start the recursion. Each
successive call to GetReferencedFiles will pass in the current
IEdmReference5 object to traverse the references of. Whenever
GetReferencedFiles calls itself, the Level argument is incremented
from its current value.
Private Sub GetReferencedFiles( _
ByVal Reference As IEdmReference5, _
ByVal FilePath As String, _
ByVal Level As Integer, _
ByVal ProjectName As String, _
ByRef RefFilesDictionary _
As Dictionary(Of String, String))

Try
Dim Top As Boolean = False
If Reference Is Nothing Then
'This is the first time this function was
'called for this reference tree,
'ie. this is the root
Top = True
'Add the top level file path to the dictionary
RefFilesDictionary.Add(FilePath, _
Level.ToString())
Dim File As IEdmFile5 = Nothing
Dim ParentFolder As IEdmFolder5 = Nothing
File = vault.GetFileFromPath(FilePath, _
ParentFolder)
'Get the reference tree for this file
Reference = File.GetReferenceTree(ParentFolder.ID)
GetReferencedFiles(Reference, "", Level + 1, _
ProjectName, RefFilesDictionary)
Else
'Enter here when this function has recursively
'called itself, ie. this is not the top level
'IEdmReference in the tree

53
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

'Recursively traverse the references


Dim pos As IEdmPos5
pos = Reference.GetFirstChildPosition( _
ProjectName, Top, True, 0)
Dim ref As IEdmReference5
While Not pos.IsNull
ref = Reference.GetNextChild(pos)
RefFilesDictionary.Add(ref.FoundPath, _
Level.ToString())
GetReferencedFiles(ref, "", Level + 1, _
ProjectName, RefFilesDictionary)
End While
End If
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

3 Add code to start the recursive reference tree traversal.


Add the code below to the click event handler for the
WriteXmlButton control. An IEdmVault object will be created if
needed and logged in to. A Dictionary collection object will then be
created and a reference tree traversal will be initiated for each file that
the user had selected. The data from the traversal will be stored in the
Dictionary collection.
Private Sub WriteXmlButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles WriteXmlButton.Click

Try
'Only create a new vault object
'if one hasn't been created yet
If vault Is Nothing Then vault = New EdmVault5
If Not vault.IsLoggedIn Then
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())
End If

54
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

'Get the file paths of all the referenced files


'and store them in RefFilesDictionary as keys,
'the level they were found at in the file hierarchy
'will be stored as values
Dim RefFilesDictionary As Dictionary(Of String, _
String) = New Dictionary(Of String, String)()
For Each FileName As String In BatchRefListBox.Items
GetReferencedFiles(Nothing, FileName, 0, "A", _
RefFilesDictionary)
Next FileName

Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

4 Add code that will add the file info to the utility objects.
Add the code below to create the IEdmClearLocalCache and
IEdmBatchListing utility objects and iterate through the Dictionary,
adding the stored file information to the utility objects. Once the files
have been added to the IEdmClearLocalCache object, call its
CommitClear method to clear the cache.
For Each FileName As String In BatchRefListBox.Items
GetReferencedFiles(Nothing, FileName, 0, "A", _
RefFilesDictionary)
Next FileName

'Since selecting a file in the Open File Dialog has


'the side effect of adding the file and its
'references to the local cache, we'll clear the
'local cache here in order to demonstrate that
'the IEdmBatchListing methods don't add the files
'to the local cache

55
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

'Declare and create the IEdmClearLocalCache object


Dim ClearLocalCache As IEdmClearLocalCache
ClearLocalCache = vault.CreateUtility( _
EdmUtility.EdmUtil_ClearLocalCache)
'Declare and create the IEdmBatchListing object
Dim BatchListing As IEdmBatchListing
BatchListing = vault.CreateUtility( _
EdmUtility.EdmUtil_BatchList)

'Add all the reference file paths to the


'IEdmClearLocalCache object to clear from the
'local cache and to the IEdmBatchListing object
'to get the file information in batch mode
For Each KvPair As KeyValuePair(Of String, String) _
In RefFilesDictionary
ClearLocalCache.AddFileByPath(KvPair.Key)
DirectCast(BatchListing, IEdmBatchListing2). _
AddFileCfg(KvPair.Key, Nothing, KvPair.Value, _
"@", EdmListFileFlags.EdmList_Nothing)
Next
'Clear the local cache of the reference files
ClearLocalCache.CommitClear()

Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)

5 Add code to create the batch file listing.


Add the code below to generate the batch file listing. The first
argument passed to the IEdmBatchListing2.CreateListEx method
allows you to specify any data card variables whose values you would
like to retrieve. In this example, we’ll ask for the values of the
Description and the Number data card variables.
Once the batch file listing has been generated, we can get the file
information with a call to the GetFiles method. This method returns an
array of EdmListFile structures, which hold the file information.
The data card variable values will be held in the moColumnData
member, which holds an array of values that are stored in the order that
they were specified in.
'Clear the local cache of the reference files
ClearLocalCache.CommitClear()

56
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

'Create the batch file listing along with the file


'card variables Description and Number
DirectCast(BatchListing, IEdmBatchListing2). _
CreateListEx(vbLf + "Description" + vbLf + _
"Number", EdmCreateListExFlags. _
Edmclef_MayReadFiles, Nothing, Nothing)
'Get the generated file info
Dim BatchListFiles() As EdmListFile = Nothing
BatchListing.GetFiles(BatchListFiles)
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)

6 Add code to build the hierarchical data structure.


Add the recursive subroutine below to take the file data that we’ve
gathered so far and using our custom FileRef class, assemble a
hierarchical data structure that will be later written out to an XML file.
Private Sub AddFileRef( _
ByRef BatchListFiles() As EdmListFile, _
ByRef curIndex As Integer, _
ByVal curLevel As Integer, _
ByRef FileRefs As List(Of FileRef))
Try
While curIndex < BatchListFiles.Length
Dim curListFile As EdmListFile = _
BatchListFiles(curIndex)
'if the depth level of this listfile is greater
'than the current depth level
If curListFile.mlParam > curLevel Then
'create a new FileRefs list
FileRefs(FileRefs.Count - 1).FileRefs = _
New List(Of FileRef)
'recurse using a new FileRefs list
AddFileRef(BatchListFiles, curIndex, _
curListFile.mlParam, _
FileRefs.Item(FileRefs.Count - 1).FileRefs)
Else
'Create a new FileRef object to hold the
'file information
Dim FileRef As New FileRef
'Assign the FileRef properties
FileRef.CheckedOutBy = curListFile.mbsLockUser
FileRef.CurrentState = _

57
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

curListFile.moCurrentState.mbsStateName
FileRef.Description = _
curListFile.moColumnData(0)
Dim File As IEdmFile5
File = vault.GetObject( _
EdmObjectType.EdmObject_File, _
curListFile.mlFileID)
FileRef.FileName = File.Name
FileRef.LatestRevision = _
curListFile.mbsRevisionName
FileRef.LatestVersion = _
curListFile.mlLatestVersion
FileRef.Number = curListFile.moColumnData(1)
FileRef.FileRefs = Nothing
'Add the FileRef to this level's list
FileRefs.Add(FileRef)
curIndex += 1
End If
End While
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

7 Add code to initiate building the data structure for export.


Add the code below at the end of the click event handler for the
WriteXmlButton control. We will initiate the call to the recursive
subroutine AddFileRef by passing in an empty List of type FileRef
which will hold the data to export once finished. The List of FileRef
objects is then exported to an XML file using the XmlSerializer class.
'Get the generated file info
Dim BatchListFiles() As EdmListFile = Nothing
BatchListing.GetFiles(BatchListFiles)

'Create the list where we'll store all the


'file information
Dim FileRefs As New List(Of FileRef)
'Recursively add the file information to the list
AddFileRef(BatchListFiles, 0, 0, FileRefs)

58
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

If Not Directory.Exists("C:\temp") Then


MessageBox.Show("Directory ""C:\temp"" does " + _
"not exist, please create it and try again.")
Else
'Write out the file references to an XML file
Dim XmlSer As New XmlSerializer( _
GetType(List(Of FileRef)))
Dim StrWriter As New StreamWriter( _
"C:\temp\BatchFileRefInfo.xml")
XmlSer.Serialize(StrWriter, FileRefs)
StrWriter.Close()
End If
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

8 Build and run the application.


Press F5 to build and save the application and run it in the debugger
environment.
Choose a Vault View from the
drop-down list.
Click the Browse button and
select one or more files in the File
Open dialog to get reference tree
information for.
Click the Open button in the File
Open dialog to confirm your file
selection and dismiss the dialog.
Click the Write File Reference
Info to XML File button. The
application will retrieve the reference tree and batch listing information
for the selected files and export the hierarchical information to the
XML file C:\temp\BatchFileRefInfo.xml.
9 Stop the application and verify the results.
Click the close icon in the upper right corner of the form.
Double click on the file C:\temp\BatchFileRefInfo.xml to open the
XML file and observe the resulting exported information.

59
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

Items Items in SOLIDWORKS PDM Professional contain all the same meta
data as files except that there is no actual file associated with them.
Because Item information is so similar to file information, much of the
API functionality for Items is exposed on the IEdmFile interface. In
other words, if you have an IEdmItem interface, in C++ you can query
for the IEdmFile interface or in VB you can assign the value of a
variable of type IEdmItem to a variable of type IEdmFile.
The The IEdmBatchItemGeneration interface allows you to create any
IEdmBatchItem- number of Items at the same time. You can generate all the initial Items
Generation needed for a new project, for example. While you are creating the
Interface Items, you can also assign values to their variables as well.
The IEdmBatchItemGeneration interface is created using the
IEdmVault7.CreateUtility method by passing in the enumeration
value EdmUtil_BatchItemGeneration as an argument. If you would
like to assign any variables to the Items that you create, you will need
to create an array of EdmVarVal structures to hold the variable IDs or
names and their values. You would then call the
IEdmBatchItemGeneration2.AddSelection2 method once for each
Item that you would like to create, passing in the EdmVarVal array to
assign variables, if desired, a name for the item, and file related
information if links to files are to be created. Once the Item information
is added, the IEdmBatchItemGeneration2.CreateTree method
needs to be called to compute the file reference tree. The ShowDlg
method can then optionally be called if the display of a user interface is
desired. The IEdmBatchItemGeneration2.GenerateItems method
can then be called to actually create the items.
Case Study: In this case study, we will create an application that creates a set of
Create Items from stand-alone Items from data that is imported from an XML file.
Imported Data

1 Open project and review


code.
Open the project
AddItems and open the
NewItem.vb file. Look at
the definition of the
NewItem class. The Public
properties of this class will
be used to store the
imported information about
the Items to add to the
vault.

60
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

Public Class NewItem


'Value of "Description" variable
Private mDescription As String
'Value of "Project Name" variable
Private mProjectName As String
'Value of "Project number" variable
Private mProjectNumber As String
'Value of "Part Type" variable
Private mPartType As String
'Item name
Private mItemName As String

Public Sub New()

End Sub

Public Property Description() As String


Get
Description = mDescription
End Get
Set(ByVal Value As String)
mDescription = Value
End Set
End Property

Public Property ProjectName() As String


Get
ProjectName = mProjectName
End Get
Set(ByVal Value As String)
mProjectName = Value
End Set
End Property

Public Property ProjectNumber() As String


Get
ProjectNumber = mProjectNumber
End Get
Set(ByVal Value As String)
mProjectNumber = Value
End Set
End Property

61
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

Public Property PartType() As String


Get
PartType = mPartType
End Get
Set(ByVal Value As String)
mPartType = Value
End Set
End Property

Public Property ItemName() As String


Get
ItemName = mItemName
End Get
Set(ByVal Value As String)
mItemName = Value
End Set
End Property

End Class

2 Add code to import item information.


Add the code below to read information from an XML file about items
to add to the vault. The information about each Item will be stored in a
NewItem object and all the NewItem objects will be stored in an
ArrayList so we can easily add new objects to the collection. We’ll
make use of the .NET XmlReader class to read the XML data, but any
XML library could have been used.
Private Sub AddItemsButton_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
AddItemsButton.Click
Try
ItemsListBox.Items.Clear()
Dim NewItems As ArrayList = New ArrayList

Using XmlReader As Xml.XmlReader = _


Xml.XmlReader.Create(XmlTextBox.Text)

XmlReader.Read()
XmlReader.ReadToNextSibling("ArrayOfAnyType")
XmlReader.ReadToDescendant("anyType")

62
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

Do
Dim CurItem As New NewItem
XmlReader.ReadToDescendant("Description")
CurItem.Description = XmlReader.ReadString()
XmlReader.ReadToNextSibling("ProjectName")
CurItem.ProjectName = XmlReader.ReadString()
XmlReader.ReadToNextSibling("ProjectNumber")
CurItem.ProjectNumber = XmlReader.ReadString()
XmlReader.ReadToNextSibling("PartType")
CurItem.PartType = XmlReader.ReadString()
XmlReader.ReadToNextSibling("ItemName")
CurItem.ItemName = XmlReader.ReadString()
NewItems.Add(CurItem)
Loop While XmlReader.ReadToFollowing("anyType")
End Using
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + ex.ErrorCode. _
ToString("X") + vbCrLf + ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

3 Add the Items to the IEdmBatchItemGeneration object.


Add the code below to log into the vault and add the information
needed to create the new Items.

Tip Whenever you login with an instance of an IEdmVault object using a


different user account, a new connection to the vault database is created
and will remain open until your application closes. To keep the number
of open connections to the vault at a minimum, you should create only
one instance of the IEdmVault object and use it throughout the
application.
One technique for making sure that only one instance of an object is
created throughout an application is demonstrated here in the
EdmVaultSingleton class. Whenever we need an instance of the
IEdmVault object, we’ll ask for it through the
EdmVaultSingleton.Instance property and the class will either
create a new IEdmVault instance if one doesn’t exist yet or return the
existing one if it does.
Once we have the IEdmVault instance, log in to the selected vault as
the current user with the IEdmVault5.LoginAuto method.

63
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

Add the code to create the IEdmBatchItemGeneration utility object


and add the Item values that were imported earlier. In order to add the
variable data, we’ll need to create an array of EdmVarVal structures to
hold the data while it is being passed as an argument to the
IEdmBatchItemGeneration2.AddSelection2 method. There should
be one EdmVarVal structure element in the array for each variable that
will be assigned.
XmlReader.ReadToNextSibling("ItemName")
CurItem.ItemName = XmlReader.ReadString()
NewItems.Add(CurItem)
Loop While XmlReader.ReadToFollowing("anyType")
End Using
'Obtain the only instance of the IEdmVault5 object
Dim vault As IEdmVault5 =
EdmVaultSingleton.Instance

If Not vault.IsLoggedIn Then


'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())
End If

'Create the batch interface


Dim BatchItemGen As IEdmBatchItemGeneration2
BatchItemGen = vault.CreateUtility( _
EdmUtility.EdmUtil_BatchItemGeneration)
Dim VarVals(3) As EdmVarVal
VarVals(0).mlEdmVarValFlags = 0
VarVals(0).moVarIDorName = "Description"
VarVals(1).mlEdmVarValFlags = 0
VarVals(1).moVarIDorName = "Project Name"
VarVals(2).mlEdmVarValFlags = 0
VarVals(2).moVarIDorName = "Project number"
VarVals(3).mlEdmVarValFlags = 0
VarVals(3).moVarIDorName = "Part Type"
For i As Integer = 0 To NewItems.Count - 1
VarVals(0).moValue = NewItems(i).Description
VarVals(1).moValue = NewItems(i).ProjectName
VarVals(2).moValue = NewItems(i).ProjectNumber
VarVals(3).moValue = NewItems(i).PartType
BatchItemGen.AddSelection2(vault, VarVals, _
NewItems(i).ItemName)
Next i

64
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + ex.ErrorCode. _
ToString("X") + vbCrLf + ex.Message)

4 Generate and display the items.


Add the code below to create the item tree, generate the new items and
display their names and status in the listbox.
The first step is to call the IEdmBatchItemGeneration.CreateTree
method, which will compute the file reference tree to create items for.
Calling the IEdmBatchItemGeneration.GenerateItems method
will then perform the actual item creation. Information about the
created items will be returned in an array of EdmGenItemInfo
structures. In order to display information about the items to the user,
iterate through the array and add information about each new item to
the ItemsListBox control.
BatchItemGen.AddSelection2(vault, VarVals, _
NewItems(i).ItemName)
Next i
'Build the item tree.
Dim CreateSuccess As Boolean
CreateSuccess = BatchItemGen.CreateTree( _
Me.Handle.ToInt32, _
EdmItemGenerationFlags.Eigcf_Nothing)
'EdmItemGenerationFlags.Eigcf_OpenItemsCheckbox)
If (CreateSuccess = False) Then Exit Sub

'Generate the items


Dim ReturnedItems() As EdmGenItemInfo = Nothing
Dim bOpenExplorer As Boolean = False
BatchItemGen.GenerateItems(Me.Handle.ToInt32, _
ReturnedItems, bOpenExplorer, Nothing)

'Display the new Item information in the ListBox


Dim msg As String = ""
If ReturnedItems.Length = 0 Then
msg = "No items were added."
ItemsListBox.Items.Add("No items were added.")
Else
For Each ItemInfo As EdmGenItemInfo _
In ReturnedItems

ItemsListBox.Items.Add("Item name: " + _


ItemInfo.mbsItemName)

65
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

ItemsListBox.Items.Add("Alternate name: " + _


ItemInfo.mbsItemAlternativeName)
ItemsListBox.Items.Add("Status: " + _
vault.GetErrorMessage(ItemInfo.mhResult))
ItemsListBox.Items.Add("")
Next ItemInfo
End If
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + ex.ErrorCode. _
ToString("X") + vbCrLf + ex.Message)

5 Build and run the


application.
Press F5 to build and save
the application and run it in
the debugger environment.
Click the Browse button
and select an XML file to
import item data from.

Click the Add Items button. An exception is thrown and the


MessageBox below is displayed.

6 Stop the application.


Click the close icon in the upper right corner of the form.

66
SOLIDWORKS PDM Professional Lesson 2
Files, Folders, Items and References

7 Change EPDM.Interop.epdm property.


By default, Visual Studio assigns the Embed Interop Types property
of referenced interop assemblies a value of True, when the target
framework is .NET Framework 4 or higher. This simplifies the
deployment process for your application by embedding type
information for COM types directly within the application’s managed
assembly. This eliminates the need to distribute the interop assembly
when deploying your application.
Unfortunately, using embedded interop types will result in an exception
being thrown in situations where it is necessary to pass an array of
structures in a COM method. In the code above, the line:
BatchItemGen.AddSelection2(vault, VarVals, _
NewItems(i).ItemName)

attempts to pass an array of structures. The variable VarVals in the


second argument is declared as an array of EdmVarVal structures.
Dim VarVals(3) As EdmVarVal
In order to avoid an exception being thrown, we will need to not embed
interop types in our application’s assembly.
In Solution Explorer, double-click My Project in order to display the
project’s properties. Click the References tab to display the project’s
references. Click the Properties tab or press F4 then select the
EPDM.Interop.epdm reference. In the reference’s properties window,
change the Embed Interop Types property to False.

Now when deploying the application, it will be necessary to provide the


interop assembly EPDM.Interop.epdm.dll as well as the application
assembly AddItems.exe.
In addition, when initializing an empty array of structures in your code,
you should set it equal to Nothing. For example:
Dim ReturnedItems() As EdmGenItemInfo = Nothing

67
Lesson 2 SOLIDWORKS PDM Professional
Files, Folders, Items and References

8 Build and run the application.


Press F5 to build and save the application and run it in the debugger
environment.
Click the Browse button and select an XML file to import item data
from.
Click the Add Items button. The XML data will be read, the new items
generated and information about each new item will be displayed in the
list box.
9 Stop the application.
Click the close icon in the upper right corner of the form.
10 Observe the new items
using Item Explorer.
Start the Item Explorer
application and observe the
newly created items.

68
SOLIDWORKS PDM Professional Exercise 2
Traverse Files and Folders

Exercise 2:
Traverse Files
and Folders

Open the project Exercise 2 and add code to the


TraverseFoldersButton_Click subroutine that will:
 Log in to the vault whose name is displayed in the ComboBox.
 Launch a subroutine for traversing files and folders.

Create a new subroutine that will:


 Recursively traverse all the files and folders in the vault.
 Display the path of any files that are checked out.

69
Exercise 2 SOLIDWORKS PDM Professional
Traverse Files and Folders

Imports EPDM.Interop.epdm

Public Class Exercise2

Private Sub Exercise2_Load( _


ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load

Try
Dim vault As IEdmVault8 = New EdmVault5
Dim Views() As EdmViewInfo = Nothing

vault.GetVaultViews(Views, False)
VaultsComboBox.Items.Clear()
For Each View As EdmViewInfo In Views
VaultsComboBox.Items.Add(View.mbsVaultName)
Next
If VaultsComboBox.Items.Count > 0 Then
VaultsComboBox.Text = VaultsComboBox.Items(0)
End If

Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub TraverseFoldersButton_Click( _


ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles TraverseFoldersButton.Click

Try
'Declare and create an instance of IEdmVault5 object
Dim vault As IEdmVault5 = New EdmVault5()
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())

Debug.Print(vbCrLf + "Checked out files:" + vbCrLf)


TraverseFolder(vault.RootFolder)

70
SOLIDWORKS PDM Professional Exercise 2
Traverse Files and Folders

Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub TraverseFolder( _


ByVal CurFolder As IEdmFolder5)
Try
'Enumerate the files in the folder.
Dim FilePos As IEdmPos5
FilePos = CurFolder.GetFirstFilePosition
Dim file As IEdmFile5
While Not FilePos.IsNull
file = CurFolder.GetNextFile(FilePos)
'Get its checked out status
If file.IsLocked Then
Debug.Print(file.LockPath)
End If
End While

'Enumerate the sub-folders in the folder


Dim FolderPos As IEdmPos5
FolderPos = CurFolder.GetFirstSubFolderPosition
While Not FolderPos.IsNull
Dim SubFolder As IEdmFolder5
SubFolder = CurFolder.GetNextSubFolder _
(FolderPos)
TraverseFolder(SubFolder)
End While
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

End Class

71
Exercise 2 SOLIDWORKS PDM Professional
Traverse Files and Folders

72
Lesson 3
Users and Groups

Upon successful completion of this lesson, you will be able to:


 Understand the use of IEdmUserMgr interface.
 Understand the use of IEdmUser objects.
 Understand the use of IEdmUserGroup objects.
 Traverse the users in a vault.
 Traverse the groups in a vault.
 Traverse the members in a group.
 Use data from an XML file to create new users.

73
Lesson 3 SOLIDWORKS PDM Professional
Users and Groups

The IEdmUser The IEdmUser interface represents a SOLIDWORKS PDM


Interface Professional user. It has members that can get information about the
user such as the user’s name and initials and determine whether the
user has permission to perform certain tasks within SOLIDWORKS
PDM Professional.
The The IEdmUserGroup interface represents a SOLIDWORKS PDM
IEdmUserGroup Professional user group. It has members that can get information about
Interface the group such as the permissions that have been assigned to it as well
as enumerating and adding to the users within the group.
The IEdmUserMgr The IEdmUserMgr interface is used to enumerate and manipulate
Interface users and groups. In the case studies below, we will use
IEdmUserMgr methods to list all the users and groups that are
assigned to a vault.
Case Study: The same enumeration technique is used for traversing the users in a
User Traversal vault as for traversing files in a folder. The same IEdmPos object is
used, but this time to retrieve each of the IEdmUser objects.

1 Open project and add code to traverse users.


Open the UsersAndGroups project and open the
UsersAndGroups.vb file. Add code to the click event handler of the
TraverseUsersButton to traverse all the users in the vault.

Private Sub TraverseUsersButton_Click(ByVal sender _


As System.Object, ByVal e As System.EventArgs) _
Handles TraverseUsersButton.Click

'Declare and create an instance of IEdmVault5 object


Dim vault As IEdmVault5 = New EdmVault5()
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())

'Declare an IEdmUserMgr5 object


Dim UserMgr As IEdmUserMgr5
'The IEdmUserMgr5 interface is implemented by the
'same class as the IEdmVault5 interface,
'so in VB we can simply assign the value of
'the IEdmVault5 object
UserMgr = vault

74
SOLIDWORKS PDM Professional Lesson 3
Users and Groups

Dim Users As String = vbNullString


Dim UserPos As IEdmPos5
UserPos = UserMgr.GetFirstUserPosition()
While Not UserPos.IsNull
Dim User As IEdmUser5
User = UserMgr.GetNextUser(UserPos)
Users = Users + User.Name + vbCrLf
End While
MessageBox.Show(Users, vault.Name + _
" Vault User List", MessageBoxButtons.OK, _
MessageBoxIcon.Information)
End Sub

Case Study: The same enumeration technique is used for traversing the groups in a
Group Traversal vault as for traversing the users in a vault. The same IEdmPos object is
used, but this time to retrieve each of the IEdmUserGroup objects.

1 Add code to traverse groups.


Add code to the click event handler of the TraverseGroupsButton to
traverse all the groups in the vault.
Private Sub TraverseGroupsButton_Click(ByVal sender _
As System.Object, ByVal e As System.EventArgs) _
Handles TraverseGroupsButton.Click

'Declare and create an instance of IEdmVault5 object


Dim vault As IEdmVault5 = New EdmVault5()
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())

'Declare an IEdmUserMgr5 object


Dim UserMgr As IEdmUserMgr5
'The IEdmUserMgr5 interface is implemented by the
'same class as the IEdmVault5 interface,
'so in VB we can simply assign the value of the
'IEdmVault5 object
UserMgr = vault

Dim Groups As String = vbNullString


Dim UserGroupPos As IEdmPos5
UserGroupPos = UserMgr.GetFirstUserGroupPosition()
While Not UserGroupPos.IsNull

75
Lesson 3 SOLIDWORKS PDM Professional
Users and Groups

Dim UserGroup As IEdmUserGroup5


UserGroup = UserMgr.GetNextUserGroup _
(UserGroupPos)
Groups = Groups + UserGroup.Name + vbCrLf
End While
MessageBox.Show(Groups, vault.Name + _
" Vault Group List", MessageBoxButtons.OK, _
MessageBoxIcon.Information)
End Sub

Case Study: The same enumeration technique is used for traversing the members of
Group Member in a group as for traversing groups in a vault. The same IEdmPos
Traversal object is used again, but this time it is used by members of the
IEdmUserGroup5 interface instead of the IEdmUserMgr5 interface.
In the example below, as each group is traversed, the GetMembers
function is called to traverse the members of the group and return their
names.

1 Add code to traverse the users in groups.


Add code to the click event handler of the
TraverseGroupMembersButton to traverse all the users in the
groups in the vault.
Private Sub TraverseGroupMembersButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles TraverseGroupMembersButton.Click

'Declare and create an instance of IEdmVault5 object


Dim vault As IEdmVault5 = New EdmVault5()
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())

'Declare an IEdmUserMgr5 object


Dim UserMgr As IEdmUserMgr5
'The IEdmUserMgr5 interface is implemented by the _
'same class as the IEdmVault5 interface, _
'so in VB we can simply assign the value of the _
'IEdmVault5 object
UserMgr = vault

76
SOLIDWORKS PDM Professional Lesson 3
Users and Groups

Dim Groups As String = vbNullString


Dim UserGroupPos As IEdmPos5
UserGroupPos = UserMgr.GetFirstUserGroupPosition()
While Not UserGroupPos.IsNull
Dim UserGroup As IEdmUserGroup5
UserGroup = UserMgr.GetNextUserGroup _
(UserGroupPos)
Groups = Groups + UserGroup.Name + " Members :" _
+ vbCrLf
Groups = Groups + GetMembers(UserGroup)
End While
MessageBox.Show(Groups, vault.Name + _
" Vault Group Member List", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

2 Add a method to get the members in a group.


Add a method to traverse all the users in a group.
Private Function GetMembers(ByVal UserGroup _
As IEdmUserGroup5) As String

GetMembers = vbNullString
Dim Users As String = vbNullString
Dim UserPos As IEdmPos5
UserPos = UserGroup.GetFirstUserPosition()
While Not UserPos.IsNull
Dim User As IEdmUser5
User = UserGroup.GetNextUser(UserPos)
Users = Users + " " + User.Name + vbCrLf
End While
GetMembers = Users
End Function

77
Lesson 3 SOLIDWORKS PDM Professional
Users and Groups

Case Study: If we know the name of the group we are interested in, we can retrieve
Using IEdmUser the IEdmUserGroup object directly. We can then traverse the users of
Properties to that group and take some action based on the values of the user
Search for Users properties.
In the example below, we will look for users that belong to a particular
group that are currently logged in and send them a mail message.

1 Add code to find logged in members of a group.


Add code to the click event handler of the
SendConsultationRequestButton to traverse all the users in the
Project A group and send a message to those that are currently logged
in.
Private Sub SendConsultationRequestButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles SendConsultationRequestButton.Click

'Declare and create an instance of IEdmVault5 object


Dim vault As IEdmVault5 = New EdmVault5()
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())

'Declare an IEdmUserMgr5 object


Dim UserMgr As IEdmUserMgr5
'The IEdmUserMgr5 interface is implemented by the
'same class as the IEdmVault5 interface,
'so in VB we can simply assign the value of the
'IEdmVault5 object
UserMgr = vault

78
SOLIDWORKS PDM Professional Lesson 3
Users and Groups

Dim UserGroup As IEdmUserGroup5


UserGroup = UserMgr.GetUserGroup("Project A")
If Not UserGroup Is Nothing Then
Dim UserPos As IEdmPos5
UserPos = UserGroup.GetFirstUserPosition()
While Not UserPos.IsNull
Dim User As IEdmUser5
User = UserGroup.GetNextUser(UserPos)
If User.IsLoggedIn Then
User.SendMsg("Informal review request", _
"Please stop by my office sometime " + _
"this morning for a quick informal " + _
"review of my design changes before " + _
"I submit for approval.")
End If
End While
End If
End Sub

Case Study: With the IEdmUserMgr7 interface’s AddUsers2 method, we can


Adding New Users create new users and assign properties and permissions for them in the
vault. Information about each new user to be added to the vault is
specified in an EdmUserData2 structure. For users whose system
permissions are to be set when they are created, an array of
EdmSysPerm enum values can be assigned to the
EdmUserData2.moSysPerms member. Each member of the array of
EdmSysPerm values represents a system permission to be assigned to
the user.
All the new user data is passed to the AddUsers2 method in an array
of EdmUserData2 structures in its single argument.
When the AddUsers2 method returns, each user ID, the status of the
creation operation and optionally the IEdmUser6 interface for each
user is returned in various members of the EdmUserData2 structure.
In this case study, we will create an application that creates a set of new
users from data that is imported from an XML file.

79
Lesson 3 SOLIDWORKS PDM Professional
Users and Groups

1 Open project and review code.


Open the AddUsers project and open the User.vb file. Look at the
definition of the User class. The Public properties of this class will be
used to store the imported information about the users to add to the
vault.
Public Class User
Private mSn As String'First name
Private mGivenName As String'Last name
Private mTitle As String'Title
Private mCn As String'Complete name
Private mUsername As String'Email address

Public Sub New()

End Sub

Public Property sn() As String


Get
sn = mSn
End Get
Set(ByVal Value As String)
mSn = Value
End Set
End Property

Public Property givenName() As String


Get
givenName = mGivenName
End Get
Set(ByVal Value As String)
mGivenName = Value
End Set
End Property

Public Property title() As String


Get
title = mTitle
End Get
Set(ByVal Value As String)
mTitle = Value
End Set
End Property

80
SOLIDWORKS PDM Professional Lesson 3
Users and Groups

Public Property cn() As String


Get
cn = mCn
End Get
Set(ByVal Value As String)
mCn = Value
End Set
End Property

Public Property username() As String


Get
username = mUsername
End Get
Set(ByVal Value As String)
mUsername = Value
End Set
End Property

End Class

2 Add code to read XML data and log in to vault.


Add the code below to read the user data from an XML file using the
User class and the XmlSerializer.Deserialize method.
Get the one instance of the IEdmVault object and log in.
Since the IEdmUserMgr7 and the IEdmVault interfaces are
implemented by the same object, a simple assignment of the vault
variable will retrieve the IEdmUserMgr7 interface.

Private Sub AddUsersButton_Click( _


ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles AddUsersButton.Click
Dim StrReader As StreamReader = Nothing
Try
'De-Serialize Users from an XML file.
Dim ExtraTypes() As Type = _
{Type.GetType("AddUsers.User")}
Dim XmlSer As New XmlSerializer( _
Type.GetType("System.Collections.ArrayList"), _
ExtraTypes)
StrReader = New StreamReader(XmlTextBox.Text)
Dim NewUsers As ArrayList = _
XmlSer.Deserialize(StrReader)

81
Lesson 3 SOLIDWORKS PDM Professional
Users and Groups

'Obtain the only instance of the IEdmVault object


Dim vault As IEdmVault5 = EdmVaultSingleton.Instance

If Not vault.IsLoggedIn Then


'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())
End If
'Assign IEdmVault object to the IEdmUserMgr7 object
Dim UsrMgr As IEdmUserMgr7 = vault
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
If Not StrReader Is Nothing Then
StrReader.Close()
End If
End Try
End Sub

3 Create the EdmUserData2 array and add user to vault.


The IEdmUserMgr7.AddUsers2 method requires the user
information to be passed in as an array of EdmUserData2 structures.
Add the code below to create the array and populate it with the data
imported from the XML file and then add the new users with the
AddUsers2 method.
'Assign IEdmVault object to the IEdmUserMgr7 object
Dim UsrMgr As IEdmUserMgr7 = vault

'Declare EdmUserData array to hold new user data


Dim UserData(NewUsers.Count - 1) As EdmUserData2
'Set the EdmUserData members for each new user
For i As Integer = 0 To NewUsers.Count - 1
If Not NewUsers(i) Is Nothing Then
UserData(i).mbsCompleteName = NewUsers(i).cn
UserData(i).mbsEmail = NewUsers(i).username
UserData(i).mbsInitials = _
NewUsers(i).givenName.Substring(0, 1) + _
NewUsers(i).sn.Substring(0, 1)
UserData(i).mbsUserName = _
NewUsers(i).username.Split("@")(0)

82
SOLIDWORKS PDM Professional Lesson 3
Users and Groups

'Return user's IEdmUser6 interface in mpoUser


UserData(i).mlFlags = _
EdmUserDataFlags.Edmudf_GetInterface
'Add this user even if others can't be added
UserData(i).mlFlags += _
EdmUserDataFlags.Edmudf_ForceAdd

'Set permissions according to some criteria


If NewUsers(i).title.Contains("Manager") Then
Dim perms(1) As EdmSysPerm
perms(0) = _
EdmSysPerm.EdmSysPerm_EditUserMgr
perms(1) = _
EdmSysPerm.EdmSysPerm_EditReportQuery
UserData(i).moSysPerms = perms
Else
Dim perms(0) As EdmSysPerm
perms(0) = EdmSysPerm. _
EdmSysPerm_MandatoryVersionComments
UserData(i).moSysPerms = perms
End If
End If
Next i

'Add the users to the vault


UsrMgr.AddUsers2(UserData)
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)

4 Display the status of the added users.


The resulting status of the AddUsers2 method for each user will be
returned in the EdmUserData2.mhStatus member. The users’ IDs
will be returned in the EdmUserData2.mlUserID member and if the
Edmudf_GetInterface flag was set and passed in through the
mlFlags member, the IEdmUser6 interface will be returned in the
mpoUser member.
Add the code below to iterate through the EdmUserData2 array and
report the status of each user in a MessageBox.
'Add the users to the vault
UsrMgr.AddUsers2(UserData)

83
Lesson 3 SOLIDWORKS PDM Professional
Users and Groups

Dim msg As String = ""


For Each usr As EdmUserData2 In UserData
If usr.mhStatus = 0 Then
msg += "Created user """ + usr.mpoUser.Name _
+ """ successfully. ID = " _
+ usr.mpoUser.ID.ToString() + vbCrLf
Else
msg += "Error creating user """ _
+ usr.mbsUserName + """ - " _
+ vault.GetErrormessage(usr.mhStatus) + vbCrLf
End If
Next
MessageBox.Show(msg)
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)

5 Build and run the application.


Press F5 to build and save the
application and run it in the
debugger environment.
Select the vault to add the new users
to.
Click the Browse button and select
the XML file to import user data
from.
Click the Add Users button to
import the user data from the
selected XML file and add the new
users to the selected vault.
The status of the new users will be
displayed in a MessageBox.

6 Stop the application.


Click the close icon in the upper
right corner of the form.

84
SOLIDWORKS PDM Professional Exercise 3
Find Users

Exercise 3:
Find Users

Open the project Exercise 3 and add code to the


TraverseUsersButton_Click subroutine that will:
 Log in to the vault whose name is displayed in the ComboBox.
 Find logged in users that have permission to modify Categories.
 Send them a message requesting assistance to add a file type to a
category.

85
Exercise 3 SOLIDWORKS PDM Professional
Find Users

Imports EPDM.Interop.epdm

Public Class Exercise3

Private Sub Exercise3_Load( _


ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load

Try
Dim vault As IEdmVault8 = New EdmVault5
Dim Views() As EdmViewInfo = Nothing

vault.GetVaultViews(Views, False)
VaultsComboBox.Items.Clear()
For Each View As EdmViewInfo In Views
VaultsComboBox.Items.Add(View.mbsVaultName)
Next
If VaultsComboBox.Items.Count > 0 Then
VaultsComboBox.Text = VaultsComboBox.Items(0)
End If

Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub TraverseUsersButton_Click( _


ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles TraverseUsersButton.Click

Try
'Declare and create an instance of IEdmVault5 object
Dim vault As IEdmVault5 = New EdmVault5()
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())

86
SOLIDWORKS PDM Professional Exercise 3
Find Users

'Declare an IEdmUserMgr5 object


Dim UserMgr As IEdmUserMgr5
'The IEdmUserMgr5 interface is implemented by the
'same class as the IEdmVault5 interface,
'so in VB we can simply assign the value of
'the IEdmVault5 object
UserMgr = vault

Dim UserPos As IEdmPos5


UserPos = UserMgr.GetFirstUserPosition()
While Not UserPos.IsNull
Dim User As IEdmUser5
User = UserMgr.GetNextUser(UserPos)
If User.IsLoggedIn Then
If User.HasSysRight(EdmSysRightFlags. _
EdmSysRight_ModifyCategories) _
Then
User.SendMsg("Category request", _
"Please stop by my office sometime " + _
"this morning to discuss adding " + _
"a new file type to a Category.")
End If
End If
End While

Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

End Class

87
Exercise 3 SOLIDWORKS PDM Professional
Find Users

88
Lesson 4
Card Variables, Versions and
Revisions

Upon successful completion of this lesson, you will be able to:


 Understand the IEdmEnumeratorVariable interface.
 Get and set data card variables.
 Understand the IEdmversion interface.
 Understand the interfaces and structures related to revisions.
 Update revision number counters to set file revisions based on data
card variable values.
 Understand and use the IEdmDictionary interface to store and
find key and value pairs in the database.

89
Lesson 4 SOLIDWORKS PDM Professional
Card Variables, Versions and Revisions

Card Variables The IEdmVariable interface represents the definition of a variable


used in a SOLIDWORKS PDM Professional file or folder data card. It
has members that can get information about its definition such as which
attributes the variable is mapped to and it data type.
To enumerate the list of existing defined variables or to create new
variable definitions, the IEdmVariableMgr interface can be used.
In order to get or set the value of a card variable that is associated with
a file, the file’s IEdmFile interface and its
IEdmEnumeratorVariable interface are used.
IEdmEnumerator- The IEdmEnumeratorVariable interface is used to read and write
Variable variables in a file or folder data card. For files, the
IEdmEnumeratorVariable interface is obtained by calling the
IEdmFile.GetEnumeratorVariable method. For folders, an
IEdmEnumeratorVariable object variable can simply be assigned
from an IEdmFolder object.
GetVar and SetVar To get and set the value of a card variable, the
IEdmEnumeratorVariable.GetVar and SetVar methods can be
used. The variable name and configuration name are passed to these
methods as arguments. You should use an empty string for the
configuration name of folders and files that don’t support
configurations and use the string “@” for the configuration name when
referring to those custom properties of a file that are not configuration
specific.
CloseFile When the IEdmFile.GetEnumeratorVariable method is called, the
file is kept open until the IEdmEnumeratorVariable8.CloseFile
method is called. While the file is kept open, other operations on the
file may fail with sharing violations, so it is important to call the
IEdmEnumeratorVariable8.CloseFile method when you are
finished updating a file.
File Versions File versions are represented by the IEdmversion interface. This
interface has members that can provide information such as the version
comment, any revisions set on the version, the user who created the
version and the version number.
File Revisions The IEdmRevision interface represent a revision of a file. It has
members that can provide information such as the revision name, the
date and time the revision was created, the user who created the
revision and the version on which the revision was set.
The IEdmRevisionMgr interface provides methods for obtaining
information about and making changes to the revision number and
revision number component definitions that are in the vault.
The IEdmRevisionMgr2.GetRevisionNumberIDFromFile method
will retrieve the ID of the revision number for a particular file.

90
SOLIDWORKS PDM Professional Lesson 4
Card Variables, Versions and Revisions

The IEdmRevisionMgr2.GetRevisionNumbers method can return


all revision numbers in the vault or one revision number if its ID is
specified. In either case, the result is returned as an EdmRevNo
structure array.
The EdmRevNo structure has members that hold the ID of the revision
number, its name and format string.
The format string will contain some combination of literal text and
revision number component IDs. The component IDs are bracketed
with a “%” and an “n”. For example, if the format string consists of the
text “Rev-%1n”, the literal part is “Rev-”, which is followed by the
revision number component whose ID is 1.
The IEdmRevisionMgr2.GetRevisionNumberComponents2
method can return all revision number components in the vault or a
particular revision number component specified by name or ID or it can
return all the revision number components used by a revision number if
the negated ID of the revision number is specified. The revision
number components are returned as an EdmRevComponent2
structure array.
The EdmRevComponent2 structure has members that hold the ID of
the revision number component, its name and format string or list
items, depending on its type.
The IEdmRevisionMgr.SetRevisionCounters method can be used
to set the values of a file’s revision number component counters to new
values. The new values are passed in to this method in an array of
EdmRevCounter structures.
The EdmRevCounter structure has members that hold the name of a
revision number component and its new counter value.
Once the counter values are set, in order to change a file’s revision
according to the new counter values, a call needs to be made to the
IEdmRevisionMgr.IncrementRevision method.
In order to save the new revision value to the database, a call to the
IEdmRevisionMgr.Commit method needs to be made.

91
Lesson 4 SOLIDWORKS PDM Professional
Card Variables, Versions and Revisions

Case Study: Using the interfaces and structures that we’ve discussed, let’s create a
Set Revisions stand alone application that will take a list of files, retrieve the value of
the card variable named Revision for each file and if it holds a value
compatible with the file’s revision number format string, update the
revision number counters and set the file’s revision to the value of the
card variable.
This functionality could be useful, for example, to set the initial
revision number in the database of legacy files to match their existing
revision number that is mapped to the Revision data card variable.
1 Open project and add code.
Open the project SetRevision and add the following code to the click
event handler of the SetInitialRevisionButton control.
Private Sub SetInitialRevisionButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles SetInitialRevisionButton.Click

'Declare and create an instance of IEdmVault5 object


Dim vault As IEdmVault5 = New EdmVault5()

'Log into selected vault as the current user


vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())

'Display a "File Open" browse window for user to


'choose which file(s) to set the initial revision on
Dim PathList As EdmStrLst5
PathList = vault.BrowseForFile( _
Me.Handle.ToInt32(), _
EdmBrowseFlag.EdmBws_ForOpen + _
EdmBrowseFlag.EdmBws_PermitMultipleSel + _
EdmBrowseFlag.EdmBws_PermitVaultFiles, _
"SOLIDWORKS files " + _
"(*.sldprt; *.sldasm; *.slddrw)|" + _
"*.sldprt;*.sldasm;*.slddrw|" + _
"All Files (*.*)|*.*||", _
"", "", vault.RootFolderPath, _
"Select Files to Set Initial Revision on.")

'Exit if the user pressed "Cancel"


If PathList Is Nothing Then Exit Sub

92
SOLIDWORKS PDM Professional Lesson 4
Card Variables, Versions and Revisions

'Traverse the selected files


Dim pos As IEdmPos5
pos = PathList.GetHeadPosition
While Not pos.IsNull
'Get each file path from the selected files list
Dim FilePath As String
FilePath = PathList.GetNext(pos)
'Get the IEdmFile5 object corresponding
'to the path
Dim FileObj As IEdmFile5
FileObj = vault.GetFileFromPath(FilePath)

'Skip any files that are checked out


If FileObj.IsLocked Then
MessageBox.Show(FilePath + _
" is checked out." _
+ vbCrLf + "Check it in and try again." _
+ vbCrLf + "Skipping this file.", _
"File is checked out.", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
Continue While
End If

'Get the value of the file data


'card "Revision" variable
Dim EnumVarObj As IEdmEnumeratorVariable8
'Keeps the file open
EnumVarObj = FileObj.GetEnumeratorVariable

Dim GetVarSuccess As Boolean


'GetVar returns a Variant
Dim RevisionObj As Object = Nothing
GetVarSuccess = EnumVarObj.GetVar("Revision", _
"@", RevisionObj)
EnumVarObj.CloseFile(False)'Pass True to flush

93
Lesson 4 SOLIDWORKS PDM Professional
Card Variables, Versions and Revisions

'Skip any files without a "Revision" data


'card variable value
If RevisionObj Is Nothing Then
MessageBox.Show("The ""Revision"" custom " + _
"property of " + FilePath + _
" is not set to a value." _
+ vbCrLf + "Skipping this file.", _
"Revision custom property empty.", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
Continue While
End If

'Check to see if it's a String type


Dim RevType As System.Type
RevType = RevisionObj.GetType()
If Not RevType.Name = "String" Then
MessageBox.Show("The ""Revision"" " + _
"variable type is not ""String""." _
+ vbCrLf + "Skipping this file.", _
"Revision custom property empty.", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
Continue While
End If

Dim RevisionProp As String


RevisionProp = RevisionObj

'Skip any files whose "Revision" value


'isn't formatted appropriately
If Not RevisionProp.Length = 1 Then
MessageBox.Show("The ""Revision"" custom " + _
"property of " + FilePath + _
" does not conform to the expected " + _
"revision number format." + vbCrLf + _
"Skipping this file.", _
"Revision custom property wrong format.", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
Continue While
End If

94
SOLIDWORKS PDM Professional Lesson 4
Card Variables, Versions and Revisions

'Create an IEdmRevisionMgr2 object


Dim RevMgr As IEdmRevisionMgr2
RevMgr = vault.CreateUtility( _
EdmUtility.EdmUtil_RevisionMgr)

'Get the revision number ID


Dim CanIncrement As Boolean
Dim RevisionNumberID As Long
'Returns 0 if there is no revision number
'generator defined for the file's current state
RevisionNumberID = _
RevMgr.GetRevisionNumberIDFromFile( _
FileObj.ID, CanIncrement)

'Skip this file if there is no


'revision number generator for it
If RevisionNumberID = 0 Then
MessageBox.Show("Move " + FilePath + _
" to a state where a Revision Number " + _
"is defined." + vbCrLf + _
"Skipping this file.", _
"No Revision Number is Defined " + _
"for this State.", MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
Continue While
End If

'Get the revision number info for this file


Dim RevNumbers() As EdmRevNo = Nothing
RevMgr.GetRevisionNumbers(RevisionNumberID, _
RevNumbers)
Dim RevNoFormatString As String
RevNoFormatString = RevNumbers(0).mbsData
Dim RevNoFormatLiteral As String
Dim PercentPos As Integer
PercentPos = RevNoFormatString.IndexOf("%")
RevNoFormatLiteral = _
RevNoFormatString.Substring(0, PercentPos)
Dim NewRev As String
NewRev = RevNoFormatLiteral + RevisionProp

95
Lesson 4 SOLIDWORKS PDM Professional
Card Variables, Versions and Revisions

'Check the file's current revision


Dim CurRev As String
CurRev = FileObj.CurrentRevision

'Give the user the option to skip this file


'if it already has a revision set
If Not CurRev = String.Empty Then
Dim MsgBoxResult As _
System.Windows.Forms.DialogResult
MsgBoxResult = MessageBox.Show( _
"The current revision of " _
+ FilePath + " is """ + CurRev + """." + _
vbCrLf + "The new revision will be """ + _
NewRev + """" + vbCrLf _
+ "Would you like to continue?", _
"File already has a revision", _
MessageBoxButtons.OKCancel, _
MessageBoxIcon.Question)
If MsgBoxResult = _
Windows.Forms.DialogResult.Cancel Then _
Continue While
End If

'Get the revision number components for the _


'revision number used by this file
Dim RevComponents() As EdmRevComponent2 = Nothing
RevMgr.GetRevisionNumberComponents2( _
-RevisionNumberID, RevComponents)
Dim RevComponentName As String
RevComponentName = _
RevComponents(0).mbsComponentName

'Declare an array of EdmRevCounter structures


'even though we are only using one
'and assign the values we want to set
Dim RevCounters(0) As EdmRevCounter
'Assign the name of the revision counter
'that we want to set
RevCounters(0).mbsComponentName = _
RevComponentName

96
SOLIDWORKS PDM Professional Lesson 4
Card Variables, Versions and Revisions

'Assign the new revision counter value to the


'value stored in the Revision card variable
'converted to an integer
Dim RevInt As Long
RevInt = _
Asc(RevisionProp.ToUpper()) - Asc("A") + 1
RevCounters(0).mlCounter = RevInt

'Set the revision counter to the new values


RevMgr.SetRevisionCounters(FileObj.ID, _
RevCounters)

'Set the revision of the file to the new values


RevMgr.IncrementRevision(FileObj.ID)

'Save the new values to the database


Dim RevErrors() As EdmRevError = Nothing
RevMgr.Commit("Set starting revision for " + _
"legacy file.", RevErrors)
End While
End Sub

2 Check the current revision of


Block1.SLDPRT.
Block1.SLDPRT currently has
no revision set.

97
Lesson 4 SOLIDWORKS PDM Professional
Card Variables, Versions and Revisions

3 Check the value of the Revision data card variable.


The Block1.SLDPRT Revision data card variable’s current value is
G.

4 Build and run the application.


Press F5 to build and save the application
and run it in the debugger environment.
Select the vault and click Set Initial
Revision.
Select the file named Block1.SLDPRT and
click Open.
5 Check the new revision of
Block1.SLDPRT.
Once the click event handler
method for the
SetInitialRevisionButton has
completed, open a File Open
dialog and check the new revision
of the Block1.SLDPRT file.
6 Exit the Set Revision application.

98
SOLIDWORKS PDM Professional Lesson 4
Card Variables, Versions and Revisions

The Data card variables are associated with specific types of files and
IEdmDictionary folders and so individual data card variable values are managed by the
Interface SOLIDWORKS PDM Professional software whenever an associated
file or folder is created, deleted or copied. If you need to store some
data within the SOLIDWORKS PDM Professional database but don’t
want it to be linked to any particular file or folder, you can store the
data in a dictionary. A dictionary is a data structure that is managed by
an IEdmDictionary object. An IEdmDictionary object is similar to
the .NET Dictionary class objects that we’ve used previously in the
BatchRefTreeInfo case study in Lesson 3, except that with an
IEdmDictionary object you can store information in the
SOLIDWORKS PDM Professional database and access or modify it
whenever you need to. The dictionary is organized as pairs of keys and
values. The keys can be either integer or string values and the values
are stored as strings. The dictionary can efficiently search for both keys
and values.
Case Study: To get a feel for using dictionaries, we’ll create an application that can
Dictionaries add new dictionaries to the vault, retrieve and delete existing ones, add
new key and value pairs to a dictionary, retrieve existing data and
remove selected key and value pairs.

1 Open the project and add code to get a Dictionary.


Open the project AddDictionary and add the following code to the
SelectedIndexChanged event handler of the DictionaryComboBox
control.
To get an existing dictionary from the vault or to create a new one, the
IEdmVault5.GetDictionary method is used. The name of the
dictionary is passed in as an argument and a flag indicating whether a
new dictionary should be created if it doesn’t already exist.
Private Sub DictionaryComboBox_SelectedIndexChanged( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles DictionaryComboBox.SelectedIndexChanged
Try
If Not vault.IsLoggedIn Then
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())
End If

'Get the selected Dictionary, if it exists


Dim Dictionary As IEdmDictionary5
Dictionary = vault.GetDictionary( _
DictionaryComboBox.Text, False)

99
Lesson 4 SOLIDWORKS PDM Professional
Card Variables, Versions and Revisions

'Display the Dictionary contents


DisplayDictionaryItems( _
DictionaryComboBox.Text, _
Dictionary, KeyValueListBox)
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

2 Retrieve and display the keys and values.


Add code to the DisplayDictionaryItems subroutine that will iterate
over all the key and value pairs and display them.
The dictionary can be traversed by calling the
IEdmDictionary5.StringGetFirstPosition which will return the
now familiar IEdmPos5 interface object that corresponds to the first
key and value pair in the Dictionary. The remaining keys and values in
the Dictionary can be obtained by repeatedly calling the
StringGetNextAssoc method.
If the keys were stored as integers the LongGetFirstPosition and
LongGetNextAssoc methods would be used instead.
Private Sub DisplayDictionaryItems( _
ByVal DictionaryName As String, _
ByVal Dictionary As IEdmDictionary5, _
ByVal ListObject As Object)
Try
ListObject.Items.Clear()

If Dictionary Is Nothing Then


ListObject.Items.Add(DictionaryComboBox.Text + _
" dictionary doesn't exist.")
Else
'Traverse and display the Key / Value pairs
'in the dictionary
Dim Key As String = ""
Dim Value As String = ""
Dim Pos As IEdmPos5
Pos = Dictionary.StringGetFirstPosition()
While Not Pos.IsNull
Dictionary.StringGetNextAssoc(Pos, Key, Value)
ListObject.Items.Add(Key + vbTab + Value)

100
SOLIDWORKS PDM Professional Lesson 4
Card Variables, Versions and Revisions

End While
End If
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
3 Create a new Dictionary.
Add code to determine whether the selected Dictionary already exists
and create it if it doesn’t. The IEdmVault5.GetDictionary method
will return Nothing if the bCreateIfNew argument is False and the
Dictionary doesn’t exist. When the bCreateIfNew argument is True,
the Dictionary will be created if it doesn’t already exist.
Private Sub CreateButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles CreateButton.Click
Try
KeyValueListBox.Items.Clear()

If Not vault.IsLoggedIn Then


'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())
End If

'Get the selected Dictionary, if it already exists


Dim Dictionary As IEdmDictionary5
Dictionary = vault.GetDictionary( _
DictionaryComboBox.Text, False)
'If it doesn't exist, create it
If Dictionary Is Nothing Then
'Create it since it doesn't exist
Dictionary = vault.GetDictionary( _
DictionaryComboBox.Text, True)
KeyValueListBox.Items.Add( _
DictionaryComboBox.Text + _
" dictionary created.")

101
Lesson 4 SOLIDWORKS PDM Professional
Card Variables, Versions and Revisions

Else
'If it does exist, simply inform the user
KeyValueListBox.Items.Add( _
DictionaryComboBox.Text + _
" dictionary already exists.")
End If

'Add the new dictionary name to the dropdown list


'if it's not already there
If Not DictionaryComboBox.Items.Contains( _
DictionaryComboBox.Text) Then
DictionaryComboBox.Items.Add( _
DictionaryComboBox.Text)
End If
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

4 Delete a Dictionary.
Add the following code to the Click event handler of the
DeleteButton control. The IEdmDictionary5.RemoveDictionary
method will delete the Dictionary.
Private Sub DeleteButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles DeleteButton.Click
Try
KeyValueListBox.Items.Clear()
If Not vault.IsLoggedIn Then
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())
End If

102
SOLIDWORKS PDM Professional Lesson 4
Card Variables, Versions and Revisions

'Get the selected Dictionary, if it exists


Dim Dictionary As IEdmDictionary5
Dictionary = vault.GetDictionary( _
DictionaryComboBox.Text, False)
'If it doesn't exist, simply inform the user
If Dictionary Is Nothing Then
KeyValueListBox.Items.Add( _
DictionaryComboBox.Text + _
" dictionary doesn't exist.")
'If it does exist, delete it and inform the user
Else
Dictionary.RemoveDictionary()
KeyValueListBox.Items.Add( _
DictionaryComboBox.Text + _
" dictionary deleted.")
End If
'Remove the Dictionary name from the dropdown list
DictionaryComboBox.Items.Remove( _
DictionaryComboBox.Text)
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

103
Lesson 4 SOLIDWORKS PDM Professional
Card Variables, Versions and Revisions

5 Remove selected key and value pairs.


Add the code below to the Click event handler for the RemoveButton
control. Extract the key from the current selection and pass it as an
argument to the IEdmDictionary5.StringRemoveAt method to
remove the key and value pair.
Private Sub RemoveButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles RemoveButton.Click
Try
If KeyValueListBox.SelectedIndex = -1 Then
MessageBox.Show("No Key / Value was selected.")
Exit Sub
End If

Dim KeyValue As String


KeyValue = KeyValueListBox.Items( _
KeyValueListBox.SelectedIndex)
Dim key As String
key = Split(KeyValue, vbTab)(0)

If Not vault.IsLoggedIn Then


'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())
End If

Dim Dictionary As IEdmDictionary5


Dictionary = vault.GetDictionary( _
DictionaryComboBox.Text, False)

Dictionary.StringRemoveAt(key)
KeyValueListBox.Items.Remove(KeyValue)
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

104
SOLIDWORKS PDM Professional Lesson 4
Card Variables, Versions and Revisions

6 Add a key and value pair.


Add the code below to the Click event handler for the
AddKeyValueButton control.
Take the key and value data that the user has entered into the TextBox
controls and create a new key and value pair in the selected dictionary.
The IEdmDictionary5.StringTestAndSetAt method will ensure
that the key is unique in the Dictionary before adding the key and value
pair. Refresh the display of the Dictionary contents.
Private Sub AddKeyValueButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles AddKeyValueButton.Click
Try
If Not vault.IsLoggedIn Then
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())
End If

Dim Dictionary As IEdmDictionary5


Dictionary = vault.GetDictionary( _
DictionaryComboBox.Text, False)

'Check to make sure the user has entered valid data


If KeyTextBox.Text = "" _
Or ValueTextBox.Text = "" Then
MessageBox.Show("Please enter a key and a value.")
Exit Sub
End If

'Add the data if it's not already in the dictionary


Dim SuccessSet As Boolean = False
SuccessSet = Dictionary.StringTestAndSetAt( _
KeyTextBox.Text, ValueTextBox.Text)
If Not SuccessSet Then
MessageBox.Show("The data was not added.")
Else
DisplayDictionaryItems(DictionaryComboBox.Text, _
Dictionary, KeyValueListBox)
KeyTextBox.Text = ""
ValueTextBox.Text = ""
End If

105
Lesson 4 SOLIDWORKS PDM Professional
Card Variables, Versions and Revisions

Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

7 Add a new Dictionary to hold project information.


Add the code below to the Click event handler for the
AddProjectItemsButton control. Create a new Dictionary named
Projects in the selected vault and add several key and value pairs.
The keys will represent project numbers and the values will represent
the associated project names. We will use this Dictionary later in
Lesson 5 to automatically update data card variables.
Private Sub AddProjectItemsButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles AddProjectItemsButton.Click
Try
If Not vault.IsLoggedIn Then
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())
End If

Dim ProjectDictionary As IEdmDictionary5


ProjectDictionary = vault.GetDictionary( _
"Projects", True) 'Create it if it doesn't exist

'Add the new dictionary name to the dropdown list


'if it's not already there
If Not DictionaryComboBox.Items.Contains( _
"Projects") Then
DictionaryComboBox.Items.Add("Projects")
End If

106
SOLIDWORKS PDM Professional Lesson 4
Card Variables, Versions and Revisions

Dim SuccessSet As Boolean = False


SuccessSet = ProjectDictionary.StringTestAndSetAt _
("1000", "Mercury")
SuccessSet = ProjectDictionary.StringTestAndSetAt _
("1001", "Venus")
SuccessSet = ProjectDictionary.StringTestAndSetAt _
("1002", "Earth")
SuccessSet = ProjectDictionary.StringTestAndSetAt _
("1003", "Mars")
SuccessSet = ProjectDictionary.StringTestAndSetAt _
("1004", "Jupiter")
SuccessSet = ProjectDictionary.StringTestAndSetAt _
("1005", "Saturn")

If DictionaryComboBox.Text = "Projects" Then


DisplayDictionaryItems("Projects", _
ProjectDictionary, KeyValueListBox)
Else
DictionaryComboBox.Text = "Projects"
End If
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
8 Add a new Dictionary to hold serial number counters.
Add the code below to the Click event handler for the
AddCounterItemsButton control. Create a new Dictionary named
Counters in the selected vault and add several key and value pairs.
The keys will represent serial number categories and the values will
represent the next serial number to be used for the associated category.
We will use this Dictionary later in Lesson 5 to generate serial numbers
that are based on file categories.
Private Sub AddCounterItemsButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles AddCounterItemsButton.Click
Try
If Not vault.IsLoggedIn Then
'Log into selected vault as the current user
vault.LoginAuto(VaultsComboBox.Text, _

107
Lesson 4 SOLIDWORKS PDM Professional
Card Variables, Versions and Revisions

Me.Handle.ToInt32())
End If

Dim CounterDictionary As IEdmDictionary5


CounterDictionary = vault.GetDictionary _
("Counters", True)'Create it if it doesn't exist

'Add the new dictionary name to the dropdown list


'if it's not already there
If Not DictionaryComboBox.Items.Contains( _
"Counters") Then
DictionaryComboBox.Items.Add("Counters")
End If

Dim SuccessSet As Boolean = False


SuccessSet = CounterDictionary.StringTestAndSetAt _
("Electrical", "5")
SuccessSet = CounterDictionary.StringTestAndSetAt _
("Hydraulic", "10")
SuccessSet = CounterDictionary.StringTestAndSetAt _
("Mechanical", "15")
SuccessSet = CounterDictionary.StringTestAndSetAt _
("Manufacturing", "20")

If DictionaryComboBox.Text = "Counters" Then


DisplayDictionaryItems("Counters", _
CounterDictionary, KeyValueListBox)
Else
DictionaryComboBox.Text = "Counters"
End If
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

108
SOLIDWORKS PDM Professional Lesson 4
Card Variables, Versions and Revisions

9 Build and run the application.


Press F5 to build and save the
application and run it in the debugger
environment.
Select Projects from the Select
Dictionary dropdown list.
The application will log into the
selected vault, attempt to open the
selected Dictionary and display all the
key and value pairs contained in the
dictionary. At this point the Projects
dictionary doesn’t exist yet so a
message to that effect is displayed in
the Keys - Values ListBox.

Type NewTest as the name of a


Dictionary in the Select Dictionary
ComboBox and click Create.
A new Dictionary is created.

109
Lesson 4 SOLIDWORKS PDM Professional
Card Variables, Versions and Revisions

Enter 1 in the Key TextBox and First


in the Value TextBox and click Add
Key / Value. A new key and value pair
is added to the NewTest Dictionary
and is displayed in the Keys - Values
ListBox.
Try adding a few more key and value
pairs. The key and value pairs will not
necessarily be stored in the order that
they were entered or in any particular
order.

If you try entering a key that already exists in


the Dictionary, the
IEdmDictionary.StringTestAndSetAt
method will return False and a MessageBox
will notify the user.

110
SOLIDWORKS PDM Professional Lesson 4
Card Variables, Versions and Revisions

Select an entry in the Keys - Values


ListBox and click Remove Selected
Key / Value to delete it.

The Delete button will remove the


Dictionary whose name is currently
visible in the Select Dictionary
ComboBox.

Click Add Project Items and Add


Counter Items to create those
Dictionaries in the selected vault and
populate them with some initial key
and value pairs.
These two Dictionaries will be used in
the Lesson 5 case studies.

10 Stop the application.


Click the Close icon in the upper right corner of the form.

111
Exercise 4 SOLIDWORKS PDM Professional
Find Cards where a Variable is Used

Exercise 4:
Find Cards
where a
Variable is Used

Open the project Exercise 4 and add code to the


FindCardsButton_Click subroutine that will:
 Log in to the vault whose name is displayed in the ComboBox.
 Find all the file type data Cards in the vault that have the variable
Description mapped to an attribute and display their names.

112
SOLIDWORKS PDM Professional Exercise 4
Find Cards where a Variable is Used

Imports EPDM.Interop.epdm

Public Class Exercise4

Private Sub Exercise4_Load( _


ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load

Try
Dim vault As IEdmVault8 = New EdmVault5
Dim Views() As EdmViewInfo = Nothing

vault.GetVaultViews(Views, False)
VaultsComboBox.Items.Clear()
For Each View As EdmViewInfo In Views
VaultsComboBox.Items.Add(View.mbsVaultName)
Next
If VaultsComboBox.Items.Count > 0 Then
VaultsComboBox.Text = VaultsComboBox.Items(0)
End If

Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub FindCardsButton_Click( _


ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles FindCardsButton.Click

Try
'Declare and create an instance of
'IEdmVault5 object
Dim vault As IEdmVault5 = New EdmVault5()

113
Exercise 4 SOLIDWORKS PDM Professional
Find Cards where a Variable is Used

'Log into selected vault as the current user


vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())

Dim Cards As New ArrayList


Cards.Clear()

Dim Folder As IEdmFolder5


Folder = vault.RootFolder

Dim VarMgr As IEdmVariableMgr5


VarMgr = vault

''We could get the "Description" variable directly,


''but we'll get it by enumerating through all
''the variables until we find it -
''just to make it more interesting
'Dim DescVar As IEdmVariable5
'DescVar = VarMgr.GetVariable("Description")

Dim VarPos As IEdmPos5


VarPos = VarMgr.GetFirstVariablePosition
While Not VarPos.IsNull
Dim Var As IEdmVariable5
Var = VarMgr.GetNextVariable(VarPos)
If Not Var.Name = "Description" _
Then Continue While
Dim AttPos As IEdmPos5
AttPos = Var.GetFirstAttributePosition("")
While Not AttPos.IsNull
Dim Att As IEdmAttribute5
Att = Var.GetNextAttribute(AttPos)
Dim Extensions() As String
Extensions = Att.Extensions.Split(",")
Dim Extension As String
For Each Extension In Extensions
Dim Card As IEdmCard5
Try
Card = Folder.GetCard(Extension)
If Card.cardtype = _
EdmCardType.EdmCard_File Then
If Not Cards.Contains(Card.Name) Then
Cards.Add(Card.Name)
End If

114
SOLIDWORKS PDM Professional Exercise 4
Find Cards where a Variable is Used

End If
Catch ex As _
Runtime.InteropServices.COMException
'E_EDM_INVALID_NAME
If Not ex.ErrorCode = &H8004021D Then
Throw New _
Runtime.InteropServices.COMException _
(ex.Message, ex.ErrorCode)
End If
End Try
Next Extension
End While
End While

Dim CardName As String


For Each CardName In Cards
Debug.Print(CardName)
Next CardName
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class

115
Exercise 5 SOLIDWORKS PDM Professional
Find Revisions That Use a Component

Exercise 5:
Find Revisions
That Use a
Component

Open the project Exercise 5 and add code to the


FindRevisionsButton_Click subroutine that will:
 Log in to the vault whose name is displayed in the ComboBox.
 Find all the Revisions in the vault that use the component
ProjectSW and display their names.

116
SOLIDWORKS PDM Professional Exercise 5
Find Revisions That Use a Component

Imports EPDM.Interop.epdm

Public Class Exercise5

Private Sub Exercise5_Load( _


ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load

Try
Dim vault As IEdmVault8 = New EdmVault5
Dim Views() As EdmViewInfo = Nothing

vault.GetVaultViews(Views, False)
VaultsComboBox.Items.Clear()
For Each View As EdmViewInfo In Views
VaultsComboBox.Items.Add(View.mbsVaultName)
Next
If VaultsComboBox.Items.Count > 0 Then
VaultsComboBox.Text = VaultsComboBox.Items(0)
End If

Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub FindRevisionsButton_Click( _


ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles FindRevisionsButton.Click

Try
'Declare and create an instance of
'IEdmVault5 object
Dim vault As IEdmVault5 = New EdmVault5()

117
Exercise 5 SOLIDWORKS PDM Professional
Find Revisions That Use a Component

'Log into selected vault as the current user


vault.LoginAuto(VaultsComboBox.Text, _
Me.Handle.ToInt32())

Debug.Print _
("Revisions that use component ""ProjectSW"":")
Debug.Print("")

Dim RevMgr As IEdmRevisionMgr2


RevMgr = vault.CreateUtility( _
EdmUtility.EdmUtil_RevisionMgr)

Dim RevNumbers() As EdmRevNo = {}


RevMgr.GetRevisionNumbers(Nothing, RevNumbers)
Dim RevNo As EdmRevNo
For Each RevNo In RevNumbers
Dim RevComponents() As EdmRevComponent2 = Nothing
RevMgr.GetRevisionNumberComponents2 _
(-RevNo.mlRevNoID, RevComponents)
Dim RevComponent As EdmRevComponent2
For Each RevComponent In RevComponents
If RevComponent.mbsComponentName = "ProjectSW" _
Then
Debug.Print(RevNo.mbsRevNoName)
End If
Next RevComponent
Next RevNo
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class

118
Lesson 5
Add-In Applications

Upon successful completion of this lesson, you will be able to:


 Understand the differences between add-in and stand-alone
applications.
 Understand the use of the IEdmAddIn interface.
 Understand the use of the Implements keyword.
 Create a SOLIDWORKS PDM Professional add-in application.
 Add menu items to the SOLIDWORKS PDM Professional user
interface.
 Respond to events triggered by the interactive user’s actions.
 Change a data card variable’s value when another variable’s value
is changed.
 Generate serial numbers based on built-in or custom counters.
 Install and debug add-ins.

119
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

SOLIDWORKS SOLIDWORKS PDM Professional add-in applications can not be


PDM executed directly like the stand-alone executables that we have been
Professional creating thus far. Add-ins are created as dynamically linked libraries
Add-Ins that are loaded by the SOLIDWORKS PDM Professional software.
They are more tightly integrated with SOLIDWORKS PDM
Professional and allow custom menu items to be added as well as the
ability to take actions in response to events that take place within the
SOLIDWORKS PDM Professional application.
The IEdmAddIn The IEdmAddIn interface allows the add-in application to initiate
Interface communication with the SOLIDWORKS PDM Professional software.
This interface must be implemented by the add-in in order to be
recognized as a valid add-in. There are only two methods on this
interface, but they both need to be implemented by the add-in.
 GetAddInInfo - This method is called by the SOLIDWORKS PDM
Professional software when it first loads the add-in into memory.
From this method, the add-in can provide information about itself
such as its name, company name, a description of the add-in and the
minimum version of the SOLIDWORKS PDM Professional
software it requires in order to run successfully. The add-in can also
add menu items and tell the SOLIDWORKS PDM Professional
software which events it would like to receive notifications about.
 OnCmd - This method is called by the SOLIDWORKS PDM
Professional software whenever one of the add-in’s menu items is
pressed by the interactive user or whenever one of the events that
the add-in has registered for is sent.
Case Study: Let’s create a simple add-in that does nothing more than minimally
Creating an Add-In implement the IEdmAddIn interface. We will add more functionality
later on but for now we’ll just examine the minimum requirements for
an add-in.

120
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

1 Create a new project.


From the Visual Studio File menu, choose New, Project.
From the Installed, Templates list, select Visual Basic, Windows.
From the Templates list, select Class Library.
Browse to a suitable folder for the project location.
Name the new project EpdmVbAddin.
The Solution Name will automatically adapt to the name that you’ve
given the project.
Click OK.

A new class library project is created with an initially empty class.


Public Class Class1

End Class

121
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

2 Rename the class.


In the Solution Explorer tab, right click on the source file named
Class1.vb and rename it to something more descriptive. In this case
name it VbAddIn.vb.

This will automatically cause the class to also be renamed.


Public Class VbAddIn

End Class

3 Add a reference to the SOLIDWORKS PDM Professional type


library.
From the Project Menu, click Add Reference.

122
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

Click the Browse button and navigate to the SOLIDWORKS PDM


Professional installation folder. Select EdmInterface.dll and press
Add, then OK.

4 Add an Imports statement.


Since the SOLIDWORKS PDM Professional interfaces that we will be
using are located within the EdmLib namespace, add a line at the top
of the file to import the EdmLib namespace.
Imports EdmLib

Public Class VbAddIn

End Class

Without the Imports statement, whenever we use a SOLIDWORKS


PDM Professional API interface, structure or enumeration name we
would need to prefix it with the namespace name EdmLib separated
with a period. By adding the Imports statement we can reduce the
code size and the amount of typing we need to do when writing code.

123
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

The Implements In order for SOLIDWORKS PDM Professional to be able to


Statement communicate with an add-in, the add-in needs to implement the
IEdmAddin5 interface. The Implements statement is used to let the
Visual Basic compiler know that we intend to implement an interface.
The Implements statement informs the compiler that the
IEdmAddIn5 interface will be implemented within the class that this
statement appears in. This means that unless all the members of that
interface are implemented, the project will not compile.

5 Add an Implements statement.


Add the following Implements statement to your code just below the
class declaration.
Imports EdmLib

Public Class VbAddIn


Implements IEdmAddIn5

End Class

Note We can use the Object Browser to see all the members of the interface
that will need to be implemented.
6 Inspect the IEdmAddIn5 interface.
Click on the Class View tab and expand the EpdmVbAddin
namespace in the upper pane. Expand the VbAddIn class and the Base
Types folder and select the IEdmAddIn5 interface. This will cause
the interface members to display in the lower pane. There are only two
members listed, GetAddInInfo( ) and OnCmd( ). These are the
members that we will need to implement.

124
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

Double-clicking on a member in the lower pane of the Class View tab


will open the Object Browser window and display the method
prototype in the lower pane.
Double-click on the GetAddInInfo( ) method in the lower pane of the
Class View tab.
The Object Browser window will open allowing you to inspect the
IEdmAddIn5 interface and its members in detail.

125
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

Simple Since the definitions of the IEdmAddIn5 members are specified in the
Implementation type library and the type library has been referenced in the project, the
Visual Studio environment is aware of what members need to be
implemented and their definitions.
When we press the Enter key at the end of the Implements statement,
Visual Studio will help us out by providing the stub code needed to
implement all the members of the IEdmAddIn5 interface.

7 Implement the IEdmAddIn5 interface.


Click on the VbAddIn.vb tab and place the cursor at the end of the
Implements statement.
Press the Enter key and Visual Studio will generate the code needed to
implement the IEdmAddIn5 interface.
Imports EdmLib

Public Class VbAddIn


Implements IEdmAddIn5

Public Sub GetAddInInfo(ByRef poInfo As _


EdmAddInInfo, ByVal poVault As _
IEdmVault5, ByVal poCmdMgr As _
IEdmCmdMgr5) _
Implements IEdmAddIn5.GetAddInInfo

End Sub

Public Sub OnCmd(ByRef poCmd As EdmCmd, _


ByRef ppoData As System.Array) _
Implements IEdmAddIn5.OnCmd

End Sub
End Class

This is all the code that the compiler needs for the interface to be
considered fully implemented and the project will now compile.
Of course the code that was generated is simply a minimal framework
that we will add code to in order to create a functional add-in.

126
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

COM Registration In order for other applications to use the COM interface that we have
now implemented, some entries need to be made in the system registry.
Visual Studio will handle the COM registration details for us if we tell
it to.
8 Set the COM-Visible and the Register for COM interop properties.
From the Project menu, select EpdmVbAddin properties.

In the Application tab, press the Assembly Information button.

127
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

In the Assembly Information pop-


up dialog, check the Make assembly
COM-Visible check box.
Press OK in the Assembly
Information pop-up dialog.

In the Compile tab, check the


Register for COM interop check
box.

GetAddInInfo SOLIDWORKS PDM Professional will now be able to access our


IEdmAddIn5 implementation but in order to be able to load our
application as an add-in we will need to provide some information that
will be returned from our GetAddInInfo( ) method.
When SOLIDWORKS PDM Professional tries to load an add-in, it
calls the add-in’s IEdmAddIn5.GetAddInInfo( ) method, passing it
an EdmAddInInfo structure by reference. This means that any
changes that the add-in makes to that structure argument will be
available to SOLIDWORKS PDM Professional. This is how the add-in
provides information about itself to the SOLIDWORKS PDM
Professional software.
At a minimum, the add-in needs to provide a name for itself and the
oldest version number of SOLIDWORKS PDM Professional that it
requires in order to run properly.

9 Assign values to required EdmAddInInfo members.


Add the following code to the GetAddInInfo( )method.
Public Sub GetAddInInfo(ByRef poInfo As _
EdmAddInInfo, ByVal poVault As _
IEdmVault5, ByVal poCmdMgr As _
IEdmCmdMgr5) _
Implements IEdmAddIn5.GetAddInInfo

poInfo.mbsAddInName = "Minimal VB.NET Add-In"


'Minimum SOLIDWORKS PDM Professional version
'needed for VB.Net Add-Ins is 6.4
poInfo.mlRequiredVersionMajor = 6
poInfo.mlRequiredVersionMinor = 4
End Sub

128
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

Minimum Version At this point, we have all the code needed for an add-in to be
Required successfully loaded by the SOLIDWORKS PDM Professional
software.
Of course, the add-in doesn’t actually do anything useful yet but it is a
benchmark for a minimal add-in.
In the code above, we have specified that the add-in requires at least
version 6.4 of SOLIDWORKS PDM Professional in order to function
properly. If an older version of SOLIDWORKS PDM Professional
were to start loading our add-in, it would be rejected and stop loading
once the updated value of the poInfo argument was inspected.

Note We chose a minimum version of 6.4 here because that is the oldest
version of SOLIDWORKS PDM Professional that supports VB.NET
add-ins.
The minimum version required for each interface and its members is
documented throughout the SOLIDWORKS PDM Professional
Programmer’s Reference Guide. Attention should be paid to the
minimum required versions of the API members used within your code
and the value of poInfo adjusted accordingly.
Additional Add-In The EdmAddInInfo structure has additional members that are useful
Information for providing information to a SOLIDWORKS PDM Professional
administrator when the add-in is being installed. This information will
appear in the add-in’s Properties dialog box.

10 Provide additional information.


Add the following code to the GetAddInInfo( ) method.
Public Sub GetAddInInfo(ByRef poInfo As _
EdmAddInInfo, ByVal poVault As _
IEdmVault5, ByVal poCmdMgr As _
IEdmCmdMgr5) _
Implements IEdmAddIn5.GetAddInInfo

poInfo.mbsAddInName = "Minimal VB.NET Add-In"


poInfo.mbsCompany = "EPDM API Fundamentals Course"
poInfo.mbsDescription = "Example demonstrating " _
+ "the minimum requirements for an add-in."
poInfo.mlAddInVersion = 1

'Minimum SOLIDWORKS PDM Professional version


'needed for VB.Net Add-Ins is 6.4
poInfo.mlRequiredVersionMajor = 6
poInfo.mlRequiredVersionMinor = 4
End Sub

129
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

11 Build the application.


This information will now display in the add-in’s Properties dialog
box that appears when the add-in is installed in the next step.

Installing an In order to run, add-ins need to be installed by a SOLIDWORKS PDM


Add-In Professional administrator. The administrator can install an add-in into
a vault to be deployed to users or the add-in can be installed for
debugging. When installed for debugging, the add-in will run only on
the local client and will not be available to other users. Add-ins should
only be installed for debugging until development is complete and the
add-in is fully tested.
Since we are still developing our add-in, we will install it for
debugging.

12 Install for debugging.


Start the SOLIDWORKS PDM Professional Administration software.
In the tree view, expand the vault where you would like to install the
add-in.
Right-click on the Add-ins folder.

130
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

Select Debug Add-ins from the context menu.

In the Debug Add-ins dialog box, press the Add Add-in button.

131
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

In the Open dialog box, navigate to the folder where your add-in’s
debug version of the dll is located and select the dll.
Press the Open button.

In the Debug Add-ins dialog box press the OK button.


Your add-in is now installed for debugging and ready to load.

Debugging a DLL Debugging a DLL is most easily accomplished by launching the


application that will load it directly from the debugger. In the case of a
SOLIDWORKS PDM Professional add-in, the add-in is loaded by the
SOLIDWORKS PDM Professional software which in turn is loaded
from some other application.
SOLIDWORKS PDM Professional is typically loaded by and used
from within the Windows Explorer application. If we were to launch
Windows Explorer from the debugger and then activate
SOLIDWORKS PDM Professional by interactively manipulating files
in a vault from within Windows Explorer, our add-in would load and
we would be able to debug it. However, if we make any changes to the
add-in, the Windows Explorer application would not re-load the new
version of the add-in until the Windows Explorer application is
restarted or the machine is rebooted.

132
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

While in development, debugging a software program typically


requires making frequent changes to the code, rebuilding and
reloading. It would be inconvenient to have to re-start the Windows
Explorer application each time a change is made to the code so we’ll
use a simpler application to load our add-in from. Any application that
has a File, Open dialog will serve to launch the SOLIDWORKS PDM
Professional application, which in turn will load any installed add-ins.
A simple and ubiquitous application that will serve our purposes is
Windows Notepad.

13 Set to launch NotePad for debugging.


From the Project menu, select EpdmVbAddin properties.
In the Debug tab, select the Start external program radio button.

Browse to the location of the Notepad.exe file and select it. This is
typically in the C:\Windows\ folder.
In the Select File dialog, press the Open button.
Now when you start debugging, the Visual Studio debugger will launch
Notepad, which will load SOLIDWORKS PDM Professional, which in
turn will load your add-in and allow it to be debugged.

133
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

14 Set a break point.


Select the VbAddIn.vb tab to view the add-in source code.
To set a break point, click in the gray bar to the left of the line of
executable code to break at. A red dot will appear and the source code
will highlight in red.

Now we will know the moment that the add-in is loaded because it will
stop execution when it reaches the breakpoint.

134
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

15 Start debugging.
From the Debug menu, select Start Debugging.
When Notepad starts, from its File menu, select Open.
In Notepad’s Open dialog, browse to the SOLIDWORKS PDM
Professional vault folder and select a file.
When the add-in is loaded, SOLIDWORKS PDM Professional will call
the add-in’s GetAddInInfo( ) method and execution will stop at the
break point.

At this point we know that the add-in has attempted to load.


Press F10 to single step over each line of code or press F5 to continue.
At this point the add-in should have completed loading.
In Notepad’s Open dialog, press the Cancel button.
Exit the Notepad application.

135
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

The IEdmVault Now that we have a very basic add-in working and are able to debug it,
Argument we are ready to start adding some code to do more useful things.
The SOLIDWORKS PDM Professional application passes the add-in’s
GetAddInInfo( ) method two other arguments when it is loaded
besides the poInfo argument that we’ve used to pass information about
ourselves back to the SOLIDWORKS PDM Professional application.
Unlike stand-alone applications that require logging into a vault
through an IEdmVault interface in order to attach to a specific vault
and make use of most of the IEdmVault methods, add-ins get an
IEdmVault object passed to them already logged in and ready to use.
Since the SOLIDWORKS PDM Professional application is already
running and logged in when the add-in is loaded, the currently logged
in vault is passed in as the add-in’s GetAddInInfo( ) method’s second
argument.

16 Display vault status.


Add the following code at the end of the GetAddInInfo( ) method and
debug.
Public Sub GetAddInInfo(ByRef poInfo As _
EdmAddInInfo, ByVal poVault As _
IEdmVault5, ByVal poCmdMgr As _
IEdmCmdMgr5) _
Implements IEdmAddIn5.GetAddInInfo

poInfo.mbsAddInName = "Minimal VB.NET Add-In"


poInfo.mbsCompany = "EPDM API Fundamentals Course"
poInfo.mbsDescription = "Example demonstrating " _
+ "the minimum requirements for an add-in."
poInfo.mlAddInVersion = 1

'Minimum SOLIDWORKS PDM Professional version


'needed for VB.Net Add-Ins is 6.4
poInfo.mlRequiredVersionMajor = 6
poInfo.mlRequiredVersionMinor = 4

'Check to see if we're logged into a vault


If poVault.IsLoggedIn Then
MsgBox("We are logged in to the " + _
poVault.Name + " vault.")
Else
MsgBox("We are not logged in to a vault.")
End If
End Sub

136
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

The IEdmCmdMgr The third argument that the SOLIDWORKS PDM Professional
Argument application passes to an add-in when it is loaded is an IEdmCmdMgr
object. This object can be used to create menu items and register for
event notifications.
The AddCmd The IEdmCmdMgr.AddCmd( ) method allows you to add menu
Method items to the Windows Explorer Tools menu and the context menu that
is launched when you right click in the file listing or on a folder in the
folder tree while the user browses in a SOLIDWORKS PDM
Professional file vault. In Open and Save As dialog boxes, the menu
items will only appear in the context menu.
You can also add toolbar buttons to the Windows Explorer toolbar.

17 Add a menu item.


Add the following code at the end of the GetAddInInfo( ) method and
debug.
'Check to see if we're logged into a vault
If poVault.IsLoggedIn Then
MsgBox("We are logged in to the " + _
poVault.Name + " vault.")
Else
MsgBox("We are not logged in to a vault.")
End If

' Register a menu command


poCmdMgr.AddCmd(1, _
"Minimal VB.Net Add-In menu item")
End Sub

Right click in the file listing area.


Notice the new context menu item has been added.

137
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

The AddHook The IEdmCmdMgr.AddHook( ) method allows your add-in to


Method register to receive notifications of events that occur within the
SOLIDWORKS PDM Professional application. The available
notifications can be found in the EdmCmdType documentation in the
SOLIDWORKS PDM Professional Programmer’s Reference Guide.

18 Register to receive an event notification.


Add the following code at the end of the GetAddInInfo( ) method.
' Register a menu command
poCmdMgr.AddCmd(1, _
"Minimal VB.Net Add-In menu item")

'Register to receive a notification when


'a file is about to be checked out
poCmdMgr.AddHook(EdmCmdType.EdmCmd_PreLock)
End Sub

The IEdmAddIn5. At this point we have added a menu item and have registered to receive
OnCmd Method a notification whenever a file is about to be checked out. In order to
take some action whenever our menu item is pressed or a notification is
received, we’ll need to add some code to the other IEdmAddIn5
interface member that we’ve implemented in our add-in, OnCmd( ).
The EdmCmd The add-in’s OnCmd( ) implementation will be called by the
Argument SOLIDWORKS PDM Professional software whenever one of the add-
in’s menu items is pressed or an event that it has registered for has
occurred. Information about the reason OnCmd( ) was called will be
passed in through the first argument, which is of type EdmCmd
structure. The EdmCmd member meCmdType will hold an
enumeration value of type EdmCmdType which will tell us whether
OnCmd( ) was called due to the user selecting one of the add-in’s
menu items or tell us which specific event triggered a notification to be
sent. We can look on the EdmCmdType enumeration page in the
Constants section of the SOLIDWORKS PDM Professional
Programmer’s Reference Guide to see all the available values. These
are the same values that can be passed in to the
IEdmCmdMgr5.AddHook method to register for a particular event.

138
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

The EdmCmdData The second argument to the OnCmd method is an array of


Array EdmCmdData structures, one structure for each file or folder affected
by the command. The members of the EdmCmdData structure are
general and their meaning will vary depending on the current command
type being processed. In order to know the meaning of the
EdmCmdData structure members for any given command type, you
will need to check the EdmCmdData page in the SOLIDWORKS
PDM Professional Programmer’s Reference Guide and look in the
section that corresponds with the EdmCmdType of interest. Any
members that are not specifically documented for a particular
command type should not be used because their values are undefined.
For example, the EdmCmdData structure has the following members:

Type Member
Integer mlObjectID1
Integer mlObjectID2
Integer mlObjectID3
Integer mlObjectID4
String mbsStrData1
String mbsStrData2
String mbsStrData3
Integer mlLongData1
Integer mlLongData2
Integer mlLongData3
Object mpoExtra

For the command type EdmCmd_Menu, only the members below


have meaning.

Type Member Description


Integer mlObjectID1 ID of file (or zero if a folder is selected).
Integer mlObjectID2 ID of folder (or zero if a file is selected).
Integer mlObjectID3 ID of parent folder of the selected file or
folder.
String mbsStrData1 Name of file or folder. (Only the name,
not a full path.)

139
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

19 Add code to OnCmd.


Add the code below to the OnCmd method to take some action
depending on the reason it was called.
Public Sub OnCmd(ByRef poCmd As EdmCmd, _
ByRef ppoData As System.Array) _
Implements IEdmAddIn5.OnCmd

Dim AffectedFile As EdmCmdData


Dim AffectedFileNames As String = vbCrLf + vbCrLf
Select Case poCmd.meCmdType
'A menu item was selected
Case EdmCmdType.EdmCmd_Menu
Select Case poCmd.mlCmdID
'The command ID is 1
Case 1
For Each AffectedFile In ppoData
AffectedFileNames += _
AffectedFile.mbsStrData1 _
+ vbCrLf
Next AffectedFile
AffectedFileNames += vbCrLf
MsgBox("The Minimal VB.Net Add-In " + _
"menu item was pressed with " + _
AffectedFileNames + " selected.")

'The command ID is not recognized


Case Else
MsgBox("An unknown menu command " + _
"was issued.")
End Select

'A file is about to be checked out


Case EdmCmdType.EdmCmd_PreLock
For Each AffectedFile In ppoData
AffectedFileNames += _
AffectedFile.mbsStrData1 + vbCrLf
Next AffectedFile
AffectedFileNames += vbCrLf
Dim MsgBoxResult As MsgBoxResult
MsgBoxResult = MsgBox("The files below are " _
+ "about to be checked out" + _
AffectedFileNames + _
"would you like to continue?", _
MsgBoxStyle.OkCancel)

140
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

If MsgBoxResult = _
Microsoft.VisualBasic.MsgBoxResult.Ok Then
'Proceed with check out
poCmd.mbCancel = False
Else
'Cancel check out
poCmd.mbCancel = True
End If

'The event isn't one that we've registered


Case Else
poCmd.mpoVault.MsgBox(poCmd.mlParentWnd, _
"An unknown command type was issued.")
End Select
End Sub

20 Debug the add-in.


Debug the add-in and observe the behavior when selecting the custom
menu item or trying to check out files. Now code from the add-in will
be executed in those cases.

Case Study: If we register for EdmCmdType.EdmCmd_CardInput events, we


Changing Card can take some action whenever a data card variable value has changed.
Variable Values For example, we can watch for a change in the value of a particular
variable, look up any associated data from a source of our choosing and
display the associated data in another data card variable.
In this case study, we’ll use the Projects Dictionary that we created in
Lesson 4 to look up information about project names and project
numbers.

1 Create a new add-in.


Create a new add-in and name it CardVariables.
2 Add code to the GetAddInInfo method.
Set members of the poInfo argument to inform SOLIDWORKS PDM
Professional about our add-in.
Public Sub GetAddInInfo( _
ByRef poInfo As EdmAddInInfo, _
ByVal poVault As IEdmVault5, _
ByVal poCmdMgr As IEdmCmdMgr5) _
Implements IEdmAddIn5.GetAddInInfo

141
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

Try
poInfo.mbsAddInName = "VB.NET Card Variable Add-In"
poInfo.mbsCompany = "EPDM API Fundamentals Course"
poInfo.mbsDescription = "Example demonstrating " _
+ "updating a card variable based on another."
poInfo.mlAddInVersion = 1
'Minimum SOLIDWORKS PDM Professional version
'needed for VB.Net Add-Ins is 6.4
poInfo.mlRequiredVersionMajor = 6
poInfo.mlRequiredVersionMinor = 4

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

3 Register for data card variable changes.


Add code to let SOLIDWORKS PDM Professional know that our add-
in wants to be called whenever a data card variable’s value changes.
poInfo.mlRequiredVersionMajor = 6
poInfo.mlRequiredVersionMinor = 4

'Register to receive a notification when


'a data card variable value has changed
poCmdMgr.AddHook(EdmCmdType.EdmCmd_CardInput)
Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)

142
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

EdmCmdData Looking in the SOLIDWORKS PDM Professional Programmer’s


Members for Reference Guide on the EdmCmdData structure page, we can check
EdmCmd_ for the meaning of the EdmCmdData structure members when the
CardInput command type is EdmCmd_CardInput.
For the command type EdmCmd_CardInput, only the
EdmCmdData members below have meaning.

Type Member Description


Integer mlObjectID1 ID of the modified card control.
Integer mlObjectID2 ID of the file (zero for folder
cards).
Integer mlObjectID3 ID of the folder.
Integer mlObjectID4 ID of the card.
String mbsStrData1 Name of the active
configuration.
String mbsStrData2 Full path to the file.
Integer mlLongData1 ID of the updated variable.
IEdmStrLst5 mpoExtra Pointer to an IEdmStrLst5
interface with all configuration
names.

In addition, the EdmCmd.mpoExtra argument will hold an


IEdmEnumeratorVariable5 object which we can use to get and set
the data card variable values.
The EdmCmd.mbsComment argument will be set to the name of the
modified variable.

143
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

4 Add code to watch for variable changes.


Add code to the OnCmd method that will watch for changes to data
card variable values. If a change occurs to a variable named Project
Name in the default configuration, look up the corresponding Project
Number value from the Projects Dictionary and set the value of the
Project Number data card variable appropriately.
Conversely, if a change occurs to a variable named Project Number
in the default configuration, look up the corresponding Project Name
value from the Projects Dictionary and set the value of the Project
Name data card variable appropriately.

Public Sub OnCmd( _


ByRef poCmd As EdmCmd, _
ByRef ppoData As System.Array) _
Implements IEdmAddIn5.OnCmd
Try
'Take appropriate action based on
'the reason OnCmd was called
Select Case poCmd.meCmdType

'A data card variable value has changed


Case EdmCmdType.EdmCmd_CardInput
Static VariableChangeInProgress As Boolean = _
False
Dim vars As IEdmEnumeratorVariable5 = _
poCmd.mpoExtra
Dim ConfigNames As IEdmStrLst5 = _
DirectCast(ppoData(0), EdmCmdData).mpoExtra
Dim Config As String
If IsConfigInList(ConfigNames, "@") Then
Config = "@"
Else
Config = ""
End If

'Take appropriate action based on the name


'of the data card variable that has changed
Select Case poCmd.mbsComment

144
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

'The Project Name variable has changed


Case "Project Name"
'Are we here because we
'changed Project number?
If VariableChangeInProgress = True Then
VariableChangeInProgress = False
Exit Select
End If
Dim ProjectName As String = ""
vars.GetVar("Project Name", Config, _
ProjectName)

'Get the old Project Number


Dim ProjectNumber As String = ""
vars.GetVar("Project number", Config, _
ProjectNumber)

'Get the existing Projects dictionary


Dim ProjectDictionary As IEdmDictionary5
ProjectDictionary = poCmd.mpoVault. _
GetDictionary("Projects", False)

'Look up the new project number


Dim NewProjectNumber As String = ""
'Find all values containing the sub-string
'stored in ProjectName.
Dim key As String = ""
Dim value As String = ""
Dim pos As IEdmPos5
pos = ProjectDictionary.StringFindValues( _
ProjectName)
While Not pos.IsNull
ProjectDictionary.StringGetNextAssoc( _
pos, key, value)
'Traverse the values until the exact match
'is found
If value = ProjectName Then
NewProjectNumber = key
Exit While
End If
End While

'Only update the variable if it's changed


If Not NewProjectNumber = ProjectNumber _
Then
VariableChangeInProgress = True
vars.SetVar("Project number", Config, _
NewProjectNumber)
End If

145
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

'The Project number variable has changed


Case "Project number"
'Are we here because we
'changed Project Name?
If VariableChangeInProgress = True Then
VariableChangeInProgress = False
Exit Select
End If
Dim ProjectNumber As String = ""
vars.GetVar("Project number", Config, _
ProjectNumber)

'Get the old Project Name


Dim ProjectName As String = ""
vars.GetVar("Project Name", Config, _
ProjectName)

'Get the existing Projects dictionary


Dim ProjectDictionary As IEdmDictionary5
ProjectDictionary = poCmd.mpoVault. _
GetDictionary("Projects", False)

'Look up the project name


Dim NewProjectName As String = ""
ProjectDictionary.StringGetAt( _
ProjectNumber, NewProjectName)
'Only update the variable if it's changed
If Not NewProjectName = ProjectName Then
VariableChangeInProgress = True
vars.SetVar("Project Name", Config, _
NewProjectName)
End If
End Select
End Select
Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

146
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

5 Debug the add-in.


Debug the add-in and observe the behavior when changing the value of
the data card variables Project Name and Project number. Now
code from the add-in will be executed in those cases.
Be sure to try values of Project number in the range between 1000
and 1005.

Case Study: You can create custom serial numbers from an add-in if the built-in
Generating Serial serial number generators aren’t suitable for your needs. If we register
Numbers for EdmCmdType.EdmCmd_SerialNo events, our add-in will be
called upon to supply a serial number whenever one is needed by a
serial number variable that is setup to receive serial numbers from our
add-in.

1 Create a new add-in.


Create a new add-in and name it SerialNo.
2 Add code to the GetAddInInfo method.
Set members of the poInfo argument to inform SOLIDWORKS PDM
Professional about our add-in.
Public Sub GetAddInInfo( _
ByRef poInfo As EdmAddInInfo, _
ByVal poVault As IEdmVault5, _
ByVal poCmdMgr As IEdmCmdMgr5) _
Implements IEdmAddIn5.GetAddInInfo
Try
poInfo.mbsAddInName = _
"VB.NET Serial No. Add-In"
poInfo.mbsCompany = _
"EPDM API Fundamentals Course"
poInfo.mbsDescription = "Example demonstrating" _
+ " generating serial numbers with an add-in."
poInfo.mlAddInVersion = 1
'Minimum SOLIDWORKS PDM Professional version
'needed for VB.Net Add-Ins is 6.4
poInfo.mlRequiredVersionMajor = 6
poInfo.mlRequiredVersionMinor = 4
Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

147
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

3 Register for serial number generation events.


Add code to let SOLIDWORKS PDM Professional know that our add-
in wants to be called whenever it is needed to generate a serial number
and whenever a card button is pressed. We will use a file template card
to let the user enter the category for the file to generate a serial number
for. Each category will maintain its own serial number counter in the
Projects Dictionary. By watching for the EdmCmd_CardButton
event, we will know once the user has finished entering the file
template information.
poInfo.mlRequiredVersionMajor = 6
poInfo.mlRequiredVersionMinor = 4

'Register for serial number generation events


poCmdMgr.AddHook(EdmCmdType.EdmCmd_SerialNo)
poCmdMgr.AddHook(EdmCmdType.EdmCmd_CardButton)
Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)

EdmCmdData Looking in the SOLIDWORKS PDM Professional Programmer’s


Members for Reference Guide on the EdmCmdData structure page, we can check
EdmCmd_SerialNo for the meaning of the EdmCmdData structure members when the
command type is EdmCmd_SerialNo.
For the command type EdmCmd_SerialNo, only the EdmCmdData
members below have meaning.

Type Member Description


Integer mlObjectID1 ID of file to generate serial number for
(Zero if not generated for a file)
Integer mlObjectID2 ID of the file's parent folder
Integer mlObjectID3 ID of the file data card
Integer mlObjectID4 ID of the control in the file data card
String mbsStrData1 Return the generated serial number here. (C++ users must
allocate the string with the Win32 function SysAllocString)
String mbsStrData2 Path to file. This will be a folder path if the serial number is
created for the template manager as part of the folder name.
String mbsStrData3 Name of configuration
Integer mlLongData1 Serial number counter value

148
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

4 Add code to generate serial numbers.


Add code to the OnCmd method that will generate a serial number
whenever it is called upon.
Public Sub OnCmd( _
ByRef poCmd As EdmCmd, _
ByRef ppoData As System.Array) _
Implements IEdmAddIn5.OnCmd
Try
MsgBox("Attach to process, then click on OK.")

Debug.Print([Enum].GetName(GetType(EdmCmdType), _
poCmd.meCmdType))

Dim Vault5 As IEdmVault5 = poCmd.mpoVault


Select Case poCmd.meCmdType

'A serial number is needed


Case EdmCmdType.EdmCmd_SerialNo
Dim CurCmdData As EdmCmdData = ppoData(0)
Dim FileId As Integer = CurCmdData.mlObjectID1
Dim FolderId As Integer = _
CurCmdData.mlObjectID2
Dim DataCardId As Integer = _
CurCmdData.mlObjectID3
Dim CardControlId As Integer = _
CurCmdData.mlObjectID4
Dim SerialNo As String = _
CurCmdData.mbsStrData1
Dim FilePath As String = _
CurCmdData.mbsStrData2
Dim ConfigName As String = _
CurCmdData.mbsStrData3
Dim SerialNoCounterVal As Integer = _
CurCmdData.mlLongData1

If mClass = "" Then


Dim CardName As String = Vault5.GetObject( _
EdmObjectType.EdmObject_Card, _
DataCardId).Name
If CardName = "Text Card" Then
'We got here because the user selected
'"Generate next serial number
'(New Serial Number)"
'Since no template was filled out by the
'user to give us the value of mClass and
'because this file already has a serial
'number, we can derive the class
'from the current serial number

149
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

Dim File As IEdmFile5 = Vault5.GetObject( _


EdmObjectType.EdmObject_File, FileId)
Dim EnumVar As IEdmEnumeratorVariable5 = _
File.GetEnumeratorVariable()
Dim CurSerialNo As String = ""
Dim GetVarSuccess As Boolean = _
EnumVar.GetVar("Document Number", _
ConfigName, CurSerialNo)
mClass = GetClassFromSerialNo(Vault5, _
"Counters", CurSerialNo)
GenerateSerialNo(poCmd, ppoData)
If Not mCounterVal = "" Then
mCounterVal = SetDictionaryValue(Vault5, _
"Counters", mClass, mCounterVal + 1)
End If
mClass = ""
mCounterVal = ""

End If
Else
GenerateSerialNo(poCmd, ppoData)
End If
Case EdmCmdType.EdmCmd_CardButton
Dim CurCmdData As EdmCmdData = ppoData(0)
Dim FileId As Integer = CurCmdData.mlObjectID1
Dim FolderId As Integer = CurCmdData.mlObjectID2
Dim DataCardId As Integer = _
CurCmdData.mlObjectID3
Dim ActiveConfigName As String = _
CurCmdData.mbsStrData1
Dim FilePath As String = CurCmdData.mbsStrData2
Dim ConfigNames As IEdmStrLst5 = _
CurCmdData.mpoExtra

Dim EnumVar As IEdmEnumeratorVariable5 = _


poCmd.mpoExtra
Dim DataCard As IEdmCard5 = poCmd.mpoExtra
Dim ButtonCommandString As String = _
poCmd.mbsComment
If DataCard.Name = "TextFileCard" And _
ButtonCommandString = "OK" Then
'The user has dismissed the text file template
'card by pressing the OK button and accepting
'the value of the Class variable, so we'll get
'its value and store it in the mClass member
'variable where it will be used in the
'EdmCmd_SerialNo event handler
Dim GetVarSuccess As Boolean = EnumVar. _
GetVar("Class", ActiveConfigName, mClass)

150
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

ElseIf DataCard.Name = "Text Card" And _


ButtonCommandString = "OK" Then
'The user has dismissed the text file data card
'by pressing either the Open File button or the
'Create File button and has committed to
'creating the new text file so it's time to
'increment the serial number in the dictionary
If Not mCounterVal = "" Then
mCounterVal = SetDictionaryValue(Vault5, _
"Counters", mClass, mCounterVal + 1)
End If
mClass = ""
mCounterVal = ""
End If
End Select
Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Sub GenerateSerialNo(ByRef poCmd As EdmCmd, _
ByRef ppoData As System.Array)
Try
Dim FileCount As Integer
FileCount = ppoData.Length

If FileCount > 0 Then

'Create an early bound array variable


'to access to the EdmCmdData from
Dim tmpArr() As EdmCmdData
tmpArr = ppoData

'Generate serial numbers for all of the


'affected files.
Dim i As Integer
For i = LBound(tmpArr) To UBound(tmpArr)

mCounterVal = GetDictionaryValue _
(poCmd.mpoVault, "Counters", mClass)
If mCounterVal = "" Then Exit For

'Ignore the "built-in" serial number counter


'value, CounterVal = tmpArr(i).mlLongData1

151
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

Dim s As String
Dim CounterVal As String = _
String.Format("{0:00000}", _
Integer.Parse(mCounterVal))
s = Left(mClass, 2).ToUpper() + "-" + CounterVal
'Set the serial number
tmpArr(i).mbsStrData1 = s
Next i
End If
Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Private Function GetDictionaryValue( _


ByVal Vault As IEdmVault5, _
ByVal DictionaryName As String, _
ByVal KeyName As String) As String
GetDictionaryValue = ""
Try
'Get the dictionary -
'if it doesn't exist, don't create it
Dim Dictionary As IEdmDictionary5
Dictionary = Vault.GetDictionary( _
DictionaryName, False)
If Not Dictionary Is Nothing Then
'Look up the value
Dictionary.StringGetAt(KeyName.Trim(), _
GetDictionaryValue)
End If
Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function

152
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

Private Function SetDictionaryValue( _


ByVal Vault As IEdmVault5, _
ByVal DictionaryName As String, _
ByVal KeyName As String, _
ByVal Value As String) As String
SetDictionaryValue = ""
Try
'Get the dictionary -
'if it doesn't exist, don't create it
Dim Dictionary As IEdmDictionary5
Dictionary = Vault.GetDictionary( _
DictionaryName, False)
If Not Dictionary Is Nothing Then
'Set the value
Dictionary.StringSetAt(KeyName.Trim(), Value)
End If
'This will only be set if there were no exceptions
'thrown in the code above
SetDictionaryValue = Value
Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function

153
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

'This function assumes that the first two letters of the


'serial number will uniquely identify the class to which
'it belongs
Private Function GetClassFromSerialNo( _
ByVal Vault As IEdmVault5, _
ByVal DictionaryName As String, _
ByVal SerialNo As String) As String
GetClassFromSerialNo = ""
Try
'Get the dictionary -
'if it doesn't exist, don't create it
Dim Dictionary As IEdmDictionary5
Dictionary = Vault.GetDictionary( _
DictionaryName, False)
If Not Dictionary Is Nothing Then
'Look up the value
Dim Pos As IEdmPos5 = _
Dictionary.StringGetFirstPosition()
While Not Pos.IsNull
Dim Key As String = ""
Dim Val As String = ""
Dictionary.StringGetNextAssoc(Pos, Key, Val)
If Left(Key, 2).ToUpper() = _
Left(SerialNo, 2) Then
GetClassFromSerialNo = Key
Exit While
End If
End While
End If
Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function

154
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

5 Add a menu item (optional).


Add a menu item that will allow us to explicitly call the serial number
generation code while debugging.
It will be easier to debug the serial number generation code if we
enable it to be called explicitly.
In the GetAddInInfo method, add the following code.
poInfo.mlRequiredVersionMajor = 6
poInfo.mlRequiredVersionMinor = 4

'Register a menu command


poCmdMgr.AddCmd(1, "Generate serial numbers")
'Register for serial number generation events
poCmdMgr.AddHook(EdmCmdType.EdmCmd_SerialNo)
In the OnCmd method, add the following code.
Try
Debug.Print([Enum].GetName(GetType(EdmCmdType), _
poCmd.meCmdType))

Dim Vault5 As IEdmVault5 = poCmd.mpoVault


Select Case poCmd.meCmdType

'A menu item was selected


Case EdmCmdType.EdmCmd_Menu
Select Case poCmd.mlCmdID
'The command ID is 1
Case 1
mClass = "Mechanical"
GenerateSerialNo(poCmd, ppoData)
End Select

'A serial number is needed


Case EdmCmdType.EdmCmd_SerialNo
Dim CurCmdData As EdmCmdData = ppoData(0)

155
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

6 Debug the add-in (optional).


Place a break point in the OnCmd method and debug the serial number
generation code.

Select one or more files in the File, Open dialog and select the
Generate serial numbers context menu item.
Step through the code in the GenerateSerialNo method to verify it is
behaving as expected.
Keep in mind that the built-in serial number counter value obtained
from the EdmCmdData.mlLongData1 member will always be zero
when OnCmd is called in response to a menu selection and that we will
not be using it at all in this case study. We will be using our own
custom counters based on the category that the file belongs to.
Also note that when the OnCmd method is called in response to a menu
selection, returning a serial number in the
EdmCmdData.mbsStrData1 member will not actually set the serial
number since the mbsStrData1 member has a different meaning for
EdmCmd_Menu than it does for EdmCmd_SerialNo.
As you can see, debugging a serial number add-in using a menu item
has only limited usefulness.
7 Un-register the add-in for debugging.
Un-register the add-in by right-clicking on Add-ins in the
SOLIDWORKS PDM Professional Administration application. Select
Debug Add-ins from the context menu and select the Serial No. Add-
In from the installed add-ins list. Click the Remove Add-in button and
then the OK button.

156
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

8 Register the add-in.


The add-in needs to be fully registered in order for SOLIDWORKS
PDM Professional to recognize it as a valid serial number generator
when setting up serial numbers in the Administration dialog.
Register the SerialNo add-in in a file vault the normal way; not for
debugging. Right click on Add-ins in the Administration application
and select New Add-in. Navigate to the SerialNo.dll file and control-
select it and the Interop.EdmLib.dll file and click Open. Click OK in
the Properties dialog. A warning dialog will appear informing you that
all client machines will have to be restarted if this is an updated version
of an add-in that was previously installed. Click OK.

9 Create a serial number.


Right click on the Serial Numbers node in the SOLIDWORKS PDM
Professional Administration application and select New Serial
Number. Create a new serial number named TestSerialNo and select
Serial number from add-in as the type.
Select the new add-in, SerialNo, from the Name of add-in list and
click OK.
10 Create a new variable.
In the SOLIDWORKS PDM Professional Administration application,
right click on the Variables node, and select New Variable. Create a
new variable of type Text and name it Class. Click OK.

157
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

11 Connect the serial number to a data


card variable.
To connect the serial number to a
control in a data card, open the default
Text Card file data card and select the
Document Number edit box.
In the Edit-box properties pane, select
Serial number for the Default value
and select the new serial number that
we created, TestSerialNo.

Add a static text box and enter the text


Class.
Add an edit box and attach its value to
the new variable named Class.

Save the card and close the Card Editor.

Create a new Template Card and name it TextFileCard. Choose


Template Card for the card type.
Add a static text control to the card and enter Class into the text box.
Add a ComboBox drop-down list control and enter the text Electrical,
Hydraulic, Mechanical and Manufacturing into the text box.

158
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

Connect it to the Class variable.

Save the card and exit the Card Editor.

159
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

Create a new Template and for the Menu string enter File\Text.
Click Template Cards and then click Template Variables. Create a
new Template Variable named tClass. Set its type to Format string
and click OK.
Click Add Card and add TextFileCard to the template and set the Card
Variable to Class and the Template Variable to tClass.

12 Set Files and Folders dialog settings.


Click Files and Folders.
Select Current Folder.
Click New.
From the Select Template File dialog, navigate to and select a text file
from within the vault that will be used as a template and click Open.

160
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

13 Set New File dialog settings.


In the New File dialog, check the Show file data card when file is
created Check Box and clear the other Check Boxes.
In the Copy these variables to the file data card list, map the tClass
template variable to the Class card variable and click OK.

Give the appropriate users and groups permission to use the template.
Click OK to accept and close the Template Editor.
Launch a file open dialog and create a new text document by clicking
New in the context menu in a File, Open dialog and selecting File,
Text.
Choose one of the categories from the
Class dropdown list box in the File\Text
dialog and click OK.

The MsgBox that is launched from the


SerialNo add-in will appear.

161
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

At this point the add-in is loaded in memory and is paused while


waiting for a response to the MsgBox. This will give you an
opportunity to attach the add-in’s running process to the debugger in
order to be able to step through the code for debugging.
In Visual Studio, with the SerialNo project open, put a break point in
the OnCmd method.

Click on the Debug menu item and select Attach to Process.


In the Attach to Process dialog, select the process whose title contains
SerialNo and click Attach.

Note If the process is grayed out, it may already be attached, in which case
simply click Cancel and proceed to the next step.

162
SOLIDWORKS PDM Professional Lesson 5
Add-In Applications

In the SerialNo MsgBox, click OK.


Execution will stop at the break point
and you will now be able to step
through the SerialNo source code and
debug. Press the F10 key to step over
each line of code until the last line in
the OnCmd method is reached. Notice
that the Class data card variable value
is retrieved and stored. Press F5 to continue normal execution.
Since the add-in’s process is now already attached to the debugger,
whenever the SerialNo MsgBox appears simply click OK.
Execution will again stop at the break point. Step through the code
again and notice that this time OnCmd was called with the
EdmCmd_SerialNo command type. The previously stored Class
value will be used to retrieve the next counter value from the
corresponding Dictionary key. The counter value will be used to create
a serial number which will be passed back to the SOLIDWORKS PDM
Professional software through the EdmCmdData.mbsStrData1
member and assigned to the appropriate data card variable for the new
file, in this case the Document Number variable.

163
Lesson 5 SOLIDWORKS PDM Professional
Add-In Applications

The Modify Name and File Data Card appears. Observe the value of
the Class edit box. It should contain the value that was entered in the
File\Text template data card. The Document Number edit box should
contain a value that was generated by the add-in.

Click Create File.


OnCmd is again called, this time with the EdmCmd_CardButton
command type. The code will check to see whether this call was in
response to the user committing to creating the file and if so, will
increment the appropriate counter value in the Dictionary.
Close the File, Open dialog that was used to launch the SerialNo add-
in.
Visual Studio will stop debugging as the add-in is unloaded.
Note Once the SerialNo application development stage is complete and
there is no more need for debugging, the MsgBox code may be
commented out or deleted.

164
SOLIDWORKS PDM Professional Exercise 6
State Change

Exercise 6: Create an add-in application that will:


State Change  Receive a notification when a file has changed state.
 Display a message indicating the name of any file that changes its
state to Approved.
 Handle any COM exceptions.
 Handle any other exceptions.

165
Exercise 6 SOLIDWORKS PDM Professional
State Change

Imports System.Windows.Forms
Imports EdmLib

Public Class Exercise6


Implements IEdmAddIn5

Public Sub GetAddInInfo( _


ByRef poInfo As EdmAddInInfo, _
ByVal poVault As IEdmVault5, _
ByVal poCmdMgr As IEdmCmdMgr5) _
Implements IEdmAddIn5.GetAddInInfo

Try
poInfo.mbsAddInName = "Exercise 6 VB.NET Add-In"
poInfo.mbsCompany = "EPDM API Fundamentals Course"
poInfo.mbsDescription = "Exercise demonstrating " _
+ "responding to a change state event."
poInfo.mlAddInVersion = 1

'Minimum SOLIDWORKS PDM Professional version


'needed for VB.Net Add-Ins is 6.4
poInfo.mlRequiredVersionMajor = 6
poInfo.mlRequiredVersionMinor = 4

'Register to receive a notification when


'a file has changed state
poCmdMgr.AddHook(EdmCmdType.EdmCmd_PostState)
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

166
SOLIDWORKS PDM Professional Exercise 6
State Change

Public Sub OnCmd( _


ByRef poCmd As EdmCmd, _
ByRef ppoData As System.Array) _
Implements IEdmAddIn5.OnCmd

Try
Dim AffectedFile As EdmCmdData
Dim AffectedFileNames As String = ""
Select Case poCmd.meCmdType
'A file has changed state
Case EdmCmdType.EdmCmd_PostState
For Each AffectedFile In ppoData
If AffectedFile.mbsStrData2 = "Approved" Then
AffectedFileNames += _
AffectedFile.mbsStrData1 + vbCrLf
End If
Next AffectedFile

If AffectedFileNames.Length > 0 Then


poCmd.mpoVault.MsgBox(poCmd.mlParentWnd, _
AffectedFileNames + " has been approved.")
End If

'The event isn't one that we've registered


Case Else
poCmd.mpoVault.MsgBox(poCmd.mlParentWnd, _
"An unknown command type was issued.")
End Select
Catch ex As Runtime.InteropServices.COMException
MessageBox.Show("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class

167
Exercise 6 SOLIDWORKS PDM Professional
State Change

168
Lesson 6
Task Add-In Applications

Upon successful completion of this lesson, you will be able to:


 Understand the differences between regular add-in and task add-in
applications.
 Create and install a task add-in application.
 Understand task definitions vs. task instances.
 Create a menu item for launching a task.
 Create a custom task setup page for getting custom information
from the interactive user and displaying task details.
 Understand the IEdmSearch interface.
 Understand the workflow related interfaces.
 Send notifications with file information to users upon completion.
 Use the Task List for launching and monitoring task instances.
 Debug task add-in applications.

169
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

SOLIDWORKS Generally, SOLIDWORKS PDM Professional add-in applications


PDM execute on the client computer that had launched them. For example, if
Professional an add-in was called due to a state change, it would execute on the
Task Add-Ins machine where the change state command was run. Similarly, if an add-
in was called due to a menu command being run, the add-in would
execute on the computer where the menu command was selected.
In order to execute an add-in command on a different computer from
which it was launched from, the add-in needs to be written as a task
add-in. Task add-ins can be configured to run at scheduled times, send
status updates while executing and send a message upon completion.
Task add-ins are essentially regular add-ins with additional hooks and
properties that allow them to be configured to run in a more controlled
way. Once a task add-in has been installed on a vault as an add-in, the
administrator can use the New Task wizard to add it to the vault as a
task and configure it to run according to the properties chosen in the
New Task wizard.
These properties include information about:
 which add-in to execute.
 which card (if any) to show when the task is launched.
 which user credentials should be used to execute the add-in.
 which computer(s) to execute the add-in on.
 optional scheduling of the add-in.
 who should have permission to run the add-in.
 error and success notifications.
 add-in defined data.
Registering for the EdmCmdType.EdmCmd_TaskRun notification
type within the add-in’s GetAddInInfo method will cause the add-in to
be recognized as a task add-in.
Once installed via the New Add-in wizard in
the SOLIDWORKS PDM Professional
Administration tool, the task add-in will be
recognized by the Task Host Configuration
tool and included in its list of available tasks.
The Task Host Configuration menu item is
available by right clicking the SOLIDWORKS
PDM Professional icon in the Windows
Task Bar at the bottom of the screen.
In order to make the SOLIDWORKS PDM Professional icon available
in the Windows Task Bar, the newly installed add-in will need to be
loaded into memory. You can do this by opening a SOLIDWORKS
PDM Professional file vault from either Windows Explorer or some
other browser.

170
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

While you are in the debugging stage of development, a small


application with a File, Open browser is preferable to using Windows
Explorer.
The Task Host Configuration dialog is used to select which task add-
ins will be permitted to execute on the local computer.

Since registering for the EdmCmdType.EdmCmd_TaskRun


notification type within the add-in’s GetAddInInfo method causes the
add-in to be recognized as a task add-in, it will be available as a choice
in the New Task wizard.

171
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

The New Task wizard will provide the default pages listed below to
allow setting the task’s properties.
 Add-in
 Execution Method
 Permissions
 Success Notification
 Error Notification
Task Interfaces There are two interfaces that are dedicated to tasks in the
SOLIDWORKS PDM Professional API, the IEdmTaskProperties
interface and the IEdmTaskInstance interface. These interfaces are
associated with the definition of a task and the running instance of a
task that was created based on the task definition.
The The IEdmTaskProperties interface represents the definition of a task
IEdmTaskProperties and is closely related to the properties that the interactive user has set
Interface for the task in the Task Properties dialog. It also allows the task add-in
to customize the Task Properties dialog and task related menus.
For example, the IEdmTaskProperties.TaskFlags member allows
the task add-in to specify additional pages to be displayed in the Task
Properties dialog or to specify menu commands that the task will
support. The SetMenuCmds method allow the add-in to provide
details about how the menu commands should look and behave.
If any custom data is added to the task definition by the add-in, the data
values can be stored with the task definition using the SetVar method
for card variable values and SetValEx for values that are not related to
any card variable. These values can then be retrieved by the running
instance of the task once it has been launched.

172
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

When the task add-in’s OnCmd method is called with a command type
of EdmCmd_TaskSetup or EdmCmd_TaskSetupButton, the
OnCmd method’s poCmd argument has its EdmCmd.mpoExtra
member set to the task’s IEdmTaskProperties object, so the add-in
can retrieve it if needed.
Dim props As IEdmTaskProperties
props = poCmd.mpoExtra

The The IEdmTaskInstance interface represents the running instance of a


IEdmTaskInstance task. It has members that can be used to show a progress bar in the Task
Interface List and to inform the SOLIDWORKS PDM Professional software of
the task’s status as it progresses from start to finish.
If there is custom data available in the task definition, their values can
be retrieved with the GetVar and GetValEx methods.
When the task add-in’s OnCmd method is called with a command type
of EdmCmd_TaskDetails, EdmCmd_TaskRun,
EdmCmd_TaskLaunch or EdmCmd_TaskLaunchButton, the
OnCmd method’s poCmd argument has its EdmCmd.mpoExtra
member set to the task’s IEdmTaskInstance object, so the add-in can
retrieve it if needed.
Dim TaskInstance As IEdmTaskInstance
TaskInstance = poCmd.mpoExtra
Case Study: In this case study, we’ll examine a minimal task add-in in order to
Simple Task Add- become familiar with the various stages in the process of creating and
In using a task add-in.
We won’t actually have the task perform any useful work. We’ll set it
up to be able to launch it from a menu item and to be able to schedule it
from the SOLIDWORKS PDM Professional Administration
application.
Once the task is launched, we’ll simply set up a progress bar to display
in the Task List, update it several times, set the task’s status to
EdmTaskStat_DoneOK to let the SOLIDWORKS PDM Professional
task framework know that the task has finished successfully and exit.
We’ll add more functionality in the next case study.

173
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

1 Create a simple task add-in.


Create a new add-in project and add the following code to the
GetAddInInfo method.
'GetAddInInfo is called when New Task is selected
'from the RMB menu in the Administration tool
Public Sub GetAddInInfo(ByRef poInfo As _
EdmAddInInfo, ByVal poVault As _
IEdmVault5, ByVal poCmdMgr As _
IEdmCmdMgr5) _
Implements IEdmAddIn5.GetAddInInfo

poInfo.mbsAddInName = "Minimal VB.NET Task Add-In"


poInfo.mbsCompany = "EPDM API Fundamentals Course"
poInfo.mbsDescription = "Example demonstrating " _
+ "the minimum requirements for a task add-in."
poInfo.mlAddInVersion = 1

'Minimum SOLIDWORKS PDM Professional version


'needed for VB.Net Task Add-Ins is 10.0
poInfo.mlRequiredVersionMajor = 10
poInfo.mlRequiredVersionMinor = 0

'Register this add-in as a task add-in


poCmdMgr.AddHook(EdmCmdType.EdmCmd_TaskRun)
End Sub

Task Hooks Since we have registered to receive the EdmCmd_TaskRun type


notifications, the SOLIDWORKS PDM Professional software would
now allow us to install the add-in and to install it as a new task, but at
this point it wouldn’t actually do anything yet.
There are several task related hooks that are used to receive
notifications when a task related event takes place. Together, they help
form the complete task.

174
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

These hooks have the following enumeration values associated with


them:
 EdmCmd_TaskSetup
 EdmCmd_TaskSetupButton
 EdmCmd_TaskLaunch
 EdmCmd_TaskLaunchButton
 EdmCmd_TaskRun
 EdmCmd_TaskDetails
The first two of the task related hooks are called in response to events
related to the installation and configuration of the task. These hooks are
executed the normal way, on the client machine that calls them as a
regular add-in would.
The next two hooks are also called on the client machine when the task
is launched.
The hook that is executed on the configured machine and is the reason
for creating the task is the EdmCmd_TaskRun hook. In order to
perform some task, the EdmCmd_TaskRun hook needs to provide
code for the task to execute. This is where you would place whatever
code the add-in is intended for as well as some housekeeping to keep
the SOLIDWORKS PDM Professional framework informed of the
task’s execution status. In the example below, we will simply update
the task’s status so that we’ll be able to see that it is executing.
The EdmCmd_TaskDetails hook is called when the user click the
Details button in the Task List.

2 Check for EdmCmdType.EdmCmd_TaskRun.


Add code to check whether EdmCmdType.EdmCmd_TaskRun was
sent.
Public Sub OnCmd(ByRef poCmd As EdmCmd, _
ByRef ppoData As System.Array) _
Implements IEdmAddIn5.OnCmd
Try
Select Case poCmd.meCmdType
Case EdmCmdType.EdmCmd_TaskRun
OnTaskRun(poCmd, ppoData)
End Select
Catch
End Try
End Sub

175
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

3 Add the handler method.


Add code to update the Task List status when
EdmCmdType.EdmCmd_TaskRun is sent.
Private Sub OnTaskRun(ByRef poCmd As EdmCmd, _
ByRef ppoData As System.Array)
'Get the task instance interface
Dim inst As IEdmTaskInstance
inst = poCmd.mpoExtra
Try
'Keep the Task List status up to date
inst.SetStatus _
(EdmTaskStatus.EdmTaskStat_Running)

'Format a message that will be displayed


'in the task list
inst.SetProgressRange(10, 1, "Test is running.")
System.Threading.Thread.Sleep(5000)
inst.SetProgressPos(5, "Test is running.")
System.Threading.Thread.Sleep(5000)
inst.SetProgressPos(10, "Test is done.")
System.Threading.Thread.Sleep(5000)

inst.SetStatus(EdmTaskStatus.EdmTaskStat_DoneOK)
Catch ex As Runtime.InteropServices.COMException
inst.SetStatus _
(EdmTaskStatus.EdmTaskStat_DoneFailed, _
ex.ErrorCode, "The test task failed!")
End Try
End Sub

The task is now capable of running and displaying its status in the Task
List.
If we want to provide for any further setup or launch capabilities for a
task, we need to specify these in response to an EdmCmd_TaskSetup
event. This hook is called whenever the add-in is selected from the
Add-in list in the New Task - Properties dialog of the
SOLIDWORKS PDM Professional Administration tool and whenever
the task’s definition is later opened for editing.

176
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

4 Register to receive EdmCmdType.EdmCmd_TaskSetup


events.
Add code to the GetAddInInfo method to register to receive
EdmCmdType.EdmCmd_TaskSetup events.
'Register this add-in as a task add-in
poCmdMgr.AddHook(EdmCmdType.EdmCmd_TaskRun)
'Register this add-in to be called when
'selected as a task in the administration tool
poCmdMgr.AddHook(EdmCmdType.EdmCmd_TaskSetup)
End Sub

5 Check for EdmCmdType.EdmCmd_TaskSetup.


Add code to the OnCmd method to check whether
EdmCmdType.EdmCmd_TaskSetup was sent.
Select Case poCmd.meCmdType
Case EdmCmdType.EdmCmd_TaskRun
OnTaskRun(poCmd, ppoData)
Case EdmCmdType.EdmCmd_TaskSetup
OnTaskSetup(poCmd, ppoData)
End Select

6 Set up a menu item.


Add code to set up a menu item in Windows Explorer that will allow
the user to launch the task.
Private Sub OnTaskSetup(ByRef poCmd As EdmCmd, _
ByRef ppoData As System.Array)

'Get the property interface used to


'access the framework
Dim props As IEdmTaskProperties
props = poCmd.mpoExtra

'Set the property flag that says we want a


'menu item for the user to launch the task
props.TaskFlags = _
EdmTaskFlag.EdmTask_SupportsInitExec

177
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

'Set up the menu commands to launch this task


Dim cmds(0) As EdmTaskMenuCmd
cmds(0).mbsMenuString = "Run the test task"
cmds(0).mbsStatusBarHelp = _
"This command runs the task add-in"
cmds(0).mlCmdID = 1
cmds(0).mlEdmMenuFlags = _
EdmMenuFlags.EdmMenu_Nothing
props.SetMenuCmds(cmds)
End Sub

7 Set up to allow scheduling.


Add a task flag to include a scheduling page in the task properties
dialog.
'Set the property flag that says we want a
'menu item for the user to launch the task
'and a flag to support scheduling
props.TaskFlags = _
EdmTaskFlag.EdmTask_SupportsInitExec + _
EdmTaskFlag.EdmTask_SupportsScheduling

8 Build the application.

9 Install the task add-in.


From the SOLIDWORKS
PDM Professional
Administration application,
install the add-in as a new
add-in by right clicking on the
Add-ins node and selecting
New Add-in.
Navigate to the folder
containing SimpleTask.dll.
Select both SimpleTask.dll
and Interop.EdmLib.dll.
Click Open.

Click OK in the Properties dialog.


Click OK in the warning dialog that informs you of the need to restart
all client machines.

178
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

10 Configure Task Host.


Log into the vault from the File, Open dialog of an application such as
Notepad.

Note You may close the File, Open dialog and the application once the
SOLIDWORKS PDM Professional icon appears in the Windows
Task Bar at the bottom of the screen.
In the Windows Task Bar at the bottom of the screen, click on the
SOLIDWORKS PDM Professional icon . From the menu, select
Task Host Configuration.
In the Task Host Configuration dialog, check the checkbox that
appears next to the name of the task in order to configure the local host
to permit execution of the task. Click OK.

11 Install the task.


In the SOLIDWORKS PDM Professional Administration application,
right click on the Tasks node and select New Task. The New Task -
Properties dialog will appear.
Enter the name Simple Task for the new task.

Notice that only the Add-in page is currently available in the


navigation pane on the left side of the task properties dialog.

179
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

From the Add-in list, select Minimal VB.NET Task Add-In. This is the
name we had supplied to the mbsAddInName member of the poInfo
object in the GetAddInInfo method.
poInfo.mbsAddInName = "Minimal VB.NET Task Add-In"
Once the add-in is selected, it is loaded into memory and the task
properties dialog is customized according to the flags that were set in
the poCmd.mpoExtra.TaskFlags member in the add-in’s
EdmCmd_TaskSetup command notification handler method.
props.TaskFlags = _
EdmTaskFlag.EdmTask_SupportsInitExec + _
EdmTaskFlag.EdmTask_SupportsScheduling
In this case we had specified that we want a
menu item, which will not affect the layout of
the task properties dialog, and that we want to be
able to schedule the task, which will add a
Scheduling page link to the navigation pane.
The Execution Method, Permissions,
Success Notification and Error Notification
page links are standard links that are normally
added to the navigation pane.
Click Next to go to the Execution Method property page.
In the Computers supporting the task window, check the checkbox
beside the name of the local computer.

Note You can navigate directly to any property page in the New Task dialog
by clicking the links in the navigation pane.
Click Next to go to the Scheduling property page.
Keep the default This task is not scheduled button selected.
Click Next to go to the Permissions property page.
Check the checkbox next to the name of the user you are logged in as in
order to give permission to start the task.
Click Next to go to the Success Notification property page.
Check the Notify the user who launched the task checkbox to be
notified when the task successfully completes.
In the Subject edit box, enter the text Success subject.

180
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

In the Text edit box, enter the text The simple task successfully
completed at . With the cursor just before the period, click and
select Current Time to insert the Current Time dynamic text
variable.

Optionally, you could click Next to go to the Error Notification page


and configure the task to send a notification when the task fails.
Click OK.
12 Open the Task List.
Double click the Task List tree item under the Tasks node in the
SOLIDWORKS PDM Professional Administration application to open
the Task List dialog.
13 Launch the task from the menu.
From the Notepad File, Open dialog,
navigate to the file vault, click the
right mouse button while hovering
over a file name and select Run the
test task from the context menu.

The name of the menu item for this command was specified in the
OnTaskSetup method.
cmds(0).mbsMenuString = "Run the test task"

181
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

Observe the task’s status in the Task List as it executes and finishes.

You should soon receive a success notification.

14 Schedule the task.


Double click the Simple Task tree list item under the Tasks node in
the SOLIDWORKS PDM Professional Administration application to
open the Task Properties dialog.
On the Scheduling page of the Task Properties dialog, click This
task should be executed once on and set the current date and time.
Click OK.
When the scheduled time arrives, observe the task’s status in the Task
List as it executes and finishes.

182
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

The previous case study doesn’t perform any useful work, but it does
illustrate the various components of a simple task add-in and how they
work together to form a complete task.
In the next case study we will build on this knowledge to create a more
involved task add-in that will demonstrate how we can do something
more useful.
Case Study: In this case study, we’ll let the user schedule a task that will check the
Check Number of number of days that files have been in a selected workflow state. For
Days in State any files that have been in that state beyond the selected number of
days, a message will be sent to selected individuals or groups.
A custom setup page will be the user interface
that will allow the selection of the workflow
and states that the task will monitor and the
number of days in the specified states that will
trigger a message to be sent.
This custom setup page is implemented in the
SetupPage class in the StateAgeTask
project.

Note Since a task add-in needs to be fully installed in the vault in order to be
able to install it as a task, we won’t be able to debug it using the Debug
Add-ins type of installation that we had used previously. We’ll have to
attach the add-in’s running process to the debugger. Since add-ins are
loaded into memory and unloaded at unpredictable times, we’ll add
some code to the add-in that will display a message box in order to
force the add-in to pause, giving us the opportunity to attach the
debugger to the add-in’s process. We’ll force the add-in to pause at the
top of the two methods that the SOLIDWORKS PDM Professional
framework will call in our code, GetAddInInfo and OnCmd.
Once we’ve finished the debugging phase of the project, and before it is
ready to release for general use, we’ll need to comment out or delete
the code that displays the message box.

183
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

1 Open the StateAgeTask project.

2 Add code to the GetAddInInfo method.


Add code to the GetAddInInfo method that will provide information
about the add-in and add hooks to register to receive task related
events.
Public Sub GetAddInInfo( _
ByRef poInfo As EdmAddInInfo, _
ByVal poVault As IEdmVault5, _
ByVal poCmdMgr As IEdmCmdMgr5) _
Implements IEdmAddIn5.GetAddInInfo
Try
PauseToAttachProcess("GetAddInInfo")

poInfo.mbsAddInName = "VB.NET State Age Add-In"


poInfo.mbsCompany = "EPDM API Fundamentals Course"
poInfo.mbsDescription = "Example demonstrating " _
+ "a scheduled task that checks the length of " _
+ "time files have been in their current state."
poInfo.mlAddInVersion = 1
'Minimum SOLIDWORKS PDM Professional version
'needed for Tasks is 10.0
poInfo.mlRequiredVersionMajor = 10
poInfo.mlRequiredVersionMinor = 0

'Register to call OnCmd on Task related events


poCmdMgr.AddHook(EdmCmdType.EdmCmd_TaskSetup)
poCmdMgr.AddHook(EdmCmdType.EdmCmd_TaskSetupButton)
poCmdMgr.AddHook(EdmCmdType.EdmCmd_TaskRun)
poCmdMgr.AddHook(EdmCmdType.EdmCmd_TaskDetails)
Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

184
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

3 Add code to the OnCmd method.


Add code to the OnCmd method that will call the appropriate handler
method based on the command type.
Public Sub OnCmd(ByRef poCmd As EdmCmd, _
ByRef ppoData As System.Array) _
Implements IEdmAddIn5.OnCmd
Try
PauseToAttachProcess(poCmd.meCmdType.ToString())

Select Case poCmd.meCmdType

'This is called from the Administration tool when


'the user selects this task add-in from the
'drop-down list and whenever this task is
'subsequently edited in the Administration tool
Case EdmCmdType.EdmCmd_TaskSetup
OnTaskSetup(poCmd, ppoData)

'This event is sent when the user presses OK or


'Cancel in the task property dialog box
Case EdmCmdType.EdmCmd_TaskSetupButton
OnTaskSetupButton(poCmd, ppoData)

'This is called whenever an instance of the


'task is run
Case EdmCmdType.EdmCmd_TaskRun
OnTaskRun(poCmd, ppoData)

'This is called from the Task List in the


'administration tool whenever the task details
'dialog is displayed
Case EdmCmdType.EdmCmd_TaskDetails
OnTaskDetails(poCmd, ppoData)
End Select

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try

End Sub

185
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

4 Add the OnTaskSetup method.


Add a method that will be called when the task properties dialog is
being displayed. Here we’ll set the task flags as before, create an
instance of our custom setup page and load the controls on the page
with the appropriate data from the vault for the user to select from.
We’ll then pass our setup page object, its handle and a page name back
to the IEdmTaskProperties object to make it available from within
the task properties dialog.
Private Sub OnTaskSetup(ByRef poCmd As EdmCmd, _
ByRef ppoData As System.Array)
Try
Dim props As IEdmTaskProperties = poCmd.mpoExtra
If Not props Is Nothing Then
'Set the TaskProperties values
props.TaskFlags = _
EdmTaskFlag.EdmTask_SupportsScheduling + _
EdmTaskFlag.EdmTask_SupportsDetails

SetupPageObj = New SetupPage( _


poCmd.mpoVault, props)
'Force immediate creation of the control
'and its handle
SetupPageObj.CreateControl()
SetupPageObj.LoadData(poCmd)

Dim pages(0) As EdmTaskSetupPage


'This is the name that appears in the
'navigation pane of the Task Wizard
'in the Administration tool
pages(0).mbsPageName = "Choose states to check"
pages(0).mlPageHwnd = SetupPageObj.Handle.ToInt32
pages(0).mpoPageImpl = SetupPageObj

props.SetSetupPages(pages)

End If

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

186
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

5 Add the OnTaskSetupButton method.


Add a method that will be called when the task properties dialog is
being dismissed because the user has pressed OK or Cancel. Here, if
the user pressed OK, we’ll call the SetupPage method that takes the
values that were set by the user in the SetupPage controls and stores
them with the task definition.
Private Sub OnTaskSetupButton(ByRef poCmd As EdmCmd, _
ByRef ppoData As System.Array)
Try
'The custom setup page in SetupPageObj was created
'in method OnTaskSetup. The StoreData method
'will save the contents of the listbox in the
'user control to the IEdmTaskProperties interface
'in poCmd.mpoExtra.
If poCmd.mbsComment = "OK" And _
Not SetupPageObj Is Nothing Then
SetupPageObj.StoreData()
End If
SetupPageObj = Nothing

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

6 Add the OnTaskRun method.


Add a method that will be called when an instance of the task is
launched.
In the OnTaskRun method we’ll send status and progress information
to the SOLIDWORKS PDM Professional task framework.
We’ll retrieve the values that were set by the interactive user when they
were configuring the task and use those values to find any files that
meet the criteria. Once the files are found, the array of EdmSelItem2
objects are returned to the task framework as an argument to the
IEdmTaskInstance.SetStatus method. Information about these files
will be included by the task framework in the success message that will
be sent.

187
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

Private Sub OnTaskRun(ByRef poCmd As EdmCmd, _


ByRef ppoData As System.Array)
Try
Dim TaskInstance As IEdmTaskInstance
TaskInstance = poCmd.mpoExtra
If Not TaskInstance Is Nothing Then
TaskInstance.SetStatus( _
EdmTaskStatus.EdmTaskStat_Running)
TaskInstance.SetProgressRange(100, 0, _
"Task is running.")

Dim NoDays As String


NoDays = TaskInstance.GetValEx("NoDaysVar")

Dim States As String = ""


States = TaskInstance.GetValEx( _
"SelectedStatesVar")

Dim Items As List(Of EdmSelItem2) = _


New List(Of EdmSelItem2)

DoSearch(poCmd.mpoVault, States, NoDays, Items)

Dim NotificationArray(Items.Count - 1) _
As EdmSelItem2

Items.CopyTo(NotificationArray)

Dim ProgresssMsg As String


If (Items.Count > 0) Then
ProgresssMsg = "Found " + _
Items.Count.ToString() + " files."
Else
ProgresssMsg = ("No files found.")
End If

TaskInstance.SetProgressPos(100, ProgresssMsg)
TaskInstance.SetStatus( _
EdmTaskStatus.EdmTaskStat_DoneOK, 0, "", _
NotificationArray, ProgresssMsg)
End If

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

188
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

The IEdmSearch The IEdmSearch interface can be used to quickly find files or folders
Interface in a vault based on specified criteria. You can obtain an instance of an
IEdmSearch object by calling the IEdmVault5.CreateSearch
method.
To specify the search criteria, the IEdmSearch5 interface has a
number of properties that can be set. For example, the
IEdmSearch5.FindFiles property when set to True specifies that
files should be included in the search.
To specify additional search criteria, the IEdmSearch6.SetToken
method can also be used. This method takes as arguments an
EdmSearchToken enumeration value and a value to set it to. You can
call this method several times, once for each search token value to set.
For example, passing to the SetToken method the enumeration value
EdmSearchToken.Edmstok_StateName as the first argument will
cause the search to only find files in workflow states whose name
matches the second argument string.
Passing the SetToken method the arguments Edmstok_StateBefore
and a date value will cause the search to only find files where a state
change was made before that date.
Once the search criteria has been set, the files and folders meeting the
criteria can be iterated over by calling the method
IEdmSearch5.GetFirstResult and then repeatedly calling
IEdmSearch5.GetNextResult until it returns Nothing.

7 Add the DoSearch method.


Add the method that will find the files in the vault that meet the
selected criteria.
Public Sub DoSearch(ByVal Vault As IEdmVault11, _
ByVal States As String, ByVal Days As String, _
ByVal Items As List(Of EdmSelItem2))
Try
'Calculate date to use for search (Today - Days)
Dim dt As DateTime = DateTime.Today
Dim DaysInt As Integer = Convert.ToInt32(Days) - 1
Dim ts As TimeSpan = New TimeSpan(DaysInt, 0, 0, 0)
dt = dt.Subtract(ts)

189
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

'Split the States string into an array of


'State strings
Dim StatesObj As Object = Split(States, vbCrLf)
'Search each selected State for aged files
For Each State As String In StatesObj
'Skip any empty strings
If Trim(State) = "" Then
Continue For
End If

Dim Search As IEdmSearch6 = Vault.CreateSearch()


If Search Is Nothing Then Return

Search.FindFiles = True
Search.SetToken( _
EdmSearchToken.Edmstok_StateBefore, dt)
Search.SetToken( _
EdmSearchToken.Edmstok_StateName, State)

Dim SearchResult As IEdmSearchResult5 = _


Search.GetFirstResult()
While Not SearchResult Is Nothing
Dim SelItem As EdmSelItem2 = New EdmSelItem2()
SelItem.mlID = SearchResult.ID
SelItem.mlParentID = SearchResult.ParentFolderID
SelItem.meType = SearchResult.ObjectType
SelItem.mlVersion = SearchResult.Version

Items.Add(SelItem)
SearchResult = Search.GetNextResult()
End While
Next State

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

190
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

8 Add the OnTaskDetails method.


Add the method that will be called to add our custom page to the task
details dialog when it is displayed in the Task List. We use the same
Form that we used in the OnTaskSetup method and follow a similar
sequence to create and load it. Here the Form will only be used to
display information to the user about an already running task instance,
so the controls will be shown disabled.
Private Sub OnTaskDetails(ByRef poCmd As EdmCmd, _
ByRef ppoData As System.Array)
Try
Dim TaskInstance As IEdmTaskInstance = _
poCmd.mpoExtra
If Not TaskInstance Is Nothing Then
SetupPageObj = New SetupPage( _
poCmd.mpoVault, TaskInstance)
'Force immediate creation of the control
'and its handle
SetupPageObj.CreateControl()
SetupPageObj.LoadData(poCmd)
SetupPageObj.DisableControls()
poCmd.mbsComment = "State Age Details"
poCmd.mlParentWnd = SetupPageObj.Handle.ToInt32()
End If

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

9 Define the SetupPage class.


Add code to define the class that will be used for the task setup dialog
and the task details dialog.
Public Class SetupPage

Private mVault As IEdmVault7


Private mTaskProps As IEdmTaskProperties
Private mTaskInst As IEdmTaskInstance

191
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

10 Add the constructor used when called from task setup.


Public Sub New(ByVal Vault As IEdmVault7, _
ByVal Props As IEdmTaskProperties)
Try
InitializeComponent()
mVault = Vault
mTaskProps = Props
mTaskInst = Nothing

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

11 Add the constructor used when called from task details.


Public Sub New(ByVal Vault As IEdmVault7, _
ByVal Props As IEdmTaskInstance)
Try
InitializeComponent()
mVault = Vault
mTaskProps = Nothing
mTaskInst = Props

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

192
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

The The IEdmWorkflowMgr interface is used to get information about the


IEdmWorkflowMgr installed workflows in a vault. You can get an instance of an
Interface IEdmWorkflowMgr object from the IEdmVault7.CreateUtility
method by passing it the enum value EdmUtil_WorkflowMgr, or you
can assign an IEdmVault object to a variable declared as type
IEdmWorkflowMgr. From the IEdmWorkflowMgr object, the
methods GetFirstWorkflowPosition and GetNextWorkflow use
IEdmPos objects to traverse the workflows that are installed in the
vault.

12 Add the LoadData method.


Add code to take information from the vault and load it into the
controls on the Form. The available workflows will be retrieved from
the vault using the IEdmWorkflowMgr interface. If there was a
previously selected workflow and a number of days in state threshold
value, it will be retrieved from the task using the GetValEx method. If
the Form was created by a callback from a task definition, command
type EdmCmd_TaskSetup, then IEdmTaskProperties.GetValEx
will be used. If the Form was created by a callback from a task
instance, command type EdmCmd_TaskDetails, then
IEdmTaskInstance.GetValEx will be used.
Public Sub LoadData(ByVal poCmd As EdmCmd)
Try
'Add the names of the available workflows
'to the WorkflowsComboBox
WorkflowsComboBox.Items.Clear()
Dim WorkflowMgr As IEdmWorkflowMgr6
WorkflowMgr = mVault.CreateUtility( _
EdmUtility.EdmUtil_WorkflowMgr)
Dim WorkflowPos As IEdmPos5 = _
WorkflowMgr.GetFirstWorkflowPosition()
While Not WorkflowPos.IsNull
Dim Workflow As IEdmWorkflow6
Workflow = _
WorkflowMgr.GetNextWorkflow(WorkflowPos)
WorkflowsComboBox.Items.Add(Workflow.Name)
End While

193
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

Dim SelectedWorkflow As String = ""


Dim NoDays As String = ""
If Not mTaskProps Is Nothing Then
'Retrieve the name of the workflow that was
'selected by the user
SelectedWorkflow = _
mTaskProps.GetValEx("SelectedWorkflowVar")
'Retrieve the number of days in a state
'before sending a message
NoDays = mTaskProps.GetValEx("NoDaysVar")
ElseIf Not mTaskInst Is Nothing Then
'Retrieve the name of the workflow that
'was selected by the user
SelectedWorkflow = _
mTaskInst.GetValEx("SelectedWorkflowVar")
'Retrieve the number of days in a state
'before sending a message
NoDays = mTaskInst.GetValEx("NoDaysVar")
End If

'Select the workflow to display in


'the WorkflowsComboBox - setting this also
'causes WorkflowsComboBox_SelectedIndexChanged
'to be called so the StatesListBox will be filled
'with the available states for this workflow
If SelectedWorkflow = "" Then
WorkflowsComboBox.SelectedIndex = 0
Else
WorkflowsComboBox.Text = SelectedWorkflow
End If

'Retrieve the number of days in a state


'before sending a message
If IsNumeric(NoDays) Then
DaysNumericUpDown.Value = _
Convert.ToDecimal(NoDays)
Else
DaysNumericUpDown.Value = 0
End If

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

194
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

13 Add the StoreData method.


Add the method that will be called to store the user selections with the
task definition once the user has dismissed the setup Form.
Public Sub StoreData()
Try
'Add the selected states to the states list string
Dim StatesList As String = ""
For Each SelectedStateIndex As Integer _
In StatesListBox.SelectedIndices
StatesList += _
StatesListBox.Items(SelectedStateIndex) + _
vbCrLf
Next
'Save the states selected by the user
mTaskProps.SetValEx("SelectedStatesVar", _
StatesList)
'Save the workflow selected by the user
mTaskProps.SetValEx("SelectedWorkflowVar", _
WorkflowsComboBox.Text)
'Save the number of days selected by the user
mTaskProps.SetValEx("NoDaysVar", _
DaysNumericUpDown.Value.ToString())

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

195
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

The IEdmWorkflow The IEdmWorkflow interface allows you to get information about a
Interface workflow’s states and transitions. The IEdmPos interface is used in the
traversals. For example, to iterate over all the states in a workflow, you
would use the IEdmWorkflow6.GetFirstStatePosition and use the
returned IEdmPos object in conjunction with the
IEdmWorkflow6.GetNextState method until there are no more
states.

14 Add the SelectedIndexChanged event handler for the


WorkflowsComboBox.
Add the method that will be called when the user selects a different
workflow in the task setup Form. Once the selected workflow is
determined, the states contained in the workflow are traversed and their
names added to the appropriate control in the setup Form.
If any selected states were previously stored with the task definition,
the selection information is retrieved and applied to the state names in
the control.
Private Sub WorkflowsComboBox_SelectedIndexChanged( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles WorkflowsComboBox.SelectedIndexChanged
Try
'Find the IEdmWorkflow corresponding to the
'selected workflow name
Dim WorkflowMgr As IEdmWorkflowMgr6
WorkflowMgr = mVault.CreateUtility( _
EdmUtility.EdmUtil_WorkflowMgr)
Dim WorkflowPos As IEdmPos5 = _
WorkflowMgr.GetFirstWorkflowPosition()
Dim Workflow As IEdmWorkflow6 = Nothing
Dim SelectedWorkflow As IEdmWorkflow6 = Nothing
While Not WorkflowPos.IsNull
Workflow = _
WorkflowMgr.GetNextWorkflow(WorkflowPos)
If Workflow.Name = WorkflowsComboBox.Text Then
SelectedWorkflow = Workflow
Exit While
End If
End While

196
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

'Add the names of the available states for the


'selected workflow to the StatesListBox
StatesListBox.Items.Clear()
If Not SelectedWorkflow Is Nothing Then
Dim StatePos As IEdmPos5 = _
SelectedWorkflow.GetFirstStatePosition()
While Not StatePos.IsNull
Dim State As IEdmState6
State = SelectedWorkflow.GetNextState(StatePos)
StatesListBox.Items.Add(State.Name)
End While
End If

Dim SelectedStates As String = ""


If Not mTaskProps Is Nothing Then
SelectedStates = _
mTaskProps.GetValEx("SelectedStatesVar")
ElseIf Not mTaskInst Is Nothing Then
SelectedStates = _
mTaskInst.GetValEx("SelectedStatesVar")
End If

Dim States As Object = _


Split(SelectedStates, vbCrLf)
For Each State As String In States
If Not Trim(State) = "" Then
StatesListBox.SelectedItems.Add(State)
End If
Next

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

15 Insert breakpoints.
Put a breakpoint at the line following the PauseToAttachProcess call
in both the GetAddInInfo and OnCmd methods.

197
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

16 Install the task add-in.


From the SOLIDWORKS PDM Professional Administration
application, install the add-in as a new add-in by right clicking on the
Add-ins node and selecting New Add-in.

Navigate to the folder containing StateAgeTask.dll. Select both


StateAgeTask.dll and Interop.EdmLib.dll. Click Open.
17 Attach debugger.
When you click Open, the GetAddInInfo method of the add-in will be
called and the message box will force execution to pause.

In Visual Studio, click the Debug menu and select Attach to Process.
In the Available Processes window of the Attach to Process dialog,
select the AddInSrv.exe process and click Attach.
Click OK in the message box to dismiss it.
The GetAddInInfo method of our add-in will stop execution at the
break point.
Step through the code, pressing F10 at each line of code.
Press F5 to continue once the end of the GetAddInInfo method is
reached.

198
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

18 Finish installing the task add-in.


Click OK in the Properties dialog.
Click OK in the warning dialog that informs you of the need to restart
all client machines.

Note The GetAddInInfo method of the add-in will be called at various times
and the message box will force execution to pause each time. Once this
method has been debugged and you are satisfied that it is working
correctly, you can simply click OK to dismiss the message box without
attaching the debugger to the process.
19 Configure Task Host.
Log into the vault from the File, Open dialog of an application such as
Notepad.
In the Windows Task Bar at the bottom of the screen, click the
SOLIDWORKS PDM Professional icon . From the menu, select
Task Host Configuration.
In the Task Host Configuration dialog, check the checkbox that
appears next to the name of the task, VB.NET State Age Add-In, in
order to configure the local host to permit execution of the task.
Click OK.
20 Install the task.
In the SOLIDWORKS PDM Professional Administration application,
right click on the Tasks node and select New Task. The New Task -
Properties dialog will appear.
Enter the name State Age Task for the new task.
From the Add-in list, select VB.NET State Age Add-In.
21 Attach debugger.
As soon as you select the add-in, the OnCmd method of the add-in will
be called and the message box will force execution to pause.

In Visual Studio, click the Debug menu and select Attach to Process.
In the Available Processes window of the Attach to Process dialog,
select the ConisioAdmin.exe process and click Attach.
Click OK in the message box to dismiss it.

199
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

The OnCmd method of our add-in will stop execution at the break
point.
Step through the code, pressing F10 at each line of code until the
highlight is on the OnTaskSetup method call.

Press F11 to step into the OnTaskSetup method.


Continue pressing F10 at each line of code, pressing F11 at each
method call that you would like to step into.
Press F5 to continue once you are finished debugging the task setup
code.
22 Finish installing the task add-in.
Click Next to go to the Execution Method property page.
In the Computers supporting the task window, check the checkbox
beside the name of the local computer.
Click Next to go to the Scheduling property page.
Keep the default This task is not scheduled button selected.
Click Next to go to our custom setup page labelled Choose states to
check.
Keep the Default Workflow selection and shift-select all the states in
the Select State(s) list.
Set the Number of Days in State to 0.
Click Next to go to the Permissions property page.
Check the checkbox next to the name of the user you are logged in as in
order to give permission to start the task.
Click Next to go to the Success Notification property page.
Check the Notify the user who launched the task checkbox to be
notified when the task successfully completes.
In the Subject edit box, enter the text Success.
In the Text edit box, enter the text The state age task successfully
completed at. With the cursor just before the period, click and
select Current Time to insert the Current Time dynamic text
variable.
Click OK.

200
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

23 Debug the OnTaskSetupButton code.


A breakpoint will be hit as the OnCmd method is called with the
command type EdmCmd_TaskSetupButton.
Debug as before using F10 and F11 to step over and into methods.
Press F5 when finished debugging.
24 Open the Task List.
Double click the Task List tree item under the Tasks node in the
SOLIDWORKS PDM Professional Administration application to open
the Task List dialog.
25 Add Task.
Launch the task by clicking Add Task in the Task List dialog,
selecting State Age Task from the list of tasks to launch and clicking
OK.
26 Debug the OnTaskRun code.
The OnCmd method of the add-in will be called and the message box
will force execution to pause.

In Visual Studio, click the Debug menu and select Attach to Process.
In the Available Processes window of the Attach to Process dialog,
select the TaskExecutor.exe process and click Attach.
Click OK in the message box to dismiss it.
The OnCmd method of our add-in will stop execution at the break
point.
Debug as before using F10 and F11 to step over and into the
OnTaskRun and other methods.
Press F5 when finished debugging.

201
Lesson 6 SOLIDWORKS PDM Professional
Task Add-In Applications

Observe the task’s status in the Task List as it executes and finishes.

Click Details and select the State Age Details tab.


Observe the settings that were set in the task setup dialog and used by
this task instance.

202
SOLIDWORKS PDM Professional Lesson 6
Task Add-In Applications

You should soon receive a success notification containing the list of


files that have been in the selected states longer than the number of
days that were specified in the task setup.

27 Close the Administration tool.

203
Exercise 7 SOLIDWORKS PDM Professional
Scheduled Tasks

Exercise 7: Create an add-in Task application that will:


Scheduled  Allow a Task to be scheduled or launched from a menu that will:
Tasks  Send a success message to the user that launched the task.
 Indicate the names of all the files that are currently in the
Approved state of the Default Workflow.
 Keep the status of the task up to date in the Task List.
 Handle any COM exceptions.
 Handle any other exceptions.

204
SOLIDWORKS PDM Professional Exercise 7
Scheduled Tasks

Imports EdmLib

Public Class Exercise7


Implements IEdmAddIn5

Public Sub GetAddInInfo( _


ByRef poInfo As EdmAddInInfo, _
ByVal poVault As IEdmVault5, _
ByVal poCmdMgr As IEdmCmdMgr5) _
Implements IEdmAddIn5.GetAddInInfo

Try
poInfo.mbsAddInName = _
"Exercise 7 VB.NET Task Add-In"
poInfo.mbsCompany = "EPDM API Fundamentals Course"
poInfo.mbsDescription = _
"Exercise demonstrating a task that will list " _
+ "files in the Approved state."
poInfo.mlAddInVersion = 1

'Minimum SOLIDWORKS PDM Professional version


'needed for VB.Net Task Add-Ins is 10.0
poInfo.mlRequiredVersionMajor = 10
poInfo.mlRequiredVersionMinor = 0

'Register this add-in as a task add-in


poCmdMgr.AddHook(EdmCmdType.EdmCmd_TaskRun)
'Register this add-in to be called when
'selected as a task in the administration tool
poCmdMgr.AddHook(EdmCmdType.EdmCmd_TaskSetup)
Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Public Sub OnCmd(ByRef poCmd As EdmCmd, _


ByRef ppoData As System.Array) _
Implements IEdmAddIn5.OnCmd

Try
PauseToAttachProcess(poCmd.meCmdType.ToString())

Select Case poCmd.meCmdType


Case EdmCmdType.EdmCmd_TaskRun
OnTaskRun(poCmd, ppoData)
Case EdmCmdType.EdmCmd_TaskSetup
OnTaskSetup(poCmd, ppoData)
End Select

205
Exercise 7 SOLIDWORKS PDM Professional
Scheduled Tasks

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Private Sub OnTaskRun(ByRef poCmd As EdmCmd, _


ByRef ppoData As System.Array)

'Get the task instance interface


Dim inst As IEdmTaskInstance
inst = poCmd.mpoExtra
Try
'Keep the Task List status up to date
inst.SetStatus _
(EdmTaskStatus.EdmTaskStat_Running)

'Format a message that will be displayed


'in the task list
inst.SetProgressRange(10, 1, "Task is running.")

Dim Items As List(Of EdmSelItem2) = _


New List(Of EdmSelItem2)
inst.SetProgressPos(4, "Task is searching.")

Dim Search As IEdmSearch6 = _


poCmd.mpoVault.CreateSearch()
If Search Is Nothing Then Return

Search.SetToken( _
EdmSearchToken.Edmstok_FindFiles, True)
Search.SetToken( _
EdmSearchToken.Edmstok_WorkflowName, _
"Default Workflow")
Search.SetToken( _
EdmSearchToken.Edmstok_StateName, "Approved")

Dim SearchResult As IEdmSearchResult5 = _


Search.GetFirstResult()
While Not SearchResult Is Nothing
Dim SelItem As EdmSelItem2 = New EdmSelItem2()
SelItem.mlID = SearchResult.ID
SelItem.mlParentID = SearchResult.ParentFolderID
SelItem.meType = SearchResult.ObjectType
SelItem.mlVersion = SearchResult.Version

Items.Add(SelItem)
SearchResult = Search.GetNextResult()
End While
inst.SetProgressPos(7, "Task finished searching.")

206
SOLIDWORKS PDM Professional Exercise 7
Scheduled Tasks

Dim NotificationArray(Items.Count - 1) _
As EdmSelItem2
Items.CopyTo(NotificationArray)

Dim ProgresssMsg As String


If (Items.Count > 0) Then
ProgresssMsg = "Found " + _
Items.Count.ToString() + " files."
Else
ProgresssMsg = ("No files found.")
End If

inst.SetProgressPos(10, ProgresssMsg)
inst.SetStatus( _
EdmTaskStatus.EdmTaskStat_DoneOK, 0, "", _
NotificationArray, ProgresssMsg)
Catch ex As Runtime.InteropServices.COMException
inst.SetStatus _
(EdmTaskStatus.EdmTaskStat_DoneFailed, _
ex.ErrorCode, "The test task failed!")
Catch ex As Exception
inst.SetStatus _
(EdmTaskStatus.EdmTaskStat_DoneFailed, _
0, "Non COM test task failure!")
End Try
End Sub

Private Sub OnTaskSetup(ByRef poCmd As EdmCmd, _


ByRef ppoData As System.Array)

Try
'Get the property interface used to
'access the framework
Dim props As IEdmTaskProperties
props = poCmd.mpoExtra

'Set the property flag that says we want a


'menu item for the user to launch the task
'and a flag to support scheduling
props.TaskFlags = _
EdmTaskFlag.EdmTask_SupportsInitExec + _
EdmTaskFlag.EdmTask_SupportsScheduling

'Set up the menu commands to launch this task


Dim cmds(0) As EdmTaskMenuCmd
cmds(0).mbsMenuString = "List Approved files task"
cmds(0).mbsStatusBarHelp = _
"This command runs the task add-in to get the" + _
" names of the files in the Approved state."
cmds(0).mlCmdID = 1
cmds(0).mlEdmMenuFlags = _
EdmMenuFlags.EdmMenu_Nothing
props.SetMenuCmds(cmds)

207
Exercise 7 SOLIDWORKS PDM Professional
Scheduled Tasks

Catch ex As Runtime.InteropServices.COMException
MsgBox("HRESULT = 0x" + _
ex.ErrorCode.ToString("X") + vbCrLf + _
ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Private Sub PauseToAttachProcess( _


ByVal callbackType As String)

Try
'If the debugger isn't already attached to a
'process,
If Not Debugger.IsAttached() Then
'launch the debug dialog
'Debugger.Launch()
'OR
'use a MsgBox dialog to pause execution
'and allow the user time to attach it
MsgBox("Attach debugger to process """ + _
Process.GetCurrentProcess.ProcessName() + _
""" for callback """ + callbackType + _
""" before clicking OK.")
End If

Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

End Class

208
Appendix A
C# Examples

The material in this appendix supplements the material covered in the


lessons. It is included here for your reference.
 Connecting to a vault using C#.

209
Appendix A SOLIDWORKS PDM Professional
C# Examples

Connecting to a The code below is a simple example of connecting to a vault from a


Vault Using C# stand-alone application using C#.

using System;
using System.Windows.Forms;
using EPDM.Interop.epdm;

namespace EpdmStandAloneCS
{
public partial class FormEpdmStandAloneCS : Form
{
public FormEpdmStandAloneCS()
{
InitializeComponent();
}

private void buttonConnect_Click(object sender,


EventArgs e)
{
//Declare a file vault interface
IEdmVault5 vault = null;
try
{
//Create a file vault interface instance.
vault = new EdmVault5();
//Login to the vault
vault.LoginAuto("Your Vault Name",
this.Handle.ToInt32());
}
catch
(System.Runtime.InteropServices.
COMException ex)
{
//We will get here if any method above
//doesn't return S_OK or some other COM
//exception is thrown

210
SOLIDWORKS PDM Professional Appendix A
C# Examples

if (vault == null)
MessageBox.Show("Could not create " +
"a vault interface.");
else
{
MessageBox.Show("HRESULT = " +
ex.ErrorCode.ToString("X") +
"\n" + ex.Message);
}
}
}
}
}

211
Appendix A SOLIDWORKS PDM Professional
C# Examples

212
Index

A E H
Add Task 201 E_EDM_UNSUPPORTED_PROGRA Hover 33
AddCmd 137 M_VERSION 21 HRESULT 19
AddHook 138 EdmCmd 138 .NET 20
add-in 7, 12 EdmCmd_CardButton 148 C# 20
add-in applications 120 EdmCmd_CardInput 141 C++ 19
Adding New Users 79 EdmCmd_Menu 139 Visual Basic 20
Assigning Interfaces 34 EdmCmd_SerialNo 147
attach EdmCmd_TaskRun 175 I
running process 183 EdmCmd_TaskSetup 176 IEdmAddIn 120
Attach to Process 162, 198 EdmCmdData 139 IEdmBatchItemGeneration 60
EdmInterface.dll 7 IEdmBatchListing 49
B EdmLib namespace 7 IEdmClearLocalCache 49
break point 32 EdmRevComponent 91 IEdmCmdMgr 137
build 14 EdmRevCounter 91 IEdmDictionary 99
EdmRevNo 91 IEdmEnumeratorVariable 90
C enums 6 IEdmFile 40
Card Variables 90 EPDMResultCode Namespace 21 IEdmFolder 40
cast 34 Err 20 IEdmObject 40
Changing Card Variable Values 141 event handler 11 IEdmPos 40
Check Number of Days in State 183 exception 20 IEdmReference 48
CloseFile 90 exercises 2 IEdmRevision 90
COM IEdmSearch 189
interfaces 6 F IEdmTaskInstance 173
object model 6 F5 14 IEdmTaskProperties 172, 186
programming 6 File Open dialog 133 IEdmUser 74
Registration 127 file open dialog 50 IEdmUser Properties 78
type library 6 File References 48 IEdmUserGroup 74
COM visible 127 File Traversal 41 IEdmUserMgr 74
COMException 20 files IEdmVariable 90
Commit training 3 IEdmVariableMgr 90
IEdmRevisionMgr 91 find files or folders 189 IEdmVault interface 12
connection 63 Folder Traversal 43 IEdmversion 90
conventions fully qualified names 10 IEdmWorkflow 196
typographic 3 IEdmWorkflowMgr 193
course length 2 G Implementation
Create Items from Imported Data 60 Generate serial numbers 156 interface 126
Creating an Add-In 120 Generating Serial Numbers 147 Implements Statement 124
GetAddInInfo 120, 128 Imported namespaces 11
D GetFirst 41 install for debugging 130
Data Tips 13 GetNext 41 Installing an Add-In 130
Debug.Print 13 GetValEx 173 Intellisense 30
debugger feedback 13 GetVar 173 Interface Versioning 29
Debugging a DLL 132 GetVaultViews 15 Interfaces 6
Details 202 GetVersion 14 Arguments 6
Dictionaries 99 Group Member Traversal 76 Members 6
Group Traversal 75 interop assembly 7
Interop.EdmLib 10
IsLoggedIn 18
Items 60

213
Index SOLIDWORKS PDM Professional

K T
keys and values 99 Task Add-In
Simple 173
L Task Add-Ins 170
legacy files 92 Task Hooks 174
load event handler 15 Task Host Configuration 170, 179
local cache 50 Task Interfaces 172
Logging into a Vault 16 Task List 176, 181
Login 17 try/catch blocks 20
LoginAuto 16 type library 6
LoginAuto 17
U
M URL
mail message 78 training files 3
Message Boxes 13 User Traversal 74
Minimum Version Required 129
MsgBox 13 V
vault view 15
N VerifyVersion 21
namespaces 10 Visual Studio
New Add-in 157, 178 IntelliSense 7
New Add-in wizard 170 Object Browser 7, 10
new project 8 references 8, 22
New Task 179 templates 8
New Task dialog 180
New Task wizard 170 W
Notepad 133 Watch Windows 13
Windows Explorer 132
O Windows Task Bar 170
Object Browser 124
OnCmd 120, 138 X
Output Window 14 XML file 50

P
prerequisites 2
Programmer’s Reference Guide 25

Q
QueryInterface 34

R
reboot 132
rebuild 14
Recursive Folder Traversal 44
reference tree 48
Reference Tree Traversal 50
Remove Add-in 156
run 14

S
Set Revisions 92
stand-alone 7, 12
Start external program 133
structures 6
stub event handler 11

214

You might also like