Building a Console Application in VB for the Alibre Design API E-mail
Article Index
Building a Console Application in VB for the Alibre Design API
Getting Started
Create a Visual Basic Project
Referencing the Alibre Design API
Importing Namespaces
Adding Comments
Setting Up Command Line Flags
Reading the Command Line Arguments
Redirecting the Standard Output
Hooking Alibre Design
Looping Through Sessions
Looping Through Configurations
Finishing Up
Resources
All Pages
This tutorial will guide you through creating a simple console application (a command line application) in VB.NET that integrates with Alibre Design through the Alibre Design API. A console application does not have a Windows GUI (Graphical User Interface) -- it is intended to be run from a command line (such as a C:\> prompt) or called from another application such as Macro Express. This is a beginner level tutorial.

How to Support This Site

Tutorials like these take a good deal of time and energy, and as you can probably imagine, the audience is quite small. There are a couple of ways you can support these efforts, but the easiest way to do it is to help this site grow by browsing the articles and applications, and encouraging your friends and associates to do the same.

You can also click on "Donate Now" in the yellow "Help Me Go To College" area to make a monetary contribution. (These donations are safe and secure and go into my childrens' college funds.) I have a lot of applications, articles, and links online, so if you see something you like, please contribute and spread the word! Thank you!

If you like this article, you might also like these related articles:


Getting Started

To follow along with this tutorial you will need to have Alibre Design (or Alibre Design Xpress) installed and running on your machine. You will also need to have a Microsoft Visual Studio product such as Visual Basic Express, which is available from Microsoft free of charge, at least for a limited time.

If you don't already have these tools, pick up one of the Visual Studio Express book/CD bundles listed below and download Alibre Design Xpress from Alibre. Or, for more functionality, you can buy the full versions here:

The application we'll create in this tutorial will list all of the open Alibre Design sessions (parts, assemblies, drawings) and their configurations either to a text file or to the screen, optionally including counts of those sessions and configurations.

For more detailed instruction on Visual Basic in general, here are some excellent book and references to get you started. I highly recommend the book/CD bundles, because they often contain searchable text, example code and additional features.


Create a Visual Basic Project

This would be a good time to tell some friends about this site if you haven't already done so!

Launch Visual Basic and select New > Project... from the File menu to create a new Visual Basic application project. Browse through the project types and templates and select a Visual Basic project type and the template for Console Application. In the Name field, replace the default name (probably "WindowsApplication1") with "MyApp" and choose an appropriate location for the project in the next field. Then click OK to create the project.

You should now see a nearly blank document window that has just four lines of text including "Module Module1", "Sub Main()" and a couple others. We're pretty much going to write this application from scratch.

For more detailed instruction on the Visual Studio IDE (integrated development environment), here are a couple of great resources. These books can be difficult to find because most Visual Studio books focus primarily one of the supported programming languages.


Referencing the Alibre Design API

Your application needs to know that you want it to communicate with Alibre Design. This communication takes place through a technology called COM (pronounced like "kahm" as a word instead of spelled). You make your application aware of Alibre Design by "adding a reference" to the Alibre Design COM-compliant components already installed on your system.

From the Project menu, select "Add Reference..." and click on the COM tab so show all the COM compliant components that are registered on your computer. Scroll down to select "Alibre Automation Type Library" from the list and then click OK to add the reference.


Importing Namespaces

Many programming languages use the concept of namespaces as a way to organize and fully qualify bits of functionality. Think of namespaces as a way to "drill down" from very general to very specific categories in order to find the functionality you want. For example, you might be looking for a function called "Drive" which might exist in more than one place. The programming language will require you to fully qualify which "Drive" function you want so that it knows what bits of code to run. You can do this by continually typing in the fully qualified name (e.g. "Transportation.Automobile.Drive" or "Games.Golf.Drive"), or if you know you're only going to use only one of these namespaces, you can use the Imports keyword to give the computer a default set of namespaces to work within.

At the top of the page (above "Module Module1"), use the Imports keyword to tell the computer which namespaces you'll be using in this application. (Don't type the numbers and colons -- they're just there to help you see the line numbers we're on.)

