|
Building a Console Application in VB for the Alibre Design API An introduction to building console applications that use the Alibre Design API using Visual Basic.
All images, text and code is ©1995-2009 by Alex Franke. All rights reserved. Published: Jul 18, 2006 Updated: Oct 28, 2006
In this article:
Getting Started
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.
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:
| Alibre Design & Visual Studio - Mouse over & click | 
| 
| 
| ![Microsoft Visual Studio Standard 2005 [OLD VERSION]](http://ecx.images-amazon.com/images/I/417J8577ZBL._SL75_.jpg)
| ![Microsoft Visual Studio Professional 2005 [OLD VERSION]](http://ecx.images-amazon.com/images/I/41KCTS1WWQL._SL75_.jpg)
|
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.)
1: Imports AlibreX
2: Imports System.IO
3: Imports System.Runtime.InteropServices
4:
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.
5: Module Module1
6:
7: ' Use the form "MyApp.exe -out:D:\MyOutput.txt -conf -count"
8: Sub Main()
9:
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.
10: ' What arguments are we looking for?
11: Dim outPathFlag As String = "-out:"
12: Dim configurationFlag As String = "-conf"
13: Dim countFlag As String = "-count"
14:
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.
15: ' This is where we'll store the arguments
16: Dim outPath As String = ""
17: Dim includeConfigurations As Boolean = False
18: Dim includeCount As Boolean = False
19:
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.
20: ' Read and parse the command line arguments
21: For Each s As String In My.Application.CommandLineArgs
22: If s.ToLower.StartsWith(outPathFlag) Then
23: outPath = s.Remove(0, outPathFlag.Length)
24: End If
25: If s.ToLower.StartsWith(configurationFlag) Then
26: includeConfigurations = True
27: End If
28: If s.ToLower.StartsWith(countFlag) Then
29: includeCount = True
30: End If
31: ' More here if necessary...
32: Next
33:
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.
34: ' Redirect standard out to filestream
35: Dim outStream As StreamWriter
36: If outPath.Length > 0 Then
37: outStream = New StreamWriter(outPath)
38: Console.SetOut(outStream)
39: End If
40:
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).
41: ' Hook Alibre Design
42: Dim hook As AutomationHook = Marshal.GetActiveObject("AlibreX.AutomationHook")
43: Dim root As IADRoot = hook.Root
44:
45: ' Write out the "Version:" then the Alibre Design version
46: Call Console.WriteLine("Version: " & root.version)
47:
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.
48: ' Search through all the sessions.
49: Dim sessionCount As Integer = 0
50: Dim configCount As Integer = 0
51: For Each session As IADSession In root.Sessions
52:
53: ' Be sure it's a visible GUI
54: If session.IsGUIVisible Then
55:
56: ' Write out the name
57: Call Console.WriteLine("Name: " & session.Name)
58: sessionCount = sessionCount + 1
59: configCount = 0
60:
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.
61: ' Write out the configurations if required
62: If includeConfigurations Then
63: Dim ds As IADDesignSession = session
64: For Each configuration As IADConfiguration In ds.Configurations
65: Call Console.WriteLine(" " & configuration.Name _
66: & " (" & configuration.Type.ToString() & ")")
67: configCount = configCount + 1
68: Next
69: If includeCount Then
70: Call Console.WriteLine(" Count: " & configCount)
71: End If
72: 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.
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.
76: If includeCount Then
77: Call Console.WriteLine("Session Count: " & sessionCount)
78: End If
79:
80: If Not outStream Is Nothing Then
81: Call outStream.Close()
82: End If
83:
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.
84: ' Clean up a bit...
85: Call Marshal.ReleaseComObject(hook)
86: Call GC.GetTotalMemory(True)
87:
Finally, we can end the program.
88: End Sub
89:
90: 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. =)
|