Jan 30, 2012

Intro to the SolidWorks EPDM API

SolidWorks World 2012 is less than two weeks away.  That means I’m two weeks from sharing more tips on the SolidWorks and Enterprise PDM APIs.  I’ll be presenting two sessions: one hands-on session introducing a lucky group to the guts of the Enterprise PDM API, and one sharing some of the tips and tricks I’ve learned over the years for building automation in SolidWorks. 

For now, let’s start with some API fundamentals for SolidWorks Enterprise PDM!  I had someone ask about how to compare files that are outside of EPDM with files already in the system.  For example, if a contract design group sends you a batch of files for a design, how do you know what to put back in EPDM?  The file set may contain common parts as well as new parts, assemblies and drawings.  Trying to sift through the file set to figure out what you should add to EPDM could be extremely tedious.  I can think of four or five activities involving sticks, rocks and dirt that would be more invigorating.  Yet another chance to automate!

Connecting to EPDM


As a starting point, fire up a new SolidWorks VSTA VB.NET macro.  Alternatively, you could begin with a new Visual Studio project.  The sample code below assumes using a macro.  Once you’ve started the project, add a reference to the SolidWorks Enterprise PDM library.  Select Project, Add Reference.  You should find it under the COM tab named PDMWorks Enterprise 20XX Type Library.

Open the SolidWorksMacro.vb code file if it isn’t open already and add an Imports statement to add EdmLib (the EPDM library).  Add the following code under the main procedure.

Imports SolidWorks.Interop.sldworks
Imports SolidWorks.Interop.swconst
Imports System.Runtime.InteropServices
Imports System
Imports EdmLib

