SolidPractices: Getting Started with the SOLIDWORKS PDM API

Revision History
Rev #DateDescription
1.0Feb 2021New document Created
1.1Aug 2023

Added section on PDM Web API

Validated document for current release

Note

All SolidPractices are written as guidelines. It is a strong recommendation to use these documents only after properly evaluating your requirements. Distribution of this document is limited to Dassault Systèmes SolidWorks employees, VARs, and customers that are on active subscription. You may not post this document on blogs or any internal or external forums without prior written authorization from Dassault Systèmes SolidWorks Corporation.

This document was updated using version SOLIDWORKS 2023 SP03. If you have questions or need assistance in understanding the content, please get in touch with your designated reseller.

Acknowledgments

This document was authored by CADSharp LLC and reviewed by Dassault Systèmes SolidWorks Corporation.

Preface

The SOLIDWORKS PDM API (PDM API) is one of the most powerful features of the SOLIDWORKS PDM Professional software. The PDM API is similar to the SOLIDWORKS API in that users with knowledge of programming can use the PDM API to automate almost any part of the SOLIDWORKS PDM Professional application. This makes it possible to use SOLIDWORKS PDM in ways that are not possible under normal circumstances.

The purpose of this SolidPractices document is to share the best practices of those who spent tens of thousands of hours developing the SOLIDWORKS PDM API. These best practices can help you avoid frustrating mistakes that slow the development experience for your organization.

Your Feedback Requested

We would like to hear your feedback and suggestions for new topics. After reviewing this document, please take a few minutes to fill out a brief survey. Your feedback will help us create the content that directly addresses your challenges.

SOLIDWORKS PDM API

Requirement

: Automation through the PDM API is available with SOLIDWORKD PDM Professional. SOLIDWORKS PDM Standard does not support the API.

Working with .NET 4.0 and Beyond

The SOLIDWORKS PDM Professional software exposes functionalities through Primary Interop Assemblies (PIAs). PIAs are .NET assemblies that bridge the gap between a .NET application (such as your add-ins) and a COM server - SOLIDWORKS PDM in this case. COM is an interoperability standard that allows Windows® applications to share their functionalities with other applications (apps). This standard came into existence before the advent of the .NET framework.

In general, always use the Edm.interop.edm.dll PIA that SOLIDWORKS provides for any applications that you develop for the SOLIDWORKS PDM Professional 2013 and later software. This dynamic-link library file (DLL) typically exists in the installation directory of SOLIDWORKS PDM. You can also obtain the DLL from NuGet.org.

SOLIDWORKS does not officially support the use of NuGet packages, which come from the community.

To avoid marshaling issues with .NET and COM, specify the Embed Interop Types for Edm.Interop.Edm.dll as False if you are using C#.

Specifying the Embed Interop Types as False does not embed the APIs types into your application. Therefore, you need to include the PIA that you used with your application, which means that you need to package more than one file.

When maintaining legacy codebases written for SOLIDWORKS 2009-2012 or older versions, your application needs to designate either .NET 2.0, 3.0 or 3.5 depending on the framework in use. It is your responsibility to generate the PIAs yourself. This document provides instructions on how to do that.

Whenever is possible, it is always a recommendation to update to the latest version of the SOLIDWORKS PDM Professional software, or at least to a software version that supports the .NET 4 framework.

Object Model

Unlike modern APIs, the PDM API does not document its object model with a proper hierarchy diagram. The reason is that the underlying COM framework does not use class inheritance. The PDM API uses interface inheritance and polymorphism. Most PDM objects implement the generic IEdmObject5 interface, which contains several properties and methods that are common to all derived interfaces.

Despite the lack of proper class inheritance, it is possible to construct an access hierarchy. Such hierarchy is a key to understanding the inner workings of the PDM API. The access hierarchy defines how an interface (like IEdmAttribute5, the interface for an attribute in a variable definition for example) is retrieved from the members (methods and properties) of another interface.

At the top of this access hierarchy is the IEdmVault5 interface, which represents a PDM vault. Consequently, it is the highest-level interface (object) of the API object model. This is the object that you usually begin with when writing applications other than add-ins.

Consider the example of the attribute interface. To get the first attribute’s block name of the revision variable, you must typically follow this route:

Access hierarchy level

IEdmVault7 (direct cast from IEdmVault5) or EdmVaultCass
IEdmVault7::CreateUtility(EdmUtility.EdmUtil_VariableMgr)
IEdmVariableMgr5
IEdmVariableMgr5::GetVariable (Name:= Revision)
IEdmVariable5
IEdmVariable5::GetFirstPositionAttribute()
IEdmPos5
IEdmVariable5::GetNextAttribute(EdmPos5 = position)
IEdmAttribute5
IEdmAttribute5::BlockName
The block name of the first attribute for the revision variable.

The Interface::Member annotation

In the previous example, the PDM API uses the double colon (::) to separate the interface name from the name of a member of that interface. The member in this notation is the accessor from the perspective of the object being accessed. Each object can have multiple accessors.

