SlideShare a Scribd company logo
1 of 90
Demystifying the SolidWorks API Paul 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  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
Macro Myths Macros are in VBA No Forms/Dialogs Cannot be automated Require you to preselect Cannot handle advanced functionality (like classes)
The Ultimate Process For Non-Programmers Determine what you want your program/code snippet to do Think of some “keywords” to describe it (if you know the functions you need to use, you’re ahead of the game) http://www.google.com (add “VB” or “Visual Basic”) Ctrl-C Ctrl-V Tweak Test Tweak Test Repeat steps 6-10 ad nauseum Also check out www.krugle.org  and www.sourceforge.net 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) 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 Example: Creating a Hole Wizard Hole Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swFeatMgr As SldWorks.FeatureManager Dim swFeat As SldWorks.Feature Dim swWzdHole As WizardHoleFeatureData2 Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swFeatMgr = swModel.FeatureManager …more code here… Set swWzdHole = swFeatMgr.CreateDefinition(swFmHoleWzd) swWzdHole.HoleDepth = 0.15 swWzdHole.HoleDiameter = 0.0555 … Set swFeat = swFeatMgr.CreateFeature(swWzdHole) …more code here… 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
API Sample #1 Cycle 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 (VB.NET) – 1 of 2 Legend 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
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 SldWorksswApp variable is pre-assigned for you.     ''' </summary> Public swApp As SldWorks   End Class The Summary explains what the macro does and how it works (that’s why it’s shoved at the end like an afterthought) This is SUCH an important variable that SolidWorks makes it PUBLIC (then stuffs it at the end where nobody sees it)
Basic Framework (VB.NET) (Final code does NOT have these) 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 Shortcut Shortcut !!!ALWAYS Use  macro record  or  Tools>Macro>New!!!
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 DO NOT RENAME HERE 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
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 !! !! !! !!
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)
The SolidWorks API Development Process
Instantiating an Object Class Visual Basic.NET requires you to declare your variables Declare… PUBLICvariablenameASclassname DIMvariablenameASclassname 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.Sldworks Partial Class SolidWorksMacro '''<Summary>     	  '''Fill this in at some point     '''</Summary>     'Declare the SolidWorks application as global so it can be used throughout the class PublicswApp As SldWorks'SW Application Object PublicSub main() DimbStatusAs Boolean = False   ‘Used as SolidWorks return for most functions DimiErrorsAs Integer = 0 DimiWarningsAs Integer = 0 DimConfigNames() AsString‘The list of names that we’re going to get back Declare and define in one step You can define as you go
You’ve Declared, Now Define SET Keyword is not required for VB.NET or C#.NET (a must in VBA) Macro Record or Tools>Macro>New will get your SolidWorks object for you 3 Methods of instantiating your SldWorks.SldWorks Object (VBA) swApp = Application.SldWorks Grabs existing application (open session REQUIRED) OK to use in macros swApp = GetObject( , “SldWorks.Application”) First parameter is a pathname of file to open Second parameter is object class Must have one or the other If no pathname is specified and SolidWorks is not open, error will occur swApp = CreateObject(“SldWorks.Application”) Grabs open SolidWorks application If no SolidWorks application is open, starts a SolidWorks instance
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 DimswDocAs 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 IfswDocIs 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 ,[object Object]
CreateLine
EditConfiguration
FeatureCut
FirstFeature
ForceRebuild
InsertNote
Parameter
SaveAs
SetUnits
SketchFillet
…everything else usefulModelDoc2.Extension ,[object Object]
GetAnnotations
InsertBomTable
SaveAs
SetUserPreferencex
…and lots more,[object Object]
The SolidWorks API Development Process
Get PartDoc and Change Materials ,[object Object]
PartDoc comes directly from ModelDoc2 (DirectCast)
So do AssemblyDoc and DrawingDoc
If there’s a doubt, use Ctype (IF typeofswPart IS PartDoc…)
WARNING!! You may suffer SEVERAL MILLISECONDS performance degradation!!'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!!! DimswPartAsPartDoc = 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) 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 DimsFileNameAsString = 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) .NET string members, check ‘em out! _ means “Continued on next line”     Must have a space before it enumerations More return values, listed as ByRef in the Class Definition
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 input ByRef means output
Set Configuration-Specific Custom Property ,[object Object]
Be sure to comment your loop and IF closers                  swDoc.AddCustomInfo3(ConfigName, "Material Code", _ swCustomInfoType_e.swCustomInfoText, ConfigName.Remove(4)) NextConfigName'move to the next configuration End If 'there are one or more configurations in the document End Sub ‘main End Class ‘SolidWorksMacro Another kewl .NET string function Documenting here makes blocks easier to follow and troubleshoot
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 PublicswApp As SolidWorks.Interop.sldworks.SldWorks    'SolidWorks Application Object PublicSub main() DimbStatusAs Boolean = False DimiErrorsAs Integer = 0 DimiWarningsAs Integer = 0 DimConfigNames() AsString
Final Code: Configuration Master 5000 (Part 2 of 5)         'Grab the object for the Active SolidWorks Model DimswDocAs SolidWorks.Interop.sldworks.ModelDoc2 = CType(swApp.ActiveDoc, SolidWorks.Interop.sldworks.ModelDoc2)         'Make sure that we got a document object IfswDocIs 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. IfswDoc.GetType <> SolidWorks.Interop.swconst.swDocumentTypes_e.swDocPARTThen 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!!! DimswPartAsSolidWorks.Interop.sldworks.PartDoc = DirectCast(swDoc, SolidWorks.Interop.sldworks.PartDoc)           If ConfigNames.Length >= 1 Then For Each ConfigNameAs 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 DimsFileNameAsString = 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)) NextConfigName'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
API Example #2 Suppressing 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
Recorded Macro: Remove Pattern Instances Legend    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
The SolidWorks API Development Process
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 ModelDoc2 Feature Feature IS Linear Pattern Feature IS NOT Linear Pattern LinearPattern FeatureData
The SolidWorks API Development Process
Set up the Framework and Grab the ModelDoc2 IMPORTS SolidWorks.Interop.sldworks IMPORTS SolidWorks.Interop.swconst Partial Class SolidWorksMacro ''' <summary>     ''' Don’t forget to put this in at some point!!     ''' </summary> PublicswAppAsSldWorks Public Sub main() ‘A nice description here goes a long way! 'Get currently open document DimswPartAs ModelDoc2 = CType(swApp.ActiveDoc, ModelDoc2) 'Make sure that we have an object IfswDocIs Nothing Then Exit Sub     'This macro is only for part models. Check our document type. IfswDoc.GetType <> swDocumentTypes_e.swDocPARTThen Exit Sub
The SolidWorks API Development Process
Test for Proper Conditions and Get Feature Object 'Fetch the custom property list DimsInputListAs 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. DimswFeatureAs Feature  swFeature = swDoc.FirstFeature() Declare as you define Always put your tests up front - Try to run as little code as possible Look how far down the tree the base extrusion is!
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. DimswFeatureDataAsLinearPatternFeatureData DimsFeatureTypeAs String      'Type of feature DimiRowsAs Integer            'Number of rows in the pattern DimiColsAs Integer            'Number of columns in the pattern DimTempStringAs String = "" 		Do While swFeatureIsNotNothing'loop through the features           …OUR CODE GOES HERE… Loop DO WHILE tests BEFORE running any code (Do … Loop Until tests after) Got an object?  IsNot Nothing will tell you

More Related Content

What's hot

SolidWorks Modeling for Design Automation
SolidWorks Modeling for Design AutomationSolidWorks Modeling for Design Automation
SolidWorks Modeling for Design AutomationRazorleaf Corporation
 
Introduction to finite element analysis
Introduction to finite element analysisIntroduction to finite element analysis
Introduction to finite element analysisTarun Gehlot
 
Design of Hydraulic Scissor lift.pdf
Design of Hydraulic Scissor lift.pdfDesign of Hydraulic Scissor lift.pdf
Design of Hydraulic Scissor lift.pdfmeet kalola
 
Design considerations and engineering materials
Design considerations and engineering materialsDesign considerations and engineering materials
Design considerations and engineering materialsHimanshi Gupta
 
FEA good practices presentation
FEA good practices presentationFEA good practices presentation
FEA good practices presentationMahdi Damghani
 
ME6603 - FINITE ELEMENT ANALYSIS UNIT - IV NOTES AND QUESTION BANK
ME6603 - FINITE ELEMENT ANALYSIS UNIT - IV NOTES AND QUESTION BANKME6603 - FINITE ELEMENT ANALYSIS UNIT - IV NOTES AND QUESTION BANK
ME6603 - FINITE ELEMENT ANALYSIS UNIT - IV NOTES AND QUESTION BANKASHOK KUMAR RAJENDRAN
 
General steps of the finite element method
General steps of the finite element methodGeneral steps of the finite element method
General steps of the finite element methodmahesh gaikwad
 
Dimensions of metric hex nuts
Dimensions of metric hex nutsDimensions of metric hex nuts
Dimensions of metric hex nutstejasudas
 
The Development of Design by Topology Optimization for Additive Manufacture
The Development of Design by Topology Optimization for Additive ManufactureThe Development of Design by Topology Optimization for Additive Manufacture
The Development of Design by Topology Optimization for Additive ManufactureCallum McLennan
 
Fatigue Life from Sine-on-Random Excitation
Fatigue Life from Sine-on-Random ExcitationFatigue Life from Sine-on-Random Excitation
Fatigue Life from Sine-on-Random ExcitationAltair
 
Hydraulic Scissor Lift PPT
Hydraulic Scissor Lift PPTHydraulic Scissor Lift PPT
Hydraulic Scissor Lift PPTMechXplain
 
ME6603 - FINITE ELEMENT ANALYSIS UNIT - III NOTES AND QUESTION BANK
ME6603 - FINITE ELEMENT ANALYSIS UNIT - III NOTES AND QUESTION BANKME6603 - FINITE ELEMENT ANALYSIS UNIT - III NOTES AND QUESTION BANK
ME6603 - FINITE ELEMENT ANALYSIS UNIT - III NOTES AND QUESTION BANKASHOK KUMAR RAJENDRAN
 
Angular Contact Ball Bearings Id
Angular Contact Ball Bearings IdAngular Contact Ball Bearings Id
Angular Contact Ball Bearings IdIONEL DUTU
 
A way to reduce mass of gearbox housing
A way to reduce mass of gearbox housingA way to reduce mass of gearbox housing
A way to reduce mass of gearbox housingAltair
 

What's hot (20)

SolidWorks Modeling for Design Automation
SolidWorks Modeling for Design AutomationSolidWorks Modeling for Design Automation
SolidWorks Modeling for Design Automation
 
Introduction to finite element analysis
Introduction to finite element analysisIntroduction to finite element analysis
Introduction to finite element analysis
 
Unit 2 design of shaft
Unit 2 design of shaftUnit 2 design of shaft
Unit 2 design of shaft
 
Design of Hydraulic Scissor lift.pdf
Design of Hydraulic Scissor lift.pdfDesign of Hydraulic Scissor lift.pdf
Design of Hydraulic Scissor lift.pdf
 
Body in White
Body in WhiteBody in White
Body in White
 
Design considerations and engineering materials
Design considerations and engineering materialsDesign considerations and engineering materials
Design considerations and engineering materials
 
Engine Thesis
Engine ThesisEngine Thesis
Engine Thesis
 
FEA good practices presentation
FEA good practices presentationFEA good practices presentation
FEA good practices presentation
 
ME6603 - FINITE ELEMENT ANALYSIS UNIT - IV NOTES AND QUESTION BANK
ME6603 - FINITE ELEMENT ANALYSIS UNIT - IV NOTES AND QUESTION BANKME6603 - FINITE ELEMENT ANALYSIS UNIT - IV NOTES AND QUESTION BANK
ME6603 - FINITE ELEMENT ANALYSIS UNIT - IV NOTES AND QUESTION BANK
 
General steps of the finite element method
General steps of the finite element methodGeneral steps of the finite element method
General steps of the finite element method
 
Brochure_BIW
Brochure_BIWBrochure_BIW
Brochure_BIW
 
Bolted joint design
Bolted joint designBolted joint design
Bolted joint design
 
Dimensions of metric hex nuts
Dimensions of metric hex nutsDimensions of metric hex nuts
Dimensions of metric hex nuts
 
The Development of Design by Topology Optimization for Additive Manufacture
The Development of Design by Topology Optimization for Additive ManufactureThe Development of Design by Topology Optimization for Additive Manufacture
The Development of Design by Topology Optimization for Additive Manufacture
 
Fatigue Life from Sine-on-Random Excitation
Fatigue Life from Sine-on-Random ExcitationFatigue Life from Sine-on-Random Excitation
Fatigue Life from Sine-on-Random Excitation
 
Hydraulic Scissor Lift PPT
Hydraulic Scissor Lift PPTHydraulic Scissor Lift PPT
Hydraulic Scissor Lift PPT
 
ME6603 - FINITE ELEMENT ANALYSIS UNIT - III NOTES AND QUESTION BANK
ME6603 - FINITE ELEMENT ANALYSIS UNIT - III NOTES AND QUESTION BANKME6603 - FINITE ELEMENT ANALYSIS UNIT - III NOTES AND QUESTION BANK
ME6603 - FINITE ELEMENT ANALYSIS UNIT - III NOTES AND QUESTION BANK
 
Angular Contact Ball Bearings Id
Angular Contact Ball Bearings IdAngular Contact Ball Bearings Id
Angular Contact Ball Bearings Id
 
A way to reduce mass of gearbox housing
A way to reduce mass of gearbox housingA way to reduce mass of gearbox housing
A way to reduce mass of gearbox housing
 
Creo Demo
Creo DemoCreo Demo
Creo Demo
 

Similar to Demystifying The Solid Works Api

Robotlegs on Top of Gaia
Robotlegs on Top of GaiaRobotlegs on Top of Gaia
Robotlegs on Top of GaiaJesse Warden
 
JavaOne TS-5098 Groovy SwingBuilder
JavaOne TS-5098 Groovy SwingBuilderJavaOne TS-5098 Groovy SwingBuilder
JavaOne TS-5098 Groovy SwingBuilderAndres Almiray
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)Jose Manuel Pereira Garcia
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e bigAndy Peterson
 
닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기YoungSu Son
 
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..Mark Rackley
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderAndres Almiray
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsMark Rackley
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
MobiConf 2018 | Room: an SQLite object mapping library
MobiConf 2018 | Room: an SQLite object mapping library MobiConf 2018 | Room: an SQLite object mapping library
MobiConf 2018 | Room: an SQLite object mapping library Magda Miu
 
Advisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptAdvisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptdominion
 
SharePoint Saturday St. Louis - SharePoint & jQuery
SharePoint Saturday St. Louis - SharePoint & jQuerySharePoint Saturday St. Louis - SharePoint & jQuery
SharePoint Saturday St. Louis - SharePoint & jQueryMark Rackley
 
Mobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve MobileMobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve MobileKonstantin Loginov
 
JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4alexsaves
 
Dojo: Getting Started Today
Dojo: Getting Started TodayDojo: Getting Started Today
Dojo: Getting Started TodayGabriel Hamilton
 

Similar to Demystifying The Solid Works Api (20)

Automating Analysis with the API
Automating Analysis with the APIAutomating Analysis with the API
Automating Analysis with the API
 
Robotlegs on Top of Gaia
Robotlegs on Top of GaiaRobotlegs on Top of Gaia
Robotlegs on Top of Gaia
 
JavaOne TS-5098 Groovy SwingBuilder
JavaOne TS-5098 Groovy SwingBuilderJavaOne TS-5098 Groovy SwingBuilder
JavaOne TS-5098 Groovy SwingBuilder
 
IOC + Javascript
IOC + JavascriptIOC + Javascript
IOC + Javascript
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기
 
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilder
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
MobiConf 2018 | Room: an SQLite object mapping library
MobiConf 2018 | Room: an SQLite object mapping library MobiConf 2018 | Room: an SQLite object mapping library
MobiConf 2018 | Room: an SQLite object mapping library
 
Advisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptAdvisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScript
 
Spsemea j query
Spsemea   j querySpsemea   j query
Spsemea j query
 
SharePoint Saturday St. Louis - SharePoint & jQuery
SharePoint Saturday St. Louis - SharePoint & jQuerySharePoint Saturday St. Louis - SharePoint & jQuery
SharePoint Saturday St. Louis - SharePoint & jQuery
 
Mobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve MobileMobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve Mobile
 
JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4
 
Dojo: Getting Started Today
Dojo: Getting Started TodayDojo: Getting Started Today
Dojo: Getting Started Today
 

More from Razorleaf Corporation

COE 2017: Your first 3DEXPERIENCE customization
COE 2017: Your first 3DEXPERIENCE customizationCOE 2017: Your first 3DEXPERIENCE customization
COE 2017: Your first 3DEXPERIENCE customizationRazorleaf Corporation
 
Three Approaches to Integration that Deliver Greater PLM Value
Three Approaches to Integration that Deliver Greater PLM ValueThree Approaches to Integration that Deliver Greater PLM Value
Three Approaches to Integration that Deliver Greater PLM ValueRazorleaf Corporation
 
Discovering New Product Introduction (NPI) using Autodesk Fusion Lifecycle
Discovering New Product Introduction (NPI) using Autodesk Fusion LifecycleDiscovering New Product Introduction (NPI) using Autodesk Fusion Lifecycle
Discovering New Product Introduction (NPI) using Autodesk Fusion LifecycleRazorleaf Corporation
 
COE 2016 Live demo How to get to full Digitalization
COE 2016 Live demo How to get to full DigitalizationCOE 2016 Live demo How to get to full Digitalization
COE 2016 Live demo How to get to full DigitalizationRazorleaf Corporation
 
COE 2016: Technical Data Migration Made Simple
COE 2016: Technical Data Migration Made SimpleCOE 2016: Technical Data Migration Made Simple
COE 2016: Technical Data Migration Made SimpleRazorleaf Corporation
 
Autdoesk PLM 360 to PDM Integration with Jitterbit
Autdoesk PLM 360 to PDM Integration with JitterbitAutdoesk PLM 360 to PDM Integration with Jitterbit
Autdoesk PLM 360 to PDM Integration with JitterbitRazorleaf Corporation
 
DriveWorks World 2016 - 13 lessons in 12 years
DriveWorks World 2016  - 13 lessons in 12 yearsDriveWorks World 2016  - 13 lessons in 12 years
DriveWorks World 2016 - 13 lessons in 12 yearsRazorleaf Corporation
 
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (Tech Paper)
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (Tech Paper)AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (Tech Paper)
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (Tech Paper)Razorleaf Corporation
 
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (PPT)
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (PPT)AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (PPT)
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (PPT)Razorleaf Corporation
 
AU 2014: Autodesk PLM 360 Success Story with Inphi (PPT)
AU 2014: Autodesk PLM 360 Success Story with Inphi (PPT)AU 2014: Autodesk PLM 360 Success Story with Inphi (PPT)
AU 2014: Autodesk PLM 360 Success Story with Inphi (PPT)Razorleaf Corporation
 
AU 2014: Autodesk PLM 360 Success Story with Inphi (TECH PAPER)
AU 2014: Autodesk PLM 360 Success Story with Inphi (TECH PAPER)AU 2014: Autodesk PLM 360 Success Story with Inphi (TECH PAPER)
AU 2014: Autodesk PLM 360 Success Story with Inphi (TECH PAPER)Razorleaf Corporation
 
Deploying DriveWorks Throughout the Organization
Deploying DriveWorks Throughout the OrganizationDeploying DriveWorks Throughout the Organization
Deploying DriveWorks Throughout the OrganizationRazorleaf Corporation
 
3DVIA Composer for Assembly Instruction Storyboards
3DVIA Composer for Assembly Instruction Storyboards3DVIA Composer for Assembly Instruction Storyboards
3DVIA Composer for Assembly Instruction StoryboardsRazorleaf Corporation
 
Connecting SolidWorks EPDM and ENOVIA V6
Connecting SolidWorks EPDM and ENOVIA V6Connecting SolidWorks EPDM and ENOVIA V6
Connecting SolidWorks EPDM and ENOVIA V6Razorleaf Corporation
 
Solving Iterative Design Problems with TactonWorks
Solving Iterative Design Problems with TactonWorksSolving Iterative Design Problems with TactonWorks
Solving Iterative Design Problems with TactonWorksRazorleaf Corporation
 
COE2010 Razorleaf ENOVIA SmarTeam and V6 Readiness
COE2010 Razorleaf ENOVIA SmarTeam and V6 ReadinessCOE2010 Razorleaf ENOVIA SmarTeam and V6 Readiness
COE2010 Razorleaf ENOVIA SmarTeam and V6 ReadinessRazorleaf Corporation
 

More from Razorleaf Corporation (20)

COE 2017: Your first 3DEXPERIENCE customization
COE 2017: Your first 3DEXPERIENCE customizationCOE 2017: Your first 3DEXPERIENCE customization
COE 2017: Your first 3DEXPERIENCE customization
 
COE 2017: Atomic Content
COE 2017: Atomic ContentCOE 2017: Atomic Content
COE 2017: Atomic Content
 
Three Approaches to Integration that Deliver Greater PLM Value
Three Approaches to Integration that Deliver Greater PLM ValueThree Approaches to Integration that Deliver Greater PLM Value
Three Approaches to Integration that Deliver Greater PLM Value
 
Discovering New Product Introduction (NPI) using Autodesk Fusion Lifecycle
Discovering New Product Introduction (NPI) using Autodesk Fusion LifecycleDiscovering New Product Introduction (NPI) using Autodesk Fusion Lifecycle
Discovering New Product Introduction (NPI) using Autodesk Fusion Lifecycle
 
COE 2016 Live demo How to get to full Digitalization
COE 2016 Live demo How to get to full DigitalizationCOE 2016 Live demo How to get to full Digitalization
COE 2016 Live demo How to get to full Digitalization
 
COE 2016: Technical Data Migration Made Simple
COE 2016: Technical Data Migration Made SimpleCOE 2016: Technical Data Migration Made Simple
COE 2016: Technical Data Migration Made Simple
 
COE 2016: 10 Cool Tools for 2016
COE 2016: 10 Cool Tools for 2016COE 2016: 10 Cool Tools for 2016
COE 2016: 10 Cool Tools for 2016
 
ENOVIA v6 R2013x Tips and Tricks
ENOVIA v6 R2013x Tips and TricksENOVIA v6 R2013x Tips and Tricks
ENOVIA v6 R2013x Tips and Tricks
 
Autdoesk PLM 360 to PDM Integration with Jitterbit
Autdoesk PLM 360 to PDM Integration with JitterbitAutdoesk PLM 360 to PDM Integration with Jitterbit
Autdoesk PLM 360 to PDM Integration with Jitterbit
 
DriveWorks World 2016 - 13 lessons in 12 years
DriveWorks World 2016  - 13 lessons in 12 yearsDriveWorks World 2016  - 13 lessons in 12 years
DriveWorks World 2016 - 13 lessons in 12 years
 
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (Tech Paper)
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (Tech Paper)AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (Tech Paper)
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (Tech Paper)
 
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (PPT)
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (PPT)AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (PPT)
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (PPT)
 
AU 2014: Autodesk PLM 360 Success Story with Inphi (PPT)
AU 2014: Autodesk PLM 360 Success Story with Inphi (PPT)AU 2014: Autodesk PLM 360 Success Story with Inphi (PPT)
AU 2014: Autodesk PLM 360 Success Story with Inphi (PPT)
 
AU 2014: Autodesk PLM 360 Success Story with Inphi (TECH PAPER)
AU 2014: Autodesk PLM 360 Success Story with Inphi (TECH PAPER)AU 2014: Autodesk PLM 360 Success Story with Inphi (TECH PAPER)
AU 2014: Autodesk PLM 360 Success Story with Inphi (TECH PAPER)
 
Deploying DriveWorks Throughout the Organization
Deploying DriveWorks Throughout the OrganizationDeploying DriveWorks Throughout the Organization
Deploying DriveWorks Throughout the Organization
 
3DVIA Composer for Assembly Instruction Storyboards
3DVIA Composer for Assembly Instruction Storyboards3DVIA Composer for Assembly Instruction Storyboards
3DVIA Composer for Assembly Instruction Storyboards
 
Connecting SolidWorks EPDM and ENOVIA V6
Connecting SolidWorks EPDM and ENOVIA V6Connecting SolidWorks EPDM and ENOVIA V6
Connecting SolidWorks EPDM and ENOVIA V6
 
Automating SolidWorks with Excel
Automating SolidWorks with ExcelAutomating SolidWorks with Excel
Automating SolidWorks with Excel
 
Solving Iterative Design Problems with TactonWorks
Solving Iterative Design Problems with TactonWorksSolving Iterative Design Problems with TactonWorks
Solving Iterative Design Problems with TactonWorks
 
COE2010 Razorleaf ENOVIA SmarTeam and V6 Readiness
COE2010 Razorleaf ENOVIA SmarTeam and V6 ReadinessCOE2010 Razorleaf ENOVIA SmarTeam and V6 Readiness
COE2010 Razorleaf ENOVIA SmarTeam and V6 Readiness
 

Recently uploaded

Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

Demystifying The Solid Works Api

  • 1. Demystifying the SolidWorks API Paul Gimbel, Business Process Sherpa Razorleaf Corporation
  • 2. 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
  • 3. 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”
  • 4. 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
  • 5. 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 FREE Visual Studio Express - http://www.microsoft.com/express/product/ (Use Coupon Code “RAZORLEAF”)
  • 6. 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
  • 7. Macro Myths Macros are in VBA No Forms/Dialogs Cannot be automated Require you to preselect Cannot handle advanced functionality (like classes)
  • 8. The Ultimate Process For Non-Programmers Determine what you want your program/code snippet to do Think of some “keywords” to describe it (if you know the functions you need to use, you’re ahead of the game) http://www.google.com (add “VB” or “Visual Basic”) Ctrl-C Ctrl-V Tweak Test Tweak Test Repeat steps 6-10 ad nauseum Also check out www.krugle.org and www.sourceforge.net Also look to VBA/VSTA and SW API Help files. They’re actually somewhat helpful with good examples. I know! I was shocked, too.
  • 9. 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.
  • 10. 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
  • 11. The SolidWorks API Object Example (VBA) 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 Example: Creating a Hole Wizard Hole Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swFeatMgr As SldWorks.FeatureManager Dim swFeat As SldWorks.Feature Dim swWzdHole As WizardHoleFeatureData2 Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swFeatMgr = swModel.FeatureManager …more code here… Set swWzdHole = swFeatMgr.CreateDefinition(swFmHoleWzd) swWzdHole.HoleDepth = 0.15 swWzdHole.HoleDiameter = 0.0555 … Set swFeat = swFeatMgr.CreateFeature(swWzdHole) …more code here… CreateDefinition and CreateFeature are Methods (functions)
  • 12. Seek Professional HelpAn Interface Definition in the API Help
  • 13. Seek Professional HelpAn Interface Definition in the API Help Members = Properties and Methods
  • 14. 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
  • 15. Seek Professional HelpAn Interface Definition in the API Help This has Get only. It’s an accessor.
  • 16. 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)
  • 17. Seek Professional HelpAn Interface Definition in the API Help Old functions never die…
  • 18. The SolidWorks API Development Process
  • 19. API Sample #1 Cycle Through All Configurations of a Part
  • 20. 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
  • 21. 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
  • 22. The SolidWorks API Development Process
  • 23. Macro Record (VB.NET) – 1 of 2 Legend 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
  • 24. 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 SldWorksswApp variable is pre-assigned for you. ''' </summary> Public swApp As SldWorks   End Class The Summary explains what the macro does and how it works (that’s why it’s shoved at the end like an afterthought) This is SUCH an important variable that SolidWorks makes it PUBLIC (then stuffs it at the end where nobody sees it)
  • 25. Basic Framework (VB.NET) (Final code does NOT have these) 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 Shortcut Shortcut !!!ALWAYS Use macro record or Tools>Macro>New!!!
  • 26. 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 DO NOT RENAME HERE PARTIAL means there’s other stuff you don’t see…LOTS of it.
  • 27. 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.
  • 28. 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
  • 29. The SolidWorks API Development Process
  • 30. Do Your Research: HELP>API HELP
  • 32. We’ve Got a Lead! Variants have (rightly) been BANNED from .NET
  • 33. OK, Now To Find The Method
  • 34. OK, Now To Find The Method !! !! !! !!
  • 35. 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)
  • 36. The SolidWorks API Development Process
  • 37. Instantiating an Object Class Visual Basic.NET requires you to declare your variables Declare… PUBLICvariablenameASclassname DIMvariablenameASclassname Assign… variablename = otherVariable.accessor() Sometimes you need to guarantee the class variablename = Ctype(oVar.accessor, Class) variablename = DirectCast(oVar, Class)
  • 38. 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.Sldworks Partial Class SolidWorksMacro '''<Summary> '''Fill this in at some point '''</Summary> 'Declare the SolidWorks application as global so it can be used throughout the class PublicswApp As SldWorks'SW Application Object PublicSub main() DimbStatusAs Boolean = False ‘Used as SolidWorks return for most functions DimiErrorsAs Integer = 0 DimiWarningsAs Integer = 0 DimConfigNames() AsString‘The list of names that we’re going to get back Declare and define in one step You can define as you go
  • 39. You’ve Declared, Now Define SET Keyword is not required for VB.NET or C#.NET (a must in VBA) Macro Record or Tools>Macro>New will get your SolidWorks object for you 3 Methods of instantiating your SldWorks.SldWorks Object (VBA) swApp = Application.SldWorks Grabs existing application (open session REQUIRED) OK to use in macros swApp = GetObject( , “SldWorks.Application”) First parameter is a pathname of file to open Second parameter is object class Must have one or the other If no pathname is specified and SolidWorks is not open, error will occur swApp = CreateObject(“SldWorks.Application”) Grabs open SolidWorks application If no SolidWorks application is open, starts a SolidWorks instance
  • 40. 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 DimswDocAs 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 IfswDocIs Nothing Then Exit Sub Got ModelDoc2? got 3D? Test Early, Test Often
  • 41.
  • 52.
  • 57.
  • 58. The SolidWorks API Development Process
  • 59.
  • 60. PartDoc comes directly from ModelDoc2 (DirectCast)
  • 61. So do AssemblyDoc and DrawingDoc
  • 62. If there’s a doubt, use Ctype (IF typeofswPart IS PartDoc…)
  • 63. WARNING!! You may suffer SEVERAL MILLISECONDS performance degradation!!'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!!! DimswPartAsPartDoc = 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) We want to do this outside the loop so we only do it once
  • 64. Save the Model Out As a PDF 'Do a zoom to fit swDoc.ViewZoomtofit2() 'Retrieve the full pathname including the file name DimsFileNameAsString = 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) .NET string members, check ‘em out! _ means “Continued on next line” Must have a space before it enumerations More return values, listed as ByRef in the Class Definition
  • 65. 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 input ByRef means output
  • 66.
  • 67. Be sure to comment your loop and IF closers swDoc.AddCustomInfo3(ConfigName, "Material Code", _ swCustomInfoType_e.swCustomInfoText, ConfigName.Remove(4)) NextConfigName'move to the next configuration End If 'there are one or more configurations in the document End Sub ‘main End Class ‘SolidWorksMacro Another kewl .NET string function Documenting here makes blocks easier to follow and troubleshoot
  • 68. Configuration Master 5000 Complete Code
  • 69. 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 PublicswApp As SolidWorks.Interop.sldworks.SldWorks 'SolidWorks Application Object PublicSub main() DimbStatusAs Boolean = False DimiErrorsAs Integer = 0 DimiWarningsAs Integer = 0 DimConfigNames() AsString
  • 70. Final Code: Configuration Master 5000 (Part 2 of 5) 'Grab the object for the Active SolidWorks Model DimswDocAs SolidWorks.Interop.sldworks.ModelDoc2 = CType(swApp.ActiveDoc, SolidWorks.Interop.sldworks.ModelDoc2) 'Make sure that we got a document object IfswDocIs 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. IfswDoc.GetType <> SolidWorks.Interop.swconst.swDocumentTypes_e.swDocPARTThen 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!!! DimswPartAsSolidWorks.Interop.sldworks.PartDoc = DirectCast(swDoc, SolidWorks.Interop.sldworks.PartDoc) If ConfigNames.Length >= 1 Then For Each ConfigNameAs String In ConfigNames 'Switch to the current configuration bStatus = swDoc.ShowConfiguration2(ConfigNames(index))
  • 71. 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))
  • 72. 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 DimsFileNameAsString = 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)
  • 73. 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)) NextConfigName'move to the next configuration End If 'there are one or more configurations in the document End Sub ‘main End Class ‘SolidWorksMacro
  • 74. The SolidWorks API Development Process
  • 75. API Example #2 Suppressing Pattern Instances
  • 76. 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
  • 77. Important Concepts – Example 2 Accessing Feature objects Looping through all features in a part Handling FeatureData objects Reading custom properties
  • 78. The SolidWorks API Development Process
  • 79. Recorded Macro: Remove Pattern Instances Legend 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
  • 80. The SolidWorks API Development Process
  • 81. Seek the Path of Enlightenment How do we get the info we need out of the object? How do we get the object?
  • 82. Find The Right Property or Method
  • 83. OK, So How Do We Get The Object, Then? Accessors List
  • 84. 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
  • 85. The Full Object Path ModelDoc2 Feature Feature IS Linear Pattern Feature IS NOT Linear Pattern LinearPattern FeatureData
  • 86. The SolidWorks API Development Process
  • 87. Set up the Framework and Grab the ModelDoc2 IMPORTS SolidWorks.Interop.sldworks IMPORTS SolidWorks.Interop.swconst Partial Class SolidWorksMacro ''' <summary> ''' Don’t forget to put this in at some point!! ''' </summary> PublicswAppAsSldWorks Public Sub main() ‘A nice description here goes a long way! 'Get currently open document DimswPartAs ModelDoc2 = CType(swApp.ActiveDoc, ModelDoc2) 'Make sure that we have an object IfswDocIs Nothing Then Exit Sub 'This macro is only for part models. Check our document type. IfswDoc.GetType <> swDocumentTypes_e.swDocPARTThen Exit Sub
  • 88. The SolidWorks API Development Process
  • 89. Test for Proper Conditions and Get Feature Object 'Fetch the custom property list DimsInputListAs 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. DimswFeatureAs Feature swFeature = swDoc.FirstFeature() Declare as you define Always put your tests up front - Try to run as little code as possible Look how far down the tree the base extrusion is!
  • 90. 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. DimswFeatureDataAsLinearPatternFeatureData DimsFeatureTypeAs String 'Type of feature DimiRowsAs Integer 'Number of rows in the pattern DimiColsAs Integer 'Number of columns in the pattern DimTempStringAs String = "" Do While swFeatureIsNotNothing'loop through the features …OUR CODE GOES HERE… Loop DO WHILE tests BEFORE running any code (Do … Loop Until tests after) Got an object? IsNot Nothing will tell you
  • 91. Looping and Testing Do While swFeatureIsNotNothing'loop through the features 'Check to see if this is a pattern feature sFeatureType = swFeature.GetTypeName2 IfsFeatureType = "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 IfsInputList.Length = iRows * iColsThen'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 Browse API Help to see properties Test Early, Test Often
  • 92. 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!! 7 5 9 11 7 8 5 2 1 2 2 2 3 0 10 3 4 3 6 4 6 9 2 6
  • 93. Numbering Sequence for Linear Pattern Instances SEED = 0 (Row 1, Col 1) 5 10 15 20 (2, 1)=1 6 11 16 21 (3, 1)=2 7 12 17 22 (4, 1)=3 8 13 18 23 (5, 1)=4 9 14 19 24
  • 94. Create the Skipped Instance Array 'Create a collection for the list of instances to be skipped DimSkipColAs New System.Collections.Generic.List(OfInteger) 'Go through the characters in the string finding the O's and add that index For Index As Integer = 0 TosInputList.Length - 1 IfsInputList.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 Substrings start at 0 String method .Equals How can I remember that?!!? You don’t. Intellisense gives it to you! The input list “XXOOXOXO”… …results in the collection: (2,3,5,7) 0 1 2 3 4 5 6 7
  • 95. 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 DIMsMessageAs 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”
  • 96. The Amazing Disappearing Pattern Instance trick Complete Code
  • 97. 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> DimswAppAsSolidWorks.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 DimswPartAs SolidWorks.Interop.sldworks.ModelDoc2 = CType(swApp.ActiveDoc, SolidWorks.Interop.sldworks.ModelDoc2)
  • 98. Finished Code (Part 2 of 4) 'Fetch the custom property list DimsInputListAs 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. DimswFeatureAsSolidWorks.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. DimswFeatureDataAsSolidWorks.Interop.sldworks.LinearPatternFeatureData DimsFeatureTypeAs String 'Type of feature to test to see if it's a linear pattern DimiRowsAs Integer 'Number of rows in the pattern DimiColsAs Integer 'Number of columns in the pattern DimTempStringAs String = "" Do While swFeatureIsNotNothing'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 IfsFeatureType = "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 IfsInputList.Length = iRows * iColsThen'we're good to go
  • 99. Finished Code (Part 3 of 4) 'Create a collection for the list of instances to be skipped DimSkipColAs New System.Collections.Generic.List(OfInteger) 'Go through the collection finding the O's and add the index of that character to the collection For Index As Integer = 0 TosInputList.Length - 1 'cycle through the characters in the string IfsInputList.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 & ")")
  • 100. 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 pFeatureIsNot Nothing End Sub 'main End Class 'PARTIAL SolidWorksMacro
  • 101. PROGRAMMING Best Practices What Not To Wear: SolidWorks API Edition
  • 102. 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!!
  • 103. 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 IfswSensor.SensorType = swSensorDimensionThen‘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
  • 104. Early Binding and Fully Qualifying – Great Practices Option Explicit in VBA (implicit in VB.NET and C#.NET) DIMswFeatureAs Object Perfectly legal (with IMPORTS), but sloppy DIMswFeatureAsSolidWorks.Interop.sldWorks.Feature = swPart.GetFirstFeature Better documented Will catch more errors Enables Intellisense
  • 105. Error Trapping End Users do NOT take errors well Small errors can snowball TRY…CATCH OnErrorGotoerrhandler errhandler: Iferr.number > 0 Then‘we have an error, deal with it msgbox(“You have a problem with ” & err.description) EndIf‘we have an error ALWAYS test for objects IfswFeatureIsNotNOTHINGThen‘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
  • 106. Go Hungarian! 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? Violent objection? Don’t use it. Arguments Against HN
  • 107. 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)
  • 108. What Else can the API do? API and Beyooooooooooond
  • 109. 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…
  • 110. 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
  • 111. 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 The Sherpa Paul Gimbel Business Process Sherpa paul.gimbel@razorleaf.com www.razorleaf.com TheProcesSherpa on Twitter
  • 112.
  • 113. It takes practically no time at all
  • 114. I HONESTLY want your feedback and I do apply it
  • 115. Let’s see if the SolidWorks folks read these:PLEASE PLEASEPLEASE 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!”