Partial Class SolidWorksMacro

    Public Sub main()

        Dim vaultName As String = "EPDMVault"
        Dim CompareFolder As String = "C:\EPDM Test"

        'create a vault connection and log in
        Dim v As New EdmVault5       
        v.LoginAuto(vaultName, 0)

    End Sub

    ''' <summary>
    ''' The SldWorks swApp variable is pre-assigned for you.
    ''' </summary>
    Public swApp As SldWorks

End Class

Logging into EPDM


There’s not much to creating a connection to a local vault view and logging in.  The EdmVault5 interface just needs to be declared with the New keyword to connect.  The LoginAuto method is identical to a user opening the local view folder.  If they’re not currently logged in, the system will attempt to log them in using their Windows login.  If that fails, the login prompt is displayed.  The first argument for LoginAuto is the name of the vault.  The second argument is to help EPDM know what the calling application is (it’s window handle as an integer).  Since I’ve used a SolidWorks macro, I’m simply passing 0 to essentially ignore the argument.  It’s really a shortcut for something less than critical.

Creating a Search Interface


To compare files between the vault and an outside folder, we’ll use the EPDM search capability.  Using search through the API isn’t much different than using it through the client software.  Add the following code to the procedure to include the search definition.  We’ll fill out the details and run the search next.

    Public Sub main()

        Dim vaultName As String = "EPDMVault"
        Dim CompareFolder As String = "C:\EPDM Test"

        'create a vault connection and log in
        Dim v As New EdmVault5       
        v.LoginAuto(vaultName, 0)

        'create the search interface and initial settings
        Dim search As IEdmSearch5
        search = v.CreateSearch
        search.FindFiles = True
        search.FindFolders = False

    End Sub 

The search interface type is IEdmSearch5.  You create a search interface by calling EdmVault5.CreateSearch.  It has a handful of different settings.  Since we’re interested in finding files, we’ve set the FindFiles property to True and the FindFolders property to false.

Get the List of Files to Compare


Before we start utilizing the file and directory methods from VB.NET, it’s easiest to add a reference to the System.IO namespace.  Add the following code to import System.IO by the rest of the Imports statements.

...
Imports EdmLib
Imports System.IO

Once that’s been added, you can use FileInfo and DirectoryInfo classes from System.IO to get all files in a given folder path.  The code is finally using the CompareFolder variable to get the compare folder.

    Public Sub main()

        Dim vaultName As String = "EPDMVault"
        Dim CompareFolder As String = "C:\Test Folder"

        'create a vault connection and log in
        Dim v As New EdmVault5       
        v.LoginAuto(vaultName, 0)

        'create the search interface and initial settings
        Dim search As IEdmSearch5
        search = v.CreateSearch
        search.FindFiles = True
        search.FindFolders = False

        'get the file names from the folder to compare
        Dim searchDir As New DirectoryInfo(CompareFolder)
        Dim files As FileInfo()
        files = searchDir.GetFiles("*.*", _
            SearchOption.AllDirectories)
        Stop

    End Sub

If you run the macro to this point, you can review the array named files once you hit the Stop point.  It should have an array of FileInfo objects that include the name of every file in the test folder.

Now that we have an array of file names, we can run an EPDM search on each one.  If we find a match in EPDM, we’ll add that into a collection to later report back to the user.

Running a Search


Depending on how you have your vault configured, a search for a file name in EPDM might possibly return multiple files.  Since we’re interested in simply knowing if the file exists at all in the vault, we’ll only look for the first result.  If there isn’t a first result, we can confidently assume the file doesn’t exist in the vault.

Add the rest of the macro shown below.  If you’re looking for a shortcut, this is the entire macro.

    Public Sub main()

        Dim vaultName As String = "EPDMVault"
        Dim CompareFolder As String = "C:\Test Folder"

        'create a vault connection and log in
        Dim v As New EdmVault5       
        v.LoginAuto(vaultName, 0)

        'create the search interface and initial settings
        Dim search As IEdmSearch5
        search = v.CreateSearch
        search.FindFiles = True
        search.FindFolders = False

        'get the file names from the folder to compare
        Dim searchDir As New DirectoryInfo(CompareFolder)
        Dim files As FileInfo()
        files = searchDir.GetFiles("*.*", _
            SearchOption.AllDirectories)

        'collect any duplicates found in EPDM
        Dim duplicates As New Collection
        For Each f As FileInfo In files
            'run the search for this file name
            search.FileName = f.Name
            Dim sr As IEdmSearchResult5
            sr = search.GetFirstResult
            If Not sr Is Nothing Then
                'found a file in the vault with the same name
                duplicates.Add(f.Name)

                'optionally, get a local copy of the file
                Dim eFile As IEdmFile5
                eFile = sr 'get the file from the search result
                eFile.GetFileCopy(0) 'get the latest file copy
            End If
        Next

        'report back the files found
        Dim myMessage As String = "Duplicate file list:" & vbCrLf
        For Each dup As String In duplicates
            myMessage = myMessage & dup & vbCrLf
        Next
        MsgBox(myMessage & vbCrLf & duplicates.Count & _
            " duplicate files", MsgBoxStyle.Information)

        'reset the collection
        duplicates = Nothing

    End Sub 

I’ve used a Collection to keep track of the files found during the search.  It was easier than an array since I could simply add new elements and didn’t have to worry about resizing.
The EPDM search is run by setting the FileName property and then calling the GetFirstResult method.  The rest is simply formatting a message to return the list to the user.

I've also added a few additional lines of code to get a local file copy in the vault.  You need to first get the IEdmFile5 interface (directly from the IEdmSearchResult5 interface).  There are several optional arguments to the GetFileCopy method, but if you're just getting the latest version, you can use the exact syntax posted.

20 comments:

  1. Awesome Mike! Good to see you blogging about the API. I live in the EPDM API so it is good that someone is passionately talking about the fun and power it can bring. Keep it up!

    ReplyDelete
  2. Hi Mike, I am new to the api. Once I find the file, how do I get the latest version copied to the local machine?

    ReplyDelete
    Replies
    1. The GetFileCopy method of the IEdmFile5 interface will do it. I just realized I didn't post how to get the file interface either. I'll updated the post to add the steps.

      Delete
  3. Hey Mike,

    I've created a Windows Service that wakes up and creates folders in a vault from predefined templates and goes back to sleep. Problem is, the folders get created on the first elapsed interval but not for subsequent ones. I'm wondering, could it be that something isn't being flushed and the API still thinks it's logged into the vault since there is no "Logoff" sub on the EDMVaultx interface. Anyone run across this but me?

    ReplyDelete
  4. I haven't heard of that being a problem, but you might do a quick check when your process runs. Use IEdmVault.IsLoggedIn to see if you are currently logged in or if you need to call the Login or LoginAuto method again for the new session.

    You might also consider initiating a new connection to EPDM each time your service runs to ensure you have an active connection.

    ReplyDelete
  5. Hi Mike, I am new to the api. Once I find the file, how do I get the latest version copied to the local machine?epdm Rubber

    ReplyDelete
  6. Hi Mike, I am totally new to the api, I am planning to create an interface between epdm and erp software. The idea is to transfer an article property to the erp by pressing a button. Could you please give me some info on the epdm api, or any idea ? I appreciate that!

    ReplyDelete
    Replies
    1. Thanks for the question. There is a lot of detail behind what you've described so simply. My book, shown above, details out how to access variable values from a file in EPDM. You would then need to handle the entry of that data into your ERP system. You would also need to decide on a trigger. If you'd like a button, EPDM cards can have buttons that run an executable with arguments. Build your tool as a console application with arguments and you can run it from a button.

      Hope that helps get you started!

      Delete
    2. Thank you Mike for the feedback!
      As you said, I just described my question so simply, but at this time I want to start with the EPDM first. There are many possibilities to handle the entry of the data into the ERP system known as Abas (e.g. TCP/IP, hopefully will be the easiest). What do you mean by trigger ? Could you please elaborate it more ?

      Thanks again!
      P.S. I am planning to buy your book, now looking for cheaper price :)

      Delete
    3. This comment has been removed by the author.

      Delete
    4. Hi Mike,
      I hope you are doing fine, didn't hear from you since long. By the way, your book is in my hand and it is really helpful, easy and simple to use. Becaue of it my project is moved one step forward.
      At the moment, I have one question, I am able to access variable values from a file in EPDM, but not able to access the BOM of an assembly using the API, could you please give me a hint. This part seems not included in the book. For my project the PDM type is Enterprise not Workgroup. I am waiting for your kind response.
      I thank you in advance!

      Delete
    5. For your info, I am using the 2013 version.

      Delete
    6. Hello Awelkiyar,
      There is a new 11 page chapter in my 2015 edition of the book dedicated to EPDM BOMs. It will not be in the 2013 edition.

      The API Help has a good example of BOM access titled "Access Bill of Materials Example". It should give you a good start. The main calls are GetComputedBOM and GetDerivedBOMs from the IEdmFile7 interface.

      Delete
    7. This comment has been removed by the author.

      Delete
    8. Hi Mike,
      Thank you for your answer and the information. Good to hear that you new 2015 editon book.

      I have been playing with API Help examples about accessing bill of materials. But in my case I am deveoping an Add-in Application, the problem is initializaiton of the variable of type IEDMFile7 within my code. After this step I think it is easy to continue with the calls to GetComputedBOM and GetDerivedBOMs.

      I appreciate for any feedback.

      P.S. Just for information, the action of reading the BOM is occured after pressing a card button.

      Delete
    9. If you haven't found it yet, the add-in help topic describes the OnCmd procedure that runs whenever any EPDM hook is triggered. You can get to the file interface by utilizing the file ID which is a member of the ppoData argument (EdmCdmData type). Once you have the file ID, use the GetObject method of the Vault interface.

      It does take a few steps, but it is consistent with nearly every hook.

      Also, you are right about the code example I suggested. Its method of connecting to the file is different, but the logic for accessing BOM should be helpful, but more work is still needed to finish the process.

      Delete
  7. This comment has been removed by the author.

    ReplyDelete
  8. Thanks again for your feedback.
    After a little bit of work finally it is working perfectly. By the way, your feedback was helpful.

    Now I will start working on the erp side. But in case I have a question I will contact you again.

    ReplyDelete