The IEdmAttribute5 object is accessed through IEdmVariable5::GetNextAttribute. Therefore, IEdmVariable5::GetNextAttribute is considered an accessor for IEdmAttribute5.

Accessors are a crucial element of understanding the API object model.

Using the API help (preferably the offline help), find the IEdmVariable5 topic. For example:

The list of accessors for this interface appear at the bottom of the page. The references show the interface and the method from which you can get this interface.

There is more information about using the SOLIDWORKS PDM offline help later in this document.

Version Compatibility

The question of version interoperability is addressed in part in section 2.a of this guide. Working within the realm of the same .NET framework, SOLIDWORKS PDM add-ins remain backward and forward compatible. No action is required. The only issue that might arise is calling API calls that might not exist in an earlier version of SOLIDWORKS PDM where the add-in is installed.

For example, Imagine that you have an add-in that was developed with the PIAs shipped with SOLIDWORKS 2020 SP0.0. Calling any new API calls that were introduced in SOLIDWORKS 2020 SP0.0 in an earlier version vault results in an error.

  1. Common Pitfalls

  2. Embed Interop Types = False

If you are working with C#, it is a strong recommendation that you define this option as false and ship the PDM PIA with your application. The .NET framework omits interop type definitions that it does not find in the assembly it is compiling. The compiler also fails to detect the use of some API structs in method signatures. Alternatively, you can force the inclusion of those interop types by explicitly declaring instances of them anywhere in your add-in and switching the embed interop types to True.

  1. Wrapping IEdmAddIn5::GetAddInInfo and IEdmAddIn5::OnCmd in a try-catch block

SOLIDWORKS PDM Professional throws a COMException with a generic message that states that your add-in is not implementing IEdmAddIn5 if your add-in throws a .NET exception.

It is a strong recommendation that you enclose your GetAddinInfo and OnCmd implementation in a try-catch block. Unhandled exceptions within your implementation are reported to the user in a generic fashion, with much of the important information lost.

If an exception occurs within your implementation, you should catch it locally and log the details of the exception for later analysis.

By using Exception:InnerException, log all inner exceptions because the innermost exceptions sometimes provide a more meaningful explanation of the root cause of the outer most exception.

Use caution when displaying message boxes or modal dialogs to the user because SOLIDWORKS PDM calls GetAddinInfo extensively. In many cases, GetAddinInfo is called during unattended operations. Displaying message boxes blocks further processing of potentially long tasks.

  1. Paying attention the phwnd

Pay close attention to the program window handle parameter that some API calls require. This is normally the handle of the main window (or the active window) of the application. If you are working from within the scope of the SOLIDWORKS PDM add-in, the SOLIDWORKS PDM Professional software provides that information for you from the EdmCmd parameter in the OnCmd method.

This allows SOLIDWORKS PDM to determine where to paint over the user interface (UI). A good example of that is the Login method. Specifying the appropriate handle allow SOLIDWORKS PDM to paint the blue login box atop your active window.

If your application is a console application, a WinForms app or a Windows Presentation Foundation (WPF) app, you can use System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle.ToInt32() to the get the handle of the main window. Consequently, if your active window is not the main window, you need to programmatically get the handle of that window and pass it to SOLIDWORKS PDM.

  1. Using IEdmFile5::Refresh to update the check-in status

Imagine that you need to check in the content of a folder that contains an assembly and all of its references. The typical approach is to traverse the folder content and check in files one-by-one. Some referenced documents in a subassembly may get checked into the vault when you check in the subassembly file itself. You then run the risk of checking in those referenced documents twice.

Because IEdmFile5::IsLocked is not a dependency property, the value of IsLocked is not guaranteed to update. Using IEdmFile5::Refresh causes the file to refresh the lock state.

  1. Some API calls require ByRef arguments

Whenever an API requires a ByRef parameter, you must declare a variable of the type of the parameter, and assign a default value before you feed into the API call.

  1. Always use IEdmVault5::GetObject instead of IEdmVault5::GetFileFromPath when possible

Whenever you have the ID of a file, it is always more efficient to use IEdmVault5::GetObject to get the PDM object instead of IEdmVault5::GetFileFromPath. The latter uses the complete file path to the actual file, which is environment dependent. This is very useful for tasks when you need to transfer data from the task-initiating machine to the task-running machine.

  1. Some API calls are faster at than others

The PDM API includes specific API interfaces and methods that are more efficient at processing large sets of files, because of more efficient use of network and database bandwidth. Here is an exhaustive list of the most used API calls and their batch-enhanced counterparts.

Operation

API call

API interface enhanced for batch processing

Check out

IEdmFile::LockFileIEdmBatchGet

Check in

IEdmFile::UnlockFileIEdmBatchUnlock

Undo Check out

IEdmFile::UndoLockFileIEdmBatchGet

Set data card variables

IEdmEnumeratorVariable5::SetVarIEdmBatchUpdate2

Adding files to vault

IEdmFolder6::AddFilesIEdmBatchAdd2

Adding folders to vault

IEdmFolder5::AddFolderIEdmBatchAddFolders