Editor's Notes

  1. The program lists this as a beginners session, and that is the truth in that we’re targeting this session towards folks that have not yet done much in the way of SolidWorks programming. This is an intro to the SolidWorks API. We’ll look at the basics, certainly. Examples? You betcha. Details into what parameters each method and property require and return? Nope. That’s all documented for you. Well, mostly. I’ll show you how to find it on your own, but we’re not getting into that level of detail. This also is NOT a programming class. I’m not going to teach you how to write code or teach you how to use the development environments that SolidWorks provides. You folks are obviously smart, or you’d be at the SolidEdge conference. So I’m confident you can figure that stuff out on your own or find some books or info online about that.
  2. What I want to do today is to inspire you. That’s right, I perspire to inspire. I want you to walk out of here saying, wow, all I need to do is get a copy of that presentation, tape it to my wall, and I can really do this! I want you to walk out of here and be so distracted thinking of what macros and programs you’re going to write that you miss all of the other sessions. Except for my other sessions, 1:30 both tomorrow and Wednesday.
  3. Here’s the mandatory and cliché review of me and my company. Razorleaf is a services-only company providing implementation and customization, training and support for PDM including EPDM, SmarTeam, Aras, and Matrix, as well as Design Automation (that’s my specialty) including DriveWorks, Tacton, and custom solutions. As I said, services-only, so I won’t be trying to sell you anything, don’t worry.I am Paul Gimbel, known in the SolidWorks community as simply “The Sherpa.” I’ve been to every SolidWorks World, presented at quite a few of them. A trainer and demojock since the original, SolidWorks 95. So yes, I’m old, and yes, I’m starting to look it.
  4. There are a bunch of ways that you can get code into SolidWorks. The first, and easiest, is with macros. These are little scripts, little nuggets of code that you can run from inside of SolidWorks. You can use TOOLS, MACROS, RUN to execute the macro, or you can use the CUSTOMIZE SolidWorks to add your macro to a menu or as an icon. Macro features are macros that get stuck into the Feature Manager that get executed every time SolidWorks rebuilds that part of the tree. We’ll talk more about them later.Add-ins are programs that are embedded right into the SolidWorks user interface. You may have dialogs, but more likely, you will add ribbons to the SolidWorks menus, you will add a Property Manager window, and possibly something in the Task Pane on the right side of the screen.You can use code in other programs, like in an Excel or Microsoft Access macro, to launch and do things in SolidWorks.And you can also write your own programs that run all by themselves from the Windows Start menu that call SolidWorks.As you can imagine, as you go down this list, the difficulty and skill required increases.Here’s a nice handy chart to see what you can use. You’ll see that .NET is supported across the board, as is VB6. This simply means that these are languages that can be compiled and stored as separate files. You will need something like Visual Studio for these, but you can get an express version for free from Microsoft. Imagine that, getting something free from Microsoft.
  5. This presentation uses VB.NET. Why? Because it’s my presentation. Want C#? Get your own show. SolidWorks 2009 introduced the ability to macro record straight into VB.NET and C#.NET. The VB.NET can be edited with the free, included VSTA (Visual Studio Tools for Applications) environment. VB is a lot easier for beginners to understand. And VBA is dead. The only ones left using it are Microsoft Office and a few other products based on using Office. Most of the examples that you will find, in the API help and online, are in VB or VBA. Taking VBA and making it .NET is pretty easy. Making it C#, not so much. If you are only going to learn one language, make it a .NET language.
  6. Some quick myths about macros. Despite what you’ve heard, you can create forms and dialogs to interact with your users. You can automate macros quite easily. And macros do not require you to have objects preselected. Most samples have you preselect, because fetching the right feature is a pain in the assssss…embly. And you most certainly can create classes and other fun stuff in macros enabling you to automatically react when SolidWorks notifies you someone is trying to save a file, for example.
  7. Here’s the first piece of good news for those of you that question whether you can be a programmer. I was shocked to find out that even the most hardcore code junkie doesn’t write code! Everyone uses Google to find code that is close to what they want. They copy it, paste it, tweak it and test it. One of my engineering professors told me, “A good engineer knows nothing, but knows where to find everything.” At which point I asked him why his exams were not open book. But that’s right folks, life is an open book exam! So cheat as much as you can. Or as they say in codie circles, “repurpose code.”
  8. So the big deal is how to figure out what properties or methods you need and what objects those belong to. One great method, as mentioned earlier, is to use Google. Look around this convention center. There are LOTS of people here that are writing code. There are even more that didn’t make it here that are writing code. Most of them post it somewhere for free consumption. Heaven knows I do. But there actually is a lot of information in the API Help. This is a sample of an Interface or class member page. This shows all of the properties and methods for the Idimension interface, or the Dimension class.
  9. You want to look for these pages that list the MEMBERS. Remember, that’s all of your properties and methods.
  10. The properties section lists all of the properties, click on them for more info. Pay attention to whether they are read only, or if they can get AND set a value. Also pay attention to what they get. Methods are actions performed by or on the object. Follow the links to see what inputs and outputs are involved in these as well.
  11. The links give you more details, but notice that some give you back objects. Those are the accessors to other classes.
  12. Also notice that SolidWorks likes to obsolete a lot of properties and methods. Here, they took a property away and put in two methods to get and set the value.
  13. In other cases, SolidWorks will modify the property or method. In these cases, they will never remove the old member, because that would render your old code obsolete. They simply create a new function with an incremented number after it.
  14. So here it is. The ultimate process for developing a SolidWorks API program. Let’s run through it and see it in action.
  15. This macro takes a currently open part and gets a list of all of the configurations in it. It goes through them one at a time, activating the configuration, changing its material, rebuilding it, saving it as a PDF, and adding a configuration-specific property to it.
  16. These are some of the fun things that I hope you will take out of this example. Most important is the flow for how you obtain objects and use them. These are also very common actions for API macros, so you will be able to “repurpose” my code to your heart’s delight.
  17. OK, here’s the process. Step 1, use Macro Recorder to perform one or more steps of what you’re trying to do. Then check out what SolidWorks came up with to see if it’s useful or at least provides any useful clues.
  18. This is what the macro recorder recorded when I changed the material for a few configs. The code is split onto this slide and the next. The most important things to note about the macro recorder are that it will record a lot of things that you do not care about and it may not record everything that you are after. So why record at all? Well, it’s quick, doesn’t cost much, and you may find clues to the members and objects and maybe even some some snippets that you can use. So let’s take a look at the basic format of the macro and at what SolidWorks is putting in here. First is the stuff in blue. It’s the header. It’s always going to be there. Let’s look at the declarations on slide 1. We’ve got a ModelDoc2. You’ll learn soon that you pretty much ALWAYS have a ModelDoc2. A PartDoc, ok, sounds reasonable since we’re working with a part. But look at these variables. A DrawingDoc object? Don’t need it. AssemblyDoc? Nope. In fact, over half of these are extraneous, unnecessary variables that are declared and never used. Minus 15 style points. But there, at the bottom, there it is. SetMaterialPropertyName2. That’s it. Jot it down, copy it to your clipboard, whatever you want to do. THAT is what we’re after.
  19. The second half isn’t all that much help. The other thing that you’ll see a lot in the macro recorder are selections, clears, view changes and a bunch of other clicks that we will never replicate in a macro. We do see, however, a nice little ShowConfiguration2. That one sounds useful, we’ll tuck that away as well. Some other thins to notice in the format, we have a summary here, at the end, where nobody will see it. And we have the swApp. The most important variable in the whole class. So important that it’s hidden away.
  20. Barebones, this is what you should have. It starts with these IMPORTS statements that tell VB what libraries classes you’re going to be pulling from. This is what allows us to say DIM swDoc As ModelDoc2, and VB knows what a ModelDoc2 is. You will notice that these are conspicuously missing from my final code. The objects instead have their full names. I prefer to do it that way. It is longer, but actually not that much more typing and it makes it a lot easier to read and follow later on. You should ALWAYS use Tools, Macro, New or Tools, Macro, Record, or if you have a template that you already built from one of those two sources, that’s fine. Make sure that you let SolidWorks built your framework, though.
  21. Your class definition header is next, telling everyone what your class is going to be called. Leave the PARTIAL in there. It shows that there is a lot more going on behind the scenes than you know. If you want to change the name of your class, for goodness, sake, don’t just type over it here.
  22. If you MUST rename it, do it in the Project Explorer on the right side. A quick peek at the SHOW ALL button reveals that there is a WHOLE LOT of stuff that you don’t normally see. Just typing over that name will cause untold levels of problems.
  23. Comments are critical and they belong right here up front. Anything after an apostrophe is treated as a comment and ignored. Use them A LOT! This swApp is also really important, so it deserves to be up front. It doesn’t make it run any differently, it just adds visibility to the most important object you have.
  24. OK, so we did our macro recorder, we actually got what we think are two of the methods that we need. Let’s do some research.
  25. We’ll stick with the SolidWorks API Help, because you really need to see how to use it. It’s takes some finesse. We know we need to deal with configurations. We want a list of the config names. So let’s just search on CONFIGURATION. Here’s what we find. The first entry (of 500) looks somewhat relevant, so let’s follow the link. That shows us that there’s a ConfigurationManager object. OK, I’ll bite. Let’s see if we need that.
  26. So here, I didn’t see anything that really meant anything to me, but I did notice that there were a lot of examples. This one especially caught my eye, because it talks about doing something with ALL CONFIGURATIONS. Now it’s VBA, not VB.NET, but what I’m really looking for at this point is what objects and what methods do I need. That’s going to be universal. And VBA and VB.NET aren’t THAT much different in terms of readability. I would stay away from the C# examples if vous no parlez C++.
  27. So I scanned through that code and it was pretty simple at the top. A bunch of DIM statements. I know what those are. But down here, we see swModel.GetConfigurationNames. That sounds REALLY good. What doesn’t look so good is that they’re using VARIANTS. That means we need to do more research to figure out how to use this method.
  28. OK, so we found the method that we need. We’ll search on that and the search comes up with GetConfigurationNames. Great, let’s follow it. OK, that’s obsolete. Quite often, you will get the obsolete one first. Don’t worry, just keep going.
  29. The obsolete one led us to the current one. So from this screen, we get a few pieces of information, very few. One, we see what object we need to have to take this action, the ModelDoc2 object. Second, we find out what SolidWorks returns to us, sort of. It gives us back an object. Um, that could pretty much be anything. It’s a bit of a cop-out if you ask me. Down here, they give you a little more info, letting you know that it is an array. VBA was very sloppy and let you get away with a lot, but in .NET, we need to know for sure. It turns out to be an array of strings. How do I know? I guessed and tried it.
  30. OK, so we did our research. Onto the next step.
  31. In VB, we need to declare, or tell VB what our variables are going to be before we use them. We do this with a PUBLIC or DIM statement. We tell it the variable name that we’re going to use and we tell it the class of the object. Once VB knows what it’s going to be, we can then put a value or assign an object to it. Remember that Accessors are the methods that are used to obtain objects. You need an object to get an object. Sometimes, though, we’re not 100% sure what we’re getting back from our accessor, so we use an insurance function, called Ctype, that converts the output from the accessor into the specific type that we want. DirectCast is also sometimes used for pretty much the same reason. So don’t be shocked if you see these.
  32. At the top, we can put variables that we know we’re going to use. Notice that we can declare and define in a single line.We can also define them as we go, so don’t worry if you don’t know them all. You can put them up here later, or just declare them down in the code.
  33. The first thing that we need to do is to latch onto the open session of SolidWorks. There are three common ways to do this. You can just set it to Application.Sldworks. This requires that SolidWorks be open and running. If you’re running a macro, then it’s a pretty good bet that SolidWorks is running. You can do a GetObject which is a bit more robust, and what’s cool about this one is that you can put a parameter in here telling SolidWorks which window to open. This is not a FILE, OPEN, this gets you latched onto the SolidWorks Application with a certain document window open. If the document and SolidWorks are not open, Error City, USA. CreateObject is a bit more robust in that it will open SolidWorks if it’s not already open. Great for standalone apps or calling SolidWorks from another program.
  34. So we need to grab the ModelDoc2 object. Why? Because the process says that we always need to. Remember that accessors are methods, so we need an object to access other objects. What object is that? Typically, it’s the ModelDoc2. So we’re going to use the swApp object with its accessor .ActiveDoc to get the ModelDoc2 object. Where do we define the swApp object? Well, that’s done by SolidWorks in that big jumble of stuff that’s hidden from you. It is ALWAYS important that whenever you define or instantiate an object, that you check to make sure that you have it. If you assume that you have it and go on, SolidWorks will barf at you and your users will laugh at you.
  35. It is very important to know where the method or property that you need lies. ModelDoc2 does an awful lot. So much in fact, that they had to create another object, ModelDoc2.Extension. But some other things that you would imagine would be on the ModelDoc2 are more document-type specific. So you need to get a PartDoc object or AssemblyDoc object or DrawingDoc object.
  36. So now we have the ModelDoc2, and we know that the ModelDoc2 can get us the configuration names. The first thing that we do is check to make sure that we got names. If we do, then we start looping through them. For Each…In loops are a great way to go through arrays or collections without having to care how many there are. Within the loop, we’ll switch the active config with the ShowConfiguration2 that we saw in the macro recorder, and we’ll rebuild as well. It’s interesting to note that these methods actually return a true/false value telling you if they worked or not. In practice, you will want to do an IF…THEN to make sure that they succeeded. And we will always be careful to close out our loops and our IF blocks.
  37. So we have our ModelDoc2 and we used it to get the config names. Now we need to change the material and we know that’s on the PartDoc object.
  38. Now normally we would use an accessor to get the Part object from the modeldoc2 object. But ModelDoc2 has a weird relationship with PartDoc, AssemblyDoc and DrawingDoc. They’re kind of the same. So you don’t need an accessor, you just set them equal. This is the only place you will see this, so don’t worry. This is generally the only time we’ll use DirectCast, too. So just set swPart equal to our ModelDoc2 object, swDoc, and recast it as a PartDoc object. Notice that we are outside of the loop, that is, before we start going through the configs because we don’t want to reassign this every time. But back inside the loop, we can then go ahead and set the material since we now have the right object.
  39. Saving the model as a PDF is pretty easy. All of the methods that we need to use are on the ModelDoc2 object. We’re doing a little string manipulation here. By the way, go online and check out the VB.NET string members, they are way cool. You may also see this from time to time. A space-underscore means that this was too long to fit on one line, so it bleeds over to the next. I has to be a space-underscore. Not just an underscore. Down here, you can see that we have methods that will return values listed in the parameters. In the API Help, they’re listed as BYRef. ByVal, means that you are giving an input to the method, ByRef means that you are getting an output. Since you can only have one thing on the left side of an equals, this is how they pass back more. And finally, notice that two of the parameters here, VERSION and OPTIONS are integers. We use enumerations for these.
  40. Enumerations are nothing more than aliases. Why they make them a number, I have no idea. What is the integer representing SolidWorks 2009? Who knows. So instead, we use an enumeration. The enumerations are stored in the SolidWorks.Interop.swconst (that’s out second IMPORTS that we always have at the top). The help will tell you (if you click) what enumeration to use, but if you just type SolidWorks.Interop.swconst (you’ll see that it autofills in most of it for you), then you will get a nice list to choose from. So you will not need to memorize any of these…ever.
  41. The last step that we have is to set the custom property. Here we’re using another cool VB.NET string function. And what’s most important here is that we’re closing out our loops and our IF…THEN blocks. But which is which? You could have a half-dozen END Ifs in a row. That is not uncommon. A nice little comment afterwards lets you easily keep track of which is which.
  42. And here is the complete code for the configuration example.
  43. This example was for a company that uses DriveWorks to automate the design of their parts. DriveWorks has the ability to kick off a macro upon the completion of the generation of a part, and these folks had a bit of an odd situation. For anonymity’s sake, let’s say that they make plates with holes. The plates come in different sizes with different size hole patterns. The customizability comes in because not every hole is needed every time. So we needed a way for the end user, a non-SolidWorks user, you specify which holes needed to be there, and which holes should not. In SolidWorks this is easy, you right-select the pattern, edit definition, then choose the instances to skip from the pattern. But this was automated. There’s nobody there to pick. So what we did was to have DriveWorks generate a series of Xs and Os representing the pattern. X means there’s a hole and O means there is no hole. DriveWorks passed this into the part as a custom property. Our macro would then read the custom property, scan the part for a pattern that matched, then do its magic.
  44. This one is fun because it works with features. It shows you how to loop through features, looking for patterns, and it deals with something that comes up often and is a bit weird, a FeatureData object. And now we get to read a custom property that we learned to write in the last example.
  45. So we’re going to follow the same process. Step one, macro record.
  46. So this is what we get out of the Macro Recorded this time. We see our ModelDoc2, which we know we’re going to need and…well, that’s about it. You can see the Hole Pattern being selected, but that’s about it. No help whatsoever. This happens sometimes.
  47. So we go into the research phase empty handed. No worries.
  48. We know we want to work with linear patterns. So let’s search on Linear Pattern and see what comes up. ILinearPatternFeatureData. That sounds like quite the interesting class, let’s see what it’s all about, and more importantly, what properties and methods it has. We look at the interface page and we see the link for the MEMBERS which will tell us what properties and methods this class has. We also notice the accessors area at the bottom that tells us how to obtain this object.
  49. So looking at the members for that ILinearPatternFeatureData object, we see towards the bottom, a SkippedItemArray property. This allows us to get or set the list of instances to skip. Sounds precisely like what we want.
  50. So how do we get this ILinearPatternFeatureData object, then? Well, the Accessors section says to use Feature.GetDefinition. By the way, this double colon really means nothing. When you use it, you will use it with a dot like you always do. You will use swFeature.GetDefinition. OK, so the GetDefinition Accessor is a method of the Feature class or Ifeature Interface. How do we get the Feature object? Simply click on the link for the IFeature interface and look at its page. Scroll down to the accessors are and here are the accessors. As you can see, there are more than a few ways to get a feature object.
  51. OK, so let’s look just at the ways to get from a ModelDoc2 or a PartDoc to a feature. There are a few good candidates here. We’ve got FirstFeature, which I’m guessing is descriptively named, and FeatureByName. Well we COULD force the user to provide a specific name to the Linear Pattern Feature, but that would make this code a bit too specific, not very reusable or flexible. So we’ll grab the first feature, but can we get to the next feature from there? Well let’s look at the accessors to get from one feature to another. Sure enough, there’s GetNextFeature.
  52. So here’s the flow. We get our ModelDoc, We use that to get the first feature, then we cycle through the features. If it’s a pattern, we check to see if it’s the right size. If not, we use that feature object to get the next feature.
  53. OK, we know what to do, let’s do it
  54. OK, so let’s get our ModelDoc2 object and then test it for existence, and test it to make sure that it’s a part.
  55. OK, let’s get the rest of our objects and use them!
  56. Let’s start by retrieving the list from the custom property. Again, we’ll declare and define in the same line. Custom properties are retrieved with methods from the ModelDoc2 object. We’ll immediately test the string to make sure that it’s a good string. Once we know we have a good string, we’ll retrieve that first feature. Now note, that the first feature is WAY UP there on the tree. You will get a lot of features that you didn’t even know were features.
  57. Now that we have our first feature, let’s start looping. We have a few variables that we’ll need. One to tell us how many rows and one for how many columns. OurLinearPatternFeatureData object, and a string to check the type of feature that we have. How do I know I’m going to need these? Because I already wrote the code. You find them as you go along, and you add them to the list. We’ll use a DO WHILE loop, because it checks before it runs through each iteration of the loop. So we make sure that we have a feature object, and once we know that we do, then we start processing it.
  58. The first step is to get the feature type, that’s a method called GetTypeName2 on the feature. The best way to find most of these is to declare the feature object, then just type swFeature dot. As soon as you hit that dot, Microsoft will show you a list of all of the members of that class. It’s called Intellisense. Once you start calling a method, it then tells you wnaat parameters of what classes you need. You don’t need to go to the API Help all the time. So once we see that it is a linear pattern, then do the GetDefinition to get the LinearPatternFeatureData object. Once we have that object, we can pull the direction1 and direction2 quantities off of it to find the size of the matrix. Check that against the length of the string. If it’s a match, then we can move on.
  59. Now the last piece to this puzzle is to take the string and turn it into a list, a numerical list, of instances to be skipped. SolidWorks wants an array, but we’re going to use another VB.NET tool to get there. The Collection. I’m not going to go into details about collections, again, this is not a programming class, but the difference between a collection and an array is one of flexibility. Arrays are a predefined size. If you want to change the size, you have to re-declare it. Sorting, shuffling, and other such actions are not that easy with arrays. Collections are more flexible. The drawers are a fixed size with a fixed number of slots in each drawer. With collections, you just add on another bin and another and another. VB.NET has a ton of great methods for working with collections.
  60. So how does SolidWorks number these linear pattern instances? This way. How do I know? I tried it. Sometimes, that’s what you have to do.
  61. So what we want to do is to walk through the string, counting as we go. And every time we hit an O, then we throw that number into the collection. It’s a pretty basic, but pretty cool little loop. Things to note here are that in a string, the substring starts at position 0. We’re also using the EQUALS method to compare strings instead of a regular equal sign. This allows us to use a comparison method that ignores case. Again, how do you remember the enumerations? You don’t. Intellisense gives them to you.
  62. So we built our collection with our loop, but SolidWorks wants an array. Not a problem, VB.NET collections have a method called ToArray. This is another commonoccurance within SolidWorks, especially when you’re working with features. Once you have pushed values to properties in an object. In order for those changes to be propagated to the model, you need to kick off some form of Modify or Update method. The other critical thing is that when you make any changes to the model, you will want to rebuild. The last thing that we’re showing here is how to handle the ELSE cases. What happens when the pattern is not the right size? Well when you’re testing, throwing a message box is nice. But when you’re having others use the program, they don’t like seeing errors. So what we did was to write the error out to a custom property. We built the message by piecing together some strings and properties, then passed that string to a custom property.
  63. And here’s your finished code.
  64. DOCUMENT EVERYTHING!!! I cannot stress this enough. You want to see as much, if not more green in your code than any other color. Use your comments to turn the VB, which sounds roughly like English, into complete, sensible sentences. Make sure you use it to keep track of IF blocks and loops.
  65. Here are a couple of things that I want you to always do. In VBA, make your first line, ALWAYS, OPTION EXPLICIT. What that does is that it requires you to tell VBA what your variables are before you use them. You have to declare or DIM your variables. In VB.NET, this is always a requirement. Think of it as the REQUIRE FULLY DEFINED SKETCHES of the programming world.So you have to DIM your variables. You can be vague about them and declare them of type object, or you can tell VBA exactly what kind of object it’s going to be. Being very specific like this is called early binding or fully qualifying your variables. It is a MUST. IF you do this, your code will be easier to read and when you hit a period after your object variable’s name to get to a property or method, you will get a list to choose from. Select a method and Intellisense will tell you what parameters you need to provide in what data types. All that, just for being tidy.In VB.NET, we’re used to having SolidWorks putting the IMPORTS at the top of our macro so that we can shortcut our SolidWorks class names. Yes, it’s shorter, but I recommend spelling it out. It makes it easier to follow.
  66. We check our return values to make sure that we have objects and we check to make sure that we are getting non-empty strings, and so on. But you’re still going to get errors. Look into the methods that are available to handle these errors. TRY…CATCH blocks in VB.NET are very powerful. OnErrorGoto is good both in VB.NET and VBA.
  67. This one is a bit controversial, but I like it. Hungarian notation means that you put an abbreviation at the beginning of your variable to show what kind of variable it is. I for integer, d for double, s for string, and so on. I put sw for SolidWorks objects. You can get more specific if you want. If you’re a seasoned coder and you think this is a terrible idea, then don’t use it.
  68. I’ve also included a little slide here listing some of the VB.NET functionality that you should know. Check these out and Google them to see what they are and how they work.
  69. The last thing I want you to hear and think about is what kind of things you can do with the API. This is the part of the show where you start to think of what your first project is going to be.
  70. Number one is don’t limit yourself to just what core SolidWorks can do. Most of the SolidWorks add-ins that come with Premium include APIs. Everything from SolidWorks Utilities to Simulation to PDM and Routing. It’s all in there. I’ll be doing a presentation tomorrow about Automating Design Validation with the API. You’re ready for that now. On Wednesday, I’ll be doing a session on linking Excel with SolidWorks through the API and VBA. Same can be done with MathCAD or other calculation engines. Use them to calculate and pass values to SolidWorks. Then have SolidWorks do a mass prop or a simulation run, then send values back. But the big reasons to write macros are to save time, create iterations that can be performed quickly so you can do more iterations, and finally, to allow people who are not as smart as you to use the power of SolidWorks.
  71. Finally, I said I would mention macro features. The concept here is that you embed a macro into a feature in the feature manager. When SolidWorks rebuilds, it starts at the top and works its way down. When it hits the Macro Feature, it fires the code off. This could be a validation step, it could run a mass props and update your geometry to accommodate. The sky’s the limit. There’s lots of good info out there on Macro Features as well if you’re interested. The most important thing of all is to start thinking of how you can use this, then GO TRY IT!!
  72. If you have questions, I’ll be happy to take them now or at any time during or after the conference. If you see me in the hall, feel free to grab me. Just be careful where you grab me. I’m ticklish. If I can’t talk then, we can set up a time to sit down and chat.