Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
Team Developer – Quick Start Guide to BuildingBusiness Applications on Windows and Linux
By Raj Parmar
November 2004
Introduction ..............................................................7
Executive Summary ...................................................7
Installation..............................................................12
Team Developer components...................................12
Overview of Team Developer ....................................... 12
SQLWindows................................................................ 12
SQLTalk ....................................................................... 13
Deploy ......................................................................... 13
TOM ............................................................................. 13
SQLBase ...................................................................... 13
The GUPTA Client/Server-System............................13
SQLWindows ...........................................................14
Graphical User Interface.............................................. 14
The Outline Editor........................................................ 15
Tabs............................................................................. 17
Layout View................................................................. 18
Controls Tool Bar ......................................................... 18
Coding Assistant .......................................................... 19
Attribute Inspector ...................................................... 19
Database Explorer ...................................................20
Programming Basics in SAL .....................................21
Overview ..................................................................... 21
Datatypes .................................................................... 21
MDI - Form .................................................................. 22
Form - Container for Child Window.............................. 22
TableWindow - Normal Form Window with a built-inTable............................................................................ 23
Dialog box ................................................................... 23
Non-modal Dialog Windows......................................... 24
Dialog elements (Child Windows)................................ 24
Object Attributes ......................................................... 26
Exercise: Form building, compiling and running apps .. 26
Constants .................................................................... 27
Variables ..................................................................... 28
Declarations and length of existence................................. 28
Visibility ............................................................................ 29
Referencing ....................................................................... 30
Arrays................................................................................ 31
Object Variables ................................................................ 32
Naming Conventions.......................................................... 33
Operators .................................................................... 34
Expressions ................................................................. 34
Statements .................................................................. 35
Functions..................................................................... 38
Internal Functions ............................................................. 38
External Functions............................................................. 39
Function event................................................................... 39
Function Parameters ......................................................... 40
Exercise: Coding in the Outline .................................... 41
Working with Windows Objects ................................... 42
Windows Properties .......................................................... 42
Exercise: Coding the Outline – global functions ........... 43
Event-oriented Programming ..................................44
The Concept of Event-Orientation ................................ 44
Events –Messages -Methods ..................................... 45
SQLWindows Internal Messages .................................. 45
Message Variables ....................................................... 46
Programmed Events / Messages in SQLWindows ........ 47
Functions Used for Sending Messages ......................... 47
SalPostMsg() ..................................................................... 47
SalSendMsg() .................................................................... 48
SalSendMsgToChildren() ................................................... 49
Exercise: Events and messaging .................................. 49
Debugging ...............................................................49
Tools............................................................................ 49
Testing the content of Variables ........................................ 49
Viewing / Evaluation of Expressions ........................................ 52
Breakpoints .............................................................52
Administration of Breakpoints ..................................... 53
Overriding the normal Program Flow........................... 53
Special Features .......................................................... 54
Assignment of Variables .................................................... 54
Animation.......................................................................... 54
Database connections in Team Developer ...............55
Database Access Cycle................................................. 55
The Binding of SQL ...................................................... 56
Exercise: Database access and retrieving information. 56
SQL Error Handling ...................................................... 57
Error handling at the statement level. ............................... 58
Error Handling at the Global Program Level....................... 58
SQLWindows Standard Error Handling............................... 58
Exercise: Error handling .............................................. 59
Table Objects...........................................................60
Table as a self-standing window with a toolbar........... 60
Table as a Child Window within a Parent Window ....... 60
Table Columns ............................................................. 61
Table Properties .......................................................... 61
Runtime-adjustable Properties.......................................... 61
Context Rows and focus .............................................. 62
Marking Row Flags....................................................... 63
The Table Window Cache ............................................. 63
How the Table Window Cache Functions ........................... 64
Filling a Table Window with Data: ............................... 64
Tables in the Application.............................................. 65
Exercise: Using and populating Tablefields.................. 66
Short glance at Report Builder.................................67
Properties and Options ................................................ 68
Connection to SQLWindows ......................................... 68
Basic procedure................................................................. 68
Exercise: Reports......................................................... 70
Multi-user Programming..........................................72
Introduction ................................................................ 72
Locks ........................................................................... 72
Granularity ........................................................................ 72
Type of Locks..................................................................... 72
Transactions ................................................................ 73
Isolation Levels ........................................................... 74
Read repeatability (RR)..................................................... 74
Cursor Stability (CS).......................................................... 74
Read Only (RO) ................................................................. 75
Release Locks (RL) ............................................................ 75
ROW-ID ....................................................................... 75
Safeguarding of the Result Set .................................... 75
Exercise: Database locking and isolation levels ........... 76
Introduction
This document introduces Team Developer’s features and benefits whenused to write business applications. Team Developer is an extremelypowerful and wholly integrated visual development environmentavailable both on the Windows and Linux platforms. It boasts an easyand intuitive learning curve with compelling features allowingapplications to be coded approximately 40% faster than other tools inthe marketplace. In addition, the code written is truly cross-platform,with only the need to recompile on different environments. No codechanges are necessary.
Industry leading features and benefits are pointed out before tunnelingdown to the basic components of the visual development environmentand taking the reader through many exercises to solidify theunderstanding. Sample answers to exercises are also available.
Executive Summary
Enjoy true Rapid Application Development (RAD) of businessapplications on Windows and Linux Desktops with Team Developer.Experience rich and easy-to-use user interfaces while having the benefitof faster development of nearly 50-100 percent faster than if done inJava and other visual development tools.
Cross platform development and deployment ensures the investmentyou are making can be leveraged in the Linux as well as the Windowsmarket - greatly enhancing your return on investment and profitability.The source code of your application can be written on either platformthen simply re-compiled on the other platform to create the sameapplication
Time and money saving RAD software developmentRapid Application Development means smart software development.Team Developer speeds up software development and enables you towin projects as you can deliver faster and with less cost than yourcompetition using Microsoft tools or Java.
Quickly react to new customer requirementsYou have all experienced a similar situation - you are presenting yoursoftware to a prospect who is very interested, however, there is thisone workflow that needs to be different in the software to bettersupport the customer’s organization. How fast you can deliver thechange determines whether you win the deal or not. With TeamDeveloper you can deliver changes faster than your competition.
Protects code investments through backward compatibilityGUPTA works hard so you can move from one technology platform tothe other without constantly rewriting existing code. This enables your
Page 7
organization to concentrate on improving your solution - not on keepingpace with changes in underlying technologies. Java forcesapproximately 20% code rewrite when moving from one version to theother. Microsoft® tools require an even higher rewrite percentage forexisting code. For example, about 40% of existing code has to berewritten when moving from Visual Basic 6 to Visual Basic.Net. ForLonghorn release, independent software magazines predict a rewriterate of 100%.
Easy ProtypingDuring the initial phase of a project, your customer might not be clearabout all their project requirements. Creating prototypes with a fewmouse-clicks ensures the workflow; requirements and expectations aredefined at a very early stage in the project. The risk in deliveringsomething that does not meet expectations is greatly reduced.
Quick codingTeam Developer’s outline editor is well known as the best possible coderepresentation and new employees will understand existing codequickly.
Keep the project cost low and provide your organization the opportunityto increase your profit margin.
Page 8
Projects and solutions continue to grow over the years and developerson a project keep changing. The well-structured outline format of TeamDeveloper source code is very simple to read and understand. Thegraphical outline editor increases productivity of new developers quicklydue to its intelligence in allowing only appropriate objects/segments inspecified places. This coupled with an Active Coding Assistant (ACA)reduces errors and increases developer productivity.
Renowned database connectivity and development databaseincludedTeam Developer supports fast and effective database connectivity toGUPTA SQLBase and many other industry databases. This databaseconnectivity is now available to Oracle and ODBC in Team Developer forLinux. Oracle databases can be accessed natively, and all otherdatabases can be accessed using the Linux ODBC interface. Forexample, ODBC can be used to access MySQL and other databases thatoffer Linux ODBC connectivity. Team Developer includes a Developersversion of the fast and powerful SQLBase database. With SQLBaseincluded, it is easy to develop complex multi-user applications using anon-network connected laptop and still have full industry strengthdatabase features and support.
Complete source-code management including a class browserManage multiple developers’ working on the same source code with
Page 9
complete check-in and check-out facilities. Have a true picture of theobject hierarchy with the class browser
Includes comprehensive reporting tool ReportBuilderAd-hoc and application reporting are the strengths of ReportBuilder.End-Users can define new queries with just a few mouse clicks. Thegraphical query designer gives users an overview of existing tables andviews and allows them to create joins using drag and drop technology.After the query has been designed, the report design module offers allthe tools to create stunning reports - including multiple break groups,easy formatting, graphics support and a lot more.
ReportBuilder includes full support for printer trays and enables theuser to assign changing trays for the pages of the report. Developerscan include reporting into their business solutions. All the advanceduser features are also available and can be programmed from within aTeam Developer application. Your business applications can includecomplex reporting such as printing of invoices or complex multi-passreports for management information systems
An example report showing conditional formatting
Page 10
Full and comprehensive debugging facilities
Team Developer supports major Desktop Linux distributionsGUPTA is partnering with Novell/SUSE and Red Hat to create best of
Page 11
breed Linux products that integrate well into world leading Linuxplatforms.
• Novell SUSE Desktop 1.0 (SLD 1.0)
• Novell SUSE 9.1 Professional
• Novell SUSE Linux Enterprise Server 8
• Novell SUSE Linux Enterprise Server 9
• Red Hat Enterprise Linux v3 (WS, ES, Enterprise Desktop)
Installation
Installation on both Windows and Linux are Java Virtual machine (JVM)based. There is no need to configure and use the ‘make’ tool to buildand use the product – just follow the installers simple steps.
For Linux, the installer ships with a custom build of Crossover 4.1,which is based on a specific build of the Wine environment on Linux.
If you already have Crossover 3.1 installed – the installer will detectthis and allow you to use the existing binaries. Linux distributionssupported are noted in the Executive summary.
Team Developer components
Overview of Team Developer
Team Developer consists of various components that are divided up intothe following broad areas: Development Environment, SoftwareDistribution, Team Support and Development Server.
SQLWindowsSQLWindows is the name of the 32-bit Programming environment forTeam Developer. It’s in this environment and language whereprogrammers design and develop in a 4GL Object Orientatedenvironment.
The CDK (GUPTA Developers Extension Kit) is also integrated intoSQLWindows. It serves to expand the GUPTA Team Developerenvironment (e.g. the creation of assistants and utilities within thedevelopment environment).
Page 12
SQLTalk
SQLTalk is the SQL Shell used for direct queries and Administrativetasks involving a connected database. It allows both Data DefinitionLanguage (DDL) and Data Manipulation Language (DML) commands.
Deploy
Team Developer Deployment contains the Runtime Environment forprograms developed with SQLWindows. It contains all the files that areneeded for the distribution of written applications. A deploy executableis copied to the user environment and run to install the runtime on aspecific machine. Due to licensing restrictions, the SQLWindowsDevelopment Environment itself cannot be circulated.
TOM
Team Object Manager (TOM) is the component used for team-orientedproject development. The project-related files (SQLWindows, Sourcecode, Documentation, etc.) can be stored in a Repository. Full source-code management features are available for development teamsworking on the same applications. The repository database can beuser-specified e.g. SQLBase, Oracle etc.
SQLBase
GUPTA’s SQLBase database is included with Team Developer. It isprovided to allow development of client applications in a context whereeither there’s no SQL Database Server available, or the development issimply not intended for a Production Server.
The GUPTA Client/Server-System
Team Developer is a development environment for the creation of ClientSoftware in a Client-Server Environment and for Web developmentusing Web extension classes. The Server side of the system is either aSQL Database Server or an ODBC/OLEDB compliant data source.Typically, in a network, there will be several clients connected to aServer.
All client applications access a common interface, which in turnaccesses a network interface. These interfaces are implemented in theform of DLL’s (Dynamic Link Libraries) on Windows and Shared Objectson Linux.
The SQL/API Application Programming Interface is responsible fordatabase communication. The named dll for this function isSQLWNTM.DLL on Windows and the Shared Object sqlwntm.dll.so onLinux.
Page 13
SQLWindows
Graphical User Interface
The graphic surface of the development environment contains all thecomponents that are needed for developing SQLWindows applications.
The construction of the development environment is contained within aMulti-Document Interface (MDI). This allows for several views of theApplication in various Windows within the environment. Each view isdivided up in two sections similar to MS Windows Explorer: On the leftside the components of the view are shown in the form of a treestructure. (Tree View) on the right are shown the details of thecomponents that were chosen on the left.
Tabs are used to switch between the various details on the right panel.
Page 14
The graphical surface of SQLWindowsLeft Panel:
• Hierarchical of Viewing.
• Quick location of Objects via icons.
Right Panel:
• Detail view of the Objects chosen in the left panel.
• Various views (large Symbols, small Symbols, Lists, Details)
• Several sort options
• Scrollable tabs on the bottom window border for changingstandard categories.
The Outline Editor
• Each component (e.g. Function, Class, Window, Childwindow) orsubcomponent (e.g. variables, constants) have associatedOutline code
• Structural layout
• Enhances Programming
• Improves Clarity
• Visual block building through Indentation
Page 15
• Specific Coding elements can be displayed or hidden
• Standard elements/views accessible via tabs
• Active Coding Assistant (ACA)
The Outline Editor facilitates the editing of source code within eachview. The structure of the source text is predetermined and aids thedeveloper. The Outline is intelligent in that it will not allow incorrectcode to be placed at a point where it does not make sense, for example,if the developer tries to put code for a click event (On SAM_Click) into avariable declaration or class definition then it will be disallowed. TheActive Coding Assistant (ACA) helps reduce errors further by onlypresenting choices that are specific to the appropriate part of theOutline as well as detailing required parameters and functioninformation.
Programming blocks are defined by indentations within the Outlinetherefore eliminating the need for brackets or the typical “Begin…End”
The standard elements of the Outline, accessible via the tabs at thebottom window border, are tailored towards the context of thecomponents chosen within the left panel.
The Active Coding Assistant only showing allowable calls in theOutline editor
Page 16
Tabs• Tab 'Layout'
• Tab is only visible when a window component is in focus.
• The window is firmly positioned in view.
• Window can be previewed
• Child windows nested within MDI Windows and Menus are
only shown in preview mode.
• Preset tab sequence
• Positioning of window location and size for runtime.
• Code cannot be edited while the preview window is open
• A view can display only one window at a time.
Page 17
Layout View
Layout View of a Window Object containing a Child Window.
The Layout section of a view can only be activated when there’s awindow component is highlighted in the left panel
Controls Tool Bar• Tools collection• Contains all Child Window Objects• Shows all the Classes for Windows Objects• Integration of Custom Controls• Integration of ActiveX Components• Display and exit with Alt + 4• Docking (Can be prevented by using the CTRL key)
Page 18
The Controls Tool Bar makes available all Child Windows and theirrespective classes. One can then use their mouse to drop and positiona chosen Object onto the surface of a Parent window.
Coding Assistant
An additional coding assistant (from earlier versions) can be turned onaid in developer productivity.
• Supports the coding of the following elements:• Functions, Constants, Variables• SAL Functions• User-defined Functions• Messages• Class Definitions• Objects• Menus• Show and exit with Alt +2• Docking (Can be prevented by using the CTRL key)• Context- sensitive limitation of the selection based on the
position of the cursor in the code.
Attribute Inspector• Setting of Object Attributes (Properties)• Docking (Can be prevented by using the CTRL key)
Page 19
Database Explorer• Display and Management of Tables, Views, Indices, and
Stored Procedures.• Makes it possible to run SQL Scripts directly from
SQLWindows• Explorer – User Interface• Is represented as an MDI Child Window within SQLWindows• Supports diverse selection of Databases
Page 20
Programming Basics in SAL
OverviewScalable Application Language (SAL) is the language used forProgramming SQL Windows
The language encompasses:
• Datatypes• Objects• Variables• Arrays• Expressions• Operators• Constants• Functions• Object Orientated techniques and capability• Special Support for SQL
Datatypes
Strings of variable lengths must always be placed in apostrophes
Long String -This special type is used for accepting values of LONGVARCHAR database columns. They can be of arbitrary length andcontent (BLOB)
Boolean - A variable of this type can accept either TRUE=1, FALSE=0
Number - Numeric type with a range of precision of up to 22 decimalplaces (for use with both Real and Integer datatypes)
Date/Time - Date/Time entry. The ISO description must be used whenassigning date/time within programming text
File Handle - Is needed for File operations
Sql Handle - Identifies a database connection. Every communicationwith a database requires that one provide a SQL Handle, which isdelivered via SqlConnect( )
Windows Handle - Serves to identify Windows objects. Must bespecified using functions that involve editing Windows.
Objects - The GUPTA Window Objects provided by SQLWindows greatlyfacilitates the programming of the user interface (Windows, Dialogboxes, Buttons, etc). The collection of Objects consists of the basicObjects found in all Standard Windows Components.
Page 21
MDI - Form
Form - Container for Child Window
Page 22
TableWindow - Normal Form Window with a built-in Table
Dialog box• Cannot be resized• Has no System menu• Cannot be minimized or maximized
Modal Dialog Box
• Has to be closed before the rest of the application can beaccessed again.
• Can be used to start/initiate other applications
Page 23
Non-modal Dialog Windows
• Can remain open
• Does not lock the application
Dialog elements (Child Windows)
Dialog elements, also called Child Windows, are objects that are locatedwithin the Parent window. Parent Windows are Dialogs, Form Windows,Table Windows, or MDI Windows.
They can only exist within these Parent Windows.
The Toolbox aids in placing the Dialog elements in a Parent Window.
Page 24
Dialog element Example
Background TextDescription
Pushbutton Exit pushbutton
Datafield
Multiline Field
“This is a test with awrapping Multiline Textfield.”
List Box
Scroll Bar
Group Box
Radio Button Group File format
Check Box Produce report
Options-Button
Combo Box
Table
Table columns
Picture
Frame
Line
Page 25
Object Attributes
For every Object there are certain Attributes, also known as“Properties”.
A distinction is made between those Attributes that are set at DesignTime, and those that are set at the Program Functions Runtime. TheAttribute Inspector assists in setting Attributes at the Developmentstage.
Attributes that are set at the Development phase deal mainly with thefollowing:
• Name of the Object
• Text of the Object
• Appearance
• Size
• Position
• Colors
• Font Style/Size
• Data Types
• Visible/Invisible
• At the Runtime of the ProgramActive/Inactive
• Text of the Object
• Visible/Invisible
• Position
• Colors
• Font Style/Size
Exercise: Form building, compiling and running apps
During this course a Company Information System will be programmedthat tracks the company’s employees and their hire dates.
• Create a Form Window and place the Objects onto the FormWindow with the help of the Tools Window.
• Go through the various properties of the Object and assign thedefault properties.
Page 26
• Look at the window in Preview Mode (Ctrl-L)
• Choose a sensible TAB order and functioning Accelerators (Altkey)
• Save the Program
• Compile, start (F7) and test your application.
• Your running application should look something like below:
ConstantsConstants come in the following types:• String• Number• Boolean• Date/Time
Example of Defining a Constant:♦ Application Description: SQLWindows Standard Application
Template♦ Libraries♦ Global Decl arations♦ Window Defa ults♦ Formats◊ External Functions♦ Constants
◊ System♦ User
◊ Number: PM_New = SAM_User + 1◊ Date/Time: DT_Start = 1998-12-31◊ String: MSG_New = "Anlegen eines neuen
Datensatzes"◊ Boolean: B_OK = TRUE
Page 21
Page 27
Variables
Declarations and length of existence
A Variable can be of any of the aforementioned datatypes. Theycan be declared in various places within the source code.
Global♦ Global Decl arations♦ Window Defa ults♦ Formats♦ External Fu nctions♦ Constants♦ Resources♦ Variables♦ String: sUs erName
• Global declarations exist during the program’s entireruntime.
In Functions♦ Function: f UserFunction♦ Description :♦ Returns♦ Parameters♦ Static Vari ables♦ Number: nCo unter♦ Local Varia bles
♦ String: sUs erName♦ Actions
• Local Variables exist during a functions cycle.
• Static Variables retain their value during two function calls.
• They are initialized with 0 in Windows
♦ Dialog Box: frmMain♦ Description :♦ Tool Bar♦ Contents♦ Functions♦ Window Para meters♦ Window Vari ables
◊ String: sUserName♦ Message Act ions
• Windows Variables exist only as long as the window in whichthey reside. Existence does not mean necessarily that they arevisible.
Page 28
In Classes
♦ Pushbutton Class: cpbGreen♦ Description : Grüner Button♦ Derived Fro m♦ Class Varia bles
◊ Number: nCount♦ Instance Va riables
◊ String: sWindowText♦ Functions♦ Message Act ions
• Class Variables exist only as long as there’s an Instance of aClass available.
• Instance Variables exist only as long as the Instance itself.
Visibility
Variables have a certain period of validity (Scoping Rules). One alsospeaks of a Variables visibility.
Global VariablesGlobal Variables are visible within the entire program Windows andFunctions can call them alike.
Windows Variables• Can be called from anywhere, (like global Variables) provided
they exist.• Windows Variables exist only as long as the window in which
they reside.• No compiler warnings.• There’s a danger of runtime errors anytime windows Variables
are used as global Variables.
♦ Form Window : frmForm◊ ....♦ Window Vari ables◊ String: sName
♦ Dialog Box: dlgDialog♦ ....♦ Message Act ions♦ On SAM_Crea te◊ Set sName = " Education Center"
In the event of a name conflict between global and local Variables,the local Variable will be called.
Declarations♦ Variables◊ String: sName
dlgDialog♦ Window Vari ables
♦ String: sNa me♦ Message Act ions
♦ On SAM_Crea te◊ Set sName = "EC"
Page 29
A naming conflict between names at the same level will result in atranslation error.
♦ Form Window : frm1♦ Window Vari ables
♦ String: sNa me
♦ Dialog Box: dlg1♦ ....♦ Window Vari ables♦ Message Act ions♦ On SAM_Crea te
♦ Set sName = "EC"
♦ Form Window : frm2◊ ....◊ ◊ Window Variables♦ String: sNa me
Local Variables• Can only be called from within the function.• An attempt to call a local function from outside the function will
result in a translation error.
♦ Function: f Test◊ Description:◊ Returns◊ Parameters◊ Static Variables♦ Local Varia bles
♦ String: sTe st♦ Actions
◊ Set sTest = "Hello"
ReferencingExternal ReferencingAn external reference is a reference to a Variable, an object, or afunction that is defined in a given parent window but is alsoreferenced from another window.
In order to prevent naming conflicts due to the visibility of Objects,Variables, or Functions inside of a program, it’s recommended thatone use a fully-qualified reference anytime one is going to access avalue or function outside of its own parent window.
Qualified ReferenceThe object will prefix the name of the surrounding Parent Window.Syntax: Template.ObjectName
◊ Set frm1.sName = "Hello"
Page 30
Goal: The Object can then also be referenced, even though anObject of the same name exists in another window.
Window Semi-Qualified ReferenceThe Objects will be prefixed to the Window Handle.Syntax: WindowHandle.ObjectName
◊ Set hWndFrm.sName = "Hello"
Goal: To be used for the programming of general functions withouthaving to use a specific window name (i.e. for use with an array ofWindows Handles).
◊ Window Handle: hWndArray[*]◊ ...◊ Set hWndArray[1].sName = "Hello"
Fully Qualified ReferenceThe object will prefix the name of the surrounding Parent Window,as well as the Window Handle.
Syntax: WindowHandle.Template.ObjectName
◊ hWnd1 = SalCreateWindow ( frm1, hWndOwner )◊ hWnd2 = SalCreateWindow ( frm1, hWndOwner )◊ ...◊ Set hWnd1.frm1.sName = "Hello"◊ Set hWnd2.frm1.sName = "Hello"
Goal: The Object can also be referenced; even though severalInstances of a window exist that have the same name.
Arrays
An array is an ordered list of Variables of the same type.Limitations: Every type except Long StringProperties:
• Multi-Dimensional Arrays• Dynamic Size (With multi-dimensional arrays, only 1
dimension is dynamic)• Borders (scope) can be specified.• Indices usually begin with 0.• Min/Max Indices can be defined.
Example:
◊ Number: nPosition[10]◊ Number: nPosition[0:9]◊ Number: nPosition[*]◊ Number: nPosition[1:*]◊ String: strAngestellte[10,3]◊ String: strAngestellte[*,3]
Page 31
◊ String: strAngestellte[1:10,1:3]◊ String: strAngestellte[1:*,1:3]
Access:◊ Set value = nPosition [5]
Functions used for editing arrays:SalArray* (e.g. SalArrayMin, SalArrayMax,...)
Object VariablesAll Dialog Elements / Objects have in addition to their visualcharacteristics, their value as Variables (Object Variables) as well.
Limitations: Push Button, Background Text, Group Box, Line, Frame• The Variable name is the name of the Object• Every Object Variable has a datatype.• Some Objects can have several datatypes.
Object Variable Datatypes
Element Datatype
Data Field String, Longstring, Date/Time, Number
Combo Box String, Long String
Radio Button Boolean
Check Box Boolean
Scroll Bar Number
Multiline Field String, Long String
Listbox String
Column String, Longstring, Date/Time, Number
Picture Bitmap (Icon-) File oder OLE Daten
Object Type:Pushbutton Class default
BackgroundText
Class default
Line Class default
Frame Class default
Group Box Class default
Page 32
Dialog Elements can also be used as Variables in assignmentstatements.
◊ Set dfName = "GUPTA Education Center"◊ Set sbScroll = 10
Naming ConventionsHungarian Notation: Small letters precede Variables to denote theirtype. The expanded name consists of a word chain that begins withcapitol letters.
Note• Using this notation you can read example programs easier.• Your programs will be easier to read for colleagues and
coworkers, not to mention more easily maintainable.
With Objects:
Object Prefix Example
Data Field Df.. dfData
Multiline Text ml.. mlMemo
Push Button Pb.. pbOk
Radio Button Rb.. rbMybutton
Check Boxes Cb.. cbCompiled
Combo Box Cmb.. cmMycombo
List Box Lb.. lbMylistbox
Picture Pic.. picLogo
MDI-Form Mdi.. mdiMDIform1
Form Window Frm.. frmMain
Dialog Dlg.. dlgAbout
Table Window Tbl.. tblCompanytable
TB – Column Col.. colColumnvalueScroll Bar Sb.. sbBrowse
With Variables
Variable Prefix Example
String Str../s.. strText
Number n.. nNum1
Boolean b.. bFlag
Date/Time Dt.. dtTimenow
Window Handle HWnd.. hWndForm
Sql Handle HSql.. hSql1
File Handle HFile.. hFileTextDate
Page 33
With Constants• Messages, SQL Statements• Similar to Hungarian Notation
With respect to System Variables, there’s a division of Constantsinto groups through the use of a prefix in Capitals followed by anunderscore.
Type of Constant Prefix Example:
SQLWindows ApplicationMessages
SAM_.. SAM_Click
Table Window Constants TBL_.. TBL_NoMoreRows
File Open Constants OF_.. OF_Binary
User Defined Messages PM_.. PM_Insert
Operators
Symbol Operation
+, -, *, / basic arithmetic operations
=, !=, >, <, <=, >= Comparison operators
AND, OR, NOT Boolean
& bitwise AND
| bitwise OR concatenation operators
|| Concatenation
Expressions
Expressions are built using Function outputs, Variables,Constants, or Expressions bound together with Operators.
• Interpretation from left to right with AND, OR, NOT• Interpretation with AND, OR
Example:◊ Set bOk = TRUE◊ Set nCount = 1000◊ Set sSelect = "SELECT " || sFields ||
" FROM " || sFrom
Page 31
Page 34
Statements• A statement consists of a line of programming• Statements are edited in the Outline• Only one statement per line• Choose using Outline-Option• The ENTER key adds blank lines• Exclamation marks indicate commented lines• Break lines with CTRL-RETURN (For statements encompassing
several lines)• A RETURN terminates line editing• Lines / Blocks of Statements can be staggered / relocated by
pressing ALT with either a DOWN or UP arrow.• Enter one line at a time.
A second line enter and with the ALT + UP ARROW combinationmove upwards into the first position.
SAL Statements
Set• Setting the value of the variable.• Variables can also be set using the result value of a function.
Syntax Set,Variable/ObjectVariable=Expression
Example:◊ Set sName = "GUPTA Education Center"◊ Set nCount = fCounter(nCount)
Call• Calling functions• Recursion possible• Nesting of functions is possible
Syntax: Call <Functioname([parameter1,parameter2,...])
Example:◊ Call SalQuit()
Comments• Coding documentation
Syntax ! Description Text
Example:◊ ! this is a comment
If...Else/Else If• Conditionals in the programming code.• Blocks are set apart using indentation• No Begin and End is needed
Syntax If <expression>
Page 35
Else If <expression>
Else
Example:
♦ If i = 0◊ ! further Statements
◊ Set nCount = i♦ Else If i = 1◊ ! further Statements
◊ Set nCount = -1♦ Else◊ ! further Statements
◊ Set nCount = 99
Select Case...• Of a numeric expression• A Break has to be placed at the end of a Case• Default should always be included
Syntax: Select Case <numeric expression>
Case <numeric Constant>
Break
Default
Example:♦ Select Case i
♦ Case 1◊ Set sIdentifier = Company
Administration◊ Break
♦ Case 2◊ Set sIdentifier = Partner
◊ Break♦ Default◊ Set sIdentifier = General
Loop• Looping construction without Break criterion• Has to end with a Break, otherwise it’s endless.• Can be nested
Syntax: Loop <[Name of Loop]>
Break <[Name of Loop]>
Example:♦ Loop OUTER
◊ Set nCount = nCount + 1♦ Loop INNER
◊ Set i = i + 1♦ if i = 10
◊ Break INNER♦ Else if nCo unt > 10
Page 36
◊ Break OUTER◊ Set nCount = nCount + 1♦ If nCount = 10◊ Break OUTER
While• Looping construction with a Break criterion• Can be nested
Syntax While <boolean expression>
Example:
♦ While i < 1 0◊ Set nEvent = i * i◊ Set i = i + 1
On• Defines the handling of a message• Can only be used in either Message Actions or Applications
Actions.
Syntax On <Message>
Example:
◊ On SAM_Click
Return• Ends a function or the handling of a message• Must always return a value.• May only be used when a return value is defined in the head
of a function.
Syntax Return <value>
Example:◊ Return TRUE◊ Return sName◊ Return 0
When SqlError• Local SQL error handling.• Must always be located before the SQL statement.• Must always be located before the SQL statement.
Syntax When SqlError
Example:
◊ When SQLError◊ Call SalMessageBox( SQL Error, Beware,
MB_Ok)
Page 37
Functions
Internal Functions
Internal Functions - Internal functions are defined and coded withinTeam Developer.
Function Template in the OutlineWhen a function’s added, a function body is created that has to befilled out.
♦ Function:Fu nction: <Name of a function>◊ Description:◊ Returns◊ Parameters◊ Local Variables◊ Actions
Global Functions• Can always be addressable and valid• Should only be used for global tasks.
♦ Application♦ ...♦ Global Decl arations
♦ ...♦ Internal Fu nctions
♦ Function: f Add◊ Description:
◊ Add 2 Digits♦ Returns
◊ Number:♦ Parameters
◊ Number: pnDigit1◊ Number: pnDigit2◊ Static Variables
♦ Local Varia bles◊ Number: nEvent
♦ Actions◊ Set nEvent = pnDigit1 + pnDigit2◊ Return nEvent
Local Functions• In Parent Windows (Form Windows, Dialog boxes, MDI Windows,
Table Windows)• Table Child Windows• Are valid or exist only as long as the window in which they
reside.• Should be used only for local functionality• Must be referenced when being addressed externally.
♦ Form Window : frmCompanyInfo♦ Description :♦ ...
Page 38
♦ Functions♦ Function: f Add
◊ Description:◊ Add 2 Digits
♦ Returns◊ Number:♦ Parameters
◊ Number: pnDigit1◊ Number pnDigit2
◊ Static Variables♦ Local Varia bles
◊ Number: nEvent♦ Actions
◊ Set nEvent = pnDigit1 + pnDigit2◊ Return nEvent
External Functions
• Are imported from DLL’s• External functions are only defined within Team Developer.
These functions’ coding is contained within DLL’s and is written,for example, with C++
♦ External Fu nctions♦ Library nam e: sqlwntm.dll
♦ Function: s qldbn♦ Description :♦ Export Ordi nal: 0♦ Returns
◊ Number: SHORT♦ Parameters◊ String: LPCSTR◊ String: LPCSTR◊ Receive Number: LPUSHORT
Function event• The Return Value is always of a certain type.• The Return Value is requested using the keyword
Return<value>• Return without a value creates a translation error.• The Return Value can be transferred to the program that called
the function.Also, simply because a Return Value’s specified during the definitionof a function does not mean that it has to be processed by theprogram. Calling a function is something different.
◊ Set nEvent = fAdd (1,1)◊ Call fAdd (1,1)
Page 39
Function Parameters
• Function parameters are specified during a function’s definition.• Function parameters are of a certain type.• Parameters can be handled from within a function just like
normal variables.There are 2 different types of Parameters to pass:• Parameters as a copy of a variable.• Parameters as an address of a variable.
Parameters as a copy (Call by Value)• A copy of the value will be given to the function upon being
called.• The value as original in the surrounding program cannot be
changed.• Any changes are lost upon termination of the function.Example:
♦ Parameters◊ Number: nDigit1
Parameters as a copy (Call by Value)• The address of the value will be given to the function upon
being called.• Any changes in the values of the parameters will be passed
onto the surrounding program.• Only variables can be passed to a function, not constants.• It’s possible to pass several values from a function to the
program.
Example:♦ Parameters◊ Receive Number nDigit1
Page 40
Exercise: Coding in the OutlineTask:Modify the starter program in Exercise 6.6 to add an internal functionthat deletes all of the form’s data fields.
Tips:• Pay close attention that you only display those parts of the
programming code that are immediately needed, by choosing asensible level of detail. (Double-click on )
• Use the SQLWindows function SalClearField()
• You should insert a popup menu called “file” in your window, withthe menu choice “new” so that you can test the function.
Definition of the function:♦ Global Decl arations
♦ .....♦ Internal Fu nctions
♦ Function fC learForm♦ Description :♦ Returns♦ Parameters♦ Static Vari ables♦ Local Varia bles♦ Action
Calling of the function♦ Form Window : frmCompanyInfo
♦ Description♦ Named Menus♦ Menu
♦ Popup Menu: &File♦ Enabled whe n:♦ Status Text :
♦ Menu Item: & New♦ Status Text♦ Keyboard Ac celerator: (none)♦ Menu Settin gs♦ Menu Action s
Page 41
◊ Call fClearForm()♦ Menu Separa tor♦ ....
Working with Windows ObjectsNext to the database connections, the user interface is the mostimportant thing in a Windows program. The interface is most frequentlyimplemented using windows. Therefore, it’s really important to knowthe windows properties, and the relationships between the variouswindows objects.All Parent Windows and Dialog Elements are treated as Windows by MSWindows.Thus, for example, Data fields and Radio Buttons are windows as well.
Windows Properties
Parent/Child Relationship
All windows underlie a hierarchy every dialog element has a ParentWindow as its superior in the hierarchy. The dialog element itself isthen designated as a Child Window in this relationship.
Window TextEvery window has window text, the display of which is dependent onthe type of window.
Window HandleEvery window within Windows has a unique number or ID, which isknown as a Window Handle. If one wants to work with this window,he/she must know its Window Handle. SQLWindows simplifies this
Page 42
concept, in that it equates the name of the Window with its WindowHandle.
Visibility of WindowsWindows can be visible or invisible. It’s possible to either hide orshow a window at the runtime of an application.
Active/Inactive
Windows can be active or inactive. An inactive window does notreact to the actions of the user. We can query through SAL whatthe state of a Window is.
PositionWindows have a position on the monitor/display. This can be set inabsolute relation to the monitor/display or relative to the ParentWindow.
Message ReceiptEvery window receives messages. Every message effects, as with afunction call, the execution of a block of programming code. InSQLWindows these program blocks are formed in SAL. The cause forsending messages is events occurring.
Exercise: Coding the Outline – global functionsThe internal global function
• fClearForm(...)should now be implemented for every class.
Therefore, don’t use the name of the individual window, but ratherlocate with the help of functions.
• SalGetFirstChild(• SalGetNextChild( )
The designated Data field, and delete the respective field from withinthe loop. One can use the SQLWindows constant hWndNULL for the endof the loop.
Consider which of the Parameters are actually needed and make sensein terms of the global implementation of this function.
♦ Internal Fu nctions♦ Function: f ClearForm♦ Description :
♦ Returns♦ Parameters
◊ ???
Page 43
♦ Static Vari ables♦ Local Varia bles♦ Actions
◊ ???
Event-oriented Programming
The Concept of Event-Orientation
• The program was responsible for handling I/O for the OS’s• Under MS Windows, the OS takes on this task to a certain
extent.
• The OS recognizes keyboard or Mouse events. A message isgenerated that is sent to the program.
• The program waits passively for messages from Windows. Nocode is executed (e.g. Loops)
• If it encounters a message, it reacts to it. The handling occursindependently from other messages.
• The program waits passively for the next message.• The appearance of messages is not foreseeable and thus there’s
no way to presume any particular sequence.• The reaction to a message can be understood just like to a
function call within a large program.
Page 44
Events –Messages -Methods• A normal program processes its assignments actively and
sequentially.• SQLWindows program waits passively for an event.• If an event is encountered, a message is sent.• Every message can effect the execution of a method, which is
responsible for the handling of this message by the receiver.• The program controls the sequencing of events and messages.• The receiver can process this message, but it doesn’t have to.
The messages are sent regardless.
The user doesn’t communicate with the program per se, but ratherthe objects of the program. (Events: Click on a button, Enter datainto a text field, etc. The messages generated by these events aresent directly to the objects.
To program with SQLWindows = to react to the desiredmessage with the right code!
The approach:1. Which event is important to me?2. When am I going to receive a message about this?3. What is the message called?4. How should I react to it?
SQLWindows Internal MessagesNext to OS messages that are triggered by user events, there are alsoSQLWindows messages that are triggered by the runtime environmentitself. These messages correspond to the application and its objects.
Some Messages:
Message Event, Trigger, Point in Time
SAM_AppStartup Program starts, first message overall.
SAM_AppExit End of program, last message.
SAM_Create Object is created.
Page 45
SAM_Destroy Object is destroyed.
SAM_AnyEdit An altered input field is exited.
SAM_Validate Question: Is the field’s content ok?
SAM_SetFocus Field becomes the focus of input or entry.
Message VariablesJust as with parameters for functions, there are four variables that existfor messages. Their purpose is to transfer data to the message routine.The values of the variables are set by the System.
HwndForm (Window Handle)
HwndItem (Window Handle)
Wparam (Number)
Lparam (Number)
The values of the variables are a property of the message and areincluded with their description.
Example:SAM_Click with a Push Button
HwndForm Handle of the surrounding window.
HwndItem Handle of the push button.
Wparam Not used.
Lparam Not used.
SAM_Click with a picture
HwndForm Handle of the surrounding window.
HwndItem Handle of the picture.
Wparam x-coordinate of the mouse click within thepicture
Lparam y-coordinate of the mouse click within thepicture
The following is valid for programming:
Only think about the current object in scope
“I” = hwindItem, hWndForm, hWndMDI
Page 46
Programmed Events / Messages in SQLWindows• SQLWindows system and MS Windows can only create and send
messages based on system events.• One can simulate events, in that he creates messages that belong to
an event.• Definition of the event (Form window has to be rebuilt)• Definition of the message (PM_Build Form Window) as numeric
constants. (PM_...= SAM_User + x )• Sending of the message to the Form Window
SalSendMsg(hWndForm,PM_Build Form Window, …)• Form Window reacts to the message and rebuilds itself. (On
PM_Build Form Window)
Functions Used for Sending Messages
SalSendMsg( hWnd, nMsg, wParam, lParam )
SalPostMsg( hWnd, nMsg, wParam, lParam )
The receiver of a message is always a Window (addressed via itsname or Handle)
Parameters:
HWnd The window that receives the message
NMsg “Event” relative to the type of message
Wparam Additional information, if needed
Lparam Additional information, if needed
Example:Call SalSendMsg ( hWndForm, PM_Build Form Window, 0, 0)Call SalSendMsg ( hWndForm, PM_Build Form Window, 0, 0)
SalPostMsg()• Enters the message into the application’s message queue.• The call ends immediately and the program processes the next
assignment.• Asynchronous, Cooperative Anweiswungen
Page 47
⌦Message queue Processing
Use:Always in situations when the event’s not immediately needed forthe next assignments.
SalSendMsg()
• The message is sent immediately• The caller waits until the receiver executes his actions.• Synchronously, just as with a function call.
⌦queue Message, Processing
Use:Always in situations when the event’s important to and needed forthe next assignments.
Page 48
SalSendMsgToChildren()• Functions like SalSendMsg()• The addresser is not the window itself, but the parent.• The message is sent automatically to all Child Windows.
Exercise: Events and messagingReplace the internal function fClearForm() in exercise 6.14.2 withEvents Messaging’ to achieve same result.
Should work with a Developer-generated message, PM_CLEAR
• Which SAL functions make sense?• Do we pass any parameters?• In what kind of functions would using wParam and lParam make
sense?• Does this approach even make sense?
DebuggingAn important element of any Programming environment is tools thatserve to diagnose programming code for mistakes as well as expectedapplication flow control. The search for errors within a program isknown as “Debugging” GUPTA SQLWindows provides the followingdescribed tools to aid in this purpose:
Tools
Testing the content of Variables
The window for viewing the value of Variables
With the help of this tool one can view the content of Variables atruntime. It can also be checked whether or not Variable assignmentsare to be executed as expected.
This tool can be accessed via the menu:Tools / Variables or just Alt+5 in the IDE
or via the toolbar symbol (Toolbar “Debug”)
Variables
Page 48Page 49
The ordering of the Variables shown is done using the pushbutton in theupper right corner of the window. It’s here that one comes to the FormWindow for selecting the Variables to be analyzed.
Fig 9
Selection Window for VariablesIn the window shown in Fig 9 one can select among the availableVariables; their referencing corresponds to their respective context.From the selections made here one can also modify the value of theVariables.
For example, an expression can also be viewed (e.g. nCount > 0)
The Viewing of the Call Stack
Fig 10:The Viewing of the Call Stack
The Call Stack shows the actual functions that are being implementedrelative to Messages and their context. With nested function calls, thecalling hierarchy will be shown. The hierarchy shown in Fig 10 looks likethe following in code:
1 Form Window: frmMain ...
1.1 Functions1.1.1 Function: fSave
Page 50
...1.1.1.1 Actions1.1.1.1.1 Call fSaveStandards( )
...1.1.2 Function: fSaveStandards
...1.1.2.1 Actions
1.1.2.1.1 Call ... ! ActualPosition
...
1.2 Message Actions1.2.1 On SAM_Close
1.2.1.1 Call fSave( )
The viewing of the Call Stack is accessed via the menu:
Tools / Call Stack or just Alt+6 in the IDE
or via the toolbar symbol (Toolbar “Debug”)
Call Stack
Viewing of Messages
Fig 11: The window for viewing messages.
Since the principle of event-control /orientation is one of the basicconcepts of Windows Programming, it’s also necessary to have a toolfor monitoring all occurring events.
All the events that occur during the running of the program are shownin Fig 11 as messages with their assigned Variables (Window Handle,wParam, lParam).
The view is restricted to the GUPTA SQLWindows-defined SAMmessages.
The viewing of the Messages Window is accessed via the menu:Tools / Messages or by Alt+7 in the IDE
or via the toolbar symbol (Toolbar “Debug”)
Page 51
Message
Viewing / Evaluation of Expressions
Fig. 12: Window for Viewing / Evaluating Expressions
With the help of this tool it is possible to monitor or execute anyexpressions, function calls, and assignments during the running of theprogram. Next to that is the executed line of the evaluated expressionappearing as a Combo Box, in the Window lying beneath that appearsnot only the type of the event, but the event itself.
Note: Using this tool it is possible to interfere with running of theprogram. For example, should any manually executed changes to thecontents of Variables occur, this changed content is then available tothe program.
The environment that is applicable to the tool, is always the context ofthe actual position within the program
The viewing of the tool for evaluation of expressions is accessed via themenu:
Tools / Expressions or Alt+8 in the IDE
or via the toolbar symbol (Toolbar “Debug”)
Expressions
BreakpointsThe tool mentioned in the previous Chapter may only be used in theframework of a controlled, running program. Manual control of therunning of the program is obtained by using what is known asBreakpoints.
Breakpoints are specific markings in programming code. They interruptthe running program and can be set within the Developmentenvironment to take place before the start and during the execution ofa program. They are usually marked in red in the source text.
Should a breakpoint be encountered during the running of a program,the developer can manually override whether further execution willoccur (towards the next breakpoint or end of the program).
Page 52
Administration of BreakpointsA Breakpoint can be set at a marked line in the source code via themenu:Debug / Breakpoints / Toggle or F9
Or by choosing the Standard Toolbar symbol
Toggle Breakpoint
In order to remove a previously set Breakpoint, one follows the sameprocedure.Besides setting and removing individual breakpoints, the followingoptions exist:• Deletion of all breakpoints in the programming code.• Deactivation of all breakpoints. (The breakpoints will still exist, but
will be ignored during the program’s execution.• Activation of all breakpoints. (The program will stop at the
breakpoint.)
Overriding the normal Program FlowSeveral tools are available for manually controlling a program’s flow
(after reaching a breakpoint).• Continuation of the program until the next breakpoint (if one exists,
otherwise until the end of the program. via the menu): Debug /Continue Debugging or CTRL F7
Continue
• Interruption of the program flow via the menu: Debug / Break or bychoosing the following symbol in the Debug Toolbar:
Break
• Single step execution (detailed) executes the next statement andthen returns the control to the Debug Toolbar. Should thestatement involve a function, the function will be activated and thenone can move through the various statements within the function.Thereafter the Debugger returns to the original statement.
This function is accessible via the menu: Debug / Step Into, F10, orvia the symbol
Step Into
• Single step execution contains the current statement of a program;should this be indeed executed. In contrast to the detailed single-step execution, the individual statements within the function will notbe shown.
This function is accessible via the menu: Debug / Step Over,(Ctrl+F10) or via the symbol
Page 53
Step Over
Special Features
Assignment of Variables
Just as described in Chapter 8.1.4 (View/Evaluation of Expressions)it’s also possible to control the content of variables via the“Expressions” window. Since all valid statements can be executedvia this tool, the explicit assignment of Variables can be made hereas well.
The following illustration shows an example of this:
Fig 13: Assignment of Variables in the “Expressions” Window
Note: The assignment of Variables in this way serves only to testfor possible corrections. Should this process lead to the desiredresults, it naturally has to be expressed in the adjusted code.
AnimationShould the execution of the program continue after a breakpoint isreached, it’s normally not possible to view the continued running ofthe program. But the GUPTA SQLWindows DevelopmentEnvironment offers altogether three options for viewing the runningof a program.
• No Animation (Menu: Debug / No Animate, standard setting)• Slow Animation (Menu: Debug / Slow Animate) Here the
individual statements in the program flow will be shown for apredefined duration. This interval is set using the menu optionTools / Preferences.
Page 54
Fig 14 The “Preferences” Window
• Fast Animation (Menu: Debug / Fast Animate), Fast ProgramFlow (Speed cannot be changed)
Database connections in Team Developer
Database Access CycleSQLWindows provides a set of commands that allow for connecting toSQL databases. This connection follows a certain cycle that is called the“Database Access Cycle”• SqlConnect creates a database connection. The connection is
addressed using its Handle (Sql Handle, Cursor.) Prerequisite for asuccessful database connection is that the corresponding systemvariables were initialized with valid values. (SqlDatabase, SqlUser,SqlPassword)
• SqlPrepare translates a SQL statement at the server and connectsit with the Handle.
• SqlExecute executes the SQL statement bound to the SQL Handleand creates a result set for SELECT statements.
• SqlFetchNext reads the individual datasets of the result set createdby SqlExecute. (Only with “SELECT” statements)
• SqlDisconnect terminates a database connection.
Page 55
Fig 15. The Database Access Cycle
The Binding of SQLSQLWindows offers the option to use Variables in SQL statements. Thisoccurs via Into and Bind Variables. Variables are integrated in a SQLstatement using a colon prefix.• Into - Variables specify which program defined variables the
results of a SELECT statement are placed.
• Bind - Variables transport values from the program into thedatabase.
Example:
SELECT company_name, address, city
INTO :dfName, :dfStreet, :dfCity
FROM company
WHERE company_name = :strCompanyName
Into Variables: dfname, dfStreet, and dfCity
Bind Variable: strCompanyName
Note: A frequent source of errors is a missing colon before an INTO,BIND variables.
Note: The content of INTO Variables will be filled with the respectiveactual result set of every FETCH statement
Exercise: Database access and retrieving informationThe form window labeled Company Information now has to be filledwith data.
Page 56
FunctionalitySearch:Search all records. Use the country field as search criteria.
Next:Page through all the records found.
Insert:Data in the form window will be entered into the database.
Update:Changed data in the form window will be played back by number intothe database.
Delete:Data in the form window will be deleted from the database.
Scrollbar:Program the scrollbar so that a ‘down’ click gets the next row of theresult set and ‘up’ click gets the previous row of the result set.
Necessary functions/Messages:SqlConnect, SqlDisconnect, SqlPrepare, SqlExecute, SqlFetchNext,SalEnableWindow, SalDisableWindow, SalSendMsg, SqlCommit
SAM_Create, SAM_Destroy, SAM_Click, SAM_Scrollbar, SalMessageBox
The meaning and parameters of the functions are best found inthe SQLWindows Online Help.
SQL Error HandlingThe handling of errors relating to database statements can take place in3 areas: As a basic principle, a runtime system error is intercepted withstandard error handling. However, it can also be intercepted at theglobal program or statement levels (Cascaded error handling). It is
Page 57
important to remember that these error handling routines are for‘database errors’ and not general SAL statements, e.g. when SQLErrorwill register and error in SQLConnect( ) but not in SQLPrepare( ).
Error handling at the statement level.
The ‘When SqlError’ statement at the statement level handleserrors. This has to be placed directly before the statement that’s tobe executed and on the same programming level.
Example:♦ Pushbutton: pbEnter♦ Message Act ions♦ On SAM_Clic k♦ When SqlErr or♦ Set nSqlErr or = SqlError(hSql)♦ Call SqlGet ErrorText(nSqlError, strErrorText)♦ Call SqlGet ErrorPosition(hSqlError, nErrorPos)♦ Call SalNum berToStr(nSqlError, 0, strSqlError)♦ Call SalMes sageBox(strSqlError || '-' ||
strErrorText, 'Message-Box', MB_Ok)♦ Return FALS E
◊ Call SqlPrepare(hSql, sINSERT)♦ If SqlExecu te(hSql)♦ Call SqlCom mit(hSql)♦ Call SalSen dMsg(pbSearch, SAM_Click, 0, 0)
Error Handling at the Global Program LevelThis is error handling that’s executed generally, for the entireprogram. It takes place at the “Applications Actions” level. Here theresponse will be a special message SAM_SqlError.
The system variables wParam and Iparam give information aboutthe error.
Example:♦ Application Actions♦ On SAM_SqlE rror
♦ Call SqlExt ractArgs(wParam, lParam, hSql,nSqlError, nSqlErrorPos)♦ Call SqlGet ErrorText(nSqlError, strErrorText)♦ Call SalNum berToStr(nSqlError, 0, strSqlError)◊ Call SalMessageBox(strSqlError || '-' ||strErrorText, 'Message-Box', MB_Ok)
♦ Return FALS E
SQLWindows Standard Error HandlingWhether an error to a SQL Function is intercepted at the statementlevel or at the global program level, the standard SQLWindows errorhandling takes place.
Page 58
Fig 16 Standard SQL Error handling under SQLWindows.
Note: SQL Errors should always be intercepted whenever possible,for only then is it possible to run the rest of the program in acontrolled manner. Should a user encounter a standard errormessage and have to make a decision on exiting or continuing theprogram, an uncontrolled event may still exist.
SQL Error Handling Flow Chart
Exercise: Error handlingExpand the functionality of the ‘Customer Information’ application.• Add Global Error Handling routine to catch all SQL errors.
Page 59
• The Search and Insert functions both require a database connectionto be set up. Add a specific Local Error Handling routine only to the‘Insert’ and trap for the following errors locally:
o 9268 : Cannot connect – SQLBase server is down
o 401 : Database does not exist
Test your application with (a) no SQLBase server (b) Incorrect databasename.
Notice the difference in error message for the ‘Search and‘Insert’ buttons.
Table ObjectsTable Objects were created in SQLWindows to display data in a tableformat. There are table objects in the form of Parent Windows and ChildWindows.
Table as a self-standing window with a toolbar.• The entire window surface area is a table.• A toolbar can be incorporated as well.• The table expands and contracts with the window.
Table as a Child Window within a Parent Window
• The table is located only in the Parent Window.• The table will not be automatically resized at Runtime.
Page 60
Table Columns• Table columns are the only content of a table.• Every column has a designated data type (similar to a data field)• Every column behaves like a Variable (Input Mask, Format, Data
Type, Editable…)• Columns can be interchanged (also by the user at Runtime)
Table PropertiesA table, like any Object, has certain properties. Many properties aredesignated during Development time (Visible, Position…) but can onlybe adjusted during Runtime with the aid of SAL functions.
Runtime-adjustable Properties
ConstantsTBL_Flag_
StandardInstallation
Installation Description
SizeableCols
MoveableCols
SelectableCols
HscrollByCols
ShowVScroll
GrayedHeaders
TRUE
TRUE
FALSE
TRUE
FALSE
TRUE
Changing the column width
Interchanging columns
Column Selection
Horizontal column browsing
Vertical roll bar.
Appearance of the Column and
Line headers like Pushbuttons.
The following function is used to set the properties:• SalTblSetTableFlags (hWndTable, Flag, Boolean)
Page 61
Context Rows and focus
Focus• The focus row is the line that contains the fields for entering user
data...• The focus row receives a focus.border• The focus row can be set directly by the user.
Context Row• The content of the Column Object Variables is always set via the
Context row.
◊ Set colName = "Parmar"
• The context row will automatically be set to the focus rowanytime a user changes the focus row.
• The context row is not, however, always the same as the focusrow.
Page 62
Marking Row Flags
Table rows can be seen with the following markings:
Flag Row in Table is
ROW_Selected selected by the user.ROW_MarkDeleted marked for later deletionROW_Edited changedROW_New newly entered
ROW_Hidden not visible.
There can also be several flags set for a single row. For example, a newrow that was edited:ROW_New und ROW_Edited
Search for rows with certain markings:• SalTblFindNextRow( )• SalTblFindPrevRow( )
The Table Window CacheTable data is held locally on the client machine in Table Window cache.
Attention:Not to be confused with the result set of a database, even when thecontent can be the same.
Page 63
How the Table Window Cache Functions
• Every row of the result set is read only once, provided thecache is large enough.
• The Table Window will send a SAM_FetchRow message,should there be data needed in the cache.
• SAM_FetchRow must be responded to in order to transferdata into the Table Window.
Filling a Table Window with Data:
Resetting the Table Window and the designation of a row count(0…n-1)
◊ Call SalTblReset (Tbl1)◊ Call SalTblSetRange (Tbl1,0,nRows-1)
Use of the SAM_FetchRow Message♦ On SAM_Fetc hRow◊ Call SqlFetchRow (hSql,...,lParam)◊
With this message one will be instructed to fill the row “Iparam” withvalues.
Method of functioning:1. The Table Window is assigned the task to display x-number of
records.2. For every record that fits on the screen …
2.1. ... the table sets the context row on record y in which therecord is to be shown.
Page 64
2.2. …and sends itself SAM_FetchRow with Iparam = y.2.3. …the program uses SqlFetchRow in order to fetch the y-threcord from the result set.
3. Should the user browse back and forth, steps 2.x are re-executed.
This cycle is completed with SalTblPopulate().
Tables in the Application
Database Functions for Tables
SalTblPopulate() Fills the Table Window with a SELECT query’sresult set. "SELECT * FROM..." is possible! (Canuse for a table that has no predefined columns)
SalTblDoInserts() Searches through the Table Window for newrecords and then inserts them with a SQL INSERTstatement into the database.
SalTblDoUpdates() Searches for altered records and then transfersthem via SQL UPDATE into the database.
SalTblDoDeletes() Searches for records marked for deleting andthen also deletes them via SQL DELETE from thedatabase.
Page 65
Exercise: Using and populating Tablefields
Task 1:• Create a Table Window as the Parent Window• Expand the frmCompanyInfo with the button “Communication
Partner”• Create the new window at runtime with the command,
SalCreateWindow()• Create Table Columns in order to build the database table
CONTACT. Ensure that you have the right data types.• Fill the table with help of the SAL Function SalTblPopulate()• Process the data in the table and pay special attn to the
markings of the record heads.
Task 2:• Place the buttons, delete, new record, exit, and save onto the
window’s toolbar.• Program the designated menu items.
Use the SalTblDo….()..Functions to accomplish this.
Your application should look something like below:
Page 66
Short glance at Report BuilderReport Windows is needed for the formatted output of data to a printer.It developed itself from a tool used for creating reports to a completequery tool with the possibility of defining database queries.
Here the functionality for simple template definition is explored.
Page 67
Properties and Options• Use of all Fonts (?, Formats)• Use of Graphics (Lines, Rectangles…)• Data Grouping (Breakgroups)• Calculation of Groups• Automatic Page Break• Preview Option
If the report is used in this way, the program delivers the data.• The use of any data is possible.• No limit on data tables.
Connection to SQLWindows
Basic procedure
Tools collection
Report Template Creation
• Start Report Builder• Import a Standard Template Menu Edit / Import Template• Open the file NEWREP.QRP
Page 68
• Define the input item in the Input Items area (right mouse click/ New…)
• Enter every new input item with NEW, and note the data type• Place and format the Input Items onto the empty lines of the
template using Drag&Drop.
Programming SQLWindows
• SalReportPrint()• SalReportView()
Parameters of the Function, SalReportView:
hWndForm The window that receives the messageSAM_FetchRow Normally, the window thatcalls SalReport.
hWndRptTemp Window for the Report. The Report createsit’s own window using hWndNULL
strTemplate Name of the Report (filename)strVariables List (String) of the SQLWindows variables,
separated by comma.strInputs List (String) the input items, separated by
comma.nErr Return of the error number The variable
must be set to 1 before the call.
Additional parameters of SalReportPrint:
Reading values from the database
NCopies The number of copies to be printed.NOptions Output options:
Print everything, partial print, fast print(draft)
NFirstPage With partial printing: 1st pageNLastPage With partial printing: last page
Page 69
The data must be read and input items assigned using the message:
SAM_ReportFetchNext.SqlPrepare() binds input items with Variables.SqlExecute prepares the reading of the data.SqlFetchNext() replaces input items with their values.
Exercise: Reports
Template Creation• Define 8input items: COMPANY_ID, INVOICE_ID, COMPANY_NAME,
INVOICE_DATE, INVOICE_PAID, STATUS, AMOUNT, EMP_ID• Look at the ‘Invoice’ table in the ISLAND database and choose
appropriate datatypes.• Place the input items in the report. Use COMPANY_NAME in the
header.• Enter meaningful background text• Control using Report-Preview• Save the Report
Now modify the previous ‘Company Information’ application:
• Add a new menu item called ‘Invoice Report’• Make use of the following SAL functions / Events:
1. SalReportView
Page 70
Code this in the new menu item. Use parameters:
Name of the report file
Names of the SQLWindows variables
Names of the Report Windows variables
2. SAM_ReportStartTo translate the required SQL SELECT statement:Use SqlPrepare() in the designated Message Action Section of thewindow.
3. SAM_ReportFetchInit
To execute the SQL statement: Use SqlExecute() in the designatedMessage Action Section of the window.
4. SAM_ReportFetchNextIn the designated Message Action of the window, fill the SQLWindowsvariables with values using SqlFetchNext()Report Builder will use the names of the SQLWindows variables toreceive its values.
This will be repeated until SAM_FetchNext is ended with Return FALSE.
Your final running report should look something like below:
This exercise covered the basics of using Report Builder. There aremany more features that make this tool very powerful and flexible. Youshould investigate its full potential.
Page 71
Multi-user Programming
IntroductionIn a Client/Server environment there are several users communicatingwith the server. The server has to process each request with as little aspossible side effects on the other requests. To that end the server useslocks that are partially automatic or set intentionally and can beremoved later.
Locks
Granularity
A database system uses locks to guarantee a multi-user operation.Locks differentiate between the granularity and the type of locks.Locks are designed to prevent further access to an Object.Granularity specifies the size of the Object to be locked.
Locks exist on:• Database level• Table level• Page level• Row level• Field level
The whole database can be locked with the access of one user. Thatsurely prevents any side effects, but other users aren’t able to work,should they also want to work with the same data. It’s similar tolocks on the table level. The best compromise is locks on rows or onthe record/field level. For that, a user locks one or several recordsfor editing. In theory, one could also lock individual fields, but rarelydo two users work on a single field. Also the administrativeoverload on a database would be very high if one or more locks hadto be placed on each field.For reasons of efficiency, SQLBase implements locks on a pagelevel. Collected data is administered in pages of 1024 bytes.Whatever complete pages the desired record needs will be locked,independent of how many records a page actually contains.Naturally, this can lead to “uninvolved” records also being locked.But the risk of this in everyday practice is by far smaller than onewould imagine.
Type of Locks
There are several different types of locks used. In practice, thereare two types of significance:
• Shared- or s-locks• Exclusive or x-locks
When a user reads a record (using a SELECT command) he does thisby being assigned an s-lock. Other users can do this as well, so thatseveral users can read this record simultaneously. That is, severals-locks can, by all means, exist on the same record.
Page 72
Updates or deletions of records will always be assigned an x-lock.“Exclusive” means that no other user can update or delete therecord. That is, this type of lock can only be set 1 x per record.Indeed, the update or deletion of a record by a user also preventsthe setting of any s-lock. Conversely, this applies to SQLBase aswell: If a record’s been assigned an x-lock due to updates beingmade by a user, that record cannot be read, not even in its oldform!
SQLBase always sets locks indirectly. There’s no command or add-on that exists in the scope of the standard SQL language that canexplicitly set locks (like “lock-record”). X-locks are always set whenany of the following commands are executed:• Update• Delete• Insert
Obviously this is assuming that no other locks exist on the recordsat issue. S-locks are set with this command:• Select
How exactly SQLBase handles locks can be set using one of fourisolation levels.
Transactions
Generally, every action on the database is put in execution usingtransactions. Transactions are one or more SQL statements that areeither completely executed, or not at all. This gives the Programmer thesecurity of knowing that the database will not end up in a state it’s notsupposed to be in, or for which it’s not intended. An example for this isan order: The Operator chooses articles by which the inventory islowered. That worked flawlessly with the first seven articles, but nowwith the eighth article he has to cancel the whole order, since the item’sno longer available. A transaction can be reversed while in processwithout any effects using the command “rollback”. That is, the sevenarticles up to that point are again fully available and counted asinventory.
Transactions are also important internally. Should SQLBase malfunctionin the middle of a transaction (for example, due to a defective harddrive), SQLBase makes note of that during a restart and reverses thestate of the database back to the state it was in prior to themalfunction.
Transactions are started implicitly anytime data is updated, deleted, orentered. They’re ended using the “commit” command, or as the usermay, reversed using the “rollback” command. SQLBase first logsupdates without directly altering the original value as a rollback wouldnot be possible.
Read operations also proceed in the framework of Transactions. Thesedon’t cause any changes to the database so they are “unimportant” to
Page 73
either a restart or a “commit/rollback” SQLBase does not need to logany of this activity.
When a transaction cannot be carried out, due to the desired recordbeing locked, SQLBase waits for a preset amount of time for the recordto be released (timeout).
The following applies as a rule of thumb for programming:• The shortest possible transactions, time-wise.• To always end transactions with a commit or rollback. That is,
never hold transactions “open” unnecessarily.• Define transactions. That is, to always stop the program in a
transaction-based state. That applies especially to an idle state(nothing will be shown).
• Use a short “timeout” period.• Lock only those records that are absolutely needed.
Isolation LevelsIsolation levels designate how SQLBase is to place locks during readoperations, e.g. (selects). Every read causes the creation of a resultset. Even if this set contains only one row or column. Normally a resultset consists of several rows. The cursor always specifies the currentfield or row. All reads in a program are handled by this cursor.The use of s-locks is specified and implemented using Isolation Levels.The Programmer can choose for this between 4 levels:• Read repeatability (RR)• Cursor Stability (CS)• Read Only (RO)• Release Locks (RL)
Read repeatability (RR)With this setting, the user is guaranteed that he can always readany record that has already been read. It’s impossible for anotheruser to delete or update any of these records. For that reason, everyrecord will be locked with an s-lock, for that will prevent any x-lock(via update or delete) from being set on this record. There cancertainly be more than one s-lock on this record!
This setting is not well-suited for multi-user, as there will simply betoo many locks placed which will lead to “timeouts”, since there willalways be a lot of records locked (whether needed or not).
Cursor Stability (CS)
After the Server has created the result set for the client, it willposition the cursor on the first record. With SQLBase, any recordwithin this result set can be read without limitation. It doesn’tmatter which one is read last. The cursor always positions itself onthe last read record. Precisely this record will be set with an s-lock.If the cursor wanders to another record, this one will be “taken withit”. It can certainly happen that suddenly no more records exist orthat none have been updated. Example: All customers are readwhose names begin with a “K”. There are ten in all, from which the
Page 74
first customer is shown. The program jumps one to the lastcustomer, after which one would like to view the first again. Anotheruser updated one record while the other ten were being displayed.That works flawlessly, since it’s only the current record (the oneshown here) that was protected from x-locks with an s-lock.
Read Only (RO)
With this setting only reads are possible. The advantage here is thatabsolutely no locks are set, and therefore no obstruction of otherusers is possible. Reads are always executed, even when recordsare locked with an x-lock (no timeouts). In this case, the value issimply read before the transaction. This setting is very suitable foranalysis and statistics.
Release Locks (RL)In this situation no locks are placed during read operations. S-locksare set only very shortly during the creation of result sets, and thenimmediately re-released, hence the name. This setting is specific toSQLBase, but also very well suited for multi-user programming. Itshould always be used as the Standard.
Please note that x-locks are always set independently from theisolation levels. It’s impossible with RL as well, that two usersupdate the same record at the same time.
ROW-ID
It’s possible with the RL setting programmed, that the record shown isupdated or deleted by another user (there’s no s-lock that wouldprevent this). As long as this transaction’s in effect, this record will belocked with an x-lock that will prevent the first user from updating it, oreven re-reading it, as records locked with an x-lock are not readable).What is then, if the second user has terminated the update with a“commit” and therefore the x-lock was deleted? SQLBase offers in thissituation the elegant process of a ROW-ID validation. With readoperations, not only will the actual data be read, but the ROW-ID aswell (select rowid, …from…). This will be saved on the Client, but it willnot be displayed. If you wish to do an update, the record will beretrieved using this ROW-ID (update …where rowid = local_rowid).Since SQLBase also changes this ROW-ID with every update of therecord, SQLBase can tell as if using a timestamp that the record hasbeen changed in the meantime (as the ID’s are different). SQLBasethen warns the Programmer using an error message to which theProgrammer can react appropriately. In contrast to a timestamp, it’snot necessary to re-read “the old” stamp before the update andcompare it to the local one. SQLBase does this job automatically.
SQLBase is normally programmed using the RL setting with ROW-IDValidation.
Safeguarding of the Result SetUnfortunately, the confirmation of a transaction (commit) also causesthe result set to be discarded. When there are many updates within aresult set, the result set has to be recreated and reread many times.
Page 75
For example, should one have to reassign a new Salesman to a certainPLZ area, first all the customers have to be selected. Then the update iscommitted for the first customer for whom the Salesman has changed,so that the x-lock has been removed. Thereafter, one wants to updatethe second customer. To do so, one would simply read the next recordin the program. This is no longer possible, as a commit has sincedeleted the result set, and it has to be recreated.
Result sets are not deleted [upon commits] (that is, the contentremains visible) when the “context preservation” setting is used. Thissetting is indeed a very comfortable way to program, but thetransaction recommendations are nevertheless still valid.
Exercise: Database locking and isolation levels• Open up 2 SQLTalk sessions. Session-A and Session-B
1. In Session-Aa. Connect ISLANDb. SELECT * from INVOICE
2. In Session-Ba. Connect ISLANDb. UPDATE INVOICE SET COMPANY_NAME = ‘Amazons
Apparels’ WHERE COMPANY_ID = 103
What behavior do you see?
Session-B is ‘hanging’ as it is waiting for the shared-lock to bereleased by Session-A
3. In Session-Aa. COMMIT
What behavior do you see?
Session-B now completes as the transaction has now beencommitted and the shared-lock released by Session-A
4. In Session-Ba. COMMIT
Now both Session-A and Session-B have completed theirtransactions and have committed.
5. In the SQLTALK Session-A, choose the ‘Options’ menu-item then‘Session Settings’. Change the ‘Isolation Level’ to ‘ReleaseLocks’ and hit ‘OK’
6. Repeat steps 1b and 2b and observe the behavior with the new‘Isolation Level’.
Page 76
Can you explain why Session-B was now allowed to complete theUPDATE operation?
Copyright © 2004 Gupta Technologies LLC. Gupta, the Gupta logo, andall Gupta products are licensed or registered trademarks of GuptaTechnologies, LLC., All other products are trademarks or registeredtrademarks of their respective owners. All rights reserved.
Page 77