Imports AlibreX
Imports System.IO
Imports System.Runtime.InteropServices

The AlibreX namespace contains functionality specific to Alibre Design, the System.IO namespace allows us to output data to a file, and the System.Runtime.InteropServices namespace allows us to contact Alibre Design through COM.


Adding Comments

Comments make code easier to read and help you remember what you were thinking and doing when you revisit your code later. They don't hurt the performance of the application at all, so it's wise to include as many comments as necessary to tell the whole story.

In Visual Basic you indicate that a line will be a comment by starting it with an apostrophe or single quote.

Add a comment right above "Sub Main()" that describes how we intend this application to be called. In this case we're looking for some command line arguments, so this line will provide an example of how it can be called. It should look something like this when you're done.

Module Module1
  ' Use the form "MyApp.exe -out:D:\MyOutput.txt -conf -count"
  Sub Main()


Setting Up Command Line Flags

From the comment above, you can see that we're going to be looking for a couple of very specific command line flags to either enable or disable program functionality. We'll write a few lines to declare these flags as strings so we don't have to keep retyping them in the program.

    ' What arguments are we looking for?
    Dim outPathFlag As String = "-out:"
    Dim configurationFlag As String = "-conf"
    Dim countFlag As String = "-count"

Now that we'll be able to identify the command line arguments by these specific flags, we need to set up some variables that give meaning to the flags within our program. In the first case, we want to store the characters immediately following the "-out:" flag, if included on the command line, as the path and filename where we want to save the output of the program. We'll store it in a string called "outPath". In the next two cases, all the program really cares about is whether or not these flags were present on the command line. So, we'll set up a Boolean (a True/False value) and give it the default value of False. In the next section of code, we're change this to True if we came across the appropriate flag on the command line.

    ' This is where we'll store the arguments
    Dim outPath As String = ""
    Dim includeConfigurations As Boolean = False
    Dim includeCount As Boolean = False


Reading the Command Line Arguments

Now it's time to see if any of the command line arguments we specified above were present when the program was run. We do this by systematically looking at each of the arguments that were passed in, and comparing them to the arguments that our program cares about -- the ones we defined above. The block of code between the "For Each" line and the "Next" line will be run once for each argument on the command line. Each time it's run, we'll be able to use the variable "s" to look at the command line argument we're currently examining.

In all cases, we're converting the command line argument to lower case, then seeing if it starts with one of the flags we defined in lines 11-13. If we get a match, the computer will run the code between the appropriate "If" and "End If" lines. In the first case, we're essentially removing the flag from the argument and storing the remainder of the string into the variable "outPath". This leaves us with only the path and filename that was included after the flag (e.g. "D:\MyOutput.txt"). In the last two cases, we're simple setting the boolean values defined in lines 17-18 to true if the command link flag was found.

    ' Read and parse the command line arguments
    For Each s As String In My.Application.CommandLineArgs
      If s.ToLower.StartsWith(outPathFlag) Then
        outPath = s.Remove(0, outPathFlag.Length)
      End If
      If s.ToLower.StartsWith(configurationFlag) Then
        includeConfigurations = True
      End If
      If s.ToLower.StartsWith(countFlag) Then
        includeCount = True
      End If
      ' More here if necessary...
    Next


Redirecting the Standard Output

The next bit of code will redirect any output that would have normally gone to the screen to a file instead -- but only if we have an output path to use. If an output path or the "-out:" flag wasn't included as a command line argument, then the output will just go to the screen.

    ' Redirect standard out to filestream
    Dim outStream As StreamWriter
    If outPath.Length > 0 Then
      outStream = New StreamWriter(outPath)
      Console.SetOut(outStream)
    End If


Hooking Alibre Design

Now we need to contact Alibre Design through COM. Be sure that Alibre Design is currently running on your system when you start this application. The "Root" in this case is basically the top-level Alibre Design application -- like the Home window -- and it allows us to do things such as displaying the Alibre Design version number (line 46).

    ' Hook Alibre Design
    Dim hook As AutomationHook = _
      Marshal.GetActiveObject("AlibreX.AutomationHook")
    Dim root As IADRoot = hook.Root

    ' Write out the "Version:" then the Alibre Design version
    Call Console.WriteLine("Version: " & root.version)


