Using Custom Classes in Scripts - CATIA V5 Automation
Using Custom Classes in Scripts - CATIA V5 Automation
CATIAV5Automation
IncreaseyourCATIAprogrammingskillstoday!
Home
About
LearningSeries
Downloads
Contact
Typetexttosearchhere...
Home>TheVisualBasicLanguage>Usingcustomclassesinscripts
Usingcustomclassesinscripts
April13,2010LeaveacommentGotocomments
22Votes
InthisarticleIwillshowhowtocreateanduseacustomclasswithinascript.Ifyou
programinVBA,VB6or.NETyoumightbefamiliarwithbuildingyourownclassesbut
youmaynotknowthatyoucanalsousetheminascript.Incaseyouarewonderingwhat
aclassis,Iwillstartbybrieflydiscussingthataswell.IhavetoadmitthatIhaveonly
usedclassesinsidescriptsahandfuloftimes,butinthosesituationsitprovedtobevery
useful.
Whatisaclass?
WhenyouwriteprogramsusingtheCATIAautomationAPI,youareworkingwithobjects
thatrepresentvariousthingsinthesoftware.Forexample,eachdocumentthatisopenis
representedbyaseparateDocumentobject.Thatobjecthasvariouspropertiesthathold
somedataorattributesassociatedwithit.Forexample,theDocumentobjectprovidesa
Pathpropertytoretrievethefilepathwhereitiscurrentlysaved.Objectsalsomayprovide
methodswhichcanbethoughtofasservicesoractionsthatcanbeperformed.Asan
example,thedocumentobjectprovidesaSavemethodtosaveanychangesthatwere
made.
Alloftheseobjectsareactuallyinstancesthatgeteachtheirdefinitionfromamaster
template.Thattemplateiscalledaclassandithasthreebasicpurposes:
Itdefineswhatpropertiesandmethodswillbeprovided(calledmembers)
Itdefineshowitsdatawillbestored
Itprovidesalloftheunderlyingcodethatgetsexecutedwhencallsaremadetoits
instances
Whycreateaclassinsideofascript?
https://v5vb.wordpress.com/2010/04/13/classesinscripts/ 1/10
5/17/2017 Usingcustomclassesinscripts|CATIAV5Automation
Addingaclasstoyourscriptallowsyoutodefineanewobjecttypethatcanbeveryeasily
used(instantiated)againandagaininthescript.Generally,aclasswillrepresentsome
typeofrealthingsoitmightmakesensetogroupallattributesandservicesthatthing
willprovideintoaneasytouseobject.WhenIhaveusedthem,mostoftentheyare
relativelysimpleandwillduplicatesomefunctionalitythatisnotavailableinascript
language.
Declaringtheclass
Theclassdefinitionneedstobeseparatedfromtheotherprocedures(subroutinesand
functions)inthescript.ThisisdonebyenclosingalloftheclasscodeinsidetheClassand
EndClassstatements.Soyoumighthavesomethinglikethistostart:
SubCATMain()
'Thisisthemainsubforyourprogram
EndSub
Class
'Allofthecodeforyourclassgoeshere
EndClass
DefiningProperties
Thefirststephereistodecidewhatpropertiesyourclassshouldprovideandtheirdata
types.AgoodwaytothinkaboutthisistomimicthewayCATIAclassesorotherobjects
youmayhaveusedinthepastaredefined.Mostcommercialapplicationshaveverywell
thoughtoutobjectmodels,sotrytofollowthesamesortsofconventionstheydo.Once
youhavedonethat,youshoulddeclareaprivatevariableinsidetheclasstoholdeach
pieceofdata.Thisstepiscalledencapsulationbecauseitprotectsthatdatafrombeing
accessedintheprogramunlessitisaccessedthroughtheclassproperties.Next,you
shouldcreateaseparateproceduretoretrieveandseteachpropertyvalue.Thisisshown
below.
'Declareaprivatevariabletoholdthepropertyvalue
Privatep_strNameAsString
'Thisprocedureisexecutedwhenthispropertyisread
PropertyGetName()AsString
'Likeafunction,returnthevaluebyassigningittothepropertyname
Name=p_strName
EndProperty
'Thisprocedureisexecutedwhenavalueisassignedtotheproperty
PropertyLetName(iNameAsString)
'Simplyassignthepassedinvaluetotheprivatevariable
p_strName=iName
EndProperty
Importantnotes
Propertiescanbevalues(number,string,boolean,etc.)orotherobjects.Toretrieve
aproperty,youwillalwaysdefineaPropertyGetprocedure.However,toassigna
propertytherearetwodifferentwaysdependingonwhetherthedatatypeisavalue
https://v5vb.wordpress.com/2010/04/13/classesinscripts/ 2/10
5/17/2017 Usingcustomclassesinscripts|CATIAV5Automation
oranobject.Toassignavalue,youwilldefineaPropertyLetprocedure(asshown
above)andtoassignanobjectyouwilldefineaPropertySetstatementasshown
below.
Privatep_objPartAsPart
'Thisprocedureisexecutedwhenanobjectisassignedtotheproperty
PropertySetPart(iPartAsPart)
'Simplyassignthepassedinobjecttotheprivatevariable
Setp_objPart=iPart
EndProperty
Ifyouwantapropertytobereadonlyorwriteonly,simplydefineonlyone(not
both)oftheGetProperty/LetProperty/SetPropertyprocedures.Forexample,if
thereisnotaPropertyGetprocedure,thatpropertycanbeassignedbutnotread.
DefiningMethods
Addingmethodstoaclassisverysimple.Allyouhavetodoisincludeasubroutineor
functionforeach.
AnExample
AgreatexamplethatIhaveusedinsomeofmyscriptsisacollectionclass.Ifyouhave
writtencodeinVBA,VB6,.NET,etc.youareprobablyfamiliarwithcollections.They
simplyholdabunchofvaluesorobjects.Theygenerallyprovidethefollowingbasic
capabilities:
Querythesizeofthecollection(Count)
Additemstothecollection
Removeitemsfromthecollection
Retrieveanitemfromthecollection
TheVBscriptlanguagedoesnotprovideitsowncollectionclass.So,acommon
alternativeistouseanarraytostorevalues.Whileanarraydoeswork,itcanrequirealot
ofcodethroughoutyourprogram.Acollectionclassmaycontainafairamountofcode,
butitcanbereusedinotherscriptseasilyanditgreatlysimplifiestherestofthecodein
thescript.AnotheroptionistouseadictionaryobjectintheWindowsScriptingRuntime
Library.ThisisagoodoptionandIhaveuseditmanytimesaswell.
Anexamplecollectionclassisprovidedbelow.Ionlyincludedthemostbasiccapabilities
anditissetuptostoreandretrieveobjects(notvalues).Ifyouwanttomanagevalues,you
willneedtoreplacethePropertySetprocedureswithPropertyLetProcedures.
'Starttheclassdefinition
ClassCustCollection
'Declareprivatevariables.Thesecannotbeaccesseddirectly.
'Insteadtheycanonlybeaccessedthroughapropertyormethod
Privatep_varItemArray()AsVariant
Privatep_intCountAsInteger
PrivateSubClass_Initialize()
'Theinitializeprocedurewillexecutewheneveranewobjectinstanceiscreated
'Hereyoushouldinitializeanydefaultvalues
p_intCount=0
https://v5vb.wordpress.com/2010/04/13/classesinscripts/ 3/10
5/17/2017 Usingcustomclassesinscripts|CATIAV5Automation
p_intCount=0
EndSub
PropertyGetCount()AsInteger
'Usedtoretrievehowmanyitemsareinthecollection
'Simplyreturnthevaluestoredintheprivatevariable
Count=p_intCount
EndProperty
SubAdd(iObject)
'Usedtoaddanitemtothecollection
'Incrementthesizeofthecollection
p_intCount=p_intCount+1
'Resizethearraypreservingalloftheexistingitems
ReDimPreservep_varItemArray(p_intCount)
'Addthenewitemtothearray
Setp_varItemArray(p_intCount)=iObject
EndSub
FunctionItem(ByValiIndexAsInteger)AsObject
'Usedtoretrieveanitemfromthecollection
'Iftherequestedindexexists,returnit
'Otherwiseraiseanerror
IfiIndex<>0AndiIndex<=p_intCountThen
SetItem=p_varItemArray(iIndex)
Else
Err.RaisevbObjectError+1,"Collection.Item()","Indexoutofrange"
EndIf
EndFunction
SubRemove(ByValiIndexAsInteger)
'Usedtoremoveanitemfromthecollection
DimintIndexAsInteger
'Fromtherequestedindextotheupperboundof
'thearraymoveallexistingitemsdownoneindex
ForintIndex=iIndexTop_intCount1
Setp_varItemArray(iIndex)=p_varItemArray(iIndex+1)
Next
'Resizethearraydestroyingthelastelement
p_intCount=p_intCount1
ReDimPreservep_varItemArray(p_intCount)
EndSub
EndClass
Thefollowingexampleshowshowtousetheclassinyourscript.Eachoftheproperties
andmethodsprovidedbythenewCustCollectionclassaredemonstrated.
SubCATMain()
DimobjColAsCustCollection'Declareanewvariable
DimobjItemAsObject
https://v5vb.wordpress.com/2010/04/13/classesinscripts/ 4/10
5/17/2017 Usingcustomclassesinscripts|CATIAV5Automation
'Instantiateanewcollectionobject
SetobjCol=NewCustCollection
'Displaythecurrentcollectioncount
MsgBoxobjCol.Count,0,"Count(Initial)"
'Addthe3stdplanesfromtheactiveparttothecollection
objCol.AddCATIA.ActiveDocument.Part.OriginElements.PlaneXY
objCol.AddCATIA.ActiveDocument.Part.OriginElements.PlaneYZ
objCol.AddCATIA.ActiveDocument.Part.OriginElements.PlaneZX
'Displaythecurrentcollectioncount
MsgBoxobjCol.Count,0,"Count(Afteraddingstdplanes)"
'Getthe2nditeminthecollectionanddisplayitsname
SetobjItem=objCol.Item(2)
MsgBoxobjItem.Name,0,"Nameof2ndItem"
'Removethe2ndItem
objCol.Remove2
'Displaythecurrentcollectioncount
MsgBoxobjCol.Count,0,"Count(Afterremoving2nditem)"
'Getthe2nditeminthecollectionanddisplayitsname
'Whentheoriginal2nditemwasremovedthe3rditemmovedtothe2ndindex
SetobjItem=objCol.Item(2)
MsgBoxobjItem.Name,0,"Nameof2ndItem"
EndSub
Wrapup
Onceyoucreateaclasssuchasthecollectionexampleshownabove,youcanreuseitin
futurescriptprojectsbyjustpastingintheclassdefinition.Creatingeasytousecustom
classestakessomepractice.Asyoucreatemoreofthem,youwillbegintolearngoodand
badpracticesbutingeneral,trytomimicthewayotherobjectsworkinotherapplications.
Forexample,Imadethecollectionclassaboveprovidethepropertiesandmethodsyou
wouldexpecttoseeandthewaytheyareusedisfamiliar.
PleasetakeamomenttoratethisarticleJustclickthestarsupnearthetitle.
https://v5vb.wordpress.com/2010/04/13/classesinscripts/ 5/10
5/17/2017 Usingcustomclassesinscripts|CATIAV5Automation
Advertisements
0:00
Sharethis:
Like
Bethefirsttolikethis.
Related
Comments(7)Trackbacks(0)LeaveacommentTrackback
1.
Julian50
April14,2010at1:44pm
Reply
nothingtosay,justperfect,pleasedontstopandkeepgoing!
2.
Karteek
April16,2010at12:30am
Reply
Mike,
YouareintroducingustothemanypossibilitiesofMacros.Agreateasyto
understandexplanation.
https://v5vb.wordpress.com/2010/04/13/classesinscripts/ 6/10
5/17/2017 Usingcustomclassesinscripts|CATIAV5Automation
Onusisonustolearnanduseit.
Thanks,
Karteek
3.
Vishal
April27,2010at12:11am
Reply
Pleaseprovideanotherexamplewhichworksinvba.
Icopy/pastedthecodeinvbabutitdidnotwork.
Ademonstration/examplewillbemoreuseful.
Thanks
v5vb
April27,2010at5:23am
Reply
ThisdoesntworkinVBA,itisonlysupportedinVBScript(soitshouldwork
withCATScriptandcatvbs).TomakeyourowncustomclassesinVBA,just
rightclickontheprojectandselectinsertclassmodule.Fromthere,theideais
basicallythesameexceptyouwillnotusetheClassandEndClassstatements.
Thosestatementsareusedonlyinscripttoseparatetheclasscodefromthe
restofthecodesinceitisalllistedtogether,butinVBAeachclassisdefined
inaseparatemodulesotheyarentneeded.
4.
Calin
May14,2010at1:11pm
Reply
CongratulationsMikeforyourtremendouseffortandforthecompetentexplanations
youprovide!
Welldonejob!
OneremarkIwouldliketoputup.Whenyoudescribehowtodefinetheproperties
yousayThisstepiscalledencapsulationbecauseitprotectsthatdatafrombeing
accessedintheprogramunlessitisaccessedthroughtheclassproperties.Wouldnt
becorrecttosaythatthedataisbeingaccessedbytheclassmethods(not
properties)?
Thankyou.
v5vb
May14,2010at3:57pm
Reply
https://v5vb.wordpress.com/2010/04/13/classesinscripts/ 7/10
5/17/2017 Usingcustomclassesinscripts|CATIAV5Automation
Thanks!Gladyoulikethesite.Asforyourquestion,eitheristechnically
correct.Imentionedpropertiesbecauseprivatevariablevaluesaremostoften
retrievedorsetthroughapropertyprocedure,notamethod.Withthatsaid,
propertiesandmethodsbothhaveaccesstotheprivatevariablesinsidethe
classsoitispossibleeitherway.Thebasicideaofencapsulationisjustthat
youcannotdirectlygetthevalueorchangethevalueofthoseprivatevariables
directlyyouonlyhaveaccessviaapropertyprocedureoramethod.
5.
Vinod
April18,2012at9:57am
Reply
Wowawsmedudekeepgoing
1.Notrackbacksyet.
LeaveaReply
Enteryourcommenthere...
CATIAV5programmingfundamentalsIntroduction(Announcement)Newdownload
madeavailabletoday
RSSfeed
Disclaimer
Theopinionsexpressedinthisblogaresolely
thoseoftheauthoranddonotreflectinanyway
thoseoftheauthor'semployer.Allsamplecodeis
providedonan"asis"basis,withoutwarrantyof
anykind.Notliableforanydamagesorcostsof
anytypearisingoutofanyactiontakenbyyouor
othersrelatedtothesamplecode.
EmailSubscription
Clicktosubscribetothisblogandreceive
notificationsofnewpostsbyemail.Subscribers
alsogainaccesstotheDownloadsareaandthe
LearningSeries.
Signmeup!
TopicCategories
General
ProgrammingTechnique&Theory
https://v5vb.wordpress.com/2010/04/13/classesinscripts/ 8/10
5/17/2017 Usingcustomclassesinscripts|CATIAV5Automation
QuickTips
System
TheCATIAObjectModel
TheVisualBasicLanguage
UserForms
MostPopularTags
ActiveDocumentbatchCatalogcenterofgravityCodeOrganization
CommonDialogsCompiler CustomClassesDebuggingDeclaring
variablesDeletingdensityDisassembleDownloaddrawingerrorsFiles
Forms FormulasGeometryTypes
GetNameToUseInRelation
HybridShapeFactoryinertiaIntellisenseLicenseMacro
LibrarymassMeasureModuleObjectBrowser
Archives
March2012
October2010
September2010
July2010
June2010
May2010
April2010
March2010
February2010
January2010
December2009
https://v5vb.wordpress.com/2010/04/13/classesinscripts/ 9/10