Demystifying The Solid Works Api

Post on 21-Jan-2015

4.041 views 18 download

Tags:

description

SolidWorks World 2010 presentation by Paul Gimbel of Razorleaf. This session provides an introduction to programming with the SolidWorks API and how to work with the SolidWorks Object Model. Not a programmer? No problem. This session was designed to inspire you and guide you to get started.

Transcript of Demystifying The Solid Works Api

Demystifying the SolidWorks APIPaul Gimbel, Business Process Sherpa

Razorleaf Corporation

What You Will NOT Hear

• This is an INTRODUCTION to the SolidWorks API

• Examples – YES

• Syntax Details – NO

• Not a lesson on how to use the VBA or VSTA Interface

That’s a great idea for another session!

• Not a programming class

• Not designed for programmers

You won’t hear “Polymorphic Inheritence” used properly in a sentence

Slide 2 of 39,430,177

My Main Goal

I want you to leave here saying:

“I can do that!”

“That even looks like fun”

“That could save me time”

“I could really go for a burrito”

Who Is This Guy and Where Did He Come From?

• Razorleaf Corporation SolidWorks Service Partner

Services ONLY (we’re not trying to sell you anything, we’re neutral)

Data Management (EPDM, SmarTeam, Aras)

Design Automation (DriveWorks, Tacton)

Workflow Automation (Microsoft SharePoint and Tools)

• Paul Gimbel (aka “The Sherpa”) 10+ years as Demo Jock, Applications Engineer, Trainer, Support Tech

5 years as Design Automation Implementer

Specializing in SolidWorks, DriveWorks, Tacton, Custom Programming

• (THERE! Now I can report this trip as reimbursable.)

The Sherpa

Where Can I Find Programming?What Languages Can I Use?

• Macros: Scripts called from inside of SolidWorks to do things automatically

• Macro Features: Scripts run when at a point in the Feature Manager™

• Add-Ins: Programs called from inside of SolidWorks through a custom UI

• Companion Application: Another program’s macros can call SolidWorks

• Standalone Application: A program that you wrote can call SolidWorks

Code/Language VBA VB6 VB.NET C#.NET Pig Latin

Macros Macro Features Add-Ins Companion App Standalone App

FREE Visual Studio Express - http://www.microsoft.com/express/product/ (Use Coupon Code “RAZORLEAF”)

Why VB.NET?

This presentation uses VB.NET (VSTA) Macros

• Macro Recorder (2010) supports VBA, VB.NET, C#.NET

• All built into SolidWorks

• VBA and VSTA (Visual Studio Tools for Applications) development environments are included with SolidWorks

• VB.NET is the current version of VB

VBA is based on VB6 (1998 technology, Support ended 2008)

NOBODY uses VBA anymore…well, except Microsoft Office

Even AutoDesk dropped VBA out of AutoCAD products in January 2010

• Tons of examples are out there in VB, more than any other language

Most SolidWorks examples are in VBA (since they’re old)

• Not too difficult to convert from VBA to VB.NET

The Ultimate Process For Non-Programmers

1. Determine what you want your program/code snippet to do

2. Think of some “keywords” to describe it (if you know the functions you need to use, you’re ahead of the game)

3. http://www.google.com (add “VB” or “Visual Basic”)

4. Ctrl-C

5. Ctrl-V

6. Tweak

7. Test

8. Tweak

9. Test

10.Repeat steps 6-10 ad nauseum

Also look to VBA/VSTA and SW API Help files. They’re actually somewhat helpful with good examples.

I know! I was shocked, too.

Object-Oriented Programming**

“Everything you need to do in the SolidWorks API has to be done by or to an object.”

• Class – A definition (blueprint) of something (think: blank spec for a washer or bolt)

• Interface – A more generic definition incorporating multiple classes (ex. Hardware)

• Object – A specific instance of a class (completed spec - ex. 1/4-20 x 3 SHCS)

• Property – A parameter value that an object has (ex. Diameter)

• Method – Something (sub or function) that an object can do (ex. Install)

• Accessor – A method used to get an object (ex. GetFeature, GetChildren)

• Dot (.) –Separates an object from its property or method or “child” objects

Ex. Bolt.Length or Bolt.Thread.item(“Lead”).Pitch

• Instantiate – To make a real thing as defined by a class

Ex. Upper Flange Bolt #3 or Rear Axle Nut−Those are then called “instances” and “objects”

**To appease any true code junkies out there. VBA doesn’t REALLY support full OOP with inheritance and polymorphism, but this is a DEMYSTIFYING session. I don’t want to MYSTIFY this stuff any more than it is.

SolidWorks Objects

“Everything you need to do in the SolidWorks API has to be done by or to an object.”

• Everything in SolidWorks (even SolidWorks itself) has an object

• The SolidWorks Object Model is a hierarchy of objects/classes/interfaces

• You use an object higher in the tree to fetch an object “beneath” it (accessors)

Be prepared to go several steps down (objects beget objects beget objects…)

• Be VERY SPECIFIC as to what type of objects you have (fully qualified)

Easier to read

Easier to write (Microsoft will help you)

• Learn your way around the HELP file to figure out the object path you need

Throwing darts is most effective in many cases

The SolidWorks API Object Example (VBA)