Getting the values of datacard variables

IEdmEnumeratorVariable5::GetVarIEdmEnumeratorVariable7::GetVersionVars

You will only experience major improvements for large set of files that are a few thousand items and more.

  1. Use the search interface more efficiently

There is a bit of overhead involved when creating an IEdmSearch5 object. Therefore, if you intend to perform several searches, call IEdmSearch5::Clear to clear and reuse the current search object instead of calling IEdmVault5::CreateSearch to create new search objects.

Using the Offline Help: Navigating the API Documentation Successfully

The API help is the best documentation resource for the PDM API. The SOLIDWORKS PDM offline help is easier to navigate than the online help.

The PDM API offline help installs with SOLIDWORKS and not SOLIDWORKS PDM Professional. This help exists in the API folder within the SOLIDWORKS installation directory. The name of the file is API_GB.chm.

To look up an interface, a method, or a property, use the Index tab. The most relevant search result appears at the top.

The Different Types of PDM Apps Available Through the SOLIDWORKS PDM API.

There are two types of applications for SOLIDWORKS PDM:

In-process apps: These apps include dispatch scripts, SOLIDWORKS PDM add-ins, and PDM task add-ins. These applications are added from the vault and piggyback off the logged-in user connection and permissions.

Out-process apps: These apps include the console, WinForm or WPF applications, and class libraries to which third party applications refer.

  1. Languages - VBA, C# and VB.NET

  2. VBA

Visual Basic for Applications (VBA) continues to be the community choice for automating SOLIDWORKS and SOLIDWORKS PDM Professional. You can write scripts for SOLIDWORKS PDM Professional if the SOLIDWORKS task add-in is installed in your vault. This add-in allows you to embed VBA scripts and run them in a task. You can write VBA macros for SOLIDWORKS and can interact with SOLIDWORKS PDM Professional. The EdmInterface.dll file contains all of the API types for VBA. From the Visual Basic Editor (VBE), go to Tools > References and look for PDMWorks Enterprise 20XX Type library.

  1. C#

Thanks to the interoperability between COM and .NET, it is possible to write PDM applications with languages such C#. C# is the flagship programming language for Microsoft® and is by far the most supported language in the Microsoft technology stack. With C#, you can write PDM add-in class libraries that integrate other applications that require interconnectivity with SOLIDWORKS PDM.

VB.NET

VB.NET and C# share the same foundations in the Microsoft.NET framework. They are equally useful when programming the SOLIDWORKS PDM API.

VB.NET evolved from VB6 and shares similar syntax to VBA. Where it differs, the integrated development environment (IDE) often corrects the VBA or VB6 syntax automatically. VB.NET is a good choice if you are familiar with VB6 or VBA.

  1. Pros and Cons

  2. VBA

VBA is quite fast when compared to VB.NET and C#, and is the best language for prototyping and writing small scripts. However, VBA lacks the base class libraries (BCL) that .NET offers. Therefore, doing the simplest tasks in VBA like sorting a collection by a property of the underlying the type is not straight forward.

  1. C#

C# is the most popular language to write Microsoft applications. The C# language enjoys great support and user community activity, and a higher rate of adoption than VB.NET.

VB.NET

VB.NET is easily the de facto language for COM automation. It extends VB6 and includes the powerful .NET BCL that offers thousands of classes, interfaces and functions to fulfill every programming need. VB.NET offers a lower barrier to entry than C# for those who have used VBA or VB6. Conversely, C# has a lower barrier to entry for C++ users. Both VB.Net and C# have access to the same BCL in the .NET framework.

  1. Add-in Development

  2. Basic Requirements

The IEdmAddIn5 interface is the template that defines how a SOLIDWORKS PDM Professional vault communicates with an add-in. This interface guarantees that the main class for a SOLIDWORKS PDM Professional add-in implements two methods: GetAddInInfo and OnCmd. Section 8.c. covers these methods in more detail.

Without the selection of interoperability options in Microsoft Visual Studio, your .NET classes are compiled to a proper .NET DLL. This DLL is not compatible with SOLIDWORKS PDM and can only be loaded by another .NET application. This is where Visual Studio comes to the rescue with a set of tools that enable you to make the .NET DLL and its underlying types COM-compliant.

Your main class must be COM-visible. For that purpose, use System.Runtime.Interopservices.ComVisibleAttribute

Decorating the entry class of an add-in by the COM-visible attribute looks something like this:

***********

using System.Runtime.Interopservices ;

[ComVisible(true)]

public class MyAddIn : IEdmAddIn5 {

implementation goes here

}

***********

Visual Studio has an option to make all public classes visible. This option is accessible by going to your project Properties and clicking Assembly Information on the

Application

tab. Select the Make Assembly Com-Visible check box to activate such an option. It is a strong recommendation to NOT use this option. Make your add-in class com visible on a need-to-do basis.
  1. Your main class needs a GUID

A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. There is a very low probability of generating a duplicate GUID. You can generate a GUID attribute by going to Tools > Create GUID in Visual Studio.