Looping Through Sessions

Now let's loop through all the sessions that Alibre Design has loaded into memory. Think of a session (what Alibre Design's API calls "IADSession") as all the things that are in common about an Alibre Design document (part, assembly, etc.). For example, all types of Alibre Design document have a name that's displayed in the Alibre Design's title bar, and they can all be loaded from disk and saved again.

In lines 49-50 we create a couple of variables that we can use to count up the total number of sessions and configurations. In line 54 we start looping through all the sessions, and in line 54 we make sure the session is opened up somewhere in an Alibre Design window.

If it is opened up in an Alibre Design GUI, then we output the name of the session (Remember that at this point the output might either be going to the screen or to a file. [See lines 34-39.]), increment the session counter by one, and reset the configuration counter back to zero. We need to reset the configuration counter back to zero at this point because we're going to be re-using this variable in the next bit of code to count up the total number of configurations per session.

    ' Search through all the sessions.
    Dim sessionCount As Integer = 0
    Dim configCount As Integer = 0
    For Each session As IADSession In root.Sessions

      ' Be sure it's a visible GUI
      If session.IsGUIVisible Then

        ' Write out the name
        Call Console.WriteLine("Name: " & session.Name)
        sessionCount = sessionCount + 1
        configCount = 0


Looping Through Configurations

Next, if we got the "-conf" flag on the command line (lines 12, 17, 25-27, 62), then we go ahead and loop through all of the configurations associated with the session. In order to do this, though, we need to treat the current session we're examining as an IADDesignSession (line 63). Whereas an IADSession contains all the functionality that are in common about an Alibre Design document, an IADDesignSession is all the things that are in common about a design workspace (part or assembly) -- things like planes, points, tolerances, etc. It's the IADDesignSession that has a set of configurations.

This would be another really good time to tell some friends or associates about this site. If you've gotten this far you're obviously interested, so why not help out a bit by browsing around and spreading the word? =)

Lines 64-68 loop through the configurations, output the configuration name and type, and increment the configuration counter. Then in lines 69-71 we output the count, but only if we had originally received the "-count" flag as a command line argument.

        ' Write out the configurations if required
        If includeConfigurations Then
          Dim ds As IADDesignSession = session
          For Each configuration As IADConfiguration _
              In ds.Configurations
            Call Console.WriteLine("  " & configuration.Name _
              & " (" & configuration.Type.ToString() & ")")
            configCount = configCount + 1
          Next
          If includeCount Then
            Call Console.WriteLine("  Count: " & configCount)
          End If
        End If

One thing I should point out before I get too many emails on this, is that there's more than one way to do almost everything. For example, I could have just as easily gotten the total number of configurations by using "ds.Configurations.Count". That shortcut wouldn't have worked for sessions, though, because in this case we're only counting those sessions that are in a visible GUI.

Next we need to "close" the "If" on line 54 and continue with the "For Each" on line 51.

      End If
    Next


Finishing Up

At this point we've looped through all the visible sessions and output information about them and their configurations. This is a good time to output the session count we were maintaining and close the file we might have opened back in line 37. We need line 80, though, because we should only try to close the file if we did in fact open it -- otherwise we could get an error.

    If includeCount Then
      Call Console.WriteLine("Session Count: " & sessionCount)
    End If

    If Not outStream Is Nothing Then
      Call outStream.Close()
    End If

Now let's be good citizens and tell Microsoft's .Net Framework that we're finished communicating with another application through COM. Because setting up the COM communication channels takes up some memory in the computer, we can also tell the .Net Framework that it's free to clean up memory we're no longer using.

    ' Clean up a bit...
    Call Marshal.ReleaseComObject(hook)
    Call GC.GetTotalMemory(True)

Finally, we can end the program.

  End Sub

End Module


Resources

If you want to dive a bit deeper into API programming, here are some good (more advanced) books to keep you busy. I've also included some advanced books covering CAD, computational geometry, and geometric modeling for the very courageous. =)

Last Updated ( Monday, 28 January 2008 16:22 )