Example: Creating a Hole Wizard Hole

Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swFeatMgr As SldWorks.FeatureManagerDim swFeat As SldWorks.FeatureDim swWzdHole As WizardHoleFeatureData2

Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swFeatMgr = swModel.FeatureManager…more code here…Set swWzdHole = swFeatMgr.CreateDefinition(swFmHoleWzd)swWzdHole.HoleDepth = 0.15swWzdHole.HoleDiameter = 0.0555…

Set swFeat = swFeatMgr.CreateFeature(swWzdHole)…more code here…

Early Bound Object Declarations aka “Fully Qualified” (+5 Style Points)

Object assignment (instantiation) requires the keyword Set in VBA only

HoleDepth and HoleDiameter are Properties of the WizardHoleFeatureData2 object

CreateDefinition and CreateFeature are Methods (functions)

Seek Professional HelpAn Interface Definition in the API Help

Seek Professional HelpAn Interface Definition in the API Help

Members = Properties and Methods

Seek Professional HelpAn Interface Definition in the API Help

Properties have Get and/or Set x = object.property (Get) object.property = x (Set)

Methods are actions an object performs

Seek Professional HelpAn Interface Definition in the API Help

This has Get only. It’s an accessor.

Seek Professional HelpAn Interface Definition in the API Help

This is no longer a property. It now uses methods to get and set it.(And forget it)

Seek Professional HelpAn Interface Definition in the API Help

Old functions never die…

The SolidWorks API Development Process

•Macro Record and Investigate

•Research in API Help and Google

•Get and Use SldWorks and ModelDoc2

•Get the right Object

•Get or Set property value / Kick off method

•Rebuild Model

•Save File

•Close any files or links

API SAMPLE #1Cycle Through All Configurations of a Part

What The Macro Does

• Grabs the current open part document (Works only for parts)

• Grabs a list of all of the configuration names

• Loops through the configurations one at a time

Changes the Material of the configuration

Saves a PDF of the configuration

Sets a configuration-specific custom property value

Important Concepts – Example 1

• Programmatic Framework

• Accessing Objects

• ModelDoc/PartDoc Objects

• Accessing / Looping Through Configurations

• Editing Material Properties

• SaveAs – Exporting File Formats

• Adding Custom Properties

The SolidWorks API Development Process

•Macro Record and Investigate

•Research in API Help and Google

•Get and Use SldWorks and ModelDoc2

•Get the right Object

•Get or Set property value / Kick off method

•Rebuild Model

•Save File

•Close any files or links

Macro Record (VB.NET) – 1 of 2

Imports SolidWorks.Interop.sldworks

Imports SolidWorks.Interop.swconst

Imports System

Partial Class SolidWorksMacro

  Public Sub main()

  Dim swDoc As ModelDoc2 = Nothing

Dim swPart As PartDoc = Nothing

Dim swDrawing As DrawingDoc = Nothing

Dim swAssembly As AssemblyDoc = Nothing

Dim boolstatus As Boolean = false

Dim longstatus As Integer = 0

Dim longwarnings As Integer = 0

swDoc = CType(swApp.ActiveDoc,ModelDoc2)

boolstatus = swDoc.Extension.SelectByID2("Unknown", "BROWSERITEM", 0, 0, 0, false, 0, Nothing, 0)

swDoc.ClearSelection2(true)

swPart = CType(swDoc,PartDoc)

swPart.SetMaterialPropertyName2("Copper", "C:/Program Files/SW/lang/english/sldmaterials/SolidWorks "& _

"Materials.sldmat", "Copper")

USELESS CONTENT

Legend

Macro Record (VB.NET) – 2 of 2

swDoc.ClearSelection2(true)

boolstatus = swDoc.Extension.SelectByID2("Brass", "CONFIGURATIONS", 0, 0, 0, false, 0, Nothing, 0)

boolstatus = swDoc.Extension.SelectByID2("Brass", "CONFIGURATIONS", 0, 0, 0, false, 0, Nothing, 0)

boolstatus = swDoc.Extension.SelectByID2("Brass", "CONFIGURATIONS", 0, 0, 0, false, 0, Nothing, 0)

boolstatus = swDoc.Extension.SelectByID2("Brass", "CONFIGURATIONS", 0, 0, 0, false, 0, Nothing, 0)

boolstatus = swDoc.ShowConfiguration2("Brass")

boolstatus = swDoc.Extension.SelectByID2("Unknown", "BROWSERITEM", 0, 0, 0, false, 0, Nothing, 0)

swDoc.ClearSelection2(true)

End Sub

 

''' <summary>

''' The SldWorks swApp variable is pre-assigned for you.

''' </summary>

Public swApp As SldWorks

 

End Class

This is SUCH an important variable that SolidWorks makes it PUBLIC (then stuffs it at the end where nobody sees it)

The Summary explains what the macro does and how it works (that’s why it’s shoved at the end like an afterthought)

Basic Framework (VB.NET)

Imports SolidWorks.Interop.sldworks

Imports SolidWorks.Interop.swconst

Partial Class SolidWorksMacro  ''' <summary>

''' Put a description, tracking and revision information here

''' </summary>

Public swApp As SldWorks

Public Sub main()

Your code goes here 

End Sub ‘main

End Class ‘SolidWorksMacro

!!!ALWAYS USE MACRO RECORD

OR TOOLS>MACRO>NEW!!!

S h o r t c u t