Click Copy to copy the GUID to your clipboard. You can paste the GUID attribute above the ComVisible attribute.

Add-in Registration

Add-in registration is the process by which you use the RegAsm.exe tool to register the add-in types (main class primarily). This .NET tool is at the heart of the interoperability process. The common language runtime (CLR) versions CLR 4.0 and CLR 2.0 each have a different version of RegAsm.exe. Each CLR version also has another version of RegSsm.exe depending on the bitness of your application (x64 or x86).

When you add the add-in to the vault, you do not need to register the add-in for com interoperability because SOLIDWORKS PDM attempts to do that for you. However, you do need to register the add-in for com interoperability if you are debugging the add-in in the SOLIDWORKS PDM Administration Tool. More details about debugging add-ins later.

When a registration is required, there are two noteworthy approaches.

  1. DIY approach

The do it your approach involves performing the registration yourself by registering the add-in DLL with RegSsm.exe. For the add-ins you develop with CLR 4.0, the appropriate Regasm.exe version exists in the following location:

C:\Windows\Microsoft.NET\Framework\v4.0.30319

Invoking the RegAsm.exe tool from the Windows Terminal (or from a command prompt) shows the command arguments.

To register a DLL, use the command:

RegAsm [AssemblyPath] /codebase

To unregister a DLL, use the command:

RegAsm [AssemblyPath] /unregister

Using this approach, you only need to register your add-in DLL once.

  1. Let Visual Studio take care of it

Because running RegAsm.exe in Windows Vista or later operating system versions requires administrator privileges because of User Account Control (UAC), you must run Visual Studio as an administrator. Under the project properties go to the Build tab and activate the Register for COM interop option.

  1. The GetAddInfo, OnCmd and EdmCmdData Objects

GetAddInfo(out EdmAddInInfo poInfo, IEdmVault5 poVault, IEdmCmdMgr5 poCmdMgr)

Use this method to define your add-in. After loading the add-in in a vault or logging into a vault from Windows File Explorer, SOLIDWORKS PDM attempts to invoke this method to do the following things:

  • Read the name, description, company and required version of your add-in through the EdmAddInInfo parameter. Notice that the EdmAddInIfo structure is marked as out (or ByRef in VB.NET).

  • Allows you to use the IEdmCmdMgr5 interface to:

    • Add callbacks for hooks: This allows you to subscribe to SOLIDWORKS PDM events so that when such an event occurs (a checkout operation for example) your add-in receives notification.

    • Add menu commands and toolbar buttons.

OnCmd(Out EdmCmd poCmd, out EdmCmdData[])OnCmd is called whenever a SOLIDWORKS PDM event (menu command or hook) to which you subscribe in the GetAddInInfo() method occurs. This is where you reference the logic of your SOLIDWORKS PDM add-in. The poCmd structure contains the definition of the command that was triggered. The EdmCmdData[] array is an array of the items (files or folders for example) that were affected by the event.

All callbacks route into the same OnCmd implementation and it is the responsibility of the add-in to identify each callback. This is very important, for example, when invoking your add-in from a button in a data card.

Hooks

Hooks are basically event notifiers. When you add a hook, you are listening for changes in SOLIDWORKS PDM that pertain to the hook of interest. For example, if you add a hook to the Precheckout hook, your add-in receives notification every time a file is about to be checked out. The notification data consists of the EdmCmd (event data) and the EdmCmdData[]array, which is a list of affected files and folders.

Add your hooks in the IEdmCmdMgr5 interface. It is only accessible from the implementation of IEdmAddIn5::GetAddInfo. You can only add callbacks to hooks if your application is a SOLIDWORKS add-in. This is not possible with stand-alone applications.

IEdmCmdMgr5 interface allows you to add custom menu items to SOLIDWORKS PDM through the AddCmd method. The most important parameter of this method is ICmdID, which is the command ID. This is an integer you define, that should be unique within your add-in.

If you add menu items that appear in the context menu of a file, your OnCmd method invokes when you click the command item you added. This passes the ICmdID parameter that you specified earlier the EdmCmd.mlCmdID field.

Debugging Through the Administration Tool

The SOLIDWORKS PDM Professional application allows you to debug add-ins before deploying them to production. It is always a good idea to debug your code on a development machine before deployment.

It is a recommendation to turn off UAC during your development process if you are running Windows Vista or later.

Make sure that you always run the SOLIDWORKS PDM Administration Tool as an administrator regardless of the UAC state.

Using the SOLIDWORKS PDM Administration Tool to debug add-ins is a straightforward process. Make sure that you have administrative privileges to administrate add-ins, and log in to your vault. Right-click an add-in and the click Debug add-ins.

  1. You must register an add-in for com interop before debugging it

After building the binaries, you can add the main DLL of your add-in to the vault as a debug add-in, and then use a text editing application (like Notepad) as a start-up program for the debugging session. Use the file open function in the text editor to browse into the local view of your vault. It is preferable to debug using a text editor to debugging with Windows File Explorer because you cannot unload and overwrite the add-in assembly without stopping the host process.

Debugging Alternatives

