GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page1of110
GettingStartedwithGambas Version2:ATutorialSubject: Author:
FileName: Version: LearningVisualBasicwithLinuxandGambas
TimothyMarshalNichols GettingStartedwithGambasTutorial.odt
1.0(Revision:193) Sunday28May2006
Contents1:Introduction.....................................................................................................................................2
1.1:GAMBasAlmostMeansBasic.................................................................................................2
1.2:Projects......................................................................................................................................4
1.3:GambasResources....................................................................................................................5
1.4:License......................................................................................................................................6
1.5:Acknowledgments.....................................................................................................................6
2:YourFirstGambasProject:SimpleEdit...........................................................................................7
2.1:Creatingtheproject...................................................................................................................7
2.2:Creatingtheuserinterface......................................................................................................13
2.3:Addingthecode......................................................................................................................18
2.4:Runningtheproject.................................................................................................................23
3:DrawingProject:ImageShow........................................................................................................28
3.1:Creatingtheproject.................................................................................................................28
3.2:Creatingtheuserinterface......................................................................................................29
3.3:AddingtheCode.....................................................................................................................37
3.4:Runningtheproject.................................................................................................................52
4:DatabaseProject:Notations..........................................................................................................56
4.1:Creatingtheproject.................................................................................................................59
4.2:Creatingtheuserinterface......................................................................................................64
4.3:CheckingouruserinterfaceforCRUD...................................................................................75
4.4:Addingthecode......................................................................................................................77
4.5:Runningtheproject.................................................................................................................99
4.6:SwitchingtoaMySQLorPostgreSQLDatabase.................................................................102
5:Appendix1:DatabaseCommandswithExecandSQL..............................................................104
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page2of110
1:
Introduction
ThisisasimpleGettingStartedwithGambasTutorial.Itisintendedforfirsttimeprogrammerswho
wanttogainsomeideaofthecapabilitiesofGambas.Youcanthenseeifthisisthedevelopment
environmentthattheywouldliketolearnmorefully.ItwillalsobeusefulforVisualBasic
programmerswhoaremovingfromWindowstoLinux.
TraditionallyonUnixbasedsystemslikeLinuxyouusedanumberoftoolstodevelopan
application.Soyouusedacodeeditor,possiblyauserinterfacedesigner,acompilerandothertools.
Youpreformedeachstageofthedevelopmentprocesswiththerelevanttool.Thisprocesscanwork,
afterallmuchofLinuxwasbuiltthisway.Itdoeshavetheadvantagethatifyoudonotlikeonetool
thenyoucanreplacejustthattoolwithsomethingyoudolike.Butitcanalsohavethedisadvantage
ofcompatibilityissueswhentheoutputofonetooldoesnotfittherequiredinputforanothertool.It
alsomakesitdifficultfornewdeveloperstolearntherequiredstepstoproduceprofessionallooking
application.ToovercometheseproblemstherearenowanumberofIntegratedDevelopment
Environment(IDE)forLinux.IDE'sincludeallthetoolsyouneedtodevelopapplicationswithin
oneframework.Theyhavebeenverypopularonotheroperatingsystemsanddevelopersmovingto
LinuxexpecttofindsimilarIDE's.TwoofthemostusedIDE'sonLinuxareKDevelopand
MonoDevelop.KDevelopisanIDEforcreatingCandC++applicationsandforusingscripting
languages.MonoDevelopisanIDEfordeveloping.NETapplicationusinglanguageslikeC#and
VisualBasic.NETandothers.
GambasisaIDEforVisualBasiconLinux.YoucanbuildmostkindsofLinuxapplicationwith
Gambas.HoweverGambasisespeciallystrongatprovidingGraphicalUserInterfaces(GUI)types
ofapplications.Theycanbestandaloneapplicationsorfrontendstoaserverordatabase.Gambas
providesallthetoolsyouwouldnormallyexpectinaIDE.Ithasaformdesignerwhereyoucan
dragcontrolsandcomponentsontoyourformstodevelopyouruserinterface.Italsohasaproject
manager,acodeeditor,acodeexplorerandanintegratedhelpsystem.Youcanalsocompile,run
anddebugyourapplicationsfromwithinGambas.ItisopensourceandsofitsinwiththeLinux
philosophy.
Gambasalsohasastrongusercommunity.Thereareanumberofusefulforumswherenewusers
cangethelp.ThereisanactiveGambasmailinglist.IftherearebugswithGambasthen,inmy
experience,theyarerapidlycorrected.SeetheGambasResourcessectionbelow.
GambasisdefinitelyaVisualBasicforLinux.ItisnotsimplyaportofMicrosoftVisualBasicto
Linux.HoweverWindowsusersofVisualBasic(atleastuptoversion6)willfindmuchinthis
environmentthatisfamiliar.
1.1:
GAMBasAlmostMeansBasicBASICstandsforBeginner'sAllPurposeSymbolicInstructionCode.Thislanguagewasdeveloped
byJ.KemenyandT.KurtzatDartmouthCollegetoteachbeginnerprogrammers.Eversinceithas
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page3of110
provedtoausefulfirstlanguageforbeginnerstolearn.BASICbecameverypopularwhenpersonal
computers(PC's)firstappearedinthe1970's.Thesmalloverheadsofthelanguageandtheeaseof
learningmadeitthelanguageofchoicefornewprogrammerswiththeirfirstPC.Microsoft
understoodthisandshippedQuickBASICforMSDOS.
AlanCooperiscreditedasthe'father'ofVisualBasicandsoldtheideatoMicrosoft.Microsoftalso
learnedfromHyperCardontheMacandin1991launchedVisualBasic1.0.Butitwasnotuntil
Windows3.0andVisualBasic3.0thatthisreallybecamepopular.Sincethenithasbecameoneof
themostdominantdevelopmentenvironment,bothinthehomeandinindustry.
TherehavebeenversionsoftheBASIClanguageforalmostalloperatingsystemsandLinuxisno
exception.TherehavebeenQuickBASIClikeUnix/Linuxversions.Therearealsoversionsof
VisualBasicforLinuxlikeHBasicandKBasic.Formoreinformationandexamplessee
http://www.thefreecountry.com/compilers/basic.shtml.Arguablythemostdevelopedandusableof
theVisualBasicsforLinuxisGambas.
GambaistheSpanishforprawn.GambasisalsoanVisualBasicIDEdesignedbyBenoit
Minisini.ThefirstpublicreleaseofGambaswasVersion0.20inFebruary2002.Therethen
followedagreatdealofdevelopmentworkandreleases.ThefirststablereleaseofGambaswas
Version1.0inJanuary2005.Sincethentherehavebeenanumberofbugfixestothestableversion.
AlsoinJanuary2005camethereleaseofthenewdevelopmentversionofGambas(verion1.9.1).
Thisversionwilleventuallybecomethestableversion2.0.
AllversionofGambasareissuedundertheGNUGeneralPublicLicenseandarefreetouse.Italso
meanstheGambasruntimeisfreetouseifyouneedtoinstallitonacustomersworkstation.As
Gambasisopensourceyoucanobtain,lookatand,ifyouneedto,modifythesourcecode.Alsothe
GambasIDEiswritteninGambas.
InthistutorialweareusingthelatestdevelopmentversionofGambas.Atthetimeof
writingthelateststableversionis1.0.16(2May2006)andthelatestdevelopment
versionis1.9.28(29April2006).
MostofwhatiswrittenhereshouldworkonthestableversionofGambas.Where
changesareneededyoushallseeanotelikethis.Lookforthesymbolontheleft.
AlsointheexampleprojectsthatarepartofthistutorialthereareversionsforGambas1
and2.
AllofthescreenshotsinthistutorialarefromGambasversion2.Someofthescreens
maylookslightlydifferentinGambasversion1ornewerinstallsofversion2.
IhavebeenusingthedevelopmentversionofGambasforaboutsixmonthsatthetimeofwriting
thistutorial.IwouldsaythatGambasismorestablethanMicrosoftVisualBasic6.Ihavehadfewer
crasheswiththedevelopmentversionofGambasthanwithproductionreleaseofVB6.Itisproperly
justasstableasMicrosoftVisualBasic.NET(boththe.NETruntimes1.0and1.1)whichIhave
alsousedquiteextensively.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page4of110
1.2:
ProjectsInthistutorialweshalldevelopthreeprojectsthatdemonstratesomeofthetypesofapplications
thatcanbebuiltwithGambas.
SimpleEdit
.Asimpletexteditor.Thisisasimplefirstapplicationtodemonstrateusingthe
developmentenvironment.Itwillshowhowbyusingsomeofthecomponentsfromthetool
boxandwithalittlecodingyoucanbuildausableapplication. ImageShow.
Aimagedisplayprogramforplayingaslideshowofimagesfromaselected
directory.ThisapplicationdemonstratssomeofthedrawingfunctionsinGambas.
Notations.
Aprojectforeditingandstoringusernotes.Thisprojectdemonstrateshowto
createauserinterfacetoadatabase.Theapplicationwillalsocreatethedatabaseifitdoes
notexist.Youcanthencreate,read,updateanddeleterecordsinthedatabase.
Thefollowingscreenshotshowsallthreeapplicationsinaction.
OneissueIamnotgoingtodealwithinthistutorialisinstallingGambasitself.Installing
applicationsonLinuxcanbecomeheftychapterinitself.LookattheResourcessectionofthis
introductionforlinkswereyoucanfindmorehelpandinformation.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page5of110
1.3:
GambasResourcesThesearesomeofthewebsiteswhereyoucanfindmoreinformationaboutGambas.Youmayneed
someoftheselinkstocompletethistutorialifyourLinuxdistributionhasnotincludedallthe
requiredresources.NewsourcesofinformationaboutGambasarecomingonlineallthetime.
IndeedIhavehadtoadditemstothislistanumberoftimeswhilewritingthistutorial.Ijustkeep
discoveredmoreinformationaboutGambasontheweb.Asalwayswithweblinkstheycanbecome
outofdatefastthesewerevalidinMay2006.
Gambas: TheGambasshrine SourceforgepageforGambasdownload
TheGambashelpWiki GambasWikiBooktextbook GermanGambasWikiBook
http://gambas.sourceforge.net/
http://gambas.sourceforge.net/download.html
http://www.gambasdoc.org/ http://en.wikibooks.org/wiki/Gambas
http://de.wikibooks.org/wiki/Gambas
YoucansubscribetotheGambasmailing
https://lists.sourceforge.net/lists/listinfo/gambasuser listhere:
ItalianGambassite GambasForums: LinuxBasic MyGambasCommunity
GermanGambasClub SitiowebdeGambas(InSpanish) MoreLinks: SQLite
MySQL PostgreSQL TangoDesktopProject GNULicenses
MonoVisualBasic.NET FreeBASICCompilersandInterpreters
http://www.sqlite.org/ http://www.mysql.org/
http://www.postgresql.org/ http://tangoproject.org/
http://www.gnu.org/licenses/
http://www.monoproject.com/Language_BASIC
http://www.thefreecountry.com/compilers/basic.shtml
http://www.linuxbasic.net/ http://forum.stormweb.no/
http://gambasclub.de/ http://gambas.gnulinex.org/
http://www.gambas.it/
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page6of110
1.4:
LicenseYouarefreetousethecontentofthistutorialandexamplesourcecodeasyouwish.Alsoyoucan
distributethistutorialtowhoeveryouwish.Iwouldrequestthatyouacknowledgetheauthorand
alsomakesurethesourcecodeforexampleapplicationsisfreelyavailable(bothforVersions1and
2ofGambas).Butyouarenotforcedtothis.ThetextofthistutorialisissuedundertheTheGNU
FreeDocumentLicense.Alloftheapplicationsandcodeexamplesfromthistutorialareissued
undertheTheGNUGeneralPublicLicense2.Fordetailsseehttp://www.gnu.org/licenses/.
1.5:
AcknowledgmentsManythankstoRohnnyStormoatMyGambasCommunityforcheckingoverthistutorial.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page7of110
2:
YourFirstGambasProject:SimpleEdit
Outfirstprojectisgoingtobeasimpletexteditor.Asastartingpointthismayseemalittle
ambitiousforsomeonewhohasneverprogrammedinGambasbefore.Admittedlyourtexteditoris
notgoingtobeasfullfeaturedassomeeditorsyoumayhaveused.Butstillitwillbeausabletext
editor.Thisprojectshowsthepowerofamoderndevelopmentenvironment.Byusingthe
functionalityofprebuiltcomponentsitiseasytobuildsomeusableapplicationsquickly.
WithSimpleEdityoucandomanyofthethingsyoucandowithanyothertexteditor.Youcanopen
andsavetextdocuments.Youwillhavetowriteabitofcodetoachievethis.ButtheTextArea
componentwearegoingtousealsogivesusalotoffunctionality.Thisincludesbeingabletocut,
copyandpastefromtheclipboard.Italsogivesusanundofacility.Andwedonothavetowriteany
codetoincludethisfunctionalityinourapplication.
InthisfirstprojectforGambaswearegoingtoprovidedetailedscreenshotsformostofthesteps.
Inthelaterexampleprojectsweshallassumeyoudonotneedsomanyscreenshots.Youcanalways
referbacktothisproject.
2.1:
CreatingtheprojectThefirststepistocreateanewGambasproject.SoopenGambasandandselectNewproject....
Thiswillstartthenewprojectwizard.Thefirstpageofthewizardsimplyshowsawelcomescreen
withdetailsofhowtousethenewprojectwizard.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page8of110
ClicktheNext>>buttonforthenextpageofthewizard.Thisshowsapagewereyoucanselectthe
typeofGambasprojectyouwanttobuild.Thetypesofprojectsinclude:
Agraphicalproject.Asthisisthemostoftenusedoptionanditisthedefaultoption.This
typeofapplicationwouldhavewindowswithwhichtheuserinteracts.Itwouldbe
controlledbythemouseand/orthekeyboard.
Aterminalproject.Youwouldrunthistypeofprojectfromaterminalwindow.Youcan
readandwritedatatostandardinput,errorandoutput.Itwillacceptparametersfromthe
terminalandalltheotherthingyouwouldexpectfromacommandlineapplication.
Copyanexistingproject.Youusedthisoptionifyouwanttocloneanexistingprojectto
useasthestartingpointforanewGambasproject.
ImportaVBproject.HereyoucanimportaprojectcreatedwithMicrosoftVisualBasic.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page9of110
Wearegoingtousethedefaultoptionofagraphicalproject.SoclicktheNext>>button.This
showsapagewhenyouenterthenameandtitleforyourprojectwearegoingtocreate.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page10of110
EnterthenameofSimpleEditandthetitleofAsimpletexteditor.Leavetheother
optionsunchecked.ClickontheNext>>button.Thisshowsapagewhereyouselectthedirectory
whereyouwanttosavetheprojectfiles.
Thefollowingscreenshotshowssavingyourprojecttothedocumentsdirectory.Thisis
simplytoillustratethedialogue.Howeveritmightbeeasiertosetupadirectorywhere
yousaveallyourGambasprojects.Youcouldthenstoreallyourprojectinonelocation.
Thiswouldthenmakemanagingyourprojectseasier.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page11of110
Selectthelocationwhereyouwanttosavetheproject.ThenclicktheNext>>button.Thisfinal
pageofthewizardliststheoptionsyouhaveselectedfortheproject.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page12of110
Checkthroughtheoptionsandthenclickthe
OKbutton.WehavecreatedanewVisualBasic
projectandGambaswillopenshowingthe Gambasprojectmanager.
Gambaswillalsoopentwootherwindows.One
isaToolbox.Thisshowssomeofthecontrols
wecanuseinourprojects.Theotheristhe
Propertieswindow.Thisiswheretheproperties
ofcontrolsinyourprojectcanbeedited.Aswe
havenotcreatedanycontrolsyetitwillbe blank.
IftheisthefirsttimeyouhaverunGambasyoumayseetwootheritems.Thefirstisa
TipofthedaywindowandtheotheristheGambasmascot.
OntheTipofthedaywindowthereisaClosebuttontohidethiswindow.Alsoifyou
donotwanttoseethiswindoweachtimeyoustartGambasthenthereisacheckbox
labelledShowtipsonstartupmakesureitisunchecked.IfyouwanttoseetheTipof
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page13of110
thedaywindowagaintheselectthe?(help)menuintheGambasprojectmanagerand
thentheTipofthedayoption.
TheotheritemyoumightseeistheGambasmascot.Somepeoplelikethisandothers
donot.Youcanselectwhetherthisisshownornot.IntheGambasprojectmanager
selecttheToolsmenuandthenthePreferences...option.Thiswillshowadialogue
wheremanyofthesettingsfortheGambasuserinterfacecanbechanged.Selectthe
Otherstab.IntheMiscellaneoussectionthereisacheckboxwhereyoucanselectif
theMascotisshownornot.IfyouselectnottoshowtheMascotitwilllooksad.
2.2:
CreatingtheuserinterfaceNowwehaveaGambasproject.Thenextstepistoaddsomeelementstotheprojecttogiveusa
userinterface.Thisprojectwillhaveonewindow.Mostofthiswindowwillbetakenupwitha
TextAreacontrol.Byusingthiscontrolwegetmostofthefunctionsforourtexteditor.Thewindow
willalsohavetwobuttonatthetopofit.Withthesebuttonsyouwillbeabletoopenandsave
documentsfromtheTextArea. RightclickintheGambasproject
manager.Thisbringsupapopup menu.FromthelistselectNew.This
showsasubmenuwiththeitemswe canaddtoourproject.Weneedtoadd
aFormtoactasthemainwindowto ourapplication.SoselectForm...from
thismenu.
Thismenuoptionshowsadialoguewherewecandefinesomeofthepropertiesoftheformweare
goingtocreate.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page14of110
GivetheformthenameofFormMain andaccepttheotherdefaultoptions.
Thestartupclassistheclassthe Gambasruntimewillfirstloadwhen
theapplicationisstarted.Therecan onlybeonestartupclassinyour
project.Wewantthisformtobethe startupclasssomakesurethisoptionis
checked.Leavealltheotheroptions unchecked.NowclicktheOKbutton
tocreatetheform.TheGambasproject managershouldnowlooklikethe
screenshotontheleft.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page15of110
Wenowneedtoaddsomecontrolsontotheformwehavejust
created.Firstweshalladdtwobuttons.Makesuretheformwe
havejustcreatedisvisible.Ifitisnotthendoubleclickontheform
intheprojectmanager.AlsomakesuretheToolboxisvisible.Ifit
isnotthenselecttheprojectmanagerViewmenthenToolboxsub
menuorpresstheF6key.
Thetoolboxhasseveraltabsthatgroupthekindsofcontrolswe
canuse.MakesuretheFormtabisselected.Whenyoumovethe
mouseoveritemsinthetoolboxthetooltipchangestoshowthe
typeofobject.SelecttheButtoncontrolinthetoolbox.
PlacetwoButtonsatthetopoftheformwindow.Youcandrag
anddropitemsfromthetoolboxontoaformdesignerwindow.It
ismucheasiertodothanitistodescribehowtodoit!
NowdothesamethingwithaTextArea.PlacetheTextArea undertheButtons.
MakesuretheTextAreaispusedupunderthetwoButtonsandon
thefarleftoftheform, InGambasversion1youwillseeonlyonetabforall
thecontrols.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page16of110
YourFormMainshouldnow looksomethinglikethescreen
shotoftheleft.Theexactsize oftheTextAreadoesnotmatter
solongasthetop,leftposition iscorrect.Thisisbecausewe
aregoingtoresizethis TextAreaatruntime. Thecontrolswillhavetheir
defaultname.Howeverthese defaultnamesdonotgiveand
informationabouthowwe intendtousethem.Itisgood
programmingpracticeto changetheirnamesto somethingmeaningfulforour
application.Thiswaywewill writeselfdocumentingcode.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page17of110
Wearenowgoingtochangesomeoftheproperties
ofthesecontrols.Ifthepropertieswindowisnot
visiblethenselecttheprojectmanageViewmenu
thenthePropertiessubmenuorpresstheF4key.
NowclickonButton1intheformdesigner.Thiswill
showthepropertiesforthisbutton.Wearegoingto
changetheNamepropertytoButtonOpenandthe TextpropertytoOpen...
Nowweshallchangethesomepropertiesforthe
othercontrolsontheform.ClickonButton2inthe
formdesigner.Thiswillshowthepropertiesfor
Button2.WearegoingtochangetheNameproperty
toButtonSaveandtheTextpropertytoSave...
FinallyclickonTextArea1intheformdesigner.We
aregoingtochangetheNamepropertyto
TextAreaEditandthendeletethetextintheText
property.InotherwordsmaketheTextproperty empty.
FinallyweshallchangeonepropertyontheForm.ClickontheformthenchangetheBorder
propertytoResizeable.Thefollowingtablelistthepropertieswehavechanged.
DefaultName FormMain Button1 Button2 TextArea1 Property Border Name
Text Name Text Name Text NewValue Resizeable ButtonOpen Open...
ButtonSave Save... TextAreaEdit
Ourformshouldnowlooklikethefollowingscreenshotwhenviewedintheformdesigner.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page18of110
Thatallweneedtodowiththeformdesigner.Inmanywaysitishardertodescribewhattodothan
doit.WecanseehoweasyitistobuildauserinterfaceinGambas.
2.3:
AddingthecodeItisnowtimetoaddsomecode.Infactwewedonotneedtoaddverymuchcode.Allweneedto
handleareresizingtheTextAreawhentheformisresized.Wealsoneedtohandleopeningand
savingatextfilewhentheuserclicksononeofthebuttons.
InVisualBasicyouwritecodetohandleevents.Eventsoccurwhensomethinghappenstoacontrol
orobject.Thecontrolorobjectfirestheeventtoallowothercontrolsorobjectstorespondanddo
somethingwhentheeventhappens.Foraformobjectpossibleeventsinclude:
Whentheformisopened Whenakeyispressed
Whentheformgetclickedbytheuser Whentheformisclosed
Alongwithmanyotherevents.Forabuttonpossibleeventsincludewhenitisclickedbytheuser
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page19of110
andwhenitisdoubleclicked.InVisualBasicyouwritecodetohookuptheeventsfiredbycontrols
orobjectstotheactionsyouwantyourapplicationtoperform.
WhenyoudoubleclickonacontrolorformintheFormdesigneritshowsthedefaulteventhandler
forthatobjectinthecodeeditor.Ifthecodedoesnotexistforthedefaulteventhandleritiscreated
foryou.ForaformthedefaulteventisForm_Open.Forthisapplicationwedonotneedtodo
anythingwhenthiseventisfired.Howeverwedoneedtoaddaneventhandlerforthe
Form_Resizeevent. Toaddtheformresizingevent
handlerrightclickontheform. (Makesureyourightclickon
theform,notontheTextArea oroneoftheButtons.)This
willshowapopupmenu.From thismenuselectEvent.This
willshowasubmenuofallthe eventsyoucouldhandlethat
aregeneratedbytheform. SelectResizefromthissub menu.
Thiswilladdastubforthe Form_Resizeeventtothe
codeintheformsclass.Now weshalladdtheeventhandlers
forthebuttonclickevents.As theclickeventisthedefault
eventforthebuttonitismuch simplertoadd.IntheGambas
formdesignerDoubleclickon theButtonOpenbuttontoadd
theButtonOpen_Click event.Finallydoubleclickon
theButtonSavebuttontoadd theButtonSave_Click event.
Thesearealltheeventswewanttohandleinthisapplication.Attheendofcreatingtheevent
handlestheGambascodeeditorshouldlooksomethinglikethefollowingscreenshot.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page20of110
Nowweshalladdthecodefrom thefollowinglistingtotheseevent
stubs.Notethat iconinthe followinglistingmeansthatthisis
acontinuationofthepreviousline. HencefortheForm_Resize
eventneedonlyaddonelineof code.Soenterthefollowingcode
intothecodeeditor.
FormMain.class 'Gambasclassfile PUBLICSUBForm_Resize()
TextAreaEdit.Resize(ME.ClientWidth,ME.ClientHeight
TextAreaEdit.Top) END PUBLICSUBButtonOpen_Click()
IFDialog.OpenFile()THENRETURN
TextAreaEdit.Text=File.Load(Dialog.Path) CATCH
Message.Error(Error.Text) END PUBLICSUBButtonSave_Click()
IFDialog.SaveFile()THENRETURN
GettingStartedwithGambasVersion2:ATutorial
[email protected]
File.Save(Dialog.Path,TextAreaEdit.Text) CATCH
Message.Error(Error.Text) END
Page21of110
Youmightbewonderingwhatsomeofthiscodedoes.Soletslookindetailatthiscode.Inthefirst
procedureweresizetheTextAreawhenevertheformisresized.Thisresizeeventalsooccurswhen
theformisfirstcreatedsowedonothavetoaddextracodetohandlethiscase.
Thefirstlineofcodetellsuswearegoingtohandletheformresizeevent.Thenameforevent
handlershavethefollowingformat:
Thenameoftheobjectthatfirestheevent Anunderscore
Thenameoftheevent
SoherewearesayingwearegoingtohandletheResizeeventontheFormobject.
PUBLICSUBForm_Resize()
WethencalltheResizemethodontheTextArea.HerewetelltheTextAreawhatsizewewantitto
be. TextAreaEdit.Resize(ME.ClientWidth,ME.ClientHeight
TextAreaEdit.Top)
TheResizemethodtakesparametersthatsetthewidthandheightoftheTextArea.Wecalculatethe
sizebaseduponthesizeofthecurrentform.MEstandsforthecurrentobject,inthiscasethecurrent
form.NotethatweuseClientWidthandClientHeightwhenwegetthesizeofthecurrent
form.TheClientXXXpropertiesalwaysgivethecorrectsize.TheformalsohasWidthand
Heightproperties.Butthevaluetheyreturndependsonwhethertheformismaximised.Sothey
mightnotreturnthevalueyouexpect.Alsowewanttoleavespaceatthetopoftheformsothatour
buttonsarevisible.SowehavetodeductthevalueforthetopoftheTextAreafromtheheightofthe
form.
Thefinallinefortheproceduresignalswherethecodefortheeventends. END
Thenextlinetellsuswearehandlingtheclickeventfortheopenfilebutton.
PUBLICSUBButtonOpen_Click()
Thefirstthingweneedtodointhisprocedureisgetthepathofthefiletheuserwantstoopen.The
GambasDialogobjecthasanumberofmethodswithwhichyoucandisplayanumberofcommon
dialogs.Amongtheseisaopenfiledialogue.Alsoiftheusercancelsthedialogueweshouldexit
ourprocedureandnonothingfurther.Givingtheuserthechancetocancelanactionisgood
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page22of110
programmingpractice.TheOpenFilemethodreturnsFALSEwhentheuserclicksontheOK
buttonandTRUEotherwise.ByplacingthisstatementinsideanIFwecancheckthereturnvalueof
theOpenFilemethod.TheRETURNstatementcausestheproceduretoquitimmediately.Soifthe
userdoesnotclickontheOKbuttonafterselectingafilenamewethenweexitfromthis
procedure.Atfirstthislinelookssomewhatcounterintuitive.Butthiswayofcallingthedialogdoes
worksverywellwhenyougetusedtoit. IFDialog.OpenFile()THENRETURN
WhenwereachthenextlineweknowtheuserhasclickedontheOKbuttonandselectedafile.The
DialogobjecthasapropertycalledPathwhichwecanusetogetthefullpathtotheselectedfile.
YouusetheFileobjectwhenperformingfileinputandoutput.TheFileobjectalsohasuseful
methodsforquicklyreadingatextfile.HereweusetheFile.Load()method.Ittakesas
parameterthepathtoourfileandthenreturnsthecontentofthefileasatextstring.Thisfunction
handlesalltheopening,readingandclosingofthefileforus.Itiseasytousethisfunctionwhenwe
wanttheentirecontentofaplaintextfile.WepassthecontentofthetextfileTextArea'sText
property.ThisreplacestheentirecontentoftheTextAreawiththecontentofthefilewehave
opened. TextAreaEdit.Text=File.Load(Dialog.Path)
Wealsoneedtohandleanypossibleerrorsinourapplication.Thisisespeciallytruewhenyou
communicatewithanythingoutsideyourapplication.Herewehaveadialoguewheretheuserenters
input.Wealsohaveafilethatcouldcontainalmostanything.Withoutthefollowingerrorhandler
ourprogramwouldcrashiftheuserselectedaninvalidfileorafilewheretheydidnothaveread
permission.IfanyerroroccursthentheGambasruntimejumpstothisCATCHstatement.Herewe
willjustdisplayamessagetotheuser.ByusingtheErrormethodontheMessageobjectwe
displayaerroriconinthemessagebox.Herewehavekeptthemessageassimpleaspossible.We
simplyshowthetextfromtheerrorthatwascreated. CATCH
Message.Error(Error.Text) END
CodeafteraCATCHstatementisnotexecutedwhennoerroroccurs.Sowithvalidfilestheuserwill
neverseethemessagebox.
Thecodeforthesavefilebuttonisverysimilartothatoftheopenfilebutton.Thefirstlinetellsus
wearehandlingtheclickeventforthesavebutton.
PUBLICSUBButtonSave_Click()
Thistimewecallthesavefiledialogwhichisverysimilartotheopenfiledialogweusedabove.
Butthisdialoghasfunctionalitymoreappropriatetosavingafile.AgainthisdialogreturnsFALSE
whentheuserclicksontheOKbuttonandTRUEotherwise.SoiftheuserdoesnotclickontheOK
buttonafterselectingafilenameweexitfromtheprocedure.
IFDialog.SaveFile()THENRETURN
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page23of110
AgainweusetheFileobjectforsaving.Thisobjectalsohasausefulmethodforsavingtextfiles.
Wesimplyneedtotellitwhatpathtousewhensavingthefileandwhatstringtosave.Here,of
course,wearegoingtosavethecontentofourTextArea.
File.Save(Dialog.Path,TextAreaEdit.Text)
Hereagainwehavethesamekindoferrorhandlerasfortheopenfilebutton.
CATCH Message.Error(Error.Text) END
2.4: RunningtheprojectThat'severythingweneedforthisproject.So
letsrunit.Youruntheprojectbyclickingon
thegreenRunbuttonintheprojectmanager
windoworbypressingtheF5key.
Iftheprojectdoesnotrunthemostlikelycauseisamisspellinginthecodeweentered.
LookasthelinethatGambashighlightswhenfindinganerrorandcheckthenames
matchthenamesofthecontrolsontheform.Alsocheckthesyntaxofthehighlighted
linematchesthecodeexample.
Hereisascreenshotofthefinalrunningapplicationafterwehaveopenedthecodefileforthis
project.Asyoucanseethecodeisthesameasabove,butthereareextracommentsinthisfile.
Thesecommentsareintheexamplesthatcomewiththistutorial.Thescreenshotalsoshowsapop
upmenuwithoptionsforeditingthetext.ThismenuispartoftheTextAreacontrol.Yougetthis
menuforfreebyusingthiscontrol.TryrightclickingontheTextAreainyourapplicationwhenitis
running.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page24of110
Whenyoudevelopanykindofapplicationyouneedtotestitsfunctionality.Aboveallyoushould
notbeabletocrashtheapplication.Itshouldbeabletohandleanyerrorsgracefullyandgivethe
userausefulerrormessage.Evenforanapplicationassmallasthisyoushouldhaveatestplan.
Butwhatshouldyoutest?Thesearethemostlikelyproblemareaswithanyapplication:
Yourcode.Yourtestsshouldcovereverylineofcodeintheapplication.Thisincludesall
branchesisaselection.Alsoeveryloopshouldbetestedforzero,oneandmanyiterations.
Interactionbetweenobjects.Itisoftenintheinteractionbetweenobjectswhereerrors
occur.Thereshouldbeatestforeveryachievableinteractionbetweenobjects(interaction
thatareonlytheoreticalneednotbetested).
Interfacestotheworldoutsideyouapplication.Anyusefulapplicationhasto
communicatewithsomethingoutsideofitself.Yourapplicationshouldnottrustanydata
fromoutsideofitselfuntilithasbeenvalidatedinsidetheapplication.Thisincludesuser
inputaswellandcommunicationstoanydevices.Youalsoneedtotestforanymixof
otherwisevalidinputsthattogetherareinvalid.Alsoanyinvaliddatashouldbehandled
appropriately.
Normallyyouwouldnottestthefollowingitems(exceptwhenbuildingacriticalsystemsuchas
applicationforuseisahospital):
Operatingsystemfunctions.Thesecouldbesystemcallsorshellcommands.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page25of110
Inbuiltcontrolsforyourprogrammingenvironment.
Anythirdpartycomponentsinyourapplication.
Theseareitemsyouhavelesscontrolover.Iftherearefaultswithanyoftheseitemsthenyouwould
properlyhavetochangeyourapplicationtoworkaroundthefault.
Agoodwaytototestyouapplicationistoproduceatableoftests.Ideallyyouwouldproducethis
tablebeforeyoustartedcodingtheapplication.Ifnewfeaturesarelateraddedtotheapplication
thenaddmoreteststothetable.Inthetableyouwouldwritedowneachofthetestandtheresult
youexpectforthetesttopass.Youneedtostatetheexpectedresultsothereisnoambiguityifyour
applicationdoessomethingdifferent.Thefinalcolumnisforyoutorecordtheresultsofthetesting
process.Ourfirstsetoftestsdealwithresizingtheapplicationwindow.
FormResizingTests Test Resizethewindowusingrightedge
Resizethewindowusingbottomedge Resizethewindowusingleftedge
Resizethewindowusingtopedge ExpectedResult
Windowshouldberesizeandthetextarea resizedtofitinthewindow.
Asabove. Asabove. Asabove. Pass/Fail
Resizethewindowusingnorth/westcorner Asabove.
Resizethewindowusingsouth/westcorner Asabove.
Resizethewindowusingsouth/eastcorner Asabove.
Resizethewindowusingsouth/eastcorner Asabove.
Minimizethewindowandrestoreit Maximisethewindowandrestoreit
Thewindowshouldbecorrectlyresize whenrestored.
Windowshouldresizeandthetextarea resizetofitinthemaximisedwindow.
Thewindowshouldbecorrectlyresize whenrestored.
Makethewindowheightsmallerthenthe
Youwillnotseethetextarea.Noerror toprowofbuttons shouldresult.
Makethewindowwidthsmallerthanthe widthofbothbuttons
Noerrorshouldresult.
Thenextsetoftestsareforthebuttonwhichopensatextfile.
GettingStartedwithGambasVersion2:ATutorial
[email protected] OpenFileTests Test Opentextfile
Openanemptytextfile Openaverylargetextfile Openabinaryfile
Trytoopenafilethatdoesnotexist Trytoopenafilewhereyoudonothave
readpermission ExpectedResult Filedisplayedintextarea Textareaempty
Filedisplayedintextarea. Filedisplayedintextarea.Contentis
properlynotverymeaningful Errormessage Errormessage
Page26of110
Pass/Fail
Thefinalsetoftestsareforthebuttonwhichsavesatextfile.Whenpreformingthesavefiletests
makesureyoudonotoverwriteanyfilesyouneedoranysystemfiles.
SaveFileTests Test Entersometextinthetextareaandsavea Filesaved
newtextfiletoyourHomedirectory Entersometextinthetextareaandsaveto
Filesaved anexistingfileinyouHomedirectory.
Withnotextinthetextareasaveanempty Filesaved
filetoyourHomedirectory Openanbinaryfileandsavethisasanew Filesaved
file Trytosavethefiletoadirectorywhere youdonothavewritepermission
Errormessage ExpectedResult Pass/Fail
Trytosavethefiletoadirectorythatdoes Errormessage notexist
Wehaveendedupwithmoreteststhanlinesofcodeinourapplication.Thismayseemoverkillfor
yourfirstproject.Butthemorethoroughyouareattestingthemoreusefulyourapplicationswillbe
tootherusers.Gettingusedtoatoughtestingregimefromthestartwillpaydividendsinthelong
run.Therealproblemisbeingasmeticulousasyoucaninyourtests.Youneedtocoveranymany
optionsaspossibleandmakesureallcodeiscovered.Onehundredpercentcoverageisnotpossible,
butyoushouldaimforthis.
Soworkthroughthelistoftextandmakesureyourecordiftheypassorfail.Ifanytestfailsyou
willneedtodebugthecodetofindthefault.Alsoarethereanyteststhatshouldbeaddedtothe
GettingStartedwithGambasVersion2:ATutorial
[email protected] list?
OneofthebestpiecesofadviceIcangiveyouis:
Usetheapplicationsyoubuildyourself.
Page27of110
Ifyoubuildapaintprogramthenuseitforallyourdrawingtasks.Thatwayyoufind
whatfeaturesyouneedtoadd.(Andalsowhatfeaturesseemedagoodideaat
developmenttime,butarelittleused.)Alsoafterafewweeksmakesureyouthinkagain
abouthoweasyitisforanewusertolearnyourapplication.
Thatwasnottohard.Wehavecreatedabasicbutperfectlyfunctionaltexteditor.Wehaveachieved
thisbyusingthepowerofexistingcomponents.Thecorefunctionalityforourtexteditorwas
alreadycontainedintheTextAreacontrol.
Youcouldgoonaddingfeaturestothisprojectanddevelopitasyourowntexteditor.Forexample
youcouldaddsomebuttonstocut,copyandpastetext.Thenhooktheseuptothemethodsonthe
TextAreacontroltohandlethisfunctionality.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page28of110
3:
DrawingProject:ImageShow
Withthisprojectwearegoingtocreateasimpleslideshowapplication.Wewanttheprojecttohave
thefollowingfunctionality:
Theapplicationshoulddisplayimagesfromaselecteddirectory.
Thedisplayshouldbefullscreen.
Imagesshouldbedisplayedfullsizeandcentredonthescreen.
Ifanimageislargerthenthescreenthenitshouldbescaledtofitonthescreenkeepingthe
aspectratiooftheimage.
Onceadirectoryisselectedtheapplicationwillscrollthroughtheimagesdisplayingone
every15seconds. PressingtheEscapekeywillquittheapplication.
PressingF1willdisplayabriefhelpscreen.
Pressingspacebarorrightarrowwillscrolltothenextimage.
Pressingthebackspacekeyorleftarrowwilldisplaythepreviousimage.
Pressingthe'D'keywillallowtheusertochangetheimagedirectory.
Pressingthe'S'willstartorpausetheslideshow
Pressingthe'I'keywilldisplayinformationabouttheimage/show.
Themouseshouldbehiddenwhenimagesaredisplayed.
Thislookslikealonglistbutasweshallseethefinalapplicationisnotthatcomplex.
3.1:
CreatingtheprojectThefirststepistocreateanewGambasproject.SoopenGambasandandselectNewproject....
Thiswillstartthenewprojectwizard.Thefirstpageofthewizardsimplyshowsawelcomescreen
withdetailsofhowtousethenewprojectwizard.ClicktheNext>>buttontoforthenextpageof
thewizard.ThisshowsapagewerewecanselectthetypeofGambasprojectwewanttobuild.We
aregoingtousethedefaultoptionofagraphicalproject.SoclicktheNext>>button.Thisshowsa
pagewhenyouenterthenameandtitleforyourprojectwearegoingtocreate.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page29of110
EnterthenameofImageShowandthetitleofAsimpleimageslideshow.Leavethe
otheroptionsunchecked.ClickontheNext>>button.Thisshowsapagewhereyouselectthe
directorywhereyouyouwanttosavetheprojectfiles.
Selectthelocationwhereyouwanttosavetheproject.ThenclicktheNext>>button.Thisfinal
pageliststheoptionsyouhaveselectedfortheproject.Checkthroughtheoptionsandthenclickthe
OKbutton.WehavecreatedanewVisualBasicprojectandGambaswillopenshowingtheGambas
projectmanager.
3.2:
CreatingtheuserinterfaceNowwehaveaGambasproject.Thenextstepistoaddsomeelementstotheprojecttogiveusa
userinterface.Thisprojectwillhaveonewindowthatwillbedisplayedfullscreen.Allofthis
windowwillbetakenupwithaDrawingAreacontrol.Wecoulddrawtheimagedirectlyontheform
butusingaDrawingAreagivesussomeextrafunctionality.Wewillalsoputatimerontheform.
Thisissowecanfireeventstochangeimagesassetintervals.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page30of110
RightclickintheGambasprojectmanager.
Thisbringsupapopupmenu.Fromthelist
selectNew.Thisshowsasubmenuwiththe
itemswecanaddtoourproject.Weneedto
addaFormtoactasthemainwindowtoour
application.SoselectForm...fromthis menu.
Thismenuoptionshowsadialoguewherewe
candefinesomeofthepropertiesoftheform wearegoingtocreate.
GivetheformthenameofFormImageShowandaccepttheotherdefaultoptions.Thestartup
classistheclasstheGambasruntimewillfirstloadwhentheapplicationisstarted.Therecanonly
beonestartupclassinyourproject.Wewantthisformtobethestartupclasssomakesurethis
optionischecked.NowclicktheOKbuttontocreatetheform.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page31of110
Wenowneedtoaddsomecontrolsontotheformwehavejust
created.FirstweshalladdaTimer.Makesuretheformwehave
justcreatedisvisible.Ifitisnotthendoubleclickontheformin
theprojectmanager.AlsomakesuretheToolboxisvisible.Ifitis
notthenselecttheprojectmanagerViewmenuthenToolboxsub
menuorpresstheF6key.
Thetoolboxhasseveraltabsthatgroupthekindsofcontrolswe
canuse.MakesuretheSpecialtabisselected.Whenyoumove
themouseoveritemsinthetoolboxthetooltipchangestoshow
thetypeofobject.SelecttheTimercontrolthethetoolbox.
PlaceaTimerontheformwindow.Youcandraganddropitems
fromthetoolboxontoaformdesignerwindow.Itdoesnotmatter
whereyouputthetimerasitwillnotbevisiblewhentheprogram isrun.
NowmakesuretheContainertabisselected.Selectthe
DrawingAreacontrolinthetoolboxandplacethisontheform.It
doesmatterwhereyouplacetheDrawingAreaasitwillberesized atruntime.
ForGambasversion1thesetwocontrolsareonthe Formtab.
AtthispointourFormImageShowshouldlooklikethefollowing
screenshot.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page32of110
Thecontrolswillhavetheirdefaultname.Howeverthesedefaultnamesdonotgiveanyinformation
abouthowweintendtousethem.Itisgoodprogrammingpracticetochangethenamesto
somethingmeaningfulforourapplication.Thiswaywewillwriteselfdocumentingcode.
Wearenowgoingtochangesomeofthepropertiesofthese
controls.Ifthepropertieswindowisnotvisiblethenselectthe
projectmanageViewmenuthenPropertiessubmenuorpressthe
F4key.NowclickonTimer1intheformdesigner.Thiswillshow
thepropertiesforthisobject.WearegoingtochangetheName
propertytoTimerShow.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page33of110
ClickontheDrawingAreaobjectandchangetheName
propertytoDrawingAreaImage.
Thatallofthepropertieswearegoingtochangeinthe
Formdesigner.Someotherpropertiesoftheseobjectswill
bechangedinthecode. Wewanttoshowsomehelpinformationstotheuserwhen
theypresstheF1key.Themethodwearegoingtouseis
suitablewhentherequiredamountofhelpissmallandwill
fitononepage.TheGambasMessageboxisquitea
flexibleclassandwilltakeaHTMLformattedmessage.
Sowiththesinglelineofcode: Message.Info(File.Load("help.htm"))
wecandisplayaHTMLfile.
SoletcreatetheHTMLfileinGambas.Right
clickintheGambasprojectmanager.This
bringsupapopupmenu.Fromthelistselect
New.Thisshowsasubmenuwiththeitems wecanaddtoourproject.Weneedtoadda
TextfilesoselectTextfile...fromthismenu.
Thisshowsadialoguewherewegivethetextfileaname.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page34of110
Givethefilethename help.htmandpressthe OKbuttontosaveit.This
willaddthefiletothe datasectionofyour projectandwillopenthe
newtextfileinthe Gambastexteditor window.Thescreenshot
ontheleftshowsthe Gambastexteditor windowafterwehave
enteredsomeHTMLinto it.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page35of110
ThisisnotatutorialaboutHTMLthereareplentyofthoseontheinternet.Sowearenotgoingto
saymuchaboutthisfile.JustenterthefollowingHTMLintothetexteditor.Notethat,asbefore,the
iconinthefollowinglistingmeansthislineisacontinuationofthepreviousline.
help.htm ImageShowHelp ImageShowHelp
ImageShowpresentsaslideshowofimagesfromadirectory youselect.
Thefollowingkeyscanbeusedwhileviewingimages:
TheSpacebarorRightArrowkeystoshowthenextimage
TheBackspaceorLeftArrowkeystoshowtheprevious
image
TheDkeytoselectanew picturedirectory
TheIkeytoshow informationabouttheimage
TheSkeytoggles startingandpausingtheshow
TheEsckeytoquit
TheF1keyforhelp
ImageShowv.0.0.1wasdevelopedbyTimothyMarshalNichols
inMay2006.ItisissuedundertheTheGNUGeneralPublic
License2.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page36of110
TheGambascontrolsthatacceptHTMLformattingonlytakeasubsetofHTMLtags.Soitis
sometimestrialanderrortofindoutwhatworks.ThefollowingscreenshotshowswhatthisHTML
lookslikeinamessageboxwhentheapplicationisrunandtheuserpressestheF1key.
Thatalloftheelementsweneedfortheuserinterface.Alltherestoftheapplicationsfunctionality
isgoingtobedoneincode.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page37of110
3.3:
AddingtheCodeTherearethreeeventweneedtohandleinthisapplication.Weneedsomesetupcodewhenthe
applicationopens.Whentheuserpressesakeyonthekeyboardweneedtocheckthekeypressand,
ifrequired,respond.Wealsoneedtoupdatethescreenimageevery15secondswhentheslideshow
isrunning.
Soletsaddtheseeventstoourapplication.Thefirsteventiseasydoubleclickonthe
FormImageShowintheformdesigner.ThiswilladdtheeventForm_OpentotheFormImageShow
class.
Nextweshalladdtheeventforauserkeypress.RightclickontheontheFormImageShowinthe
formdesigner.Thiswillshowapopupmenu.SelecttheEventsoptionandthenfromthesubmenu
selectKeyPress.ThiswilladdtheeventForm_KeyPresstotheFormImageShowclass.Finally
doubleclickontheTimerShowobjectontheFormImageShow.Thiswilladdtheevent
TimerShow_TimereventtoFormImageShowclass.
Whenyouhaveaddedtheseevents theFormImageShowclassshould
looklikethisscreenshot.
NowweshalladdcodetotheFormImageShowclass.Inthistutorialchapterweshallsplitthecode
intochuckssothatwecandescribeeachsection.Weneedtwovariablestostoreinformationabout
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page38of110
ourslideshow.ThefirstvariableisaarrayofstringscalledpictureFiles.Hereweshallstore
thefilepathstoallinimagesinourslideshow.ThenextvariableispictureNumberwhichwill
holdtheindexnumberofthecurrentlydisplayedimage. FormImageShow.class
PRIVATEpictureFilesASNEWString[] PRIVATEpictureNumberASInteger
ContinuedBelow
NoticethatwedeclarethesevariablesasPRIVATE.Lateronyouwillseethatvariablesdeclared
insideaprocedureorfunctionaredeclaredusingtheDIMstatement.HoweverinGambaswhen
declaringvariablesatmoduleorclasslevelyouneedtousethePUBLICorPRIVATEkeywords.
WeshalladdcodetotheForm_Openeventwecreatedearlier.Thiseventfireswhentheformis
firstshownandonlyfiresonce.Itisausefulplacetoputanysetupcodeyouneedforaform.We
startbysettingtheformsbackgroundtoblackandmakingtheformfullscreen.(Gambasversion1
usersseethenotebelow.)
WethensetthechangesweneedtotheDrawingArea.WeresizetheDrawingAreawiththemove
statement.NormallywewouldusetheME.ClientWidthandME.ClientHeightproperties
togetthesizeofthecurrentform.Inmostcasesthesearethepropertiesyoushoulduse.Buthere
theyarestillsettotheoldformsize.Theydonotappeartobecomesettothevalueswewantuntil
theformresizeeventiscalled.AswewanttheformtobefullscreenwecanusetheDesktopobject
togetthevaluesweneed.TheDesktopobjectgivesussomeusefulinformationaboutthescreen.
AlsofortheDrawingAreawesettheCashedpropertytoTRUE.Whenthispropertyissetthe
DrawingAreawillautomaticallyhandlerefreshingofitselfifthecurrentpictureneedstobe
redrawn.ThismeanswelettheDrawingArearedrawthecurrentpicturewhenneeded.Weonlyneed
tothinkaboutdrawingwhenwewanttochangethepicture.
Wethencalltwofunctions.Thefirstallowstheusertoselectadirectoryfromwhichtobuildalist
ofimages.Thenextfunctionwilldisplayanimage.Thecodeforthesefunctionsisdescribedlater
on.Aftercallingthesefunctionswehidethemousesoitdoesnotdetractfromtheimage.
Finallywesetuptheshowtimer.Wesetthedelaytimebetweenimagesto15seconds.Butweonly
starttheshowtimerifwehavesomeimages.
FormImageShow.classContinued
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page39of110
PUBLICSUBForm_Open() 'Setformproperties ME.BackColor=Color.Black
ME.FullScreen=TRUE 'Setdrawingareaproperties
DrawingAreaImage.Move(0,0,Desktop.Width,Desktop.Height)
DrawingAreaImage.Cached=TRUE 'Selectimagedirectory
Dialog.Path=User.Home SelectImages() NextPicture() 'Hidemouse
DrawingAreaImage.Mouse=Mouse.Blank 'Startshowtimer
TimerShow.Delay=15000'15seconds
TimerShow.Enabled=(pictureFiles.Count>0) END ContinuedBelow
InGambasversion1youuseaslightlydifferentmethodofdisplaystheformfullscreen.
TheME.FullScreen=TRUElineintheabovelistingneedstobechangedtothe
following: ME.State=Window.Fullscreen
AlsotoselecttheusershomedirectoryyouusetheSystemobject.
Dialog.Path=System.Home
Thisnexteventhandlesanykeypressourapplicationreceives.Whenevertheuserpressesakeywe
selecttheoptiontheuserwants.WeusetheTimerShow.Enabledpropertyasaflagtoindicate
iftheimageshowisrunningorpaused.Forsomeofthekeypressoptionswewanttorestorethe
imageshowtoitspreviousstate.SowestorethecurrentstateinthevariabletimerState.
TheKeyobjectgivesusinformationaboutthelastkeypress.TheKey.Codepropertygivesusthe
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page40of110
keyboardcodeandwecancomparethiswithconstantsintheKeyobjectinourSELECTstatement.
WhentheEscapekeyispressedweuseME.Close()toendtheapplication.IftheF1keyis
pressedweholdtheimageshowandthendisplayourHTMLhelpfileinamessagebox.Whenthe
userclosesthemessageboxtheimageshowstateissettothesavedstate.
InGambasversion1themessageboxgetslostbehindtheformwhentheformisfull
screen.SoamendthecodefortheF1buttontothefollowing:
TimerShow.Enabled=FALSE DrawingAreaImage.Mouse=Mouse.Default
ME.State=Window.Normal ME.Border=Window.Resizable
Message.Info(File.Load("help.htm")) ME.State=Window.FullScreen
DrawingAreaImage.Mouse=Mouse.Blank TimerShow.Enabled=timerState
Thehelpmessagedoesnotlookasgoodasinversion2ofGambas.Butatleastitdoes
notgetlost.
Thenexttwocaseshandletheusermanuallyadvancingthecurrentimage.Whentheuserpresses
theRightArroworBackspacekeywedecrementthecurrentimagecounterandthencallour
proceduretodrawtheimage.SimilarlyiftheuserpressestheLeftArroworSpacebarkeywe
incrementthecurrentimagecounterandthencallourproceduretodrawtheimage.
WhentheDkeyispressedwehandletheuserchangingtheselecteddirectoryforimages.Firstwe
pausetheslideshow.Thenweshowthemousebysettingittoitsdefaultcursor.Itcouldbe
confusingtotheusertokeepthemousehidden.Wethencalltwofunctionsthatweusedinthe
Form_Openevent.Thefirstallowstheusertoselectadirectoryfromwhichtobuildalistofimages.
Thenextfunctionwilldrawanimage.Wehidethemouseagainandstarttheshowtimerifwehave
someimages.
TheSkeytogglespausingtheslideshoworstartingitrunningagain.Whenpausingtheslideshow
wesimplydisabletheslideshowtimer.Weonlyallowtheslideshowtostartiftherearesome
imagestodisplay.Iftherearesomeimagesweincrementthecurrentimagecounteranddisplaythe
nextimage.Thisgivesavisualconfirmationtotheuserthattheslideshowhasstartedrunning
again.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page41of110
WhentheIispressedwecallaprocedurethatdrawssomeinformationonthescreenaboutthe
currentstateoftheslideshowandthecurrentimage.Thisprocedureisdescribedlater.
FormImageShow.classContinued PUBLICSUBForm_Press()
DIMtimerStateASBoolean timerState=TimerShow.Enabled
SELECTCASEKey.Code CASEKey.Esc 'Closetheslideshow ME.Close()
CASEKey.F1 'ShowHTMLhelp TimerShow.Enabled=FALSE
DrawingAreaImage.Mouse=Mouse.Default
Message.Info(File.Load("help.htm"))
DrawingAreaImage.Mouse=Mouse.Blank TimerShow.Enabled=timerState
CASEKey.BackSpace,Key.Left 'Showpreviouspicture
TimerShow.Enabled=FALSE DECpictureNumber NextPicture()
TimerShow.Enabled=timerState CASEKey.Space,Key.Right
'Shownextpicture TimerShow.Enabled=FALSE INCpictureNumber
NextPicture() TimerShow.Enabled=timerState CASEKey["D"]
'Getanewslideshowfromadirectory TimerShow.Enabled=FALSE
DrawingAreaImage.Mouse=Mouse.Default SelectImages()
GettingStartedwithGambasVersion2:ATutorial
[email protected] NextPicture()
DrawingAreaImage.Mouse=Mouse.Blank
TimerShow.Enabled=(pictureFiles.Count>0) CASEKey["S"]
IFTimerShow.EnabledTHEN 'Iftheshowisrunningthenstopit
TimerShow.Enabled=FALSE ELSEIFpictureFiles.Count>0THEN
'Iftheshowisnotrunningandwehavepictures
'thenstarttheshowwiththenextpicture INCpictureNumber NextPicture()
TimerShow.Enabled=TRUE ENDIF CASEKey["I"]
'Showsomeinformationabouttheshow ShowMessage() DEFAULT 'Nothing
ENDSELECT END ContinuedBelow
Page42of110
Whentheimageshowisrunningatimereventwillbefired.Hereweincrementthecounterwehave
fortheimagenumberby1andthencallourfunctiontodrawtheimage.Wewrapthedrawingcall
withEnablingandDisablingatimer.Thisisproperlynotneededandisahangoverfromcodingin
anotherVisualBasic.Ihaveputthisinsoweresetthetimerafterhavingcompleteddrawingthe
image. FormImageShow.classContinued PUBLICSUBTimerShow_Timer()
TimerShow.Enabled=FALSE 'Gotothenextimage INCpictureNumber
GettingStartedwithGambasVersion2:ATutorial
[email protected] 'Drawthenextimage NextPicture()
TimerShow.Enabled=TRUE END ContinuedBelow
Page43of110
Wehavecalledthisnextprocedureseveraltimesabove.Itallowstheusertoselectanewimage
directoryandloadsthepathsoftheimagefilesintopictureFilesarray.Firstwecallastandard
dialoguethatallowstheusertoselectadirectory.Callingthisdialogueissimilarthewayweopened
andsavedfilesintheSimpleEditprojectabove.IftheuserdoesnotselectatheOKbuttonanda
directorywereturnfromtheprocedure.TheDialog.Pathpropertyreturnsthenameandpathof
theselecteddirectory.Iftheuserselectsadirectorywecleartheoldlistofimagefiles.
UsingtheDirfunctionwecanobtainalistofallfilesinadirectory.Asthislistisnotsortedwe
usetheSort()methodonastringarraytosortthefilelist.WethenuseaFORNEXTconstructto
loopthrougheachofthefiles.TheFileclassprovidessomeusefulmethodforextractingelements
fromafilepath.HerewewanttotestthefileextensionforeachfilesoweusetheFile.Ext
method.Inordertoprovideacaseinsensitivesearchforimagesweconverttheextensiontolower
case.WethentestthefileextensionfortheimagefiletypessupportedbyGambas.Ifwehavefound
aavalidimagefilenamethenweaddthefullfilenameandpathtoourimagefilelist.
Whenwehavecompletedtheloopwechecktoseeifwehavefoundanyimagefilesinthedirectory.
Ifwehavenotwedisplayamessagetotheuser.Wethensetthecurrentimageindextothefirst
image.WehaveaCATCHherebecauseweareinterfacingwiththefilesystemandthereisthe
possibilityoffileI/Oerrors.Hopefullytheuserwillneverseethiserrormessage.
Wehavebuiltalistofimagesbasedupontheextensionofthefile.Inmostcasesthiswillproducea
validlist.Howeverjustbecauseafilehasanextensionofjpgdoesnotmeanitisavalidjpgimage
file.Ausercangiveafileanynametheywant.Hencewhenwedisplaytheimagesweshallstill
needsomeerrorcheckingcode. FormImageShow.classContinued
PRIVATESUBSelectImages() DIMfileNameASString DIMfileListASString[]
DIMfileExtensionASString 'Getthedirectorynamefromtheuse
GettingStartedwithGambasVersion2:ATutorial
[email protected]
IFDialog.SelectDirectory()THENRETURN pictureFiles.Clear()
fileList=Dir(Dialog.Path) fileList.Sort() FOREACHfileNameINfileList
fileExtension=Lower(File.Ext(fileName)) 'Onlyselectimagefiles
IFfileExtension="png"ORfileExtension="jpeg"OR
fileExtension="jpg"ORfileExtension="bmp"OR fileExtension="gif"OR
fileExtension="xpm"THEN 'Thisisaimagesoaddtoimagelist
pictureFiles.Add(Dialog.Path&/fileName) ENDIF NEXT
IFpictureFiles.Count=0THEN
Page44of110
Message.Info("Noimagesfoundinthedirectory:\n\n"&
Dialog.Path) ENDIF pictureNumber=0 CATCH
Message.Warning("Errorselectingimagesfrom:\n\n\t"&
Dialog.Path&"\n\n"&ERROR.Text) END ContinuedBelow
AlthoughwecalltheNextPictureprocedureseveraltimeitisnotwherewedotherealworkof
drawingthecurrentimageisdone.Ratherthisprocedurecheckswehavevalidinputforthe
DisplayImageprocedure.Firstwemakesurewehavesomeimagestodisplay.The
pictureFilesarrayholdsthepathstotheimagesfilesinourshow.BymakingsuretheCount
propertyisgreaterthanzeroweensurethereissomethingtodisplay.Wethenmakesureourindex
forthecurrentpictureiswithinavalidrange.Ifourindexisgreaterthannumberofimages
availablethenwesetittothestartoftheshow.Similarlyifourindexislessthanzerothenwesetit
totheendoftheshow.ThiswaywecansafelyincrementanddecrementthepictureNumber
indexintheproceduresabove.Weknowthathereweshallwraptheindexaroundtheendsofthe
array.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page45of110
Rememberthattheindexinaarraystartsatzeroandthefinalelementofanarrayisonelessthen
theCountproperty.WhenwehaveavalidindexwecalltheDisplayImageprocedurethatdoes
alltheactualdrawingwork. FormImageShow.classContinued
PRIVATESUBNextPicture() 'Checkwehavesomeimagefilepaths
IFpictureFiles.Count>0THEN 'Limittheimagenumbertothenumberof
'filesinourarrayoffilepaths
IFpictureNumber>=pictureFiles.CountTHEN pictureNumber=0
ELSEIFpictureNumberDrawingAreaImage.ClientWidth)OR
(currentImage.Height>DrawingAreaImage.ClientHeight)THEN
'Scaleimagetofitonthescreen
scale=Min(DrawingAreaImage.ClientWidth/currentImage.Width,
DrawingAreaImage.ClientHeight/currentImage.Height)
currentImage=currentImage.Stretch(currentImage.Width*
scale,currentImage.Height*scale) ENDIF 'Calcrectanglespoints
x1=(DrawingAreaImage.ClientWidthcurrentImage.Width)/2
GettingStartedwithGambasVersion2:ATutorial
[email protected] x2=x1+currentImage.Width
x3=DrawingAreaImage.ClientWidth
Page50of110
y1=(DrawingAreaImage.ClientHeightcurrentImage.Height)/2
y2=y1+currentImage.Height y3=DrawingAreaImage.ClientHeight
'Drawimage Draw.Begin(DrawingAreaImage)
Draw.Image(currentImage,x1,y1)
'Drawrectanglesovertheareanotcoveredbythenewimage
Draw.BackColor=DrawingAreaImage.BackColor
Draw.ForeColor=DrawingAreaImage.BackColor
Draw.FillColor=DrawingAreaImage.BackColor Draw.FillStyle=Fill.Solid
'Drawtoprectangle Draw.Rect(0,0,x3,y1) 'Drawbottomrectangle
Draw.Rect(0,y2,x3,y1) 'Drawleftrectangle Draw.Rect(0,0,x1,y3)
'Drawrightrectangle Draw.Rect(x2,0,x1,y3) Draw.End END
ContinuedBelow
Thefinalprocedurewehavedrawsaninformationmessageabouttheslideshow.Thisiscalled
whentheuserpressestheIkey.Firstwebuildthestringforthemessage.Weaddsomeinformation
aboutiftheshowisrunningorpaused.Ifitisrunningweaddinformationaboutthetimeinterval
betweenimages.Wethenshowsomeinformationaboutthecurrentimage.Weshowthecurrent
picturenumberandthetotalnumberofimagesaswellastheimagepath.Notethatweaddoneto
thecurrentimageindexbecausethestringarrayindexfortheimagepathsstartsatzero.
Nextwecalculatethescreenpositionforthemessage.Wewanttoplacethemessageatthebottom
ofthescreenandinthecentre.Wewilldrawthismessageusingthedefaultfont.Weusethe
TextWidthandTextHeighmethodsontheDrawobjecttogetthesizeofthetext.Wecanthen
calculatethepositionforthetext.Theleftpositionforthetextwillbehalfthewidthofthescreen
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page51of110
minusthewidthofthetextmessage.Thetoppositionforthetextwillbetheheightofthescreen
minustheheightofthetext.
Wewanttomakesurethetextisvisible.Ifwesimplydrewthetextitcouldbeoveranycolorthat
formsthebackground.Sofirstwedrawafilledrectangleasthebackground.Thenwedrawthetext
ontopofthisrectangleatthepositionwehavecalculated.
FormImageShow.classContinued PRIVATESUBShowMessage()
DIMmessageASString DIMx1ASInteger DIMy1ASInteger
DIMmessageWidthASInteger DIMmessageHeightASInteger
'Gettheinformationmessage IFTimerShow.EnabledTHEN
message="ShowRunning(Every"&CInt(TimerShow.Delay/
1000)&"seconds)" ELSE message="ShowPaused:" ENDIF
IFpictureFiles.Count>0THEN
message&="Picture:("&(pictureNumber+1)&"/"&
pictureFiles.Count&")"&pictureFiles[pictureNumber] ELSE
message&="Nopictures" ENDIF 'Drawtheinformationmessage
Draw.Begin(DrawingAreaImage) 'Calcmessageposition
messageWidth=Draw.TextWidth(message)
messageHeight=Draw.TextHeight(message)
x1=(DrawingAreaImage.ClientWidthmessageWidth)/2'Center ofscreen
y1=DrawingAreaImage.ClientHeightmessageHeight'Bottomof
GettingStartedwithGambasVersion2:ATutorial
[email protected] screen
'Drawthemessagebackground Draw.ForeColor=Color.LightGray
Draw.FillColor=Color.LightGray Draw.FillStyle=Fill.Solid
Draw.Rect(x1,y1,messageWidth,messageHeight) 'Drawthemessagetext
Draw.ForeColor=Color.Black Draw.Text(message,x1,y1) Draw.End
END
Page52of110
3.4:
RunningtheprojectTheprojectisnowcompletesoletsrunit.YouruntheprojectbyclickingonthegreenRunbutton
intheprojectmanagerwindoworbypressingtheF5key.Adialogueshouldopenaskingyouto
selectadirectory.Selectadirectorywithsomeimagesinpngorjpgformat.Watchtheshow!
Wenowneedtotesttheapplicationworksasexpected.Soruntheapplicationandselectaimage
directory.ThenpresstheDkeytochangetheimageshowdirectory.Testtheapplicationwiththe
followingkindsofdirectories: OpenImageDirectoryTests Test
Openadirectorywithimagesinit. Tryanemptydirectory.
Tryadirectorywithnoimagesbutsome otherfiletypes.
Adirectorywithsomejpgimagefiles. Adirectorywithsomejpegimagefiles.
Adirectorywithsomepngimagefiles. Adirectorywithsomegifimagefiles.
Adirectorywithsomebmpimagefiles. ExpectedResult Imageshowdisplayed.
Anoimagesfoundmessage. Anoimagesfoundmessage. Imageshowdisplayed.
Imageshowdisplayed. Imageshowdisplayed. Imageshowdisplayed.
Imageshowdisplayed. Pass/Fail
GettingStartedwithGambasVersion2:ATutorial
[email protected] OpenImageDirectoryTests Test
Adirectorywithsomexpmimagefiles. ExpectedResult
Imageshowdisplayed.
Page53of110
Pass/Fail
Makesureinalloftheaboveteststhattheapplicationdoesnottrytoopenanyfilesthatarenot
imagesandthatalltheimagesareshown.Theapplicationshouldnotcrashandyoushouldbeable
toselectanotherdirectory.Wenowwilltestalltheotherkeysperformthecorrectaction.
KeyPressTests Test Withanimageshowpressthespacebar.
Withanimageshowpressthebackspace key.
Withanimageshowpresstheleftarrow. WiththeshowrunningpresstheSkey.
WiththeshowpausedpresstheSkey. WiththeshowrunningpresstheIkey.
ExpectedResult Nextimageshouldbedisplayed.
Previousimageshouldbedisplayed. Previousimageshouldbedisplayed.
Theshowshouldpause.(Waitmorethan 15secondstomakesure.)
Thenextimageshouldbedisplayedand theshowstartrunning.
Aninformationlineshouldbeshown.It shouldsaytheshowisrunningandgive
thecurrentimagename. Aninformationlineshouldbeshown.It
shouldsaytheshowispausedandgivethe currentimagename.
Ahelpmessageshouldbedisplayedand alsothemouse.Whenthemessageis
clearedthemouseshouldbehidden. Theapplicationshouldclose.
Pass/Fail
Withanimageshowpresstherightarrow.
Nextimageshouldbedisplayed.
WiththeshowpausedpresstheIkey.
WiththeshowrunningpresstheF1key.
PresstheEsckey.
Finallyforthisprojectweagoingtocreateaexecutableversionoftheapplication.Thiswayyou
canrunImageShowoutsidetheGambasdevelopmentenvironment.Firstmakesureyouhave
completedallthetestingdescribedabove.ThenintheGambasprojectmanagerselecttheProject
menuandthentheMakeexecutable...submenu.Thiswillshowastandarddialogueaskingforthe
nameofafile.AcceptthedefaultsandclicktheOKbutton.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page54of110
Thiswillcreatean executableversionofyour
applicationinyourproject directorycalled ImageShow.gambas.
InUnix/Linuxtheyourhomebindirectoryisagoodplacetostoreyourpersonalapplicationsand
scripts.OnmostsystemthisdirectoryisinyourPATHsoitwillbesearchedwhenyouenter
commandsfromaterminal.MovethefileImageShow.gambasthatwehavejustcreatedinyour
projectdirectorytoyour$HOME/bindirectory.
Nowopenaterminalwindowandtype ImageShow.gambas&andour
applicationshouldstart.The&afterthe
commandissotheterminaldoesnot waitfortheImageShowprocesstoend.
ItisnotrequiredtostartImageShow.
NotallLinuxdistributionhavea$HOME/bindirectory.
Onsomedistributionsyoucancdtothedirectorywheretheexecutablecontained.Then
type./ImageShow.gambasandtheexecutableshouldrun.
Onsomedistributionsyouneedtogivethefullpathtotheexecutable.Iftheexecutable
wasinadirectorycallImagesinourhomedirectorythentry:
$HOME/Images/ImageShow.gambas
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page55of110
OnereasonIwantedtocreateaexecutableforthisapplicationwastodemonstratethatfilesinthe
datasectionofaGambasprojectareincludedinthefinalexecutable.Andthattheyusetherelative
pathwithintheapplicationfortheirfilelocation.ToprovethisworkspresstheF1keyandviewthe
help.ThisshouldcorrectlyloadtheHTMLhelpfilewecreatedandloaditintothemessageboxfor
display.
Youcouldalsoaddalinktothisexecutableonyourdesktop.Thiswouldallowyoutorunour
applicationbyclickingonanicon.Howyoudothisisdependentonthewindowmanageryouare
using.Seethehelpforyourwindowmanager.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page56of110
4:
DatabaseProject:Notations
MicrosoftVisualBasicbecameverypopularontheWindowsplatform.Onereasonforthissuccess
isthatMicrosoftVisualBasicwasagoodfrontendfordatabaseapplications.Manyusers,like
myself,comingfromtheWindowsworldtoLinuxwillhaveexperienceofdevelopingapplications
withVisualBasictoactasauserinterfacetoadatabase.Theywillwanttotransfertheseskillsto
Linux.Inthisexamplewearegoingtogetyoustartedwithasmallprojecttocommunicatewithan
SQLite2database.WithGambasyoucanusealmostthesamecodetocommunicatewithaMySQL
orPostgreSQLdatabase.WithlaterversionsofGambasyoucanalsoconnecttoaSQLite3,ODBC
orFirebirddatabase. AswithinstallingGambasthistutorial
willnotcoverinstallingSQLite.SQLite shouldbeinstalledwithmostLinux
distributions.Inordertocheckyouhave
SQLiteinstalledonyourworkstation openaterminalandtypesqlite
version.Ifaversionnumberis returnedthenSQLiteisinstalled.
Notethatthiswillcheckifversion2ofSQLiteisinstalled.Weareusingversion2becauseitis
supportedbymoreversionsofGambas.NewerversionofGambasalsoworkwithSQLiteversion3.
YoucancheckforSQLiteversion3withsqlite3version.
IfSQLiteisnotinstalledthenyoushouldbeabletoinstallitthroughyoupackagemanagerorvisit
theSQLitewebsiteathttp://www.sqlite.org/.IfyouarenewtoSQLiteitisalsoworthlookingat
thedocumentationonthiswebsite.
TherearetwopossibleapproachesyoucouldtaketointerfacingwithadatabaseinGambas.The
firstistousetheGambasdatabaseobjects.Withthismethodyourcodewouldperformthe
followingactions:
CreatethedatabaseinGambasusingtheconnectionobject.
Buildthedatabasetables,indexes,etc.usingtheGambasdatabaseobjects.
ReaddatafromthedatabaseusingtheResultobject.YouwouldcreatetheResultobject
usingtheFindorEditmethodonthedatabaseconnection.
UpdateandDeleteactionsonrecordswouldbethroughtheResultobject.Youwouldcreate
GettingStartedwithGambasVersion2:ATutorial
[email protected]
theResultobjectusingtheEditmethodontheconnection.
Page57of110
AddingrecordswouldbethroughtheResultobject.YouwouldcreatetheResultobject
usingtheCreatemethodonaconnection.
Youareabstractedfromthedatabaselayer.
YoudonotneedtoknowmuchSQL(StructuredQueryLanguage).
YourcodeisportablebetweenthedatabasessupportedbyGambas.Youshouldonlyneedto
changetheconnectionparameterstoswitchdatabasetypes.
Searchandfilteringdataismoreawkwardandislesswellsupportedthandirectlyusing
SQL.
Viewsanddatabasequeriesrequiringmorethanonetablearenotaswellsupportedasin
directlyusingSQL.
Therearesomefeaturesoftheunderlyingdatabasethatyoucannotaccess.
Thisapproachhasthefollowingadvantages:
Italsohasafewdisadvantages:
Formostkindsofdatabaseapplicationtheabovemethodisthebest.Howeverthereisasecond
methodyoucoulduse.WiththismethodyouwouldbetousetheExecmethodontheconnection
objecttosendSQLstatementstothedatabase.Withthismethodyourcodewouldperformthe
followingactions:
Therearetwopossiblemethodyoucouldusetocreatethedatabase.
Createthedatabaseusingtoolsprovidedbythedatabasevendororathirdparty.
CreatethedatabaseinGambasandbuildthetables,indexesetc.usingaSQLscript.
SendthisscripttotheconnectionExecmethod.
YouwouldreaddatafromthedatabaseusingtheExecconnectionmethodusingaSQL
queryandreturnthisdatatoareadonlyResultobject.
Update,InsertandDeleteshouldalsobepreformedusingtheSQLstatementssenttothe
Execconnectionmethod.
Yougainfinegrainedcontroloverthedatabase.YoucontrolthedetailofeachSQLqueryor
command.
MostdatabasessupportmorefieldtypesfortablesthanaresupportedbyGambas.
FeaturesinthedatabasenotsupportedinGambasareeasilyaccessible.
Itiseasytoaccessdatabaseviewsandmultitablequeries.
YouneedagoodknowledgeofSQLforyourtargetdatabase.
Theadvantagesare:
Possibledisadvantagesare:
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page58of110
Youneedtoformatthedatayourselfwhensendingorreceivingitfromthedatabase.For
exampleyouneedtomakesuredatesareinaformatunderstoodbythedatabase.
YouneedmorecarefulerrorhandlingtocatchSQLerrors.DebuggingtheSQLisalsomore
complex.
Yourapplicationisproperlynotportableifyouneedtoswitchdatabasetypes.
Whichmethodshouldyouchose?Mygeneraladvicewouldbe:
Ifyouonlyrequireasmalldatabaseoryouneedportabilitybetweendatabasesthenstickto
thefirstmethod.InthiscasetrytoavoidusingtheExecmethodofobtainingdataorpassing
SQLqueriestothedatabase.
Ifyouhavealargedatabaseandthedatabasetypeisnotlikelytochangethenconsiderthe
secondmethod.Alsoconsiderthesecondmethodifyourdatabasequeriesaregoingtobe
largeorcomplex.IfyouselectthesecondmethodonlyusetheConnectionandResult
objectsandonlyusetheExecmethodtoperformqueries.
Iwouldnotmixthetwoapproaches.Ofcoursethereisnothingtostopyouifyoureallywantto.But
youcouldendupwithnoneoftheadvantagesofeithermethodandallofthedisadvantages.
Inthistutorialwearegoingtodemonstratethefirstofthesemethods.Thisisafterallatutorial
aboutGambasandnotSQL.AlsowecanthendemonstratemoreoftheGambasdatabaseobjects
youmightwanttouse.
InaAppendixtothistutorialweshalllookathowtoconvertthisNotationsexampleto
thesecondapproachusingExecandSQLstatements.
AcommonformofinterfacedesignforadatabaseistheMaster/Detaildesign.Hereyouhavealist
ofrecordsinawindow.Thereissomefieldfromthedatabasethatsummarisesthedatabaserecords
andthisisusedtocreatealist.Whenarecordfromthelistisselecteditsdetailsaredisplayedinthe
restofthewindow.Ifrequiredthedetailscanbeupdatedandsavedtothedatabase.Therewillalso
besomemechanismforaddinganddeletingrecords.ThisNotationsexamplewillfollowthisbasic
interfacedesigntoadatabaseapplication.
Withthisexamplewearegoingtocreateanotetakingapplication.Weshallstorethenotesina
SQLitedatabase.Theusershouldbeableto:
Addnotes. Viewnotes. Updatenotes. DeleteNotes.
Cut,CopyandPastetextfromtheClipboardtoandfromnotes.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page59of110
Viewalistofnotetitles.Youcanthenclickonanotetitletoviewthecompletenote.
Searchthetextinnotetitlesandnotesforagivensearchtext.
Weshallkeepourdatabaseverysimple.Thedatabasenameisgoingtobethesameasthe
applicationname.WeshallonlyneedonetableandthiswillbecalledNotes.Thefollowingentry
liststhefieldsinthetable. FieldName CreateDate LastModified Type
DATETIME DATETIME Comment
PrimaryKey.Whenanewnoteisfirstcreatedthiswillbe
settothecurrentdateandtime.
Whenanoteisfirstcreatedthiswillhavethesamevalue
aretheCreateDatefield.Eachtimeanoteisupdatedthis
fieldwillbesettothecurrenttime. Length0foraunlimitedstring
Length0foraunlimitedstring
Priorityencodedasaninteger.0islow,1ismediumand3 ishighpriority.
Title Note Priority
STRING STRING INTEGER
NotationsisnamedafterapieceofmusicbytheFrenchcomposerPierreBoulez
originallywrittenin1945.Thisearlyworkwasasetof12shortpiecesforpiano.Later,
in1978,Boulezorchestratedfourofthepiecesforlargeorchestra.Herevisedthem
againin1984.Thenaddedanadditionalorchestrationin1997.Giventhename,the
historyofthemusicandthefactthatBoulezisFrenchandsoisthemaindeveloperof
Gambas,BenoitMinisini,thisseemedagoodnameforanotetakingapplication.
4.1:
CreatingtheprojectThefirststepistocreateanewGambasproject.SoopenGambasandandselectNewproject....
Thiswillstartthenewprojectwizard.Thefirstpageofthewizardsimplyshowsawelcomescreen
withdetailsofhowtousethenewprojectwizard.ClicktheNext>>buttontoforthenextpageof
thewizard.ThisshowsapagewerewecanselectthetypeofGambasprojectwewanttobuild.We
aregoingtousethedefaultoptionofagraphicalproject.SoclicktheNext>>button.Thisshowsa
pagewhenyouenterthenameandtitleforyourprojectwearegoingtocreate.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page60of110
GivetheprojectthenameNotationsandthetitleNotationsanotetaking
application.Leavetheotheroptionsblank.ClickontheNext>>button.Selectthelocation
whereyouwanttosavetheproject.ThenclicktheNext>>button.Thisfinalpageliststheoptions
youhaveselectedfortheproject.CheckthroughtheoptionsandthenclicktheOKbutton.Wehave
createdanewVisualBasicprojectandGambaswillopenshowingtheGambasprojectmanager.
Withthisprojectwearegoingtouseatoolbartodisplaysomebuttons.Toolbarscanprovideanice
lookinginterfacetotheuserandtakeuplittlespace.Soweshallneedsomeiconsforthesebuttons.
TheTangoprojectaimstoprovideacommonlookandfeeltothedesktop.Italsoprovideagood
iconsetforuseinyourapplications.Youcangettherequirediconsfromtheexampleapplications
thatcomewiththistutorialortheTangowebsitehttp://tangoproject.org/.Thissitealsoprovides
usefulinformationaboutdesigningandusingicons.
GototheprojectdirectoryandcreateasubdirectorycalledImages.Inthisdirectoryplacethe
followingiconsfromtheTangoiconset.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page61of110
Thetangoiconsaregroupedintosizeandthencategory,Selectthe
iconsshowninthefollowingtableandplacethemintheImages directory.
IconSize 16x16 16x16 22x22 IconCategory actions status actions
IconName dialog.information.png mediarecord.png documentnew.png
documentsave.png editfind.png viewrefresh.png
accessoriestexteditor.png helpbrowser.png xdirectorytrash.png
22x22 22x22
apps mimetypes
ThefollowingscreenshotshowshowtheImagesdirectoryshould
lookaftercopyingtheseicons.
FromtheprojectmanagerwindowopentheProjectmenuandthentheProperties...submenu.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page62of110
Thisshowstheprojectpropertiesdialog.SelecttheGambasiconandthenselectthe
Images/accessoriestexteditor.pngiconfromtheImagesdirectorywecreated
above.
ClickontheOKbutton.TheProjectPropertiesshouldnowshowtheaccessoriestext
editor.pngicon.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page63of110
IntheprevioustwoapplicationsweonlyusedthestandardGambascomponents.Howeverthereare
manymorecontrolsandcomponentsavailable.Wearegoingtoaddthegb.dbDatabaseaccess
componenttotheproject.ThesewillgiveusaccesstotheGambasdatabaseobjectsandprovidethe
interfacetothedatabase.SelecttheComponentstabonthepreviousdialog.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page64of110
Makesurethegb.dbDatabaseaccesscomponentanditemischecked.ThenclicktheOKbutton
toacceptthisdialog.
4.2:
CreatingtheuserinterfaceThisapplicationisonlygoingtohaveonewindowastheinterface.Thisinterfaceisgoingtobe
slightlymorecomplexthantheprevioustwoexamples.Inordertogiveussomeideaofwhatweare
workingtowardshereisascreenshotofthelookoftheformwhenwehaveaddedallthecontrols
anditisindesignmode.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page65of110
Clickintheprojectmanagerwindowandcreateanewform.CalltheformFormNotationsand
accepttheoptionforthistobeastartupclass.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page66of110
Wearefirstgoingtocreatesomebuttonsinatoolbartogoacrossthetopoftheform.Soselectthe
ContainertabintheGambastoolbox.FromthisselecttheHPanelandaddthistothetopofthe
form.Resizethiscontrolsoitis42pixelsheighandthewidthisabitlessthanthewidthofthe
form.Theexactwidthdoesnotmatterasthiswillbecontrolledatruntime.
Toresizecontrolsfirstclickontherequiredcontrol.Thiswillshoweightresizingboxes.Thenclick
anddragoneoftheseresizingboxeswiththemouse.IfyouhavetheGambaspropertieswindow
openyouwillseetheHeightandWidthpropertieschange.Youcanalsoedittheseproperties
directlyinthiswindow.
Inthisprojectwearegoingtoaddquiteafewcontrolsthatneedtobeplaceinsidea
parentcontrol.Italltoeasytoplacethenewcontrolabovetheparentcontainerrather
thaninsidetheparentcontainer.Theformwillstilllookcorrectindesignmodebut
unfortunatelythecontrolswillnotresizecorrectlyatruntime.Trytofollowthislittle
sequenceeachtimeyouaddachildcontroltoaparentcontainercontrol:
Clickontheparentcontrol.Makesureitishighlightedanditseightresizing
boxesasvisible. Thenclickonthetoolboxcontrolyouaregoingtoadd.
Whenyouclickanddragthemousetoaddthecontrolmakesureyouareinside
therequiredparentcontrol.Alsomakesuretheeightresizingboxesarestill
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page67of110
visible.
Itisagoodideaeverysooftentomovetheparentcontrolyouareaddingchildcontrols
to.Thenmoveitbacktoitsdesiredpositionontheform.Whenyoudothischeckall
childcontrolsmovewiththeparent.Ifanychildcontroldoesnotmovewithitsparent
thenitisproperlynotplacedcorrectlyinsidetheparentcontrol.Tryaddingthethe
misplacedchildcontrolagain.
Thenextstepistoaddthebuttonswewantinourtoolbar.SelecttheFormtabintheGambas
toolbox.Thefirstbuttonisgoingtobeournewnotebutton.NowclickontheToolButtonandadd
thistotheHPanelwehavejustadded.MakesurethisbuttonisinsidetheHPanelandnotabovethe
HPanel.MovethisbuttonsoitisatthefarleftoftheHPanelandis42pixelsheighand42pixels
wide.NowaddtwomoreToolButtontotheHPanelthesearegoingtobeourDeletebuttonandour
Refreshbutton.Moveeachbuttonsoitis42pixelsheighand42pixelswideandplacednexttothe
previouslyaddedbutton.WeshouldnowhavethreebuttonsintheHPanel.
ThenextbuttontoaddistheSearchbutton.WearealsogoingtoaddaTextBoxnexttothisbutton
inwhichtoplacethenotessearchtext.WhentheHPanelisresizedatruntimeitwillmovecontrols
ontoanadditionallineiftheydonotfitonthewidthofthecontrol.Thisisnicebehaviourand
meanswecankeepallofourbuttonsvisiblenomatterhowwidetheuserresizesourformwindow.
WhatwouldalsobeniceisiftheSearchbuttonandTextBoxwerealwaysnexttoeachotherwhen
thisresizingtakesplaceatruntime.Wecanachievethisbyplacingthesetwocontrolsinsidea
PanelwhichisinsideourHPanel.Thissearchpanelwillnotbevisibleatruntime.
SoletsaddtheseSearchcontrols.SelecttheContainerstabintheGambastoolbox.Fromthis
selectthePanelandaddthistotheHPanel.MovethisPanelnexttoourRefreshbuttonandsetits
heightto42pixelsanditswidthtoabout224pixels.SelecttheFormtabintheGambastoolbox.
AddaToolButtoninsidethissearchPanel.MoveittotheleftofthesearchPanelandresizethe
buttonsoitis42pixelsheighand42pixelswide.NowaddaTextBoxtothesearchPanel.Resize
thistextboxsoitisheightis21anditswidthis168.AlsomakesureitsXvalueis42anditsY
valueis14.YoumayneedtousetheGambaspropertieswindowtochangesomeofthesevalues.
Thefinalpartofourtoolbaristwomorebuttons.Thesewillbeforupdatinganoteandahelp
dialogbutton.SelecttheFormtabintheGambastoolbox.PlacetwoToolButtonsinsidethe
HPanelnexttothesearchPanel.Resizeeachbuttonsoitis42pixelsheighand42pixelswide.
Thathasaddedallthecontrolsweneedforourtoolbar.Nowweshalladdthecontrolsthatformthe
mainpartofourwindowanddisplayournotes.Ontheleftsideoftheformwindowwearegoingto
havealistofnotes.Ontherightsidewearegoingtohavethedetailsofthecurrentlyselectednote
inthelist.InorderfortheusertoresizeeachhalfofourformwindowwearegoingtouseaHSplit
control.SelecttheContainerstabintheGambastoolbox.AddaHSplittotheformunderthe
HPanel.WeshallbeaddingmorecontrolstotheHSplitsomakeitlargeenoughforthis.Itsexact
sizedoesnotmatterasitwillberesizedatruntime.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page68of110
InGambasversion1theHSplitcontrolisnotavailablesoweshallhavetomissitout.
Thismeanstheuserwillnotbeabletoresizethetwohalf'softhewindowwiththe
centralbar.PlacetheColumnViewweaddnextdirectlyontheform.Alsowedirectly
placesecondpanelweaddlaterdirectlyontotheform.
WearegoingtouseaColumnViewtoprovidethelistofnotes.Atruntimeweshallsetthecolumn
titlesandcontentforthislist.SoselecttheFormtabintheGambastoolbox.Thenadda
ColumnViewtotheHSplitandmakesureitisinsidetheHSplit.PushtheColumnViewtothetop
leftcorneroftheHSplitandmakeitswidthaboutaquarteroftheHSplit.Oneofthenicethings
aboutusingtheHSplitcontrolisthattheresizingoftheColumnViewwillbehandledbytheHSplit
controlwhenitisresized.Weshallnothavetoaddandcodeforthis.
Thisnextgroupofcontrolsiswhereweshalldisplayaparticularnote.Wefirstneedtoaddanother
PanelsotheHSplitgroupsthesecontrolstogetheratruntime.SelecttheContainerstabinthe
Gambastoolbox.ThenaddaPaneltotheHSplit.PushthepaneltothetopoftheHSplitandnextto
theColumnView.MakethesizeofthePanelcoversmostoftheareaoftheHSplitnotoccupiedby
theColumnView.
Thefinalsetofcontrolstoaddwillshowthedetailsforaparticularnote.Allthesecontrolsgo
insidethePanelwehavejustadded.SelecttheFormtabintheGambastoolbox.Nowaddthese
controlstoourPanel.
Thesenextcontrolsareforthetitleofthenote.AddaLabeltothetopofthePanel.Underthe
LabelplaceaTextBox.
Nowaddsomecontrolswheretheusercanselectthepriorityofanote.AddanotherLabelunder
theTextBoxandthenalongsidethisaddthreeRadioButtons.
Thesenextcontrolsareforthecontentofthenote.AddanotherLabelunderthePriorityLabeland
thenaTextAreaunderthisLabel.
Wearenotdonewiththesecontrolsyet.Weneedtochangesomeoftheirproperties.Somakesure
theGambaspropertieswindowisdisplayed.Clickoneachcontrolinturnandchangetherequired
properties.Thisisalistofallthepropertiesweneedtochange.(Gambas1usersshouldskipthe
HSplit1control.)
GettingStartedwithGambasVersion2:ATutorial
[email protected] DefaultName FormNotation
Property Icon Border HPanel1 ToolButton1 Name Name ToolTip Picture
ToolButton2 Name ToolTip Picture ToolButton3 Name ToolTip Picture
Panel1 ToolButton4 Name Name ToolTip Picture TextBox1 ToolButton5
Name Text Name ToolTip Picture ToolButton6 Name ToolTip Picture
HSplit1 ColumnView1 Panel2 Label1 TextBox2 Name Name Sorted Name
Name Text Name Text NewValue
Page69of110
Images/accessoriestext editor.png Resizeable HPanelTools
ToolButtonNew Createanewnote Images/documentnew.png
ToolButtonDelete Deletetheselectednote Images/xdirectorytrash.png
ToolButtonRefresh Refreshthenoteslist Images/viewrefresh.png
PanelSearch ToolButtonSearch Searchnotesfortext Images/editfind.png
TextBoxSearch ToolButtonUpdate Updatecurrentnote
Images/documentsave.png ToolButtonHelp Displayhelp
Images/editundo.png HSplitWindow ColumnViewNotes True PanelNote
LabelNoteTitle Title: TextBoxTitle
GettingStartedwithGambasVersion2:ATutorial
[email protected] DefaultName Label2 RadioButton1
Property Name Text Name Group Text RadioButton2 Name Group Text
RadioButton3 Name Group Text Value Label3 TextArea1 Name Text Name
Text NewValue LabelNotePriority Priority: RadioButtonHigh
Page70of110
RadioButtonPriority High RadioButtonMedium RadioButtonPriority
Medium RadioButtonLow RadioButtonPriority Low True LabelNoteText
Note: TextAreaNote
Inordertotestourworksofarletsaddasmallamountofresizingcodecodetotheproject.Right
clickontheformandaddaForm_Resizeevent.NowrightclickontheHSplitWindowobject
andaddaHSplitWindow_Resizeevent.Inthesetwoeventhandlersaddthefollowingcode.
Gambasversion1userswouldonlyaddtheForm_Resizeevent.Alsotheresizing
codeisalittledifferentseebelow. FormNotations.class
PUBLICSUBForm_Resize() HPanelTools.Width=ME.ClientWidth
HSplitWindow.Move(0,HPanelTools.Height,ME.ClientWidth,
ME.ClientHeightHPanelTools.Height) END
PUBLICSUBHSplitWindow_Resize()
TextBoxTitle.Width=PanelNote.ClientWidth
GettingStartedwithGambasVersion2:ATutorial
[email protected]
TextAreaNote.Resize(PanelNote.ClientWidth,
PanelNote.ClientHeightTextAreaNote.Top) END
Page71of110
OurresizingcodeisslightlydifferentforGambasversion1.Thisisbecausewehadto
omittheHSplitcontrol. FormNotations.class PUBLICSUBForm_Resize()
HPanelTools.Width=ME.ClientWidth
ColumnViewNotes.Top=HPanelTools.Height
ColumnViewNotes.Height=ME.ClientHeight ColumnViewNotes.Top
PanelNote.Top=ColumnViewNotes.Top
PanelNote.Width=ME.ClientWidthPanelNote.Left
PanelNote.Height=ColumnViewNotes.Height
TextBoxTitle.Width=PanelNote.ClientWidth
TextAreaNote.Resize(PanelNote.ClientWidth,
PanelNote.ClientHeightTextAreaNote.Top) END
Nowitistimetotesttheworkwehavedonesofar.Hitthegreenrunbuttonintheprojectmanager
orpresstheF5key.Theapplicationwilldoverylittle.Butyoushouldbeabletograbthecentral
barbetweentheColumnViewandtheTextAreapanelandthecontrolswillresizethemselves
correctly.(AtleastforGambas2users.)
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Youshouldalsobeabletoresizetheformwindow
andthecontrolswillresizethemselves.Iftheydonot
thenthemostlikelyreasonisthatsomecontrolsare
notcorrectlyinsidetheircontainers.
YoucancheckthisusingtheGambasHierarchytool.
Indesignmodeselecttheform.Nowfromthe
GambasprojectmanagerselecttheViewmenuand
thentheHierarchyoptionorpressCtrl+H.Check
thecontrolshierarchyonyourformmatchesthe screenshotontheright.
Ifacontrolisnotattherightlevelinthehierarchy
thenclickontheoffendingcontrol.PressCtrl+Xto
cutthecontrol.Thenselectthecorrectparentcontrol
andpressCtrl+Vtopastethecontrolintoitscorrect container.
Page72of110
Ifacontrolisattherightlevelinthe
hierarchybutnotintherightorderthen Rightclickontheparentcontroland
thiswillshowapopupmenu.Selectthe Arrangementoptionandthiswillshow
asubmenu.InthismenuselectLeftto
right.Thiswillreorderthechildcontrol intheordertheyareontheform.
Wewanttoshowsomehelpinformationstotheuserwhentheyclickonthehelpbutton.Weare
goingtousethesamemethodasthepreviousproject.Thismethodissuitablewhentherequired
amountofhelpissmallandwillfitononepage.TheGambasmessageboxisquiteaflexibleclass
andwilltakeaHTMLformattedmessage.Sowiththesinglelineofcode:
Message.Info(File.Load("help.htm")) wecandisplayaHTMLfile.
SoletcreatetheHTMLfileinGambas.RightclickintheGambasprojectmanager.Thisbringsup
apopupmenu.FromthelistselectNew.Thisshowsasubmenuwiththeitemswecanaddtoour
project.WeneedtoaddaTextfilesoselectTextfile...fromthismenu.Givethefilethename
help.htmandpresstheOKbuttontosaveit.Thiswilladdthefiletothedatasectionofyour
projectandwillopenthenewtextfileintheGambastexteditorwindow.EnterthefollowingHTML
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page73of110
intothetexteditorandsaveit.Notethat,asbefore,the
iconinthefollowinglistingmeansthis
lineisacontinuationofthepreviousline. help.htm NotationsHelp
NotationsHelp Notationsisasimplenotetakingapplication.The
followingbuttonsareinthetoolbar: TheNewbuttonwillcreate
anewnote
TheDeletebuttonwill deletethecurrentlyselectednote
TheRefreshbuttonwill
showallavailablenoteinthenoteslist
TheSearchbuttonwill
findallnoteswiththesearchtextinanoteornotetitle
TheSavebuttonwill updatethecurrentnote
TheHelpbuttonwillshow thishelp
Notationsv.0.0.1wasdevelopedbyTimothyMarshalNichols
inMay2006.ItisissuedundertheTheGNUGeneralPublic
License2.
GettingStartedwithGambasVersion2:ATutorial
[email protected]
Page74of110
ThefollowingscreenshotshowswhatthisHTMLlookslikeinamessageboxwhentheapplication
isrunandtheuserpressesthehelpbutton.
Thereisonefinalfileweneed.Whenwecreatethenotesdatabaseweshallalsoaddafirstnote.
Thiswillbeawelcomenotegivingtheusersomehelpinformation.Asthetextforthisnoteisgoing
tobemorethanafewlinewearegoingtoloadthetextfromafile.Thismethodofloadingthetext
fromafilewillbeverysimilartothatusedforthehelp.Thisalsogivesusagreatdealofflexibility
ifweneedtochangethisapplicationinthefuture.Wecaneasilyincorporatetextchangestothe
welcomehelptext.
RightclickintheGambasprojectmanagerandselectthemenutoaddanewtextfile.Thistimegive
thefilethenameWelcome.txtandpresstheOKbuttontosaveit.Thiswilladdthefiletothe
datasectionofyourprojectandwillopenthenewtextfileintheGambastexteditorwindow.Enter
thefollowingtextandsavethefile.Asyouwillnoticeitisverysimilartothehelptext.
Welcome.txt
GettingStartedwithGambasVersion2:ATutorial
[email protected]
WelcometoNotations.Asimplenotetakingapplication
Thefollowingbuttonsareinthetoolbar: TheNewbuttonwillcreateanewnote
TheDeletewilldeletethecurrentlyselectednote
Page75of110
TheRefreshwillshowallavailablenoteinthenoteslist
TheSearchwillfindallnoteswiththesearchtextinanoteor notetitle
TheUpdatewillsavethecurrentnote TheHelpbuttonwillshowhelp
Notationsv.0.0.1wasdevelopedbyTimothyMarshalNicholsin May2006.
ItisissuedundertheTheGNUGeneralPublicLicense2.
Sowecreatedalltheitemweneedfortheuserinterfacetothisapplication.Wehaveonlyneeded7
lineofcode(and4ofthembeginningandend'stoprocedures)togetadecentinterface.Itshows
thatwithalittleknowledgeofhowcontainersandcontroloperatewithinGambasyoucancreate
somegooduserinterfaces.
4.3:
CheckingouruserinterfaceforCRUDManyapplicationdeveloperswouldalreadyhaveleaptintothecodingstagebynow.Butitisworth
standingbackandcheckingthedesignofourapplicationforfunctionality.Onecheckingmethod
oftenusedwithdatabaseapplicationsisCRUD.CRUDstandsforCREATE,READ,UPDATE,
DELETE.Itisachecklisttoapplytorecordsorentitiesindatabasetablesagainstoperations
performedbyusers.
TheCRUDchecklistisoftensetoutasamatrix.Alongonesidearelistedthetablesorentitiesin
thedatabase.Alongtheothersidearelistedtheuserrolesforthedatabase.Insideeachcellyoulist
theCRUDactionsthateachuserrolecanperformoneachtableorentity.Thefollowingdiagram
demonstratesanimaginaryCRUDmatrix.
GettingStartedwithGambasVersion2:ATutorial
[email protected] User User1 User2 Administrator
R,U C,R,U,D C,R,U,D Table1 R,U C,R,U C,R,U Table2 R,U C,R,U,D
Page76of110
Table3
FromthismatrixwecanseethatUser1canonlyreadandupdatetables1and2.User2has
differentlevelsofaccesstoeachtable.TheAdministratorhasfullaccesstoalltablesapartfrom
table2.Alsofortable2wehavenowayofdeletingarecord.Theseobservationsmightbecorrect
forourimaginaryapplication.ButwithaCRUDmatrixlikethisweneedtochecktherequirements
forourapplicationagaintofindout.
CRUDisachecklist.Itisachecklistthathelpsyouspotanymissingoperationsinyour
application.Thisdoesnotmeanthateveryusershouldbeabletoperformalltheseoperations.In
manycasesthereareoperationsyouwouldnotwantperformedbyallusers.Forexampleina
bankingdatabaseyouwouldnotwantalluserstobeabletodeletedetailsoffinicaltransactions.
RatherwithCRUDyouarecheckingthefunctionalityofyourdatabaseapplication.Youthenhave
tothinkaboutwhysomeusershouldhaveornothavesomeparticularfunctionality.Itisthe
thinkingprocessthatisimportant.
OftenanadditionaloperationisaddedtotheCRUDchecklist.ThisisLforLIST.Canauserlist
databaserecords?IwouldalsoaddSforSEARCH.Canausersearchdatabaserecordsusingsome
searchcriteria?
TherearelotsofdescriptionsofCRUDontheinternet.SearchforCRUD+databases.
Youcouldtry:http://en.wikipedia.org/wiki/CRUD_(acronym)
IfindCRUDisausefulchecklistevenwhenyouarenotdealingwithadatabase.Anyplaceina
applicationwhereyouareaddingorremovingdatafromcontrolsatruntimeisworthputting
throughtheCRUDchecklist.Thiscouldbeagrid,atextarea,acomboboxormanyothercontrols.
CRUDismostoftenpresentedasamatrix.InourNotationsapplicationweonlyhaveoneuserand
onetable.Sothematrixlooksabitsilly.InsteadletsusetheCRUDLSchecklisttothinkaboutthe
actionsperformedbyouruseronthedatabaserecords.
Create:Theusercancreatenotesusingtheaddbutton.Thiswilladdthecurrentcontentof
theNoteTitletextbox,PriorityselectionandNotetextareatothedatabase.
Read:ClickingonanoteinthecolumnviewwillplacethatrecordintheNotetextbox,
PriorityRadioButtonsandNotetextareasoitcanberead.
Update:Clickingontheupdatebuttonwillsaveanychangestothe