S h o r t c u t

(Final code does NOT

have these)

Basic Framework (VB.NET)

Imports SolidWorks.Interop.sldworks

Imports SolidWorks.Interop.swconst

Partial Class SolidWorksMacro  ''' <summary>

''' Put a description, tracking and revision information here

''' </summary>

Public swApp As SldWorks

Public Sub main()

Your code goes here 

End Sub ‘main

End Class ‘SolidWorksMacro

D O N O T R E N A M E H E R E

PARTIAL means there’s other stuff you don’t see…LOTS of it.

Renaming Classes

• If you feel that you MUST rename things

• Rename from the Project Explorer

• It will make the update where it needs to

Don’t believe me there’s lots you can’t see? Just click on SHOW

ALL.

Basic Framework (VB.NET)

Imports SolidWorks.Interop.sldworks

Imports SolidWorks.Interop.swconst

Partial Class SolidWorksMacro  ''' <summary>

''' Put a description, tracking and revision information here

''' </summary>

Public swApp As SldWorks

Public Sub main()

Your code goes here 

End Sub ‘main

End Class ‘SolidWorksMacro

MOVE THESE UP FROM THE BOTTOM

OF THE CLASS

The SolidWorks API Development Process

•Macro Record and Investigate

•Research in API Help and Google

•Get and Use SldWorks and ModelDoc2

•Get the right Object

•Get or Set property value / Kick off method

•Rebuild Model

•Save File

•Close any files or links

Do Your Research: HELP>API HELP

Keep Following The Trail

We’ve Got a Lead!

Variants have (rightly) been

BANNED from .NET

OK, Now To Find The Method

OK, Now To Find The Method

!! !!

!! !!

Elmo Count von Count Zoe Grover Q. Furrymonster0

20

40

60

80

100

120

Furry Quotient Vocal Squeal Relative Age Counting Ability Punchline % Confusion

Performance Characteristics of Key Muppets on Syndicated Educational Television Programs

Mandatory Charts (Gratuitous Chart of Fictitious Data)(per Microsoft PowerPoint code 2009 Section XXIV Subsection 441.K.9.ii.v)

Engineer Dietary Breakdown

Caffeine

Sugar

Vegetables

Foods ending with "-tos"

The SolidWorks API Development Process

•Macro Record and Investigate

•Research in API Help and Google

•Get and Use SldWorks and ModelDoc2

•Get the right Object

•Get or Set property value / Kick off method

•Rebuild Model

•Save File

•Close any files or links

Instantiating an Object Class

• Visual Basic.NET requires you to declare your variables

1. Declare…

PUBLIC variablename AS classname

DIM variablename AS classname2. Assign…

variablename = otherVariable.accessor()• Sometimes you need to guarantee the class

variablename = Ctype(oVar.accessor, Class)

variablename = DirectCast(oVar, Class)

Variables! Get Yer Variables Right Here!

• PUBLIC declare variables that can be used outside of the module

Useful for your SldWorks.SldWorks and ModelDoc objects

Macro Recorder puts these at the bottom, we recommend the top

• DIM or PRIVATE declares a variable for use within a function or sub

Imports SolidWorks.Interop.SldworksPartial Class SolidWorksMacro '''<Summary> '''Fill this in at some point

