November 2004
Transcription
November 2004
Team Developer – Quick Start Guide to Building Business 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-in Table............................................................................ 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 when used to write business applications. Team Developer is an extremely powerful and wholly integrated visual development environment available both on the Windows and Linux platforms. It boasts an easy and intuitive learning curve with compelling features allowing applications to be coded approximately 40% faster than other tools in the marketplace. In addition, the code written is truly cross-platform, with only the need to recompile on different environments. No code changes are necessary. Industry leading features and benefits are pointed out before tunneling down to the basic components of the visual development environment and taking the reader through many exercises to solidify the understanding. Sample answers to exercises are also available. Executive Summary Enjoy true Rapid Application Development (RAD) of business applications on Windows and Linux Desktops with Team Developer. Experience rich and easy-to-use user interfaces while having the benefit of faster development of nearly 50-100 percent faster than if done in Java and other visual development tools. Cross platform development and deployment ensures the investment you are making can be leveraged in the Linux as well as the Windows market - greatly enhancing your return on investment and profitability. The source code of your application can be written on either platform then simply re-compiled on the other platform to create the same application Time and money saving RAD software development Rapid Application Development means smart software development. Team Developer speeds up software development and enables you to win projects as you can deliver faster and with less cost than your competition using Microsoft tools or Java. Quickly react to new customer requirements You have all experienced a similar situation - you are presenting your software to a prospect who is very interested, however, there is this one workflow that needs to be different in the software to better support the customer’s organization. How fast you can deliver the change determines whether you win the deal or not. With Team Developer you can deliver changes faster than your competition. Protects code investments through backward compatibility GUPTA works hard so you can move from one technology platform to the other without constantly rewriting existing code. This enables your Page 7 organization to concentrate on improving your solution - not on keeping pace with changes in underlying technologies. Java forces approximately 20% code rewrite when moving from one version to the other. Microsoft® tools require an even higher rewrite percentage for existing code. For example, about 40% of existing code has to be rewritten when moving from Visual Basic 6 to Visual Basic.Net. For Longhorn release, independent software magazines predict a rewrite rate of 100%. Easy Protyping During the initial phase of a project, your customer might not be clear about all their project requirements. Creating prototypes with a few mouse-clicks ensures the workflow; requirements and expectations are defined at a very early stage in the project. The risk in delivering something that does not meet expectations is greatly reduced. Quick coding Team Developer’s outline editor is well known as the best possible code representation and new employees will understand existing code quickly. Keep the project cost low and provide your organization the opportunity to increase your profit margin. Page 8 Projects and solutions continue to grow over the years and developers on a project keep changing. The well-structured outline format of Team Developer source code is very simple to read and understand. The graphical outline editor increases productivity of new developers quickly due to its intelligence in allowing only appropriate objects/segments in specified places. This coupled with an Active Coding Assistant (ACA) reduces errors and increases developer productivity. Renowned database connectivity and development database included Team Developer supports fast and effective database connectivity to GUPTA SQLBase and many other industry databases. This database connectivity is now available to Oracle and ODBC in Team Developer for Linux. Oracle databases can be accessed natively, and all other databases can be accessed using the Linux ODBC interface. For example, ODBC can be used to access MySQL and other databases that offer Linux ODBC connectivity. Team Developer includes a Developers version of the fast and powerful SQLBase database. With SQLBase included, it is easy to develop complex multi-user applications using a non-network connected laptop and still have full industry strength database features and support. Complete source-code management including a class browser Manage multiple developers’ working on the same source code with Page 9 complete check-in and check-out facilities. Have a true picture of the object hierarchy with the class browser Includes comprehensive reporting tool ReportBuilder Ad-hoc and application reporting are the strengths of ReportBuilder. End-Users can define new queries with just a few mouse clicks. The graphical query designer gives users an overview of existing tables and views and allows them to create joins using drag and drop technology. After the query has been designed, the report design module offers all the 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 the user to assign changing trays for the pages of the report. Developers can include reporting into their business solutions. All the advanced user features are also available and can be programmed from within a Team Developer application. Your business applications can include complex reporting such as printing of invoices or complex multi-pass reports for management information systems An example report showing conditional formatting Page 10 Full and comprehensive debugging facilities Team Developer supports major Desktop Linux distributions GUPTA is partnering with Novell/SUSE and Red Hat to create best of Page 11 breed Linux products that integrate well into world leading Linux platforms. • 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 build and 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 detect this and allow you to use the existing binaries. Linux distributions supported are noted in the Executive summary. Team Developer components Overview of Team Developer Team Developer consists of various components that are divided up into the following broad areas: Development Environment, Software Distribution, Team Support and Development Server. SQLWindows SQLWindows is the name of the 32-bit Programming environment for Team Developer. It’s in this environment and language where programmers design and develop in a 4GL Object Orientated environment. The CDK (GUPTA Developers Extension Kit) is also integrated into SQLWindows. It serves to expand the GUPTA Team Developer environment (e.g. the creation of assistants and utilities within the development environment). Page 12 SQLTalk SQLTalk is the SQL Shell used for direct queries and Administrative tasks involving a connected database. It allows both Data Definition Language (DDL) and Data Manipulation Language (DML) commands. Deploy Team Developer Deployment contains the Runtime Environment for programs developed with SQLWindows. It contains all the files that are needed for the distribution of written applications. A deploy executable is copied to the user environment and run to install the runtime on a specific machine. Due to licensing restrictions, the SQLWindows Development Environment itself cannot be circulated. TOM Team Object Manager (TOM) is the component used for team-oriented project development. The project-related files (SQLWindows, Source code, Documentation, etc.) can be stored in a Repository. Full sourcecode management features are available for development teams working on the same applications. The repository database can be user-specified e.g. SQLBase, Oracle etc. SQLBase GUPTA’s SQLBase database is included with Team Developer. It is provided to allow development of client applications in a context where either there’s no SQL Database Server available, or the development is simply not intended for a Production Server. The GUPTA Client/Server-System Team Developer is a development environment for the creation of Client Software in a Client-Server Environment and for Web development using Web extension classes. The Server side of the system is either a SQL Database Server or an ODBC/OLEDB compliant data source. Typically, in a network, there will be several clients connected to a Server. All client applications access a common interface, which in turn accesses a network interface. These interfaces are implemented in the form of DLL’s (Dynamic Link Libraries) on Windows and Shared Objects on Linux. The SQL/API Application Programming Interface is responsible for database communication. The named dll for this function is SQLWNTM.DLL on Windows and the Shared Object sqlwntm.dll.so on Linux. Page 13 SQLWindows Graphical User Interface The graphic surface of the development environment contains all the components that are needed for developing SQLWindows applications. The construction of the development environment is contained within a Multi-Document Interface (MDI). This allows for several views of the Application in various Windows within the environment. Each view is divided up in two sections similar to MS Windows Explorer: On the left side the components of the view are shown in the form of a tree structure. (Tree View) on the right are shown the details of the components 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 SQLWindows Left 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 changing standard categories. The Outline Editor Page 15 • Each component (e.g. Function, Class, Window, Childwindow) or subcomponent (e.g. variables, constants) have associated Outline code • Structural layout • Enhances Programming • Improves Clarity • Visual block building through Indentation • 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 each view. The structure of the source text is predetermined and aids the developer. The Outline is intelligent in that it will not allow incorrect code 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 a variable declaration or class definition then it will be disallowed. The Active Coding Assistant (ACA) helps reduce errors further by only presenting choices that are specific to the appropriate part of the Outline as well as detailing required parameters and function information. Programming blocks are defined by indentations within the Outline therefore eliminating the need for brackets or the typical “Begin…End” The standard elements of the Outline, accessible via the tabs at the bottom window border, are tailored towards the context of the components chosen within the left panel. The Active Coding Assistant only showing allowable calls in the Outline 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. Page 17 • 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. 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 a window component is highlighted in the left panel Controls Tool Bar • • • • • • • Page 18 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) The Controls Tool Bar makes available all Child Windows and their respective classes. One can then use their mouse to drop and position a chosen Object onto the surface of a Parent window. Coding Assistant An additional coding assistant (from earlier versions) can be turned on aid 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 • • Page 19 Setting of Object Attributes (Properties) Docking (Can be prevented by using the CTRL key) Database Explorer • • • • • Page 20 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 Programming Basics in SAL Overview Scalable Application Language (SAL) is the language used for Programming 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 LONG VARCHAR database columns. They can be of arbitrary length and content (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 decimal places (for use with both Real and Integer datatypes) Date/Time - Date/Time entry. The ISO description must be used when assigning date/time within programming text File Handle - Is needed for File operations Sql Handle - Identifies a database connection. Every communication with a database requires that one provide a SQL Handle, which is delivered via SqlConnect( ) Windows Handle - Serves to identify Windows objects. Must be specified using functions that involve editing Windows. Objects - The GUPTA Window Objects provided by SQLWindows greatly facilitates the programming of the user interface (Windows, Dialog boxes, Buttons, etc). The collection of Objects consists of the basic Objects 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 • • Page 23 Has to be closed before the rest of the application can be accessed again. Can be used to start/initiate other applications 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 located within 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 Background Text Pushbutton Example Description Exit pushbutton Datafield Multiline Field “This is a test with a wrapping Multiline Textfield.” List Box Scroll Bar Group Box Radio Button Check Box Options-Button Combo Box Table Table columns Picture Frame Line Page 25 Group File format Produce report Object Attributes For every Object there are certain Attributes, also known as “Properties”. A distinction is made between those Attributes that are set at Design Time, and those that are set at the Program Functions Runtime. The Attribute Inspector assists in setting Attributes at the Development stage. Attributes that are set at the Development phase deal mainly with the following: • 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 programmed that tracks the company’s employees and their hire dates. Page 26 • Create a Form Window and place the Objects onto the Form Window with the help of the Tools Window. • Go through the various properties of the Object and assign the default properties. • Look at the window in Preview Mode (Ctrl-L) • Choose a sensible TAB order and functioning Accelerators (Alt key) • Save the Program • Compile, start (F7) and test your application. • Your running application should look something like below: Constants Constants come in the following types: • String • Number • Boolean • Date/Time Page 21 Page 27 Example of Defining a Constant: ♦ Application Description: SQLWindows Standard Application Template ♦ Libraries ♦ Global Decl a rations ♦ Window Defa u lts ♦ Formats ◊ External Fu nctions ♦ 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 Variables Declarations and length of existence A Variable can be of any of the aforementioned datatypes. can be declared in various places within the source code. They Global ♦ Global Decl a rations ♦ Window Defa u lts ♦ Formats ♦ External Fu n ctions ♦ Constants ♦ Resources ♦ Variables ♦ String: sUs e rName • Global declarations exist during the program’s entire runtime. In Functions ♦ Function: f U serFunction ♦ Description : ♦ Returns ♦ Parameters ♦ Static Vari a bles ♦ Number: nCo u nter ♦ Local Varia b les ♦ String: sUs e rName ♦ 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 m eters ♦ Window Vari a bles ◊ String: sUs erName ♦ Message Act i ons • Page 28 Windows Variables exist only as long as the window in which they reside. Existence does not mean necessarily that they are visible. In Classes ♦ Pushbutton C lass: cpbGreen ♦ Description : Grüner Button ♦ Derived Fro m ♦ Class Varia b les ◊ Number: nCo unt ♦ Instance Va r iables ◊ String: sWi ndowText ♦ Functions ♦ Message Act i ons • • Class Variables exist only as long as there’s an Instance of a Class available. Instance Variables exist only as long as the Instance itself. Visibility Variables have a certain period of validity (Scoping Rules). One also speaks of a Variables visibility. Global Variables Global Variables are visible within the entire program Windows and Functions 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 a bles ◊ String: sNa me ♦ Dialog Box: dlgDialog ♦ .... ♦ Message Act i ons ♦ On SAM_Crea t e ◊ 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: sNa me Page 29 dlgDialog ♦ Window Vari a bles ♦ String: sNa m e ♦ Message Act i ons ♦ On SAM_Crea t e ◊ Set sName = "EC" A naming conflict between names at the same level will result in a translation error. ♦ Form Window : frm1 ♦ Window Vari a bles ♦ String: sNa m e ♦ Dialog Box: dlg1 ♦ .... ♦ Window Vari a bles ♦ Message Act i ons ♦ On SAM_Crea t e ♦ Set sName = "EC" ♦ Form Window : frm2 ◊ .... ◊ ◊ Window Vari ables ♦ String: sNa m e 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 T est ◊ Description : ◊ Returns ◊ Parameters ◊ Static Vari ables ♦ Local Varia b les ♦ String: sTe s t ♦ Actions ◊ Set sTest = "Hello" Referencing External Referencing An external reference is a reference to a Variable, an object, or a function that is defined in a given parent window but is also referenced 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 that one use a fully-qualified reference anytime one is going to access a value or function outside of its own parent window. Qualified Reference The object will prefix the name of the surrounding Parent Window. Syntax: Template.ObjectName ◊ Set frm1.sN ame = "Hello" Page 30 Goal: The Object can then also be referenced, even though an Object of the same name exists in another window. Window Semi-Qualified Reference The 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 without having to use a specific window name (i.e. for use with an array of Windows Handles). ◊ Window Hand le: hWndArray[*] ◊ ... ◊ Set hWndArr ay[1].sName = "Hello" Fully Qualified Reference The object will prefix the name of the surrounding Parent Window, as well as the Window Handle. Syntax: WindowHandle.Template.ObjectName ◊ hWnd1 = Sal CreateWindow ( frm1, hWndOwner ) ◊ hWnd2 = Sal CreateWindow ( frm1, hWndOwner ) ◊ ... ◊ Set hWnd1.f rm1.sName = "Hello" ◊ Set hWnd2.f rm1.sName = "Hello" Goal: The Object can also be referenced; even though several Instances 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 String Properties: • 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: ◊ ◊ ◊ ◊ ◊ ◊ Page 31 Number: Number: Number: Number: String: String: nPosition[10] nPosition[0:9] nPosition[*] nPosition[1:*] strAngestellte[10,3] strAngestellte[*,3] ◊ ◊ 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 Variables All Dialog Elements / Objects have in addition to their visual characteristics, 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 Page 32 Class default Background Text Line Class default Class default Frame Class default Group Box Class default Dialog Elements can also be used as Variables in assignment statements. ◊ Set dfName = "GUPTA Education Center" ◊ Set sbScrol l = 10 Naming Conventions Hungarian Notation: Small letters precede Variables to denote their type. The expanded name consists of a word chain that begins with capitol 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 Scroll Bar Col.. Sb.. colColumnvalue sbBrowse 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 With Variables Page 33 With Constants • Messages, SQL Statements • Similar to Hungarian Notation With respect to System Variables, there’s a division of Constants into groups through the use of a prefix in Capitals followed by an underscore. Type of Constant Prefix Example: SQLWindows Application Messages Table Window Constants SAM_.. SAM_Click 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 = T RUE ◊ Set nCount = 1000 ◊ Set sSelect = "SELECT " || sFields || " FROM " || sFrom Page 34 Page 31 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 combination move 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 SalQui t() 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 Page 35 If <expression> Else If <expression> Else Example: ♦ If i = 0 ◊ ! further S tatements ◊ Set nCount = i ♦ Else If i = 1 ◊ ! further S tatements ◊ Set nCount = -1 ♦ Else ◊ ! further S tatements ◊ 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 sIdenti fier = Company Administration ◊ Break ♦ Case 2 ◊ Set sIdenti fier = Partner ◊ Break ♦ Default ◊ Set sIdenti fier = 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 u nt > 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_Clic k 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 sNam e ◊ 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 SQLErr or ◊ Call SalMes sageBox( SQL Error, Beware, MB_Ok) Page 37 Functions Internal Functions Internal Functions - Internal functions are defined and coded within Team Developer. Function Template in the Outline When a function’s added, a function body is created that has to be filled out. ♦ Function:Fu n ction: <Name of a function> ◊ Description : ◊ Returns ◊ Parameters ◊ Local Varia bles ◊ Actions Global Functions • Can always be addressable and valid • Should only be used for global tasks. ♦ Application ♦ ... ♦ Global Decl a rations ♦ ... ♦ Internal Fu n ctions ♦ Function: f A dd ◊ Description : ◊ Add 2 Digi ts ♦ Returns ◊ Number: ♦ Parameters ◊ Number: pnD igit1 ◊ Number: pnD igit2 ◊ Static Vari ables ♦ Local Varia b les ◊ Number: nEv ent ♦ Actions ◊ Set nEvent = pnDigit1 + pnDigit2 ◊ Return nEve nt 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 A dd ◊ Description : ◊ Add 2 Digi ts ♦ Returns ◊ Number: ♦ Parameters ◊ Number: pnD igit1 ◊ Number pnDi git2 ◊ Static Vari ables ♦ Local Varia b les ◊ Number: nEv ent ♦ Actions ◊ Set nEvent = pnDigit1 + pnDigit2 ◊ Return nEve nt 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 n ctions ♦ Library nam e : sqlwntm.dll ♦ Function: s q ldbn ♦ Description : ♦ Export Ordi n al: 0 ♦ Returns ◊ Number: SHO RT ♦ Parameters ◊ String: LPC STR ◊ String: LPC STR ◊ Receive Num ber: 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 definition of a function does not mean that it has to be processed by the program. 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: nDi git1 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 Num ber nDigit1 Page 40 Exercise: Coding in the Outline Task: Modify the starter program in Exercise 6.6 to add an internal function that 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 a sensible level of detail. (Double-click on ) • Use the SQLWindows function SalClearField() • You should insert a popup menu called “file” in your window, with the menu choice “new” so that you can test the function. Definition of the function: ♦ Global Decl a rations ♦ ..... ♦ Internal Fu n ctions ♦ Function fC l earForm ♦ Description : ♦ Returns ♦ Parameters ♦ Static Vari a bles ♦ Local Varia b les ♦ Action Calling of the function ♦ Form Window : frmCompanyInfo ♦ Description ♦ Named Menus ♦ Menu ♦ Popup Menu: &File ♦ Enabled whe n : ♦ Status Text : ♦ Menu Item: & N ew ♦ Status Text ♦ Keyboard Ac c elerator: (none) ♦ Menu Settin g s ♦ Menu Action s Page 41 ◊ Call fClear Form() ♦ Menu Separa t or ♦ .... Working with Windows Objects Next to the database connections, the user interface is the most important thing in a Windows program. The interface is most frequently implemented using windows. Therefore, it’s really important to know the windows properties, and the relationships between the various windows objects. All Parent Windows and Dialog Elements are treated as Windows by MS Windows. 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 Parent Window as its superior in the hierarchy. The dialog element itself is then designated as a Child Window in this relationship. Window Text Every window has window text, the display of which is dependent on the type of window. Window Handle Every window within Windows has a unique number or ID, which is known 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 Window Handle. Visibility of Windows Windows can be visible or invisible. It’s possible to either hide or show a window at the runtime of an application. Active/Inactive Windows can be active or inactive. An inactive window does not react to the actions of the user. We can query through SAL what the state of a Window is. Position Windows have a position on the monitor/display. This can be set in absolute relation to the monitor/display or relative to the Parent Window. Message Receipt Every window receives messages. Every message effects, as with a function call, the execution of a block of programming code. In SQLWindows these program blocks are formed in SAL. The cause for sending messages is events occurring. Exercise: Coding the Outline – global functions The internal global function • fClearForm(...) should now be implemented for every class. Therefore, don’t use the name of the individual window, but rather locate with the help of functions. • SalGetFirstChild( • SalGetNextChild( ) The designated Data field, and delete the respective field from within the loop. One can use the SQLWindows constant hWndNULL for the end of the loop. Consider which of the Parameters are actually needed and make sense in terms of the global implementation of this function. ♦ Internal Fu n ctions ♦ Function: f C learForm ♦ Description : ♦ Returns ♦ Parameters ◊ ??? Page 43 ♦ Static Vari a bles ♦ Local Varia b les ♦ 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 is generated that is sent to the program. The program waits passively for messages from Windows. No code is executed (e.g. Loops) If it encounters a message, it reacts to it. The handling occurs independently 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 rather the objects of the program. (Events: Click on a button, Enter data into a text field, etc. The messages generated by these events are sent directly to the objects. To program with SQLWindows = to react to the desired message 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 Messages Next to OS messages that are triggered by user events, there are also SQLWindows messages that are triggered by the runtime environment itself. These messages correspond to the application and its objects. Some Messages: Page 45 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. 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 Variables Just as with parameters for functions, there are four variables that exist for 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 are included 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 the picture y-coordinate of the mouse click within the picture Lparam 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 its name 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() • • • Page 47 Enters the message into the application’s message queue. The call ends immediately and the program processes the next assignment. Asynchronous, Cooperative Anweiswungen ⌦ Message queue Processing Use: Always in situations when the event’s not immediately needed for the 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 for the 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 messaging Replace the internal function fClearForm() in exercise 6.14.2 with Events 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? Debugging An important element of any Programming environment is tools that serve to diagnose programming code for mistakes as well as expected application flow control. The search for errors within a program is known as “Debugging” GUPTA SQLWindows provides the following described 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 at runtime. It can also be checked whether or not Variable assignments are 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 49 48 The ordering of the Variables shown is done using the pushbutton in the upper right corner of the window. It’s here that one comes to the Form Window for selecting the Variables to be analyzed. Fig 9 Selection Window for Variables In the window shown in Fig 9 one can select among the available Variables; their referencing corresponds to their respective context. From the selections made here one can also modify the value of the Variables. 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 implemented relative to Messages and their context. With nested function calls, the calling hierarchy will be shown. The hierarchy shown in Fig 10 looks like the following in code: 1 Form Window: frmMain ... 1.1 Functions 1.1.1 Function: fSave Page 50 ... 1.1.1.1 Actions 1.1.1.1.1 Call fSaveStandards( ) ... 1.1.2 Function: fSaveStandards ... 1.1.2.1 Actions 1.1.2.1.1 Call ... Position ... ! Actual 1.2 Message Actions 1.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 basic concepts of Windows Programming, it’s also necessary to have a tool for monitoring all occurring events. All the events that occur during the running of the program are shown in Fig 11 as messages with their assigned Variables (Window Handle, wParam, lParam). The view is restricted to the GUPTA SQLWindows-defined SAM messages. 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 any expressions, function calls, and assignments during the running of the program. Next to that is the executed line of the evaluated expression appearing as a Combo Box, in the Window lying beneath that appears not only the type of the event, but the event itself. Note: Using this tool it is possible to interfere with running of the program. For example, should any manually executed changes to the contents of Variables occur, this changed content is then available to the program. The environment that is applicable to the tool, is always the context of the actual position within the program The viewing of the tool for evaluation of expressions is accessed via the menu: Tools / Expressions or Alt+8 in the IDE or via the toolbar symbol (Toolbar “Debug”) Expressions Breakpoints The tool mentioned in the previous Chapter may only be used in the framework of a controlled, running program. Manual control of the running of the program is obtained by using what is known as Breakpoints. Breakpoints are specific markings in programming code. They interrupt the running program and can be set within the Development environment to take place before the start and during the execution of a 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 will occur (towards the next breakpoint or end of the program). Page 52 Administration of Breakpoints A Breakpoint can be set at a marked line in the source code via the menu: 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 same procedure. Besides setting and removing individual breakpoints, the following options 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 Flow Several 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 by choosing the following symbol in the Debug Toolbar: Break • Single step execution (detailed) executes the next statement and then returns the control to the Debug Toolbar. Should the statement involve a function, the function will be activated and then one 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, or via the symbol Step Into • Single step execution contains the current statement of a program; should this be indeed executed. In contrast to the detailed singlestep execution, the individual statements within the function will not be 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 executed via this tool, the explicit assignment of Variables can be made here as 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 test for possible corrections. Should this process lead to the desired results, it naturally has to be expressed in the adjusted code. Animation Should the execution of the program continue after a breakpoint is reached, it’s normally not possible to view the continued running of the program. But the GUPTA SQLWindows Development Environment offers altogether three options for viewing the running of a program. • • Page 54 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 a predefined duration. This interval is set using the menu option Tools / Preferences. Fig 14 The “Preferences” Window • Fast Animation (Menu: Debug / Fast Animate), Fast Program Flow (Speed cannot be changed) Database connections in Team Developer Database Access Cycle SQLWindows provides a set of commands that allow for connecting to SQL 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 a successful database connection is that the corresponding system variables were initialized with valid values. (SqlDatabase, SqlUser, SqlPassword) Page 55 • SqlPrepare translates a SQL statement at the server and connects it with the Handle. • SqlExecute executes the SQL statement bound to the SQL Handle and creates a result set for SELECT statements. • SqlFetchNext reads the individual datasets of the result set created by SqlExecute. (Only with “SELECT” statements) • SqlDisconnect terminates a database connection. Fig 15. The Database Access Cycle The Binding of SQL SQLWindows offers the option to use Variables in SQL statements. This occurs via Into and Bind Variables. Variables are integrated in a SQL statement 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 the database. 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 respective actual result set of every FETCH statement Exercise: Database access and retrieving information The form window labeled Company Information now has to be filled with data. Page 56 Functionality Search: 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 into the 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 the result 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 in the SQLWindows Online Help. SQL Error Handling The handling of errors relating to database statements can take place in 3 areas: As a basic principle, a runtime system error is intercepted with standard error handling. However, it can also be intercepted at the global 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 SQLError will register and error in SQLConnect( ) but not in SQLPrepare( ). Error handling at the statement level. The ‘When SqlError’ statement at the statement level handles errors. This has to be placed directly before the statement that’s to be executed and on the same programming level. Example: ♦ Pushbutton: pbEnter ♦ Message Act i ons ♦ On SAM_Clic k ♦ When SqlErr o r ♦ Set nSqlErr o r = SqlError(hSql) ♦ Call SqlGet E rrorText(nSqlError, strErrorText) ♦ Call SqlGet E rrorPosition(hSqlError, nErrorPos) ♦ Call SalNum b erToStr(nSqlError, 0, strSqlError) ♦ Call SalMes s ageBox(strSqlError || '-' || strErrorText, 'Message-Box', MB_Ok) ♦ Return FALS E ◊ Call SqlPre pare(hSql, sINSERT) ♦ If SqlExecu t e(hSql) ♦ Call SqlCom m it(hSql) ♦ Call SalSen d Msg(pbSearch, SAM_Click, 0, 0) Error Handling at the Global Program Level This is error handling that’s executed generally, for the entire program. It takes place at the “Applications Actions” level. Here the response will be a special message SAM_SqlError. The system variables wParam and Iparam give information about the error. Example: ♦ Application Actions ♦ On SAM_SqlE r ror ♦ Call SqlExt r actArgs(wParam, lParam, hSql, nSqlError, nSqlErrorPos) ♦ Call SqlGet E rrorText(nSqlError, strErrorText) ♦ Call SalNum b erToStr(nSqlError, 0, strSqlError) ◊ Call SalMes sageBox(strSqlError || '-' || strErrorText, 'Message-Box', MB_Ok) ♦ Return FALS E SQLWindows Standard Error Handling Whether an error to a SQL Function is intercepted at the statement level or at the global program level, the standard SQLWindows error handling 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 a controlled manner. Should a user encounter a standard error message and have to make a decision on exiting or continuing the program, an uncontrolled event may still exist. SQL Error Handling Flow Chart Exercise: Error handling Expand 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 connection to 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 database name. Notice the difference in error message for the ‘Search and ‘Insert’ buttons. Table Objects Table Objects were created in SQLWindows to display data in a table format. There are table objects in the form of Parent Windows and Child Windows. 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 • • Page 60 The table is located only in the Parent Window. The table will not be automatically resized at Runtime. 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 Properties A table, like any Object, has certain properties. Many properties are designated during Development time (Visible, Position…) but can only be adjusted during Runtime with the aid of SAL functions. Runtime-adjustable Properties Constants TBL_Flag_ SizeableCols Standard Installation TRUE Installation Description MoveableCols TRUE Interchanging columns SelectableCols FALSE Column Selection HscrollByCols TRUE Horizontal column browsing ShowVScroll FALSE Vertical roll bar. GrayedHeaders TRUE Appearance of the Column and Changing the column width 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" • • Page 62 The context row will automatically be set to the focus row anytime a user changes the focus row. The context row is not, however, always the same as the focus row. Marking Row Flags Table rows can be seen with the following markings: Flag Row in Table is ROW_Selected ROW_MarkDeleted ROW_Edited ROW_New selected by the user. marked for later deletion changed newly entered ROW_Hidden not visible. There can also be several flags set for a single row. For example, a new row that was edited: ROW_New und ROW_Edited Search for rows with certain markings: • SalTblFindNextRow( ) • SalTblFindPrevRow( ) The Table Window Cache Table 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 the content can be the same. Page 63 How the Table Window Cache Functions • • • Every row of the result set is read only once, provided the cache 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 transfer data 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 SalTbl Reset (Tbl1) ◊ Call SalTbl SetRange (Tbl1,0,nRows-1) Use of the SAM_FetchRow Message ♦ On SAM_Fetc h Row ◊ Call SqlFet chRow (hSql,...,lParam) ◊ With this message one will be instructed to fill the row “Iparam” with values. 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 the record 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-th record 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() SalTblDoInserts() SalTblDoUpdates() SalTblDoDeletes() Page 65 Fills the Table Window with a SELECT query’s result set. "SELECT * FROM..." is possible! (Can use for a table that has no predefined columns) Searches through the Table Window for new records and then inserts them with a SQL INSERT statement into the database. Searches for altered records and then transfers them via SQL UPDATE into the database. Searches for records marked for deleting and then also deletes them via SQL DELETE from the database. 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 Builder Report Windows is needed for the formatted output of data to a printer. It developed itself from a tool used for creating reports to a complete query tool with the possibility of defining database queries. Here the functionality for simple template definition is explored. Page 67 Properties and Options • • • • • • If the • • Use of all Fonts (?, Formats) Use of Graphics (Lines, Rectangles…) Data Grouping (Breakgroups) Calculation of Groups Automatic Page Break Preview Option 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 • • • Page 68 Start Report Builder Import a Standard Template Menu Edit / Import Template Open the file NEWREP.QRP • 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 hWndRptTemp strTemplate strVariables strInputs nErr The window that receives the message SAM_FetchRow Normally, the window that calls SalReport. Window for the Report. The Report creates it’s own window using hWndNULL Name of the Report (filename) List (String) of the SQLWindows variables, separated by comma. List (String) the input items, separated by comma. Return of the error number The variable must be set to 1 before the call. Additional parameters of SalReportPrint: NCopies NOptions NFirstPage NLastPage Reading values from the database Page 69 The number of copies to be printed. Output options: Print everything, partial print, fast print (draft) With partial printing: 1st page With partial printing: last page 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_ReportStart To translate the required SQL SELECT statement: Use SqlPrepare() in the designated Message Action Section of the window. 3. SAM_ReportFetchInit To execute the SQL statement: Use SqlExecute() in the designated Message Action Section of the window. 4. SAM_ReportFetchNext In the designated Message Action of the window, fill the SQLWindows variables with values using SqlFetchNext() Report Builder will use the names of the SQLWindows variables to receive 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 are many more features that make this tool very powerful and flexible. You should investigate its full potential. Page 71 Multi-user Programming Introduction In a Client/Server environment there are several users communicating with the server. The server has to process each request with as little as possible side effects on the other requests. To that end the server uses locks that are partially automatic or set intentionally and can be removed 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. That surely 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 to locks on the table level. The best compromise is locks on rows or on the record/field level. For that, a user locks one or several records for editing. In theory, one could also lock individual fields, but rarely do two users work on a single field. Also the administrative overload on a database would be very high if one or more locks had to be placed on each field. For reasons of efficiency, SQLBase implements locks on a page level. 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 one would imagine. Type of Locks There are several different types of locks used. In practice, there are two types of significance: • • Shared- or s-locks Exclusive or x-locks When a user reads a record (using a SELECT command) he does this by being assigned an s-lock. Other users can do this as well, so that several users can read this record simultaneously. That is, several s-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 the record. 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 prevents the setting of any s-lock. Conversely, this applies to SQLBase as well: If a record’s been assigned an x-lock due to updates being made by a user, that record cannot be read, not even in its old form! SQLBase always sets locks indirectly. There’s no command or addon that exists in the scope of the standard SQL language that can explicitly set locks (like “lock-record”). X-locks are always set when any of the following commands are executed: • Update • Delete • Insert Obviously this is assuming that no other locks exist on the records at issue. S-locks are set with this command: • Select How exactly SQLBase handles locks can be set using one of four isolation levels. Transactions Generally, every action on the database is put in execution using transactions. Transactions are one or more SQL statements that are either completely executed, or not at all. This gives the Programmer the security of knowing that the database will not end up in a state it’s not supposed to be in, or for which it’s not intended. An example for this is an order: The Operator chooses articles by which the inventory is lowered. That worked flawlessly with the first seven articles, but now with the eighth article he has to cancel the whole order, since the item’s no longer available. A transaction can be reversed while in process without any effects using the command “rollback”. That is, the seven articles up to that point are again fully available and counted as inventory. Transactions are also important internally. Should SQLBase malfunction in the middle of a transaction (for example, due to a defective hard drive), SQLBase makes note of that during a restart and reverses the state of the database back to the state it was in prior to the malfunction. Transactions are started implicitly anytime data is updated, deleted, or entered. They’re ended using the “commit” command, or as the user may, reversed using the “rollback” command. SQLBase first logs updates without directly altering the original value as a rollback would not be possible. Read operations also proceed in the framework of Transactions. These don’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 log any of this activity. When a transaction cannot be carried out, due to the desired record being locked, SQLBase waits for a preset amount of time for the record to 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 Levels Isolation levels designate how SQLBase is to place locks during read operations, e.g. (selects). Every read causes the creation of a result set. Even if this set contains only one row or column. Normally a result set consists of several rows. The cursor always specifies the current field 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 read any record that has already been read. It’s impossible for another user to delete or update any of these records. For that reason, every record 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 can certainly be more than one s-lock on this record! This setting is not well-suited for multi-user, as there will simply be too many locks placed which will lead to “timeouts”, since there will always 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 will position the cursor on the first record. With SQLBase, any record within this result set can be read without limitation. It doesn’t matter which one is read last. The cursor always positions itself on the 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 with it”. It can certainly happen that suddenly no more records exist or that none have been updated. Example: All customers are read whose 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 last customer, after which one would like to view the first again. Another user updated one record while the other ten were being displayed. That works flawlessly, since it’s only the current record (the one shown 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 that absolutely no locks are set, and therefore no obstruction of other users is possible. Reads are always executed, even when records are locked with an x-lock (no timeouts). In this case, the value is simply read before the transaction. This setting is very suitable for analysis and statistics. Release Locks (RL) In this situation no locks are placed during read operations. S-locks are set only very shortly during the creation of result sets, and then immediately re-released, hence the name. This setting is specific to SQLBase, but also very well suited for multi-user programming. It should always be used as the Standard. Please note that x-locks are always set independently from the isolation levels. It’s impossible with RL as well, that two users update the same record at the same time. ROW-ID It’s possible with the RL setting programmed, that the record shown is updated or deleted by another user (there’s no s-lock that would prevent this). As long as this transaction’s in effect, this record will be locked with an x-lock that will prevent the first user from updating it, or even 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 this situation the elegant process of a ROW-ID validation. With read operations, not only will the actual data be read, but the ROW-ID as well (select rowid, …from…). This will be saved on the Client, but it will not be displayed. If you wish to do an update, the record will be retrieved using this ROW-ID (update …where rowid = local_rowid). Since SQLBase also changes this ROW-ID with every update of the record, SQLBase can tell as if using a timestamp that the record has been changed in the meantime (as the ID’s are different). SQLBase then warns the Programmer using an error message to which the Programmer can react appropriately. In contrast to a timestamp, it’s not necessary to re-read “the old” stamp before the update and compare it to the local one. SQLBase does this job automatically. SQLBase is normally programmed using the RL setting with ROW-ID Validation. Safeguarding of the Result Set Unfortunately, the confirmation of a transaction (commit) also causes the result set to be discarded. When there are many updates within a result 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 certain PLZ area, first all the customers have to be selected. Then the update is committed for the first customer for whom the Salesman has changed, so that the x-lock has been removed. Thereafter, one wants to update the second customer. To do so, one would simply read the next record in the program. This is no longer possible, as a commit has since deleted the result set, and it has to be recreated. Result sets are not deleted [upon commits] (that is, the content remains visible) when the “context preservation” setting is used. This setting is indeed a very comfortable way to program, but the transaction recommendations are nevertheless still valid. Exercise: Database locking and isolation levels • Open up 2 SQLTalk sessions. Session-A and Session-B 1. In Session-A a. Connect ISLAND b. SELECT * from INVOICE 2. In Session-B a. Connect ISLAND b. 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 be released by Session-A 3. In Session-A a. COMMIT What behavior do you see? Session-B now completes as the transaction has now been committed and the shared-lock released by Session-A 4. In Session-B a. COMMIT Now both Session-A and Session-B have completed their transactions and have committed. 5. In the SQLTALK Session-A, choose the ‘Options’ menu-item then ‘Session Settings’. Change the ‘Isolation Level’ to ‘Release Locks’ 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 the UPDATE operation? Copyright © 2004 Gupta Technologies LLC. Gupta, the Gupta logo, and all Gupta products are licensed or registered trademarks of Gupta Technologies, LLC., All other products are trademarks or registered trademarks of their respective owners. All rights reserved. Page 77