It is best to debug your SOLIDWORKS PDM Professional add-in by using the approach specified in the previous paragraph. However, it is possible to debug a SOLIDWORKS PDM add-in that you add to the vault by using the add add-ins option. The trick here is to add a message box that shows the process ID where you want to start debugging. The printed process ID is the one you attach to the Visual Studio debugger tool. This is useful when you debug task add-ins.

  1. The SOLIDWORKS Task Add-in Script

  2. Creating a New Script

The SOLIDWORKS Task Add-in allows you to run automated operations on files that are open in the SOLIDWORKS application.

You can find the SOLIDWORKS Task Add-in in the SOLIDWORKS PDM Professional folder under PDM Default Data. Simply, open the SOLIDWORKS PDM Administration Tool, go to File > Import, and then browse for the file convert_gb.cex to import the SOLIDWORKS Task Add-in. To create a new task, right-click the Tasks node for your vault in the administration tool, click New task and follow the instructions.

The SOLIDWORKS task add-in script (run through the standard task add-in as shipped) is intended to run on the same computer where it is initiated. That computer must also have a SOLIDWORKS installation. This is because the script is basically a VBA script that runs inside SOLIDWORKS when you run the task.

You can then add your script to the script page:

Editing and Debugging an Existing Script

Because there is a lot of overhead that goes into running SOLIDWORKS task add-in scripts, it is a strong recommendation that you edit the script in the VBE in SOLIDWORKS. Be aware of the following points:

  1. Evaluate any aliases that the task add-in uses

The task add-in script re-evaluates the following aliases to values that are environment dependent. The following aliases are self-explanatory:

Make sure to replace these aliases with the actual values inside of the VBA IDE in SOLIDWORKS.

  1. Add a reference to EdmInterface.dll

To get access to the API calls definition from the VBE, you can add a reference to the EdmInterface.dll library in the SOLIDWORKS PDM Professional installation folder. Once added, search for the following reference:

PDMWorks Enterprise [version] Type Library

  • Debugging a script
    Add an assert to the macro (or wherever you want to start debugging). This causes the VBA editor to open and the macro to stop on that line.

For example:

***********

Sub main()   

   Debug.Assert False

    On Error GoTo Fail:

***********

When the VBA editor appears, copy the full script into a text editor and end the ongoing SOLIDWORKS process. Next, start a new SOLIDWORKS session, create a new SOLIDWORKS macro, and paste the copied script into the macro to debug the script.

  1. Developing Custom Task Add-ins

  2. Basic Requirements

In some situations, SOLIDWORKS task add-in scripts are not enough to automate your workflow. For example, imagine that you need to generate PDF files of all components that match a certain search criterion, and merge them into a single master PDF. In that case, it is common to write a custom SOLIDWORKS PDM task add-in.

In short, a SOLIDWORKS PDM task add-in is simply a SOLIDWORKS PDM add-in that has all the requirements of a SOLIDWORKS PDM add-in and implements the same interface.

Event Hooks

There are a few hooks that you need to subscribe to for your add-in to become a task add-in. The EdmCmd type defines these hooks. For more information, see the topic Programming Tasks in the SOLIDWORKS API Help.

TypeDescription
EdmCmd_TaskDetailsUse this hook to add your own custom page to the Task Details dialog box in the task list. This hook triggers in the computer of the user that initiates the task.
EdmCmd_TaskLaunchThe task is being launched. Add your own user interface to permit user input. This hook triggers in the computer of the user that initiates the task.
EdmCmd_TaskLaunchButtonThe user clicked OK or Cancel in the task launch dialog box. This hook triggers in the computer of the user that initiates the task.
EdmCmd_TaskRunThis hook is called on the task server. However, you should perform the actual work. This hook triggers in the computer of the user that is running it the task.
EdmCmd_TaskSetupUse this hook to add a task setup page to a task properties dialog box wizard.

This hook triggers in the computer of the user that adding the task to the vault.
EdmCmd_TaskSetupButtonThe user clicked OK or Cancel in the task properties dialog box wizard. This hook triggers in the computer of the user that initiated the task.

In your OnCmd method, you need to handle the implementation of those callbacks.

It is very important to be aware of where each one of these callbacks runs because it is possible to add task add-ins on one computer, initiate them on another computer, and run them on a third computer.

It is customary in the industry to dedicate a few computers for running tasks. The IEdmTaskInstance interface and IEdmTaskProperties interface allow you to store data in a task. Use the SetVar method and GetVar method to specify and get data that is retrieved from network computers that initiate and run a task.

Example:

Imagine that you have a task that prints the reference documents of an assembly that match a certain criteria as PDF files. The logic would be as follows:

It is customary to get the list of the documents from the computer that launches the task. In most cases, the task launches after the user completes a set of changes and checks the assembly back in to the vault. The user would then initiate the task on an assembly file. Some work is done locally in the OnCmd method for the EdmCmd_TaskLaunch to get a list of reference documents that match search criteria.