'''</Summary>

'Declare the SolidWorks application as global so it can be used throughout the class

Public swApp As SldWorks 'SW Application Object

Public Sub main()

Dim bStatus As Boolean = False ‘Used as SolidWorks return for most functions

Dim iErrors As Integer = 0 Dim iWarnings As Integer = 0 Dim ConfigNames() As String ‘The list of names that we’re going to get back

Declare and define in one step

You can define as you go

• Use swApp.ActiveDoc to grab currently open document

or ActivateDoc or OpenDoc7 or LoadFile4 or…

• Ctype guarantees that we’re getting a ModelDoc2 object

Check API for return, some return “object”

• ALWAYS TEST FOR PRESENCE OF AN OBJECT

'Grab the object for the Active SolidWorks Model

Dim swDoc As ModelDoc2

swDoc = CType(swApp.ActiveDoc, ModelDoc2)

'Make sure that we have a document object

'If we have no model document object to work with, we cannot go on

If swDoc Is Nothing Then Exit Sub

Got ModelDoc2?

got 3D?

Test Early, Test Often

What is ModelDoc2?...Part? Assembly? Drawing? Yup.

PartDoc Object MirrorPart

SetMaterialPropertyName2

AssemblyDoc Object

AddComponent

EditMate

DrawingDoc Object ActivateView

InsertWeldSymbol

ModelDoc2 Object CustomInfo

CreateLine

EditConfiguration

FeatureCut

FirstFeature

ForceRebuild

InsertNote

Parameter

SaveAs

SetUnits

SketchFillet

…everything else useful

ModelDoc2.Extension

CreateMeasure

GetAnnotations

InsertBomTable

SaveAs

SetUserPreferencex

…and lots more

Use ModelDoc2 to Get Configuration Names

• GetConfigurationNames returns an array of strings with our configuration names

• Test to make sure that we have names

• For Each…Next loop cycles through entries in an array

• We dimension new variables “inline” as we go

'Get the list of configuration names. This will be blank where it's not appropriate.

ConfigNames = swDoc.GetConfigurationNames

If ConfigNames.Length >= 1 Then

For Each ConfigName As String In ConfigNames

'Switch to the current configuration

bStatus = swDoc.ShowConfiguration2(ConfigName)

'Rebuild the Model

bStatus = swDoc.ForceRebuild3(True)(Next ConfigName – will be coming later)

Must be an array or collection of strings to use For Each …In…

These methods return a boolean (True/False) indicating success. We can (and should) test it.

The SolidWorks API Development Process

•Macro Record and Investigate

•Research in API Help and Google

•Get and Use SldWorks and ModelDoc2

•Get the right Object

•Get or Set property value / Kick off method

•Rebuild Model

•Save File

•Close any files or links

'Setting the Material is a method of the PartDoc object. We get that object by recasting the ModelDoc2 object.

'WE ONLY USE DIRECTCAST BECAUSE WE’VE TESTED swDoc.GetType. WE ARE CERTAIN IT IS A PART!!!

Dim swPart As PartDoc = DirectCast(swDoc, PartDoc)

…Back in the loop…

'Set the material property for this configuration. This assumes that the configuration name matches an existing material.

swPart.SetMaterialPropertyName2(ConfigName, “M:/RazorleafMatlLib/Materials.sldmat", ConfigName)

Get PartDoc and Change Materials

• We know that Material requires the PartDoc Object• PartDoc comes directly from ModelDoc2 (DirectCast)

• So do AssemblyDoc and DrawingDoc• If there’s a doubt, use Ctype (IF typeof swPart IS PartDoc…)

• WARNING!! You may suffer SEVERAL MILLISECONDS performance degradation!!

We want to do this outside the loop so we only do it once

Save the Model Out As a PDF

'Do a zoom to fit

swDoc.ViewZoomtofit2()

'Retrieve the full pathname including the file name

Dim sFileName As String = swDoc.GetPathName

'Remove the extension

sFileName = sFileName.Remove(sFileName.LastIndexOf(".")) 'remove all text after the last dot

bStatus = swDoc.Extension.SaveAs(sFileName & "_" & ConfigNames(index) & ".pdf", _

swSaveAsVersion_e.swSaveAsCurrentVersion, _

swSaveAsOptions_e.swSaveAsOptions_Silent, _

Nothing, iErrors, iWarnings)

enumerations

More return values, listed as ByRef in the Class Definition

_ means “Continued on next line” Must have a space before it

.NET string members, check ‘em out!

Enumerations

• Parameter values can be integer or long in many cases

• What is the integer for SolidWorks 2009?

• Enumerations replace numbers

• IMPORTS SolidWorks.Interop.swconst

That’s the Type Constant Library

My code fully qualifies

• Intellisense will help you if you fully qualify

• Enumerations are more readable

ByVal means inputByRef means output

Set Configuration-Specific Custom Property

swDoc.AddCustomInfo3(ConfigName, "Material Code", _

swCustomInfoType_e.swCustomInfoText, ConfigName.Remove(4))

Next ConfigName 'move to the next configuration

End If 'there are one or more configurations in the document

End Sub ‘main

End Class ‘SolidWorksMacro

• AddCustomInfo3 allows you to specify a configuration

• Be sure to comment your loop and IF closers

Documenting here makes blocks easier to follow and troubleshoot

Another kewl .NET string function

CONFIGURATION MASTER 5000 Complete Code

Final Code: Configuration Master 5000 (Part 1 of 5)

Partial Class SolidWorksMacro

'''<Summary>

'''Sample Code for SolidWorks World 2010: Demystifying the SolidWorks API

'''Razorleaf Corporation -- Paul Gimbel -- January 20, 2010

'''This macro loops through all of the configurations of a part

'''For each configuration, it saves a PDF, changes the material of the configuration and adds a configuration-specific custom property

'''See the Powerpoint Presentation (available from www.razorleaf.com) for complete documentation of the code

'''</Summary>

'Declare the SolidWorks application as a global variable so it can be used throughout the class

Public swApp As SolidWorks.Interop.sldworks.SldWorks 'SolidWorks Application Object

Public Sub main()

Dim bStatus As Boolean = False

Dim iErrors As Integer = 0

Dim iWarnings As Integer = 0

Dim ConfigNames() As String

Final Code: Configuration Master 5000 (Part 2 of 5)

'Grab the object for the Active SolidWorks Model

Dim swDoc As SolidWorks.Interop.sldworks.ModelDoc2 = CType(swApp.ActiveDoc, SolidWorks.Interop.sldworks.ModelDoc2)

'Make sure that we got a document object

If swDoc Is Nothing Then Exit Sub 'We have no model document to work with, we cannot go on

'This macro is only for part models. Check what type of document we have.

If swDoc.GetType <> SolidWorks.Interop.swconst.swDocumentTypes_e.swDocPART Then Exit Sub

'Get the list of configuration names. This will be blank where it's not appropriate.

ConfigNames = swDoc.GetConfigurationNames

'Setting the Material is a method of the PartDoc object. We get that object by recasting the ModelDoc2 object.

'WE ONLY USE DIRECTCAST BECAUSE WE HAVE ALREADY TESTED swDoc.GetType. WE ARE CERTAIN IT IS A PART!!!

Dim swPart As SolidWorks.Interop.sldworks.PartDoc = DirectCast(swDoc, SolidWorks.Interop.sldworks.PartDoc)

If ConfigNames.Length >= 1 Then

For Each ConfigName As String In ConfigNames

'Switch to the current configuration

bStatus = swDoc.ShowConfiguration2(ConfigNames(index))

Final Code: Configuration Master 5000 (Part 3 of 5)

''<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

''Drive the material to be equal to the configuration name

''<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

'Set the material property for this configuration. This assumes that the configuration name matches an existing material.

swPart.SetMaterialPropertyName2(ConfigNames(index), _

"C:/Program Files/SolidWorks Corp/SolidWorks/lang/english/sldmaterials/SolidWorks " & "Materials.sldmat", _

ConfigNames(index))

Final Code: Configuration Master 5000 (Part 4 of 5)

''<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

''Save this configuration out as a PDF

''<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

'Do a zoom to fit

swDoc.ViewZoomtofit2()

'Retrieve the full pathname including the file name

Dim sFileName As String = swDoc.GetPathName

'Remove the extension

sFileName = sFileName.Remove(sFileName.LastIndexOf(".")) 'remove from the location of the last dot on to the end

bStatus = swDoc.Extension.SaveAs(sFileName & "_" & ConfigNames(index) & ".pdf", _

SolidWorks.Interop.swconst.swSaveAsVersion_e.swSaveAsCurrentVersion, _

SolidWorks.Interop.swconst.swSaveAsOptions_e.swSaveAsOptions_Silent, _

Nothing, iErrors, iWarnings)

Final Code: Configuration Master 5000 (Part 5 of 5)

''<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

''Create a configuration specific custom property -

'' Material Code = 1st 4 letters of the material

''<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

'Setting the Material is a method of the PartDoc object. We get that object by recasting the ModelDoc2 object.

swDoc.AddCustomInfo3(ConfigNames(index), "Material Code", _

SolidWorks.Interop.swconst.swCustomInfoType_e.swCustomInfoText, _

ConfigNames(index).Remove(4))

Next ConfigName 'move to the next configuration

End If 'there are one or more configurations in the document

End Sub ‘main

End Class ‘SolidWorksMacro

The SolidWorks API Development Process

•Macro Record and Investigate

•Research in API Help and Google

•Get and Use SldWorks and ModelDoc2

•Get the right Object

•Get or Set property value / Kick off method

•Rebuild Model

•Save File

•Close any files or links

API EXAMPLE #2Suppressing Pattern Instances

Delete Pattern Instances

• Part has one or more linear patterns

• Custom property stores a text string of Xs and Os

X means there will be an instance here

O means that instance will be removed

• Main Errors to check for:

No pattern features

No instance to suppress

Text string length ≠ Number of pattern instances

XOOXXOXOOXOXOOXOXOOXOXOO

Important Concepts – Example 2

• Accessing Feature objects

• Looping through all features in a part

• Handling FeatureData objects

• Reading custom properties

The SolidWorks API Development Process

•Macro Record and Investigate

•Research in API Help and Google

•Get and Use ModelDoc2

•Get the right Object

•Get or Set property value / Kick off method

•Rebuild Model

•Save File

•Close any files or links

Recorded Macro: Remove Pattern Instances

Public Sub main()

Dim swDoc As ModelDoc2 = Nothing

Dim swPart As PartDoc = Nothing

Dim swDrawing As DrawingDoc = Nothing

Dim swAssembly As AssemblyDoc = Nothing

Dim boolstatus As Boolean = false

Dim longstatus As Integer = 0

Dim longwarnings As Integer = 0

swDoc = CType(swApp.ActiveDoc,ModelDoc2)

Dim myModelView As ModelView = Nothing

myModelView = CType(swDoc.ActiveView,ModelView)

myModelView.FrameState = CType(swWindowState_e.swWindowMaximized,Integer)

boolstatus = swDoc.Extension.SelectByID2("HolePattern", "BODYFEATURE", …)

swDoc.ClearSelection2(true)

boolstatus = swDoc.Extension.SelectByID2("", "EDGE", -0.04, 0.0127,…)

boolstatus = swDoc.Extension.SelectByID2("", "EDGE", -0.1016, …)

swDoc.ActivateSelectedFeature()

End Sub

HELPFUL CONTENT

Legend

The SolidWorks API Development Process

•Macro Record and Investigate

•Research in API Help and Google

•Get and Use ModelDoc2

•Get the right Object

•Get or Set property value / Kick off method

•Rebuild Model

•Save File

•Close any files or links

Seek the Path of Enlightenment

How do we get the info we need out of the object?

How do we get the object?

Find The Right Property or Method

OK, So How Do We Get The Object, Then?

Accessors List

IFeature.ILinearPatternFeatureData.SkippedItemArray

Let’s limit it to just ModelDoc2 and PartDoc

Once you have a feature, you

can use it to get the next one

The Full Object Path

Feature

ModelDoc2

LinearPatternFeatureData

Feature IS Linear Pattern

Feature IS NOT Linear Pattern

The SolidWorks API Development Process

•Macro Record and Investigate

•Research in API Help and Google

•Get and Use ModelDoc2

•Get the right Object

•Get or Set property value / Kick off method

•Rebuild Model

•Save File

•Close any files or links

Set up the Framework and Grab the ModelDoc2