To send that data over to the computer that runs the task (EdmCmd_TaskRun), it is a good idea to serialize an array that contains the ID of the documents, and save that information into a variable by using IEdmTaskInstance::SetVar. The code that runs the task would get that data by using IEdmTaskInstance::GetVar and deserialize that data back into an array of documents ID, and only then start processing those documents.

The OnTask Hooks and How to Debug Them

The only possible to way to debug a task add-in is by adding the task add-in to the vault as a full-add-in. Use the technique specified in the section “Debugging Alternatives”. To debug each callback by using a message box that displays the process ID of the running process. This intercepts the taskhost.exe and pauses the code execution. You can then attach the VS debugger to that process. Remember to remove your message boxes before deploying your production add-in.

  1. Add-in Installation Issues and How to Resolve Them

  2. The DLL is not a COM module

This error is straight forward. The class that implements the IEdmAddIn5 interface must be COM visible. The best way to expose a .NET class as COM visible is as follows:

You can achieve the same result by not using the ComVisible attribute and right-clicking the active project > Properties >

Application

> Assembly Information, and then selecting the Make assembly Com-Visible option. This has the unintentional consequence of making all public classes COM-Visible. Therefore, this is not a recommendation.

The Assembly Information dialog box where you can make an assembly COM-Visible

  1. Interface

Every add-in must have a class that implements the IEdmAddIn5 interface. When your vault cannot find the class that implements IEdmAddIn5, the following error message appears:

Because IEdmAddIn5::GetAddInInfo is invoked when you add an add-in to the vault, this error appears as an umbrella for any unhandled exceptions that occur within the scope of IEdmAddIn5::GetAddInInfo. See the section “Common Pitfalls” for the proper way to handle these exceptions.

  1. The add-in [Path] cannot be installed since it returned an invalid required version SOLIDWORKS PDM version from its GetAddInInfo Method

This error is self-explanatory. The specified version of the EdmAddInInfo parameter in IEdmAddInInfo::GetAddInInfo has a major or minor version that is newer than the version of the hosting SOLIDWORKS PDM Professional vault. The only way to fix this is to make sure that the minimum version specified in your code is either equal to or lower than the version of the target SOLIDWORKS PDM vault.

If you copy or download the PDM API add-in DLL files from another computer, the Windows security policy might block the DLL for security purposes on some systems. If the DLL files are blocked, the following error appears:

To add these add-in DLLs to the vault, you must first unblock them. Follow these steps:

  1. In Windows File Explorer, right-click the DLL file > select Properties.

  2. Click the General tab. If the file is blocked, the following security warning appears:

The file came from another computer and might be blocked to help protect this computer.

  1. Confirm that the file originates from a trusted source, and then click Unblock.

  2. Click OK to close the properties dialog box.

Repeat these steps for any additional DLL files that were copied or downloaded from the same source.

  1. You do not have permission to use this tool

PDM API Callbacks

In general, a callback (this is different from hooks) is an object that you reference in a method to report progress to the calling method. Callbacks are passed into a method to report progress information to a UI element that displays that information to the user.

The PDM API exposes its own callback interfaces. The following interfaces use the IEdmcallback interface to allow a user to report progress.

IEdmFolder5::CreateCardiew

IEdmBatchAdd::CommitAdd

IEdmBatchChangeState::ChangeState

IEdmBatchDelete::CommitDelete

IEdmBatchUpdate2::CommitUpdate

IEdmClearLocalCache::CommitClear

IEdmUserMgr8::CreateUserPicture

IEdmVault10::CreateCardViewEx2

IEdmVault11::CreateNewVault

And IEdmcallback6

IEdmFolder6::AddFiles

IEdmBatchAdd::CommitAdd

SOLIDWORKS PDM leaves the implementation entirely up to the developer because each application is different. In SOLIDWORKS PDM, any callback object that is passed to these methods needs to implement the IEdmCallback or IEdmCallback6 method.

It is a good idea to make your own callbacks that implement IEdmCallback6 and INotifyPropertyChanged. To avoid illegal calls across thread boundaries, make sure your IEdmCallback6 properties are in the main thread of your application by using the Dispatcher class in WPF or Control::Invoke in WinForms.

Useful Techniques of Exception and Error Logging

Exception handling and the logging of errors are the cornerstones of a properly developed application. It is a recommendation to handle your exceptions and log them whenever possible. This gives you a trace into what went wrong in your application and is helpful to find and fix defects.

  1. Log the exception of the message and the stack trace

The message of the exception tells you what the exception is about and the stack trace tells you where the exception occurred.

  1. Log the exceptions and their inner exceptions

The more information the log file contains, the quicker you can determine the issue and resolve it. Many times, the inner most exceptions have a more meaningful message than the parent exceptions.

  1. Include the pdb file whenever you deploy an application

If you are trying to log the stack trace of your exception, you need the pdb file.

  1. Catch the most specific exceptions first

A try-catch block allow you to catch specific exceptions of different types. It is always a good idea to start with the most specific exceptions and then move to the more general exceptions.

Example:

Catch COMExceptions ahead of catching any System.Exception. SOLIDWORKS PDM throws exceptions as COMExceptions and the exception message always describes the issue according to SOLIDWORKS PDM. If your application is using a second COM API, the library EPDM.Interop.EPDMResultCodeNamespace contains an enumeration called EdmResultErrorCodes_e that matches the HResult of the thrown exception. This is useful for differentiating the origin of the COM exception. For more information, see the topic EdmResultErrorCodes_e in the SOLIDWORKS API Help online.

Standalone Applications

Standalone applications are out-process binaries. Unlike add-ins, stand-alone applications run within their own process and do not load into the vault. However, they can piggyback off an ongoing SOLIDWORKS PDM session in the same way as add-ins by using IEdmVault5::LoginAuto. A stand-alone application can explicitly log in to the vault by using the IEdmVault5::Login or IEdmVault5::LoginEx to comply with the EULA to gain access to SOLIDWORKS PDM.

Search APIs

Search APIs are a great way to look for files and folders in a vault. IEdmSearch5 allows you to quickly search for files and folders. Much like any other interface in the SOLIDWORKS PDM Professional application, you can get IEdmSearch5 by means of accessors. In this case, IEdmVault7::CreateUtility or IEdmVault5::CreateSearch do the trick. There is a bit of overhead involved with creating an IEdmSearch5 object. Therefore, if you intend to perform several searches, call IEdmSearch5::Clear to clear and reuse the current search object instead of calling IEdmVault5::CreateSearch to create new search objects.

The IEdmSearch5 interface allows you to refine your search query through the public properties in the following table:

NameDescription
FilenameGets or sets the name of the file or folder for which to search.
FindFilesGets or sets whether to return files in the search.
FindFoldersGets or sets whether to return folders in the search.
FindHistoricStatesGets or sets whether to find all files that have ever been in the state specified by IEdmSearch5::State.
FindLockedFilesGets or sets whether to include checked-out files in the search result.
FindUnlockedFilesGets or sets whether to include checked-in files in the search result.
RecursiveGets or sets whether to search recursively in subfolders.
StartFolderIDGets or sets the ID of the folder in which to search.
StateGets or sets the ID or name of the workflow state in which to search.
VersionCommentGets or sets the version comment substring for which to search.

The FileName property supports the % (percent) character as a wildcard character and the _ (underscore) character for exactly one arbitrary character. Use [] (square brackets) to escape the special meaning of these characters. The default value of FindFolders is True. If you are looking for files only, make sure to specify the value as False.

The IEdmSearch5 interface uses the iterator pattern to enumerate through search results. This has the good effect of centralizing the traversal process of search results around the same object. No arrays of search results are exposed at once and you receive the search results one-search result at a time. The following self-explanatory code snippet shows how easy it is to traverse search results.

***********

IEdmSearch5 searchEngine;
// Initialize the iterator to the beginning of the list

var searchResult = searchEngine.GetFirstResult();
// check the iterator points to a valid result
while (searchResult != null) {

// do stuff here

// Get the current result and move the iterator onto the next.
searchResult = searchEngine.GetNextResult();

}

PDM Pro Web API Service

The SOLIDWORKS PDM Professional Web API is a dynamic tool that empowers you to create robust Representation State Transfer (RESTful) web applications that harness the capabilities of SOLIDWORKS PDM Professional. At its core, the API comprises a suite of controller APIs designed to oversee an array of product data operations directly from your web platform. With this integration, you can streamline your data workflows and elevate your data management experience.

REST API

The PDM PRO Web API is a Representational State Transfer (REST) API, which is a type of architectural style for designing networked applications. It is commonly used in web development to create services that can be accessed over the internet. REST APIs provide a structured way for different software applications to communicate with each other by using standard HTTP methods, such as GET, POST, PUT, and DELETE, to perform various operations on resources.

REST APIs are built around the concept of resources, which can be thought of as objects or data entities that the API exposes. Each resource is uniquely identified by a URL (Uniform Resource Locator), and the API provides endpoints that correspond to different operations that can be performed on these resources. The PDM Pro Web API resources are documented in the online API Help.

The key principles of a REST API include:

  1. Statelessness: Each API request from a client to the server must contain all the information necessary for the server to understand and fulfill the request. The server should not rely on any past requests or stored client state.

  2. Client-Server: The client and server are separate entities that can evolve independently. The client is responsible for the user interface and user experience, while the server handles data storage, processing, and security.

  3. Uniform Interface: The API should have a consistent and uniform way of accessing and interacting with resources. This typically involves using standard HTTP methods and following conventions for resource naming.

  4. Cacheability: Responses from the server can be cached to improve performance and reduce the need for repeated requests.

  5. Layered System: The architecture can be composed of multiple layers, where each layer has a specific responsibility. This enhances scalability and flexibility.

  6. Code on Demand (optional): The server can send executable code to the client, allowing the client's functionality to be extended dynamically. This principle is optional and not commonly used.

In summary, a REST API provides a structured and standardized approach for building web services that enable different software applications to communicate, exchange data, and perform actions over the internet using a set of well-defined rules and principles.

CORS