IMPORTS SolidWorks.Interop.sldworksIMPORTS SolidWorks.Interop.swconstPartial Class SolidWorksMacro ''' <summary> ''' Don’t forget to put this in at some point!! ''' </summary> Public swApp As SldWorks

Public Sub main()

‘A nice description here goes a long way!

'Get currently open document Dim swPart As ModelDoc2 = CType(swApp.ActiveDoc, ModelDoc2)

'Make sure that we have an object If swDoc Is Nothing Then Exit Sub

'This macro is only for part models. Check our document type.

If swDoc.GetType <> swDocumentTypes_e.swDocPART Then Exit Sub

The SolidWorks API Development Process

•Macro Record and Investigate

•Research in API Help and Google

•Get and Use ModelDoc2

•Get the right Object

•Get or Set property value / Kick off method

•Rebuild Model

•Save File

•Close any files or links

Test for Proper Conditions and Get Feature Object

'Fetch the custom property list Dim sInputList As String = swDoc.GetCustomInfoValue("", "SkipList")

'If the list does not exist, exit out of the function. We do not need to run the macro.

If sInputList.Length < 1 Then Exit Sub

'Get the first feature in the part.

'NOTE!! THIS DOES NOT MEAN THE BASE EXTRUSION. 'There are reference features.

Dim swFeature As Feature swFeature = swDoc.FirstFeature()

Look how far down the tree the base extrusion is!

Declare as you define

Always put your tests up front - Try to run as little code as possible

Loop the Loop

'We know from our research that we'll need the LinearPatternFeatureData ' object, the feature type, and some indices.

'We'll declare them outside of the loop so they only get declared once.

Dim swFeatureData As LinearPatternFeatureData Dim sFeatureType As String 'Type of feature Dim iRows As Integer 'Number of rows in the pattern Dim iCols As Integer 'Number of columns in the pattern Dim TempString As String = ""

Do While swFeature IsNot Nothing 'loop through the features

…OUR CODE GOES HERE…

Loop

Got an object? IsNot Nothing will tell you

DO WHILE tests BEFORE running any code(Do … Loop Until tests after)

Looping and Testing

Do While swFeature IsNot Nothing 'loop through the features

'Check to see if this is a pattern feature sFeatureType = swFeature.GetTypeName2

If sFeatureType = "LPattern" Then 'we have a pattern to process

swFeatureData = swFeature.GetDefinition 'get the feature data

iRows = swFeatureData.D1TotalInstances iCols = swFeatureData.D2TotalInstances

'Check to ensure that list matches pattern size If sInputList.Length = iRows * iCols Then 'we're good to go

… The actual work goes here…

End If 'The list length matches the pattern size End If 'This is a linear pattern feature

Loop 'through the features

Test Early, Test O

ften

Browse API Helpto see properties

Arrays and Collections

•Array Think of it as a bin system for values

Can be 1D, 2D or more

It’s a fixed size (you need to REDIM to change it)

Tough to move things around in

•Collection Think of it as a collection of stackable bins

Need another? Just add it!

Rearranging, sorting, searching…no prob, Bob!

Don’t know collections? Take the time to look them up!!

63

28

24

27

93

211

610

19

40

25

63

57

Numbering Sequence for Linear Pattern Instances

SEED = 0 (Row 1, Col 1)

(2, 1)=1

(3, 1)=2

(4, 1)=3

(5, 1)=4

7

8

9

5

6

12

13

14

10

11

17

18

19

15

16

22

23

24

20

21

Create the Skipped Instance Array

'Create a collection for the list of instances to be skippedDim SkipCol As New System.Collections.Generic.List(Of Integer)

'Go through the characters in the string finding the O's and add that index

For Index As Integer = 0 To sInputList.Length - 1 If sInputList.Substring(Index, 1).Equals _ ("O", StringComparison.CurrentCultureIgnoreCase) Then

'add this to the list of excluded items SkipCol.Add(Index) End If 'we need to add this entry to the skipped list

Next Index 'move to the next character in the string

How can I remember that?!!?

You don’t. Intellisense gives

it to you!

String method .Equals

Substrings start at 0

The input list “XXOOXOXO”……results in the collection: (2,3,5,7)

0 1 2 3 4 5 6 7

Update the Feature and Error Handling

'pass the collection as an array to the LinearPatternFeatureData object

swFeatureData.SkippedItemArray = SkipCol.ToArray()

'Tell SolidWorks to update the LinearPattern with the new information

swFeature.ModifyDefinition(swFeatureData, swDoc, Nothing)

'Rebuild the model swPart.ForceRebuild3(False)

Else 'the input size doesn't match the pattern size

DIM sMessage As String = "Pattern Size " & (iRows * iCols) & " doesn’t match input size " & sInputList.Length

System.Windows.Forms.MessageBox.Show(sMessage)

swPart.AddCustomInfo3("", "Code Errors", 30, sMessage)

End If 'the input size matches the pattern size

One of many collection methods

These methods are subs, no returns

& joins strings and values“I’m “ & iAge & “ years old”

= “I am 4257 years old”

THE AMAZING DISAPPEARING PATTERN INSTANCE TRICK

Complete Code

Finished Code (Part 1 of 4)

Partial Class SolidWorksMacro

''' <summary> '''Sample Code #2 for SolidWorks World 2010: Demystifying the SolidWorks API '''Razorleaf Corporation -- Paul Gimbel -- January 20, 2010 '''This macro removes instances within a linear pattern based on a string input of X's and O's stored in a custom property.

'''The code loops through all of the features of a part looking for linear patterns. '''For each linear pattern that it finds, it compares the input string length to the pattern size. '''If the string matches the pattern, the code builds the SkippedInstanceArray and updates the pattern.

'''See the Powerpoint Presentation (available from www.razorleaf.com) for complete documentation of the code

''' </summary>

Dim swApp As SolidWorks.Interop.sldworks.SldWorks

Public Sub main()

'Reads a list stored as a string from a custom property named "SkipList" (populated by DriveWorks)

'This list will contain an "X" if the pattern instance is to be there and an "O" (Letter Oh) if it is to be removed

'The list walks down a column, then starts at the next column, just as SolidWorks does 'When Skipping, the instances are numbered as such (Row,Col): ' (1,1) = 0, (2,1) = 1, (3,1) = 2 ' For a 3x3 array, (1,2) = 3, (2,2) = 4 and so on.

'Get currently open document Dim swPart As SolidWorks.Interop.sldworks.ModelDoc2 = CType(swApp.ActiveDoc, SolidWorks.Interop.sldworks.ModelDoc2)

Finished Code (Part 2 of 4)

'Fetch the custom property list Dim sInputList As String = swPart.GetCustomInfoValue("", "SkipList") 'If the list does not exist, exit out of the function. We do not need to run the macro. If sInputList.Length < 1 Then Exit Sub

'Get the first feature in the part. NOTE!! THIS DOES NOT MEAN THE BASE EXTRUSION. There are reference features.

Dim swFeature As SolidWorks.Interop.sldworks.Feature = swPart.FirstFeature()

'We know from our research that we'll need the LinearPatternFeatureData object, the feature type, and some indices.

'We'll declare them outside of the loop so that they only get declared once. Dim swFeatureData As SolidWorks.Interop.sldworks.LinearPatternFeatureData Dim sFeatureType As String 'Type of feature to test to see if it's a linear pattern Dim iRows As Integer 'Number of rows in the pattern Dim iCols As Integer 'Number of columns in the pattern Dim TempString As String = ""

Do While swFeature IsNot Nothing 'loop through the features checking to see if the feature is a pattern

'Check to see if this is a pattern feature sFeatureType = swFeature.GetTypeName2 If sFeatureType = "LPattern" Then 'we have a pattern to process swFeatureData = swFeature.GetDefinition 'get the feature information object iRows = swFeatureData.D1TotalInstances 'get the information that we want iCols = swFeatureData.D2TotalInstances

'Check to ensure that list matches pattern size If sInputList.Length = iRows * iCols Then 'we're good to go

Finished Code (Part 3 of 4)

'Create a collection for the list of instances to be skipped Dim SkipCol As New System.Collections.Generic.List(Of Integer)

'Go through the collection finding the O's and add the index of that character to the collection

For Index As Integer = 0 To sInputList.Length - 1 'cycle through the characters in the string

If sInputList.Substring(Index, 1).Equals("O", StringComparison.CurrentCultureIgnoreCase) Then

'add this to the list of excluded items SkipCol.Add(Index) TempString = TempString & CStr(Index) End If 'we need to add this entry to the skipped list Next Index 'move to the next character in the string

'Convert the collection into an array and pass it to the LinearPatternFeatureData object

swFeatureData.SkippedItemArray = SkipCol.ToArray()

'Tell SolidWorks to update the LinearPattern with the new information swFeature.ModifyDefinition(pFeatureData, pPart, Nothing)

Else 'the input size doesn't match the pattern size

'During testing you can have it pop up a message box 'System.Windows.Forms.MessageBox.Show _

' ("Pattern Size (" & iRows * iCols & ") does not match input size (" & Len(sInputList) & ")")

'During Production, have it write the error to a custom property swPart.AddCustomInfo3("", "Code Errors", 30, "Pattern Size (" & iRows * iCols & ") does not match input size (" & sInputList.Length & ")")

Finished Code (Part 4 of 4)

End If 'there are the correct number of entries in the list End If 'this is a pattern feature

'Go fetch the next feature swFeature = swFeature.GetNextFeature

Loop 'while pFeature IsNot Nothing

End Sub 'main

End Class 'PARTIAL SolidWorksMacro

PROGRAMMING BEST PRACTICES

What Not To Wear: SolidWorks API Edition

Programming Tips For SolidWorks

• DOCUMENT THE $#^@ OUT OF EVERYTHING!!!