CORS, or Cross-Origin Resource Sharing, is a security feature implemented in web browsers to control and manage requests for resources (such as APIs) from a domain different from the one that served the web page. This security mechanism prevents potentially malicious web pages from making unauthorized requests to a different domain's resources on behalf of the user and will be necessary for many use cases when developing with the SOLIDWORKS PDM Professional Web API.

When it comes to IIS (Internet Information Services), which is Microsoft's web server software, CORS settings can be configured to control how the server responds to cross-origin requests. CORS settings in IIS allow you to specify which domains are allowed to make requests to resources hosted on your server. This is especially relevant when your web application uses client-side scripts (like JavaScript) to fetch data from an API hosted on a different domain.

By default, most modern web browsers enforce the Same-Origin Policy, which means that web pages from one domain cannot make requests for resources (such as APIs) on another domain. CORS headers are used to relax this policy and enable controlled cross-origin requests.

To enable CORS in IIS, you typically need to set the appropriate response headers in your server's HTTP responses. These headers include:

  1. Access-Control-Allow-Origin: This header specifies the domains that are allowed to access the resource. It can be set to a specific domain, "*", which allows any domain, or a list of domains.

  2. Access-Control-Allow-Methods: This header lists the HTTP methods (such as GET, POST, PUT, DELETE) that are permitted when making cross-origin requests.

  3. Access-Control-Allow-Headers: This header indicates which HTTP headers are allowed in the actual request.

  4. Access-Control-Allow-Credentials: This header determines whether the browser should include credentials (like cookies or HTTP authentication) in the cross-origin request.

  5. Access-Control-Expose-Headers: This header lists the response headers that can be exposed to the requesting client.

It's important to configure CORS settings properly to ensure that your web application's cross-origin requests are secure and controlled. Misconfigured CORS settings can potentially expose your server to security vulnerabilities. The online documentation for the SOLIDWORKS PDM Professional Web API also includes specific information for enabling CORS.

Initial Setup

There are several prerequisites to getting started with the PDM Pro Web API Service. Each one is explained in detail in this document but you can also view up to date information in the official online documentation. Briefly, you will need the following,

  • SOLIDWORKS PDM Professional. Like the standard API, the web API is only available in PDM Professional.

  • Web API Server. The PDM server installation must include the Web API server and be configured correctly. See the installation manual for your version of PDM Professional for details.

  • Development environment. The PDM Professional WEB API service can be used in any browser-based language (Java, PHP, JavaScript, Python, etc) or in .NET. Depending on your preference, you will need,

    • Visual Studio if you wish to create an ASP.NET (.NET Framework) application or a C# Console Application (.NET Core)

    • CORS setup and configuration, if you wish to use a browser-based language or access the API from a different domain.

  • Once the prerequisites have been fulfilled and you have created a project in your development environment, the first step will be authentication. This is done via the Authentication Resource Group with api/{vaultName}/authenticate (Post).

Example Use Cases

The SOLIDWORKS PDM Professional Web API offers developers the ability to extend and customize the functionality of the data management system. Here are some example use cases where the API can be utilized:

  1. Custom Integrations: Create seamless integrations between SOLIDWORKS PDM Professional and other enterprise systems such as ERP (Enterprise Resource Planning), CRM (Customer Relationship Management), PLM (Product Lifecycle Management), or custom in-house applications. This can ensure synchronized data across different platforms and streamlined workflows.

  2. Automated Workflows: Implement automated processes for tasks like file approvals, document generation, or data migration. By utilizing the API, you can automate repetitive tasks and reduce manual intervention, leading to increased efficiency and reduced errors.

  3. Custom Reporting and Analytics: Develop custom reporting tools that extract specific data from SOLIDWORKS PDM Professional, enabling you to gain insights into usage patterns, revision history, or other relevant metrics. This can aid in making informed decisions and optimizing workflows.

  4. Bulk Data Operations: Perform bulk operations on documents and files, such as bulk importing, renaming, moving, or deleting. This is particularly useful when dealing with large datasets.

  5. Custom User Interfaces: Develop tailored user interfaces that provide a more intuitive and user-friendly experience for interacting with SOLIDWORKS PDM Professional. This can be beneficial for users who have specific needs or workflows.

  6. Secure Data Exchange: Enable secure and controlled access to specific data in SOLIDWORKS PDM Professional by creating custom portals or interfaces for external partners, customers, or suppliers.

  7. Data Migration and Onboarding: During the migration process from another system to SOLIDWORKS PDM Professional, the API can be used to ensure smooth data transfer, validation, and mapping of metadata.

  8. Lifecycle Management: Develop tools to manage the lifecycle of documents, ensuring that they follow predefined workflows, transition through different states, and adhere to company-specific processes.

These examples demonstrate the flexibility and potential of the SOLIDWORKS PDM Professional Web API in tailoring the data management system to specific organizational needs, enhancing collaboration, and improving overall productivity. Note that all of these use cases can be handled in the standard SOLIDWORKS PDM Professional API, and the Web API simply provides a different context to develop in, such as a web application.