Anything after an apostrophe in VB (‘) or (//) in C# is a comment…use them!!

• Intellisense…good. Typing…bad.

If you don’t see the option that you need, something’s wrong.

• Test for Errors

Don’t run code if you don’t have to

Runtime errors make you look like a doofus

• Compile and Test Often

Programmatic sanity checks

Insert Test Code (Debug.Print, msgbox, extraneous IF’s you can comment out)

• Use Debug Tools

Step Into, Step Over, Watches, Breakpoints, Immediate window, Stack trace, …

Errors/Warnings window at the bottom IS YOUR FRIEND!!

Documenting Your Code - Comments

• VB will ignore anything after an apostrophe (‘)

• C# will ignore anything after two forward slashes (//)

• The editor will turn all comments green

• Turn your code into complete sentences

If swSensor.SensorType = swSensorDimension Then ‘find the dimension

Else ‘we need to see if this is a mass property sensor

End If ‘this is a dimension sensor

• Keep track of the end of nested loops and if statements (don’t miss them!)End If ‘the width is over the threshold value

End If ‘the width is greater than the length

• Create section headers (Visual Studio has tools for this as well)

‘Set all of the hole wizard feature parameters

Early Binding and Fully Qualifying – Great Practices

• Option Explicit in VBA (implicit in VB.NET and C#.NET)

• DIM swFeature As Object

Perfectly legal (with IMPORTS), but sloppy

• DIM swFeature As SolidWorks.Interop.sldWorks.Feature = swPart.GetFirstFeature

Better documented

Will catch more errors

Enables Intellisense

Error Trapping

• End Users do NOT take errors well

• Small errors can snowball

• TRY…CATCH

• OnErrorGoto errhandler

errhandler:

If err.number > 0 Then ‘we have an error, deal with it

msgbox(“You have a problem with ” & err.description)

End If ‘we have an error

• ALWAYS test for objects

If swFeature IsNot NOTHING Then ‘we have a feature, go

• Watch for data types and illegal values (negatives, zeroes, “artichoke”, etc.)

• Look for anything that will make your code or SolidWorks barf

Go Hungarian!

Arg

ume

nts Ag

ainst H

N

Violent objection?Don’t use it.

• Hungarian Notation places the data type at the front of the variable name

Examples:−Dim iCounter as Integer

−Dim bResult as Boolean

−Dim dLength as Double

−Dim swApp as SolidWorks.Interop.SldWorks.SldWorks – (here “sw” indicates it’s a SolidWorks object)

• Microsoft (and Bob) now recommends against it – The Sherpa recommends it!!

• But Visual Studio Intellisense tells you the data type, it’s redundant

VBA doesn’t have that feature

Neither does my printer

• What if the data type changes!??!!?

Find/Replace – It’s 5 clicks

• If you always declare your variables, it’s documented

So I have to scroll to the top every time?

Code You Should Know

• Loops (DO, WHILE, FOR, FOR EACH)

• IF…THEN…ELSEIF…ELSE (with AND, OR, NOT)

• SELECT CASE

• WITH Blocks

• Msgbox

• String Manipulation (.Length , .Remove, .Substring, .Trim, …)

• CHR()

• Collections and Arrays

• Exit Sub (-5 Style Points, but it’s cheap and easy)

• Err Object

• Math (ABS, Trig, SQRT, Int)

• File I/O (Write, Print, Input, LineInput, Open Append/Output, Close)

• DB Access (ODBC, ADODB, DAO)

WHAT ELSE CAN THE API DO?API and Beyooooooooooond

API Areas

• APIs exist for tons of SolidWorks Modules

Automating Design Validation - Tomorrow @ 1:30

• Integrate with other programs

Automating With Excel – Wednesday @ 1:30

MathCAD or custom calculation engines

Read from/Write to your ERP or other system

• Allow less-sophisticated users to use advanced features

Build an interface for non-SolidWorks users that drives SolidWorks

• Cut mouse clicks out of your day

• Automate iterative processes

Build the model, run a test, use results to rebuild, run a test, again…

Macro Features - How Will YOU Use Them?

• Two Steps: 1) Write the macro, 2) Write a macro to insert the macro

• Macro feature appears in the SolidWorks Feature Manager™

• Macro is executed based on its position in the Feature Manager™

• Code is contained in an SWP file or a registered application* on your machine

*For the advanced: code must be in an exposed COM DLL or executable

Everyone must have access to this code to be able to use it

• Your code contains 2-4 functions

What to do when the macro feature is created (optional)

What to do when the macro feature is rebuilt (mandatory)

What to do when the macro feature is edited (mandatory)

Can feature be deleted, suppressed or edited (VBA = optional, COM = mandatory)

If you use multiple (older) versions of SolidWorks and wish to use Macro Features, check out the API Help article on Macro Features and Strong Name Versioning

Questions? Comments? Suggestions? Amusing Pet Stories?

• If you have questions you would like to discuss, please find me

Now…At any time during the conference…or After the conference

• Presentation available on www.razorleaf.com

Free newsletter with tech tips, industry insiders, free code, and more…

• Catch me in my upcoming tour dates!!

Tuesday @ 1:30 – Automating Design Validation with the SolidWorks API

Wednesday @ 1:30 – Automating Your Designs with Excel and the SW API

Paul GimbelBusiness

Process Sherpapaul.gimbel@razorleaf.com www.razorleaf.com TheProcesSherpa on Twitter

The Sherpa

• PLEASE PLEASE PLEASE fill out your survey

• It takes practically no time at all

• I HONESTLY want your feedback and I do apply it

• Let’s see if the SolidWorks folks read these:

SURVEY TIME!!!

• PLEASE PLEASE PLEASE fill out your survey

• It takes practically no time at all

• I HONESTLY want your feedback and I DO apply it

• Let’s see if the SolidWorks folks read these:

In the comments section, PLEASE end with:

“Wow, he was right. These burritos are quite tasty!”

Paul Gimbel, Razorleaf Corporationpaul.gimbel@razorleaf.com

@TheProcesSherpa on Twitter