73
Database access with EGL Rich UI

Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Embed Size (px)

Citation preview

Page 1: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Database access with EGL Rich UI

���

Page 2: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

ii Database access with EGL Rich UI

Page 3: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Contents

Access a database with EGL Rich UI . . 1Introduction . . . . . . . . . . . . . . 3Lesson 1: Plan the application . . . . . . . . 5

Sketch the interface . . . . . . . . . . . 6Assign the parts . . . . . . . . . . . . 7Add a pie chart . . . . . . . . . . . . 8Lesson checkpoint . . . . . . . . . . . 8

Lesson 2: Install and connect to MySQL . . . . . 9Install MySQL . . . . . . . . . . . . . 9Create the database . . . . . . . . . . . 9Install database driver and connect to EGL . . . 10Lesson checkpoint . . . . . . . . . . . 11

Lesson 3: Create a Record part . . . . . . . . 11Create an EGL project . . . . . . . . . . 12Edit the build descriptor . . . . . . . . . 14Create a Record . . . . . . . . . . . . 15Lesson checkpoint . . . . . . . . . . . 16

Lesson 4: Create the Service . . . . . . . . . 17Create a Service part . . . . . . . . . . 17Lesson checkpoint . . . . . . . . . . . 19

Lesson 5: Add code for the BudgetService functions 19executeSqlStatement() . . . . . . . . . . 19addExpense() . . . . . . . . . . . . . 19editExpense() . . . . . . . . . . . . . 20deleteExpense() . . . . . . . . . . . . 20getAllExpenses(). . . . . . . . . . . . 21createNewID() . . . . . . . . . . . . 21createDefaultTable() . . . . . . . . . . 22Add an import statement . . . . . . . . . 22Lesson checkpoint . . . . . . . . . . . 23

Lesson 6: Create a widget to display the Expenserecord . . . . . . . . . . . . . . . . 23

Create the ExpenseGrid widget . . . . . . . 24Lesson checkpoint . . . . . . . . . . . 26

Lesson 7: Create the DataView Rich UI Handler . . 26Create the DataView Handler . . . . . . . 27Add widgets in the Design view . . . . . . 33Lesson checkpoint . . . . . . . . . . . 34

Lesson 8: Run the budget application. . . . . . 35Run in debug mode . . . . . . . . . . 35

Lesson checkpoint . . . . . . . . . . . 36Lesson 9: Install Apache Tomcat . . . . . . . 36

Download and install the server . . . . . . 36Add Connector/J . . . . . . . . . . . 37Lesson checkpoint . . . . . . . . . . . 38

Lesson 10: Deploy and test the DataView Rich UIHandler . . . . . . . . . . . . . . . 38

Edit the deployment descriptor . . . . . . . 38Deploy the Rich UI application . . . . . . . 40Run generated code . . . . . . . . . . 41Lesson checkpoint . . . . . . . . . . . 43

Lesson 11: (Optional) Add a pie chart to the Webpage. . . . . . . . . . . . . . . . . 43

Add a pie chart . . . . . . . . . . . . 43Lesson checkpoint . . . . . . . . . . . 45

Lesson 12: (Optional) Convert BudgetService to aWeb Service . . . . . . . . . . . . . . 45

Create an Interface part . . . . . . . . . 46Change the port . . . . . . . . . . . . 47Deploy the Web service . . . . . . . . . 47Edit the DataVewHandler . . . . . . . . 48Redeploy the DataViewHandler . . . . . . 49Lesson checkpoint . . . . . . . . . . . 51

Lesson 13: (Optional) Create a separate Rich UIHandler for the description . . . . . . . . . 52

Create the Description Handler . . . . . . . 52Add DescriptionHandler to DataViewHandler . . 53Lesson checkpoint . . . . . . . . . . . 54

Summary . . . . . . . . . . . . . . . 54Finished code for BudgetRecords.egl . . . . . . 55Finished code for BudgetService.egl . . . . . . 55Finished code for ExpenseGrid.egl. . . . . . . 56Finished code for DataViewHandler.egl after Lesson7 . . . . . . . . . . . . . . . . . . 58Finished code for DataViewHandler.egl with piechart. . . . . . . . . . . . . . . . . 62Finished code for DescriptionHandler.egl . . . . 67

Index . . . . . . . . . . . . . . . 69

iii

Page 4: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

iv Database access with EGL Rich UI

Page 5: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Access a database with EGL Rich UI

In this tutorial, you create a Rich UI application that you can use to create, display,update, and delete records from an SQL database.

Learning objectives

In this tutorial, you will learn how to complete these tasks:v Plan the application and design the interfacev Install and configure the MySQL Community Edition open source databasev Create a simple MySQL databasev Install and configure the Apache Tomcat Web serverv Write a dedicated service to manage the databasev Create a Rich UI Web page that you can use to update the databasev Deploy the Web pagev (Optional) Add a pie chart to the Web pagev (Optional) Convert the dedicated service to a Web servicev (Optional) Move description to a second Rich UI handler

Time required

90 minutes

Notices

© Copyright IBM Corporation 2000, 2010.

U.S. Government Users Restricted Rights - Use, duplication or disclosure restrictedby GSA ADP Schedule Contract with IBM Corp.

Some conceptual information is reprinted by permission from IBM Rational BusinessDeveloper with EGL, Copyright © MC Press, 2008; and SOA for the BusinessDeveloper: Concepts, BPEL, and SCA, Copyright © MC Press, 2007;http://www.mc-store.com/5087.html

This information was developed for products and services offered in the U.S.A.

IBM may not offer the products, services, or features discussed in this document inother countries. Consult your local IBM representative for information on theproducts and services currently available in your area. Any reference to an IBMproduct, program, or service is not intended to state or imply that only that IBMproduct, program, or service may be used. Any functionally equivalent product,program, or service that does not infringe any IBM intellectual property right maybe used instead. However, it is the user’s responsibility to evaluate and verify theoperation of any non-IBM product, program, or service.

IBM may have patents or pending patent applications covering subject matterdescribed in this document. The furnishing of this document does not grant youany license to these patents. You can send license inquiries, in writing, to:

1

Page 6: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

IBM Director of LicensingIBM CorporationNorth Castle DriveArmonk, NY 10504-1785U.S.A.

For license inquiries regarding double-byte (DBCS) information, contact the IBMIntellectual Property Department in your country or send inquiries, in writing, to:

Intellectual Property LicensingLegal and Intellectual Property LawIBM Japan, Ltd.1623-14, Shimotsuruma, Yamato-shiKanagawa 242-8502 Japan

The following paragraph does not apply to the United Kingdom or any othercountry where such provisions are inconsistent with local law:INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THISPUBLICATION ″AS IS″ WITHOUT WARRANTY OF ANY KIND, EITHEREXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESSFOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express orimplied warranties in certain transactions, therefore, this statement may not applyto you.

This information could include technical inaccuracies or typographical errors.Changes are periodically made to the information herein; these changes will beincorporated in new editions of the publication. IBM may make improvementsand/or changes in the product(s) and/or the program(s) described in thispublication at any time without notice.

Any references in this information to non-IBM Web sites are provided forconvenience only and do not in any manner serve as an endorsement of those Websites. The materials at those Web sites are not part of the materials for this IBMproduct and use of those Web sites is at your own risk.

IBM® may use or distribute any of the information you supply in any way itbelieves appropriate without incurring any obligation to you.

Any performance data contained herein was determined in a controlledenvironment. Therefore, the results obtained in other operating environments mayvary significantly. Some measurements may have been made on development-levelsystems and there is no guarantee that these measurements will be the same ongenerally available systems. Furthermore, some measurements may have beenestimated through extrapolation. Actual results may vary. Users of this documentshould verify the applicable data for their specific environment.

Information concerning non-IBM products was obtained from the suppliers ofthose products, their published announcements or other publicly available sources.IBM has not tested those products and cannot confirm the accuracy ofperformance, compatibility or any other claims related to non-IBM products.Questions on the capabilities of non-IBM products should be addressed to thesuppliers of those products.

All statements regarding IBM’s future direction or intent are subject to change orwithdrawal without notice, and represent goals and objectives only.

2 Database access with EGL Rich UI

Page 7: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

This information contains examples of data and reports used in daily businessoperations. To illustrate them as completely as possible, the examples include thenames of individuals, companies, brands, and products. All of these names arefictitious and any similarity to the names and addresses used by an actual businessenterprise is entirely coincidental.

If you are viewing this information in softcopy, the photographs and colorillustrations may not appear.

Trademark acknowledgments

IBM, the IBM logo, and ibm.com are trademarks or registered trademarks ofInternational Business Machines Corp., registered in many jurisdictions worldwide.Other product and service names might be trademarks of IBM or other companies.A current list of IBM trademarks is available on the Web at www.ibm.com/legal/copytrade.shtml.

Java™ and all Java-based trademarks and logos are trademarks of SunMicrosystems, Inc. in the United States, other countries, or both.

Windows® is a trademark of Microsoft® Corporation in the United States, othercountries, or both.

Other tutorials for Rational® EGL Community Edition:

Format a Rich UI logon pageIn this tutorial, you will learn how to plan a simple Rich UI page and create thepage by using the EGL editor.

IntroductionIn this tutorial, you create a Rich UI application that you can use to create, display,update, and delete records from an SQL database.

Rational EGL Community Edition takes full advantage of service orientedarchitecture (SOA). This means that customers typically interact with Web pagesthat use Rich UI, while services perform the background work of communicatingwith the database.

In this tutorial, you create a service to manage a database that contains budgetinformation. Then you set up a Rich UI Web page to provide an interface to thedata, using widgets included with EGL.

The first service you create is a dedicated service. A dedicated service is availableonly within the current application. In an optional lesson, you can convert thededicated service to a Web service. Two protocols are typically used with Webservices: the Simple Object Access Protocol (SOAP) and the Representational StateTransfer (REST) protocol. To oversimplify, SOAP is highly extensible, and so allowsfor great rigor and complexity. REST is more focused on typical HTTPcommunication. This tutorial uses both protocols.

You can run the application with live data even before you deploy it to a Webproject. Deploying the application is a final step that creates the HTML and otherfiles that your customers use to run the application.

Access a database with EGL Rich UI 3

Page 8: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Learning objectives

In this tutorial, you will learn how to complete these tasks:v Plan the application and design the interfacev Install and configure the MySQL Community Edition open source databasev Create a simple MySQL databasev Install and configure the Apache Tomcat Web serverv Write a dedicated service to manage the databasev Create a Rich UI Web page that you can use to update the databasev Deploy the Web pagev (Optional) Add a pie chart to the Web pagev (Optional) Convert the dedicated service to a Web servicev (Optional) Move description to a second Rich UI handler

Time required

This tutorial takes approximately 90 minutes to finish. If you explore otherconcepts related to this tutorial, it might take longer to complete.

You can create the EGL files you need for this application in three ways:

Line by line (most helpful)Complete the individual lessons to explore the code in small, manageablechunks, explaining important keywords and concepts. This method alsorequires the longest time commitment.

Finished code filesAt the end of each lesson in which you create a file, there is a link to thecomplete code for that file, which you can copy into the EGL editor.

Project interchange fileThis archive contains the entire project, including all files and the completefolder structure. You can import this project into your workspace ratherthan creating individual files.

Skill level

Introductory

Audience

This tutorial is designed for people who know the basic concepts of programming,but have little experience with EGL. It is intended for people who work with RichUI and generate JavaScript™.

System requirements

To complete this tutorial, you must have the following tools and componentsinstalled on your computer:v Rational EGL Community Editionv A working Internet connection

4 Database access with EGL Rich UI

Page 9: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Prerequisites

You do not need any experience with EGL to complete this tutorial. The Format aRich UI logon page tutorial is a useful introduction, but is not required.

To download a project interchange file that contains the completed files for thistutorial, use the following link:

BudgetEGLProject project interchange file

The file is located in the finished_code folder in the tutorial plugin. For moreabout this file, see the ″Time Required″ section.

Expected results

You will create a Rich UI Web page that displays a record from a database table.You can use controls on the page to change, add, or delete data from the database.

Lesson 1: Plan the applicationDesign the application on paper before you begin coding.

The first step in planning an application is to list your objectives. In this tutorial,the objectives are to create an application that you can use to add, delete, ormodify records in a database. These are common business tasks, and mostcomputer users have seen tables of data on the screen where they can modifyindividual fields and add or delete entire rows.

Access a database with EGL Rich UI 5

Page 10: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Sketch the interface

The tutorial uses the scenario of a household budget application with twocolumns: Category and Amount. With a third column to display an ID number,you might create the following sketch of the screen display:

You want to edit the fields by clicking the appropriate cell in the table. To add ordelete rows, you need buttons. You might also want a button to refresh the data, incase someone changes the same database at the same time:

Because this is a practice application, you might want to have a link at the bottomof the screen to restore the default data to the database. Finally, leave room at thetop of the page for a title and a line or two of explanation:

6 Database access with EGL Rich UI

Page 11: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Assign the parts

Determine which EGL parts you need to do the job. For an EGL Rich UI interface,you typically need a combination of Services, Handlers, and widgets.

An EGL Rich UI Handler typically corresponds to a Web page. It is called aHandler because it contains code to handle events that might occur on the page.Widgets provide the content for the page: boxes, text, fields, and other screenitems. Services take care of the behind-the-scenes work.

For this tutorial, you create a Service to read from and write to the database. Tokeep things simple, you create a dedicated service, which is not visible over theWeb. It is not difficult to change a dedicated service into a Web service; a bonuslesson is included at the end of this tutorial to take you through that process.

You need a Handler to respond to changes in the UI, including making calls to theService. To show the versatility of the Handler part, a bonus lesson shows youhow to create a second Handler to provide the page title and description, andinvoke that Handler from the first one.

This tutorial uses only widgets from the EGL standard widget library and the DojoWidget library, both of which are included with the EGL package. You need thefollowing widgets to carry out the design from the sketch:

Box The container that positions the other widgets on the page

Access a database with EGL Rich UI 7

Page 12: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Grid The table that holds the information from the database

DojoButtonIndividual buttons for Add, Delete, and Refresh

Add a pie chart

To show the power of the standard widgets, add a pie chart to graph thepercentage of the total budget allotted to each category. With the pie chart, thecompleted UI looks like this:

Lesson checkpoint

In this lesson, you completed the following tasks:v Established the objectives for the applicationv Sketched the application interfacev Listed the required partsv Added a pie chart to the UI

In the next lesson, you download and install the MySQL database managementsoftware. If you already have MySQL installed, you still need the complete theparts of the lesson that create the database and connect to EGL.

8 Database access with EGL Rich UI

Page 13: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Lesson 2: Install and connect to MySQLUse the MySQL open source database manager to handle the data store for theapplication.

If MySQL is already installed on your system, skip to ″Create the database.″

Install MySQL

To install the MySQL database manager:1. Download the installable MySQL software from the following location:

http://dev.mysql.com/downloads/mysql/5.1.html#downloads

Scroll down to ″Windows downloads,″ find the row labeled ″Windows MSIInstaller (x86)″ and click the ″Download″ link.

2. Save the downloaded file on your hard disk. When the download is complete,launch the installation wizard and follow the instructions in the wizard. Duringthe installation process, you are asked for a user ID and password. You willneed this information later to connect to the database.

3. At the end of the installation process, the wizard asks if you want to installMySQL as a Windows Service (the recommended option). Leave the radiobutton selected to install MySQL as a Windows Service.

Create the database

Use the Windows Command Prompt to create an expense table in the budgetdatabase.

To create the database and table:1. Open a Windows Command Prompt (Start → All Programs → Accessories →

Command Prompt).2. Start the MySQL program as the root user:

mysql -uroot -p

Access a database with EGL Rich UI 9

Page 14: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

If you get an error message that says mysql is not recognized as a command,make sure that the MySQL bin directory is included in your PATH variable.

3. Enter the password that you created when you installed MySQL. If yourpassword is accepted, MySQL displays a welcome message.

4. Create the database for this tutorial:create database budget;

Remember to end all command lines with a semicolon. If all is well, MySQLdisplays an OK message.

5. Open the database for use:connect budget;

MySQL responds with an ID for the connection.6. Create a table in the budget database and define three columns in the table:

create table expense (id int primary key, category char(30), amount int);

7. Exit the MySQL program:quit

Your completed application will include an option to load this new table withdefault data.

Install database driver and connect to EGL

MySQL uses the Connector/J driver to connect to EGL. To install the driver:1. Start EGL with a clean workspace.2. Download Connector/J from the following Web page:

http://dev.mysql.com/downloads/connector/j/5.1.html

Scroll to the ″Generally Available (GA) Releases″ section and click the″Download″ link on the ″ZIP Archive″ row. Follow the instructions todownload the file.

3. Save the .zip file in a temporary directory or on your desktop. The .zip fileincludes the mysql-connector-java-version-bin.jar archive. This JAR archiveis the only file you need.

4. Copy mysql-connector-java-version-bin.jar to a convenient location. Thesimplest location to use is probably the EGL workspace you just created. Ifyou use the ″extract″ function of a program like WinZip to copy the file, theprogram might unpack the .jar file into a folder structure. If this happens,delete the folder structure and drag the file icon from the archive window toan explorer window that shows your destination folder. Make sure you cansee the mysql-connector-java-version-bin.jar file in its new location.

5. In the top menu of the EGL workbench, click Window and then clickPreferences → EGL → SQL Database Connections.

6. Next to the empty list of connection details, click New.7. In the Connection Profile window:

a. Under Connection Profile Types, click MySQL.b. For Name, type the following string:

MySQL Budget Connection

c. Click Next.

10 Database access with EGL Rich UI

Page 15: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

8. In the Specify a Driver and Connection Details window, find the smallplus-sign icon to the right of the Drivers field. Click this icon to create a newdriver definition.

9. In the Specify a Driver Template and Definition Name window:a. On the Name/Type page, click the MySQL JDBC Driver row with a

System Version of 5.1. EGL displays an error message that says ″Unable tolocate JAR.″ Ignore this message; you will resolve the problemmomentarily.

b. Accept the default Driver name of MySQL JDBC Driver.c. On the Jar List page, highlight the current JAR file and click Remove

JAR/Zip.d. Click Add JAR/Zip, browse to the location of the Connector/J jar file you

saved in step 4 on page 10. Click Open. The ″Unable to locate JAR″message is resolved.

e. On the Properties page, change Connection URL to the following location:jdbc:mysql://localhost:3306/budget

f. Change the Database name to the following name:budget

g. Enter the password that you created when you installed MySQL.h. Click OK.

10. In the Specify a Driver and Connection Details window, select Save password.When you work with live data, you might not want to use this option, but itsimplifies the steps for this tutorial.

11. Click Test Connection. You should see a message that says ″Ping succeeded!″Click OK to close the popup. If the test failed, get more information byclicking Details on the failure message. Make sure you have the correctinformation in all the fields of the Properties section of the Specify a Driverand Connection Details window.

12. Make sure that Connect when the wizard completes is selected and thatConnect every time the workbench is started is cleared. Click Finish.

13. In the Preferences window, click OK.

Lesson checkpoint

In this lesson, you completed the following tasks:v Installed the MySQL softwarev Created a database named budget

v Created a table within that database named expense

v Connected the database to EGL

In the next lesson, you start writing application code.

Lesson 3: Create a Record partCreate a record that corresponds to a row from your database.

In this lesson you create an EGL Record part. The part is a central concept in EGL,and the term means what it seems to: An EGL part is one separable piece of anEGL application. The Record, the Program, and the Library are examples of parts.

Access a database with EGL Rich UI 11

Page 16: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

In EGL, generatable parts are the pieces of an EGL application that can be generatedseparately. You must place each generatable part in a separate source file, and thename of the part must be the same as the name of the file. The Record is not ageneratable part, but the Service, which you will create in a later lesson, isgeneratable.

Create an EGL project

The project is the fundamental unit of organization for EGL source files. It typicallycorresponds to an application. Within a project, you can create packages if youneed greater organization. In this tutorial, you group the various kinds of parts inpackages.

To create an EGL project:1. If you are in a workbench perspective other than EGL, change to the EGL

perspective (Window → Open Perspective → [Other] → EGL). Find theperspective icon in the upper right corner of the workbench.

2. Click File → New → EGL Project, or click the New EGL Project icon on themenu bar.

3. In the New EGL Project window, enter the following information:a. In the Project name field, type the following name:

BudgetEGLProject

12 Database access with EGL Rich UI

Page 17: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

b. Click Finish.

EGL creates a project named BudgetEGLProject. There are two folders inside thedirectory:v One for EGL source codev One for the Web content that you will create

Access a database with EGL Rich UI 13

Page 18: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Edit the build descriptor

The EGL build descriptor file contains options that affect the way EGL generatesJava, JavaScript, and COBOL code from EGL source files. You need to associateyour SQL connection with the build descriptor file so that EGL can find theinformation it needs to generate properly.

To edit the build descriptor:1. Inside the BudgetEGLProject folder, expand the EGLSource folder. Double-click

the BudgetEGLProject.eglbld file. The build option editor opens.2. In the Load DB options using Connection field, click the down arrow and

select the MySQL Budget Connection that you created earlier.

14 Database access with EGL Rich UI

Page 19: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Although the sqlJNDIName is blank, you do not need to specify this value.The name is not needed for debugging, and EGL uses a default ofjdbc/databaseName in the deployed service.

3. Save and close the build descriptor file.

Create a RecordEGL uses a Record part to represent a row from an SQL table within a program.

Create a record that corresponds to the expense table in the budget database.1. In the Project Explorer Window, right-click BudgetEGLProject and then click

New → Source File, or click the New EGL Source File icon in the menu bar.

2. In the New EGL Source File window, enter the following information:a. In the EGL source file name field, enter the following name:

BudgetRecords

EGL adds the .egl file extension automatically.b. In the Package field, enter the following name:

records

c. Click Finish.

EGL creates the records directory and the BudgetRecords.egl file and thenopens the file in the EGL editor.

3. Replace the boilerplate contents of the file by copying and pasting thefollowing code:

Access a database with EGL Rich UI 15

Page 20: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

package records;

Record Expense type SQLRecordend

4. Right-click anywhere in the Record statement and click SQL record → RetrieveSQL. EGL automatically creates content for the record based on information inthe current database.

5. Inside the braces, before the keyItems property, add the following code:tableNames = [["Expense"]],

6. Add comments to indicate the purpose of the record and the meaning of thefields. The following listing shows the complete code for the record:package records;

Record Expense type SQLRecord{tableNames = [["Expense"]], keyItems=[id]}

// holds a row from the Expense table of the Budget database

// an identifier for internal useid int {column="id"};// a description of a category in the budgetcategory string {column="category", isSqlNullable=yes, maxLen=30};// an amount for that category in US dollarsamount int {column="amount", isSqlNullable=yes};end

Note:

v The SQLRecord record type enables several properties, which change thebehavior of the record part at runtime. In the code you just entered,tableNames and keyItems are both properties. Record types are at the heartof the way EGL shields you from implementation details. Because of thisrecord type, EGL knows you are doing SQL I/O when you use a variablebased on this record in an EGL get statement.

v The tableNames property assigns the expense table to the EGL record. Whenyou put a variable based on the record in an I/O statement, EGLautomatically uses the assigned table.

v The keyItems property identifies the id field in the record as the primarykey.

v The id, category, and amount fields in the record correspond to the columnsof the expense table. By default, EGL creates fields in the record with thesame names as the columns in the database.

The complete code for this file is available in “Finished code forBudgetRecords.egl” on page 55.

7. Save (Ctrl-S) and close the BudgetRecords.egl file.

Lesson checkpoint

You learned how to complete the following tasks:v Create an EGL projectv Create an EGL recordv Automate the creation of an EGL record by retrieving information from the

database

In the next lesson you will create a Service part to contain the functions you canuse to access the database.

16 Database access with EGL Rich UI

Page 21: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Lesson 4: Create the ServiceCreate the Service part you need to run a dedicated service.

A dedicated service is used only by the current application. For this reason you donot need to create an Interface part for a dedicated service.

In a later lesson you will convert this dedicated service to a Web service that otherapplications can use.

Create a Service part

To create a Service part:1. In the Project Explorer window, right-click BudgetEGLProject, then click New

→ Service.2. In the New EGL Service Part window, enter the following information:

a. In the EGL source file name field, enter the following name:BudgetService

EGL adds the .egl file extension automatically.b. In the Package field, enter the following name:

services

c. Verify that the Create as Web (SOAP) service and Create as Web (REST)service check boxes are cleared. You are creating a dedicated service, whichdoes not implement an Interface, so make sure that the ImplementsInterfaces field is empty.

Access a database with EGL Rich UI 17

Page 22: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

3. Click Finish. EGL opens the new Service part in the editor.4. Remove the boilerplate code from the file, leaving only the following lines:

package services;

service BudgetService

end

5. Save the file.Related concepts

Introduction to Service partsYou can use service parts to define a service and provide requesters with accessto the functions that are coded in that part.

18 Database access with EGL Rich UI

Page 23: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Lesson checkpoint

You learned how to create a dedicated Service that does not implement anInterface.

In the next lesson, you add code for the individual functions in the BudgetServicepart.

Lesson 5: Add code for the BudgetService functionsThe functions in the BudgetService part perform the create, read, update, anddelete (CRUD) tasks for the database.

The following exercises show the EGL code for each of the functions inBudgetService.egl, with brief explanations of how the code works. Add eachfunction, in order, before the final end statement in the file.

executeSqlStatement()

This function executes a generic SQL statement. Later, when you call this functionwith a quoted string, remember not to break the quoted string over multiple lines.

To code the function:1. In the EGL editor, copy and paste the following lines into BudgetService.egl

before the end statement:private function executeSqlStatement(sqlStatement string inOut)prepare statementID from sqlStatement;execute statementID;end

Note:

v The function is marked private so that a customer cannot accidentallydamage the database with DROP, DELETE, or UPDATE SQL statements. As aprivate function, it can only be called by other functions in the service.

v The EGL prepare statement generates an SQL PREPARE statement, and istypically used with dynamic SQL.

v The statementID variable does not have to be declared separately; theprepare statement is the declaration for the ID.

2. Save the file.Related reference

prepare considerations for SQL

execute considerations for SQLIn the context of SQL, the EGL execute statement is typically used to carry outa prepared SQL statement with dynamic elements.

addExpense()

This function adds a new, blank Expense record to the table.

To code the function:1. In the EGL editor, copy and paste the following lines into BudgetService.egl

before the end statement:

Access a database with EGL Rich UI 19

Page 24: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

function addExpense(expenseRecord Expense inOut)expenseRecord.id = createNewID();add expenseRecord;end

Note:

v The createNewID() function is part of the BudgetService service. You willadd the code for it later.

v The add statement shows the power of EGL. Because associated tableinformation is part of the Expense Record part, you do not need to specifyanything other than a record variable name (the name of a variable based onthe Record part). EGL uses the record name to find the associated table.

2. Save the file.Related reference

add considerations for SQLIn the context of the SQL query language, the add statement adds a record orset of records to a database.

editExpense()

This function replaces an existing record in the database with an edited version.The function assumes that EGL has already read the record information from thedatabase.

To code the function:1. In the EGL editor, copy and paste the following lines into BudgetService.egl

before the end statement:function editExpense(expenseRecord Expense inOut)replace expenseRecord usingKeys expenseRecord.id;end

Here is some information about the code you entered:v The EGL replace statement generates an SQL UPDATE statement.v As with the add statement, information in the record variable provides the

rest of the arguments for the SQL statement. For example, the keyItemsproperty points to the id record field to identify the record to be updated.

2. Save the file.Related reference

replace considerations for SQL

deleteExpense()

This function deletes the specified record from the table.

To code the function:1. In the EGL editor, copy and paste the following lines into BudgetService.egl

before the end statement:function deleteExpense(expenseRecord Expense inOut)delete expenseRecord usingKeys expenseRecord.id;end

Note:

20 Database access with EGL Rich UI

Page 25: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

v The EGL delete statement generates an SQL DELETE statement.v As with other EGL I/O statements, information in the record variable

provides the rest of the arguments for the SQL statement.2. Save the file.

Related reference

delete considerations for SQL

getAllExpenses()

This function reads all of the records from the table and stores them in an array.

To code the function:1. In the EGL editor, copy and paste the following lines into BudgetService.egl

before the end statement:function getAllExpenses() returns (Expense[])expenseArray Expense[];get expenseArray;return (expenseArray);end

Note:

v EGL creates an SQL SELECT statement in your generated code that is basedon your get statement and the properties of the SQL record variable in thatstatement.

v When the target of the get statement is a dynamic array of records, EGLreads the entire table into the array.

2. Save the file.Related reference

get considerations for SQLIn the context of SQL, the get statement retrieves record data from a result set.

SQL data accessEGL supports relational database access through SQL.

createNewID()

This function finds the highest numbered id value in the table and then adds 1 tothat value. The new value becomes the id for a new record (and therefore a newrow in the table).

To code the function:1. In the EGL editor, copy and paste the following lines into BudgetService.egl

before the end statement:function createNewID() returns (int)index INT?;get with #sql{SELECT MAX(id) FROM Expense} into index;

if(index == null)return(1);elsereturn(index + 1);endend

Access a database with EGL Rich UI 21

Page 26: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Note:

v The question mark after the INT type means that the new index variable isnullable, that is, it can take a null value. This is necessary so that you cancompare the variable to null.

v Use the #sql directive to customize the implicit SQL code that the getstatement generates.

2. Save and close the file.Related reference

get considerations for SQLIn the context of SQL, the get statement retrieves record data from a result set.

#sql directiveUse the #sql directive to customize implicit SQL code, or to write entirely newcode.

createDefaultTable()

This function creates a set of data that you can use to test your completedapplication.

To code the function:1. In the EGL editor, copy and paste the following lines into BudgetService.egl

before the end statement:function createDefaultTable()executeSqlStatement("DELETE FROM Expense");

addExpense(new Expense{category = "Rent", amount = 330});addExpense(new Expense{category = "Groceries", amount = 150});addExpense(new Expense{category = "Gas", amount = 80});addExpense(new Expense{category = "Utilities", amount = 110});addExpense(new Expense{category = "Entertainment", amount = 50});end

Note:

v The quoted string in the executeSqlStatement() function call must be codedon a single line.

v If you do not specify a WHERE clause for the DELETE statement, MySQLdeletes all rows from the table.

v The addExpense() statements here combine the function call with the creationof new Expense type record.

v The braces in the addExpense() statements indicate ″set-value blocks,″ whereyou can assign values to fields in a record, or to properties of the record.

2. Save the file.Related reference

Set-value blocks

Add an import statement

The Organize Imports feature automatically creates import statements to resolve asmany labels as possible. In this case, you need only one import statement, toresolve the references to the Expense record.

22 Database access with EGL Rich UI

Page 27: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

1. Right-click any blank area in the file and click Organize Imports.EGL adds the following statement:

import records.Expense;

All errors should now be resolved. If you see any red Xs, compare your codewith the finished code in “Finished code for BudgetService.egl” on page 55

2. Save and close the file.

This feature is extremely useful when dealing with more complex files, as you willsee later in this tutorial.

Lesson checkpoint

You learned how to complete the following tasks:v Execute SQL statements from inside an EGL programv Use EGL I/O statements to interact with a databasev Automatically create and organize import statements

In the next lesson, you create a Widget to hold the table of expense data.

Lesson 6: Create a widget to display the Expense recordAt the focal point of the Web page you will use to interact with the database is agrid (table) that displays rows of data.

EGL Rich UI provides an interface that you can use to interact with the service youcreated earlier. A Rich UI application is typically made up of widgets (a specialkind of Handler part) and Rich UI Handlers.

Access a database with EGL Rich UI 23

Page 28: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

A widget is a reusable element of the user interface. EGL provides a number ofwidgets, including a collection of widgets from the open source Dojo toolkit. Youcan also write new widgets, or build them from existing widgets, as you will do inthis lesson.

A Handler provides a set of functions that are triggered by specific events in theuser interface. Each Rich UI Handler file corresponds to a Web page or a part of aWeb page. You create a Rich UI Handler in the next lesson.

Create the ExpenseGrid widget

To create the widget:1. In the BudgetEGLProject folder, right-click the EGLSource folder. Click New →

Source File.2. In the New EGL Source File window, for the EGL Source File Name, enter the

following name:ExpenseGrid

3. For the Package, enter the following name:widgets

4. Click Finish. The new file opens in the EGL editor.5. Replace the comment that says ″Put EGL Source File Contents Here″ with the

following code:handler ExpenseGrid type RUIWidget {targetWidget = innerGrid,

cssFile = "css/BudgetEGLProject.css"}

end

Here is some information about the code you entered:v Create import statements later, using the ″Organize Imports″ feature.v EGL does not have a specific widget part; instead, there is a RUIWidget

type for the Handler part.v A red X indicates that the innerGrid widget is undefined. This is not a

problem; you will create the widget in the next step.6. Copy and paste the following code before the end statement:

//constants for grid sizes, to simplify adjusting the grid laterconst idWidth INT = 50;const categoryWidth INT = 150;const amountWidth INT = 100;fullWidth INT = idWidth + categoryWidth + amountWidth;

innerGrid Grid {margin = 10,headerBehaviors = [boldCells],behaviors = [GridBehaviors.tightCells,expenseSelector.enableSelection,sizeCells,appearLikeMoney],columns = [new GridColumn{name = "ID", width = idWidth },new GridColumn{name = "Category", width = categoryWidth },new GridColumn{name = "Amount", width = amountWidth }],data = []};

24 Database access with EGL Rich UI

Page 29: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Note:

v The EGL const statements define constants that you will use later to adjustthe grid.

v The innerGrid widget is a specific variant of the Grid widget that is definedin com.ibm.egl.rui.widgets.

v The innerGrid widget is now defined, but other variables are causingerrors. These other errors will be resolved as you add the rest of the code.

v The properties for innerGrid, such as margin, headerBehaviors, behaviors,and so on, are defined in the Grid widget.

7. Copy and paste the following line of code before the end statement:expenseSelector GridSelector{color = "lightblue"};

Note:

v GridSelector is a Rich UI Handler that EGL provides. You declaredexpenseSelector as a variable based on GridSelector; you can use thisvariable to call functions from the Handler.

v You specified enableSelection(), a function in the GridSelector Rich UIHandler, in the list of behaviors in the previous step.

v expenseSelector highlights the selected row of a grid; it is set to use lightblue as the highlight color.

8. Copy and paste the following private functions before the final end statement.Private functions are used for purely internal tasks within a Library, widget,Handler, or other program. They are not visible to other programs. In thiscase, you use these functions to format the cells of the grid.//behavior to set the title cellsprivate function boldCells(grid Grid in,

td Widget in,row ANY in,rowNumber INT in,column GridColumn in)

td.backgroundColor = "#EEEEEE"; //very light graytd.fontWeight = "bold";end

//behavior to resize the cellsprivate function sizeCells(grid Grid in,

cell Widget in,row ANY in,rowNumber INT in,column GridColumn in)

cell.padding = 5;cell.style = "border-spacing: 0";end

//behavior to make the Amount column have $ to look like moneyprivate function appearLikeMoney(grid Grid in,

cell Widget in,row ANY in,rowNumber INT in,column GridColumn in)

if(column.name == "Amount")html HTML = cell.children[1];html.text = "$" :: html.text;cell.style = "text-align: right";endend

9. After the private functions from the previous step, copy and paste thefollowing externally visible functions:

Access a database with EGL Rich UI 25

Page 30: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

//resets the data in the innerGridfunction setData(data Expense[])innerGrid.data = data as ANY[];end

//gets the data from the innerGridfunction getData(rowNumber INT) returns (Expense)return(innerGrid.data[rowNumber] as Expense);end

//gets all selected rowsfunction getSelectedRows() returns (Expense[])return(expenseSelector.selection as Expense[]);end

//given a cell, gets the column namefunction getColumnName(cell Widget in) returns (STRING)return(innerGrid.getColumn(cell).name);end

These functions are all straightforward:v You call setData() with an array of Expense records, and the function stores

them in the grid.v You call getData() with a row number, and the function returns the Expense

record that represents the contents of that row.v getSelectedRows() is similar to getData(), except that it returns the data in

the rows that are highlighted on the screen.v getColumnName() returns the column name for a specified cell.

10. Right-click any blank area in the file and click Organize Imports. EGL adds aseries of import statements above the handler declaration.

11. You should no longer see any red Xs. If you see any of these flags, check yourspelling. When there are no errors visible, save and close the file. You cancompare your code to the finished code in “Finished code forExpenseGrid.egl” on page 56

Related reference

as operator

Lesson checkpoint

You learned how to complete the following tasks:v Create a widgetv Use existing widgets to simplify the creation process

In the next lesson you create the Rich UI Handler that displays your new widget.

Lesson 7: Create the DataView Rich UI HandlerThis Rich UI Handler displays the widget that you created to contain the databaserecord.

Create the DataViewHandler.egl Rich UI Handler that calls the ExpenseGrid widget.You will create the program in logical sections to help you understand how eachpart of it works. Copy the sections of code from this tutorial and paste them intothe EGL editor; do not type them.

26 Database access with EGL Rich UI

Page 31: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Create the DataView Handler

DataViewHandler is the main RUI handler for the budget application. It ties useractions to service calls that access the database. Every time the user clicks a buttonor field, EGL calls dbService to complete the requested database action. Theservice returns the results, which the handler displays.

To create the Handler:1. In the BudgetEGLProject folder, right-click the EGLSource folder. Click New →

Rich UI Handler, or click the New Rich UI Handler button on the menu bar.

2. In the New Rich UI Handler part window, enter the following information:a. For EGL source file name, enter the following name:

DataViewHandler

b. For Package, enter the following name:handlers

c. Click Finish.

EGL displays the new Handler in the Design view. You can use the Designview to build a page by dragging elements from palettes onto the page.However, you will create DataViewHandler in the Source view.

3. Click the Source tab in the editor. EGL displays the stub of the Handler part.

4. Remove the existing comments. Note the initialUI property, which identifiesthe Box widget that the handler initially displays.

5. Below the handler declaration, create a variable to represent the service youcreated earlier:

Access a database with EGL Rich UI 27

Page 32: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

// variable to reference the servicedbService BudgetService{};

6. Replace the boilerplate ui declaration with the following lines:// holds the initial UIui Box{columns = 1, children = [descriptionBox, chartBox, labelBox]};

ui is the widget that was specified earlier for the initialUI property. The maincomponents of the UI include the following boxes:

descriptionBoxHolds the title and description for the page

chartBoxHolds the grid containing the database record, associated buttons, and(in a later lesson) the pie chart

labelBoxHolds error and information messages

7. Declare a variable to represent the description widget that you created in theprevious lesson and create a box to put it in:// describes the applicationprivate description STRING = "<h1>Budget file maintenance</h1>" +"<p>This is a sample database application written in EGL.</p>";descriptionBox HTML{text = description};

8. Add the following buttons to the page so that the user can interact with thedisplayed records in the grid:// buttons for interactionaddRowButton DojoButton{text = "Add", onClick ::= addRowClicked};deleteRowsButton DojoButton{text = "Delete", onClick ::= deleteRowsClicked};refreshButton DojoButton {text = "Refresh", onClick ::= refreshClicked};// box to hold the buttonsbuttonBox Box{columns = 3, paddingLeft = 10,

children = [addRowButton, deleteRowsButton, refreshButton]};

When the user clicks a button, such as addRowButton, EGL calls the associatedfunction, in this case addRowClicked(). Because these functions respond toevents, they are sometimes called event listeners. You will add these functionslater in this lesson.For an alternative way to add buttons, see ″Add widgets in the Design view.″

9. Declare a variable to represent the ExpenseGrid widget you created, and createa box to put it in:// holds the db contentsgrid ExpenseGrid{innerGrid.behaviors ::= enableEdit};gridBox Box{columns = 1, children = [buttonBox, grid, resetBox]};chartBox Box{columns = 2, children = [gridbox]}; // add pie chart here later

gridBox contains the row of buttons that you declared in the previous step,the grid that you just created based on the structure in ExpenseGrid, and thebutton you will create in the next step.

10. Create a link to load the grid with example data:// "load default" linkdefaultLink HTML{text = "<a href=#>Load Default Data</a>",

onClick ::= defaultClicked, paddingRight = 10};resetBox Box{columns = 1, alignment = com.ibm.egl.rui.widgets.BoxLib.ALIGN_RIGHT,

children = [defaultLink]};

11. Create the following areas for status and error messages:

28 Database access with EGL Rich UI

Page 33: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

// STATUS AND ERROR MESSAGESstatus STRING = "";statusLabel HTML{width = grid.fullWidth};statusController Controller{@MVC{model = status, view = statusLabel}};

error STRING = "";errorLabel HTML{color = "red", width = grid.fullWidth};errorController Controller{@MVC{model = error, view = errorLabel}};

labelBox Box{columns = 1, margin = 20, children = [statusLabel, errorLabel]};

// publish changes to the textLabel widgetsprivate function setStatus(st STRING in)status = st;statusController.publish();end

private function setError(err STRING in)error = err;errorController.publish();end

// catch-all exception handlerprivate function handleException(ae AnyException in)setError("Error calling service: " :: ae.message);end

In addition to the labelBox that holds status and error messages, you havecreated a tableBox to hold the Expense record grid and the associated buttons.The Controller part you create here communicates between the Model (in thiscase, the database) and the View (in this case the UI). For more informationabout the Model-View-Controller concept, see Rich UI validation andformatting

12. Create the functions to initialize the Expense record grid. This processincludes completing the stub start() function:// INITIALIZATIONgridEditable BOOLEAN = TRUE;

function start()setStatus("Loading current data.");call dbService.getAllExpenses() returning to refreshTableData onException initException;end

function initException(ae AnyException in)setStatus("Table is missing from database. Creating table with default data.");call dbService.createDefaultTable() returning to refresh

onException serviceLib.serviceExceptionHandler;end

function refreshTableData(expenses Expense[] in)grid.setData(expenses);setStatus("");gridEditable = TRUE;// refresh pie chart hereend

In the start() and initException functions, notice the call statement. Thisstatement loads another program or function and can optionally return to aspecified program or function. Because EGL considers a dedicated service tobe equivalent to a local program in many ways, call is the correct method ofinvoking a function from the service. The variant of the call statement usedwith services has the additional advantage of being asynchronous, so the UIdoes not freeze while waiting for the service to respond.

Access a database with EGL Rich UI 29

Page 34: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

13. Create the functions to refresh the Expense record grid:// REFRESHING// event listener for the refresh buttonfunction refreshClicked(e Event in)setError("");refresh();end

// get an array of records from the database.function refresh()setStatus("Refreshing.");call dbService.getAllExpenses() returning to refreshTableData

onException refreshTableException;end

// exception handlerfunction refreshTableException(ae AnyException in)grid.setData([] as Expense[]);setStatus("");setError("There was an error refreshing the data: " :: ae.message ::

"<br>Please try loading the default data." );gridEditable = true;end

14. Create the functions to support the default data, add, and delete buttons:// DEFAULT DATA// drop and recreate the Expense tablefunction defaultClicked(e Event in)setError("");setStatus("Restoring default data.");call dbService.createDefaultTable() returning to refresh onException handleException;end

// ADD EXPENSE// add a new recordfunction addRowClicked(e Event in)setError("");setStatus("Adding.");expense Expense{category = "New Category", amount = 0};// service determines ID for new servicecall dbService.addExpense(expense) returning to verifyAddRow onException handleException;end

function verifyAddRow(expense Expense in)refresh();end

//DELETE EXPENSEprivate deleteCount int = 0;

// delete all selected rowsfunction deleteRowsClicked(e Event in)setError("");setStatus("Deleting.");expenses Expense[] = grid.getSelectedRows();deleteCount = expenses.getSize();if ( deleteCount == 0 ) // no rows to deletesetStatus( "" );elsefor (i int from 1 to expenses.getSize())call dbService.deleteExpense(expenses[i]) returning to verifyDeleteRow

onException handleException;endendend

30 Database access with EGL Rich UI

Page 35: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

// refresh grid only when all rows are deletedfunction verifyDeleteRow(expenses Expense in)deleteCount = deleteCount - 1;if(deleteCount == 0)refresh();endend

15. Create the code to edit a row of the Expense grid:// EDIT EXPENSE// if not ID column, add editRow() as onClick listener functionprivate function enableEdit(grid Grid in, cell Widget in, row any in,

rowNumber int in, column GridColumn in)if(column.name != "ID")cell.onClick ::= editRow;cell.width = column.width;endend

// triggered when a cell in the grid is clicked.function editRow(e Event in)cell Widget = e.widget;

//add the text field to this cell only if it isn't already being editedif(cell.children[1].class == "EglRuiHTML" and gridEditable)setError("");setStatus("Editing.");gridEditable = FALSE;html HTML = cell.children[1];text string = html.text;if(StrLib.indexOf(text, "$") == 1)//drop the $ for the amount columntext = text[2:StrLib.characterLen(text)];end

//create a new text field//logicalParent is set to this cell to make changes easier when done editing//stop editing when focus is lost or when enter is pressedtextField TextField{text = text,logicalParent = cell,onFocusLost ::= stopEditRow,onKeyPress ::= editRowKeyPressed};

//adjust the ui and add the text field to the cellcase(grid.getColumnName(cell))when("Category")textField.width = grid.categoryWidth;when("Amount")textField.width = grid.amountWidth;

endcell.padding = 2;cell.children = [textField];textField.focus();endend

// on loss of focus or enter, commit the changesfunction stopEditRow(e Event in)textField TextField = e.widget;cell Widget = textField.logicalParent;

// store the original data for comparison laterrowNumber INT = cell.getAttribute("rowNumber");original Expense = grid.getData(rowNumber);updated Expense = original;

Access a database with EGL Rich UI 31

Page 36: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

commitChanges BOOLEAN = FALSE;

//figure out which cell was updatedcase(grid.getColumnName(cell))when("Category")updated.category = textField.text;commitChanges = (original.category != updated.category);when("Amount")tryupdated.amount = textField.text as INT;textField.text = "$" :: updated.amount;// don't commit if no changescommitChanges = (original.amount != updated.amount);onException(exception TypeCastException) // found non-numeric charscommitChanges = FALSE;textField.text = "$" :: original.amount; // restore original valuesetError("This field must be set to an integer value.");end

end

if(commitChanges)setStatus("Updating.");call dbService.editExpense(updated) returning to verifyEditRow onException editException;else//reset the grid formattinggridEditable = TRUE;cell.padding = 5;cell.children = [new HTML{text = textField.text}];setStatus("");endend

// enter key commits changesfunction editRowKeyPressed(e Event in)if(e.ch == 13) // ENTER keye.widget.onFocusLost.removeAll();stopEditRow(e);endend

function verifyEditRow(updated Expense in)refresh();end

function editException(ae AnyException in)setError("Error calling service: " :: ae.message);refresh();end

16. Right-click any blank area in the file and click Organize Imports. EGL adds aseries of import statements above the handler declaration.

17. If you see any red Xs, check your spelling. When no errors are visible, saveand close the file. You can compare your code to the finished code in“Finished code for DataViewHandler.egl after Lesson 7” on page 58.

Related reference

call

Rich UI validation and formattingThis topic describes how to organize logic by using the Model, View, andController (MVC) method and how Rich UI uses the concept of MVC tosupport validation and formatting.

32 Database access with EGL Rich UI

Page 37: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Add widgets in the Design view

The Design view provides a graphic interface where you can drag widgets ontoyour page. For a complete introduction to the Design view, see the Format a RichUI logon page tutorial.

Click the Design tab. To the right of the editor, EGL displays palettes of widgets.In the following figure, the Add button is selected. To create a similar button, youwould drag a Button widget from the Dojo Widgets palette.

The Properties view shows the text assigned to the Add button.

Access a database with EGL Rich UI 33

Page 38: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

The Events view shows the function that is assigned to the OnClick event for theAdd button.

For a list of available functions, click any cell in the Function column.

Lesson checkpoint

You learned how to complete the following tasks:v Create a Handler that displays the various pieces of the application you created

in previous lessonsv Bind functions to buttons in the user interfacev Use the Design view to add widgets to the page

34 Database access with EGL Rich UI

Page 39: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

The handler is now ready to test

Lesson 8: Run the budget applicationYou can now run the finished application in debug mode.

You can run a Rich UI application in two ways:v In debug mode, in the editorv Using generated code on the server

To run generated code, you must first deploy your application to a Web server.You can run a Rich UI application without a server; to prove this point, you willnot even install a server until the next lesson.

A full range of debugging tools is available when you run in Preview mode. Formore information about debugging a Rich UI application, see Debugging Rich UI.

Run in debug mode

To run the Budget application in debug mode:1. In the EGLSource/handlers folder, double-click the DataViewHandler.egl file.

When the file opens in the EGL editor, click the Preview tab. The applicationstarts. The first time it starts, it cannot locate any records, so the applicationloads default data. If you do not see any data in the grid, click Load DefaultData.

2. Use the buttons to add or delete rows from the grid and from the database.You can also change the category name or the amount by clicking theappropriate cell in the grid.

Access a database with EGL Rich UI 35

Page 40: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Lesson checkpoint

You learned how to complete the following tasks:v Run the application in debug modev Use the application to change the contents of the database

In the next lesson, you install the Apache Tomcat server so that you can deployand run the live application.

Lesson 9: Install Apache TomcatYou will use the Apache Tomcat open source Web server to display the generatedversion of your Web page.

Download and install the server

You can download and install the Tomcat Web server within the EGL workbench.If you already have the Tomcat server on your system, you still must create a copyof the server for EGL to use. To install and configure the server:1. Locate the Servers view, which is by default at the bottom right of the

workbench. Right-click the empty space and click New → Server.

2. In the Define a New Server window, expand Apache and click Tomcat v6.0Server. Accept the default values for all the other fields. Click Next.

3. In the Tomcat Server window, click Download and Install. If you already havethe Tomcat server installed, click Browse and locate the installation directoryfor the server, then go to step 4 on page 37

36 Database access with EGL Rich UI

Page 41: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Accept the terms of the license agreement that the installer displays. Browse toa directory for the application files, such as C:\Program Files\Apache. EGLdisplays the Define a New Server window again, this time with the installationdirectory filled in, while it completes the installation. Progress is shown at thebottom right of the workbench; there is no other indication that the installationis in progress.

4. When the installation is complete, click Finish.

Add Connector/J

To complete the Tomcat installation, you must make one change outside the EGLworkbench. Tomcat requires a copy of the Connector/J archive file so that it canconnect to the database. You downloaded this file in “Lesson 2: Install and connectto MySQL” on page 9.

To add Connector/J to Tomcat, copy the mysql-connector-java-version-bin.jararchive to the lib folder inside your Tomcat installation directory.

Access a database with EGL Rich UI 37

Page 42: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Lesson checkpoint

In this lesson, you completed the following tasks:v Downloaded and installed the Apache Tomcat Web serverv Configured the Web server to recognize your database

In the next lesson, you deploy the application to the Tomcat server and run itthere.

Lesson 10: Deploy and test the DataView Rich UI HandlerDuring the deployment process, EGL creates HTML files and server-specific codeto match your target environment.

Deployment is a two stage process. First you deploy the Handler to a Web project,and then you deploy the Web project to a Web server, in this case Apache Tomcat.After you deploy the application, you can run it on the server rather than in debugmode.

Edit the deployment descriptor

EGL automatically creates a deployment descriptor file for each EGLSource folder.The deployment descriptor file manages the deployment process.

To edit the deployment descriptor:1. In the EGLSource folder, double-click the BudgetEGLProject.egldd file. The EGL

deployment descriptor opens in the editor. Because you created theDataViewHandler part through the wizard, EGL automatically added it to thelist of Rich UI Handlers to deploy.

2. Because you are using a dedicated service, you do not need to set up anyService Client Bindings. The list is empty.

38 Database access with EGL Rich UI

Page 43: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

3. Next to the Target Name field, click New. EGL displays the Dynamic WebProject wizard.

4. For the Project Name, enter the following name:BudgetWeb

Any Web project is acceptable. You are creating a simple one for the purposesof the tutorial.

Access a database with EGL Rich UI 39

Page 44: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

5. Click Finish. EGL redisplays the deployment descriptor and creates the project.6. Save and close the deployment descriptor.

Deploy the Rich UI application

After you edit the deployment descriptor, the deployment process is automatic:1. In the EGLSource folder, right-click the BudgetEGLProject.egldd file.2. Click Deploy EGL Descriptor. The deployment process is automatic. At the

end of the process, the Tomcat server shows a ″Restart″ status.

40 Database access with EGL Rich UI

Page 45: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

3. Restart the server by clicking the white arrow in the green circle in the top

right of the Servers window . Alternatively, you can right-click the servername and click Restart. When the server has restarted, the status is″Synchronized.″

Run generated code1. In the BudgetWeb/WebContent folder, find the generated HTML version of the

DataViewHandler page . The name of the file is DataViewHandler-en_US.html.2. Right-click the file name and click Run As → Run on Server

EGL displays the Run On Server window.3. In the Run On Server window, select the Tomcat 6.0 Server and click Always

use this server when running this project. Click Finish.

Access a database with EGL Rich UI 41

Page 46: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

4. If you see a message saying that the server might need to be restarted, clickRestart server and select Remember my decision. Click OK.EGL displays the page. If you have not previously run the debug version of the

program, the database contains no records, so the application loads defaultdata. If you do not see any data in the grid, click Load Default Data.

42 Database access with EGL Rich UI

Page 47: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

5. Use the buttons to add or delete rows from the grid and from the database.You can also change the category name or the amount by clicking theappropriate cell in the grid.

Lesson checkpoint

You learned how to complete the following tasks:v Edit a deployment descriptor to deploy a Rich UI handlerv Run the application on the Web server

In the next lesson, which is optional, you add a pie chart to the application.

Lesson 11: (Optional) Add a pie chart to the Web pageThe pie chart widget is one of many easy additions you can make to enhance thevisual appeal of your Web page.

The DojoPieChart widget consists of an array of PieChartData Records. Thiswidget and the Record parts are automatically included in your workspace.

Add a pie chart

Create a DojoPieChart variable named expenseChart and then add a function tobuild this chart from PieChartData Records.

To add a pie chart to your Web page:1. In the EGLSource/handlers folder, double-click the DataViewHandler.egl file.

When the file opens in the EGL editor, click the Source tab.2. Find the ChartBox declaration, and add expenseChart to the list of children:

chartBox Box{columns = 2, children = [gridbox, expenseChart]};

3. Below this line, add a declaration of the expenseChart variable:

Access a database with EGL Rich UI 43

Page 48: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

// pie chartexpenseChart DojoPieChart{radius = 150, width = "350", height = "350",

labelOffset = 40, fontColor = "white"};

The properties have the following meanings:

radius The radius of the chart

width, heightThe dimensions of the container for the chart

labelOffsetThe distance that the labels are offset from the edge of the chart. Youwill assign the category names as labels for the sections later(PieChartData Records).

fontColorThe color of the font for the labels. Use one of the recognized colornames, or a six-digit numeric RGB value, preceded by a number sign,such as ″#ff0000″ for red).

4. Find the refreshTableData() function and add the following line before theend statement:buildPieChart(); // refresh pie chart

This line ensures that the pie chart is rebuilt after any changes to the grid.5. Move to the bottom of the file. Before the final end statement, add the

following function:// PIE CHARTfunction buildPieChart()tempPieData PieChartData[0];colors string[] =["#55eeaa", "#aa88cc", "#341133", "#8844aa",

"#77aa33", "#999999", "#888855", "#554444"];

for(i int from 1 to grid.innerGrid.data.getSize() by 1)if(i > 8)setError("No more than 8 chart elements are permitted.");exit for;endtempPieData.appendElement(new PieChartData{text = grid.innerGrid.data[i].category,

y = grid.innerGrid.data[i].amount, color = colors[i]});endexpenseChart.data = tempPieData;end

The function builds a local, temporary array of PieChartData records, adding anew record for each line in the grid. The y field in the record determines therelative size of the section. Because there is no easy way to automaticallygenerate colors as you go, limit the total number of sections to 8. Additionallines are displayed in the grid, but not shown in the chart. When the temporaryarray is complete, the function assigns it to the global expenseChart variable.

6. Right-click any blank area in the file and click Organize Imports. Above thehandler declaration, EGL adds the import statements for the pie chart.

7. Save the file and click the Preview tab.

44 Database access with EGL Rich UI

Page 49: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

You can compare your code to the finished code in “Finished code forDataViewHandler.egl with pie chart” on page 62

8. Try adding, deleting, and changing records. The pie chart reflects all changes tothe grid.

Lesson checkpoint

You learned how to add a pie chart widget to the Web page.

For further practice, try replacing the pie chart with a bar graph, using theDojoBarGraph widget.

Lesson 12: (Optional) Convert BudgetService to a Web ServiceCreate the Interface part and WSDL file, and then deploy the service for the Web.

DataViewHandler is the only application that can currently use the dedicatedBudgetService. If you change BudgetService into a Web application, it becomesavailable to applications anywhere in the world.

To change a dedicated service into a Web service:v Create an Interface part that lists all the functions in the Servicev Deploy the Service to a dynamic Web project, creating a Web Service Definition

Language (WSDL) file in the processv Redeploy the Rich UI Handler, providing service client binding information

Access a database with EGL Rich UI 45

Page 50: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

An Interface provides a set of prototype functions that EGL programs can use toaccess a service. You did not need to provide an Interface for the dedicated service,but you need it for a service that is available to the public.

If you had created the Interface before the Service, EGL could have used theInterface to create stub functions for all the prototypes in the Interface.

Create an Interface part

An Interface is not a generatable part. However, the best practice is to put eachInterface part in a separate file, where the name of the file matches the name of thepart, as you would with a generatable part.

After you create the Interface part, you must establish its relationship to thecorresponding Service by using the implements keyword. If you had created theInterface part first, you would have established the relationship at the time youcreated the Service.

To create an Interface for the BudgetService:1. In the Project Explorer window, right-click the BudgetEGLProject folder, then

click New → Interface.2. In the New EGL Interface Part window, enter the following information:

a. In the EGL source file name field, enter the following name:IBudgetService

EGL adds the .egl file extension automatically. The initial ″I″ character is aconvention that indicates an Interface part.

b. For the Package field, enter the following name:interfaces

c. Click Finish.

EGL creates the interfaces directory and the IBudgetService.egl file, and thenopens the file in the EGL editor.

3. Replace the example function prototype with the following code:private function executeSqlStatement(sqlStatement STRING inout);function addExpense(expenseRecord Expense inout);function editExpense(expenseRecord Expense inout);function deleteExpense(expenseRecord Expense inout);function getAllExpenses() returns(Expense[]);function createNewID() returns(INT);function createDefaultTable();

You could create this content yourself by copying the opening line of each ofthe functions in BudgetService and adding a semicolon at the end of each line.

4. Right-click any blank area in the file and click Organize Imports. EGL adds animport statement for the Expense record.

5. Save and close the IBudgetService.egl file.6. In the services package, double-click BudgetService.egl to open it in the EGL

editor.7. Change the service declaration to the following statement:

service BudgetService implements IBudgetService

8. Right-click any blank area in the file and click Organize Imports. EGL adds animport statement for IBudgetService.

46 Database access with EGL Rich UI

Page 51: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

9. Save and close the BudgetService.egl file.Related concepts

Introduction to Interface partsYou can use interface parts to access a remote service, such as a Web service.

Change the port

A port is a data structure used as an endpoint in networking. By default, Tomcatruns on port 8080. EGL uses the default port 9080 for services. To run a Webservice on Tomcat, change the default service port for the Web Services DescriptionLanguage (WSDL) file that EGL generates.

A WSDL file is used in the SOAP protocol to describe network services. For aquick overview of SOAP and REST protocols, see the “Introduction” on page 3.

To change the port:1. Click Window → Preferences → EGL → Service.2. In the WSDL Generation section, change the port number to 8080.

3. Click OK.

Deploy the Web service

You must first deploy the service as a Web service, which automatically creates aWSDL file. Later, you will redeploy the DataViewHandler, using the WSDL file.

To deploy the service as a Web service:1. In the EGLSource folder, double-click the BudgetEGLProject.egldd file. The EGL

deployment descriptor opens in the editor.2. Click the Service Deployment tab, or click Detail next to the empty Services

Deployment list.3. On the Web Service Deployment page, click Add.4. In the Add Web Services window, find the EGL service parts found section

and select services.BudgetService (BudgetEGLProject). Click Add.

Access a database with EGL Rich UI 47

Page 52: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

The BudgetService part moves to the ″to be generated″ section.5. Make sure that the SOAP Service and REST Service check boxes are both

selected, and then click Finish. For a quick overview of SOAP and RESTprotocols, see the “Introduction” on page 3.

6. Save and close the deployment descriptor.7. Right-click the BudgetEGLProject folder and click Deploy EGL Descriptor. The

deployment process is automatic. At the end of the process, the Tomcat serverhas a ″Restart″ status.

8. Restart the server. When the server has restarted, the status is ″Synchronized.″

Edit the DataVewHandler

When you create a service variable for a Web service rather than a dedicatedservice, you base the variable on the Interface part rather than the Service part.This is because you cannot assume that you have access to the code for a Webservice. The variable must also be bound to the service, using the @BindServicecomplex property. This property tells EGL to look to the deployment descriptor forinformation about the WSDL file.1. Double-click the DataViewHandler.egl file to open it in the EGL editor.2. Change the dbService declaration to the following statement:

dbService IBudgetService{@BindService};

3. Right-click any blank area in the file and click Organize Imports. EGL adds animport statement for IBudgetService.

4. Save and close the DataViewHandler.egl file.

48 Database access with EGL Rich UI

Page 53: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Redeploy the DataViewHandler

Although you just deployed the service, you must now redeploy the Rich UIapplication.

To redeploy DataViewHandler:1. In the EGLSource folder, double-click the BudgetEGLProject.egldd file. The EGL

deployment descriptor opens in the editor.2. Click the Service Client Bindings tab, or click Detail next to the empty

Services Client Bindings list.3. On the Service Client Bindings Configuration page, click Add.4. On the first Add a Service Client Binding page, leave the default SOAP Web

Binding option selected and click Next.

5. On the second Add a Service Client Binding page, provide the followinginformation:a. Select Choose wsdl file from workspace and copy it to the current project.

When this option is selected, you can browse for a WSDL file outside thecurrent project.

b. Click Browse to locate the WSDL file that EGL created when you deployedBudgetService as a Web service. The file is in BudgetWeb/WebContent/WEB-INF/wsdl and is named BudgetService.wsdl.

c. In the Interface Options section, click Use existing EGL Interface.d. Click Browse to select the EGL Interface.e. In the EGL Interface Selection window, click IBudgetService, and then click

OK.

Access a database with EGL Rich UI 49

Page 54: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

EGL redisplays the second Add a Service Client Binding page, with all thenecessary fields completed.

50 Database access with EGL Rich UI

Page 55: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

f. Click Finish. EGL redisplays the Service Client Bindings Configuration pagewith an entry for IBudgetService.

6. Save and close the EGL deployment descriptor.7. Right-click the BudgetEGLProject folder and click Deploy EGL Descriptor. The

deployment process is automatic. At the end of the process, the Tomcat serverhas a ″Restart″ status.

8. Restart the server. When the server has restarted, the status is ″Synchronized.″9. Run the application, as described in “Lesson 10: Deploy and test the DataView

Rich UI Handler” on page 38.

Lesson checkpoint

You learned how to complete the following tasks:v Create an Interface partv Change the Service to implement the Interfacev Deploy a Service to a Web projectv Change the Rich UI Handler to use a Web service rather than a dedicated

service

Access a database with EGL Rich UI 51

Page 56: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

v Redeploy the Rich UI Handler, using WSDL information provided in thedeployment descriptor

In the next lesson, you move the application description to a separate handler.

Lesson 13: (Optional) Create a separate Rich UI Handler for thedescription

Move the description information from the DataViewHandler file to a new Rich UIHandler.

You can call a widget inside a Rich UI Handler from another Rich UI Handler. Inthis lesson, you create a Handler named descriptionHandler and call it fromDataViewHandler.egl.

Create the Description Handler

DescriptionHandler is a Rich UI Handler that contains a description for the BudgetApplication.

To create the Handler:1. In the BudgetEGLProject folder, right-click the EGLSource folder. Click New →

Rich UI Handler.2. In the New Rich UI Handler part window, for EGL source file name, enter

the following name:DescriptionHandler

3. For Package, enter the following name:handlers

EGL displays the new Handler in Design mode.4. Click the Source tab in the editor. EGL displays the stub of the Handler part.

5. Remove the existing comments and delete the onConstructionFunctionproperty. That property specifies a function to be run before the page is first

52 Database access with EGL Rich UI

Page 57: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

displayed, which is not necessary here. Make sure that the set value block forthe Handler properties matches this line:{initialUI = [ ui ], cssFile="css/BudgetEGLProject.css"}

6. Immediately below the DescriptionHandler declaration, declare thedescription text:private description STRING = "<h1>Budget file maintenance</h1>" +

"<p>This is a sample database application written in EGL.</p>";

The description declaration must precede the declaration of the UI widgetthat uses it.

7. Delete the stub of the start() function.8. Change the declaration of the ui Box to display the descriptionHTML Box:

ui Box{children = [descriptionHTML]};

9. Declare the descriptionHTML widget:descriptionHTML HTML{text = description};

10. Right-click any blank area in the file and click Organize Imports. Above thehandler declaration, EGL adds an import statement for the HTML widget.

11. If you see any red Xs, check your spelling. When there are no errors visible,save the file and click the Preview tab. The header and description aredisplayed on the Web page.

You can compare your code to the finished code in “Finished code forDescriptionHandler.egl” on page 67

Add DescriptionHandler to DataViewHandler

Now that the description code is in a separate Handler, you must remove theequivalent code from the DataViewHandler and invoke the DescriptionHandlerinstead.1. Double-click DataViewHandler.egl to open it in the EGL editor.2. Immediately after the dbService variable declaration, add a blank line and the

following code:// get description from another handlerdescription DescriptionHandler {};

As before, you must use the empty braces to initialize the variable.3. In the children property of the ui Box declaration, change ″descriptionBox″ to

the following variable:description.ui

This is the ui box that is declared in the DescriptionHandler.

Access a database with EGL Rich UI 53

Page 58: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

4. Delete the block of code that begins with the comment ″describes theapplication.″ This section of the Handler now contains the following code:

Because DescriptionHandler.egl is in the same package asDataViewHandler.egl, you do not need to add an import statement for it.

5. Save and close the file.6. Redeploy the application by right-clicking the BudgetEGLProject.egldd file, and

clicking Deploy EGL Descriptor. Remember to restart the server afterdeployment.

7. Run the application, as described in “Lesson 10: Deploy and test the DataViewRich UI Handler” on page 38.

Lesson checkpoint

You learned how to complete the following tasks:v Create a Rich UI Handler to contain the title and description for your

applicationv Create a variable based on that Handler that you can use in another Handler

This lesson concludes the tutorial.

SummaryYou have completed the Use Rich UI to maintain an SQL database tutorial.

In addition to explaining the basic steps to create an SQL maintenance program,this tutorial provided opportunities to practice the following skills:v Designing your work on paper before codingv Creating a widget from other widgetsv Creating and deploying a servicev Creating a Rich UI Web page using source code

54 Database access with EGL Rich UI

Page 59: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Lessons learned

You completed the following tasks:v Plan the application and design the interfacev Install and configure the MySQL Community Edition open source databasev Create a simple MySQL databasev Install and configure the Apache Tomcat Web serverv Write a dedicated service to manage the databasev Create a Rich UI Web page that you can use to update the databasev Deploy the Web pagev (Optional) Add a pie chart to the Web pagev (Optional) Convert the dedicated service to a Web servicev (Optional) Move description to a second Rich UI handler

Additional resources

EGL Rich UI follows the Visual Formatting Model of the World Wide WebConsortium (W3C). For more information, see the W3C site at http://www.w3.org.

Finished code for BudgetRecords.eglThe following is the complete text (including tabs, comments, and blank lines) ofthe BudgetRecords.egl file after Lesson 3. If you see errors in your source file,compare your code with this version.package records;

Record Expense type SQLRecord{tableNames = [["Expense"]], keyItems=[id]}

// holds a row from the Expense table of the Budget database

// an identifier for internal useid int {column="id"};// a description of a category in the budgetcategory string {column="category", isSqlNullable=yes, maxLen=30};// an amount for that category in US dollarsamount int {column="amount", isSqlNullable=yes};end

Related tasks

“Lesson 3: Create a Record part” on page 11Create a record that corresponds to a row from your database.

Finished code for BudgetService.eglThe following is the complete text (including tabs, comments, and blank lines) ofthe BudgetService.egl file after Lesson 5. If you see errors in your source file,compare your code with this version.package services;

import records.Expense;

service BudgetService

private function executeSqlStatement(sqlStatement string inOut)prepare statementID from sqlStatement;execute statementID;

Access a database with EGL Rich UI 55

Page 60: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

end

function addExpense(expenseRecord Expense inOut)expenseRecord.id = createNewID();add expenseRecord;end

function editExpense(expenseRecord Expense inOut)replace expenseRecord usingKeys expenseRecord.id;end

function deleteExpense(expenseRecord Expense inOut)delete expenseRecord usingKeys expenseRecord.id;end

function getAllExpenses() returns (Expense[])expenseArray Expense[];get expenseArray;return (expenseArray);end

function createNewID() returns (int)index INT?;get with #sql{SELECT MAX(id) FROM Expense} into index;

if(index == null)return(1);elsereturn(index + 1);endend

function createDefaultTable()executeSqlStatement("DELETE FROM Expense");

addExpense(new Expense{category = "Rent", amount = 330});addExpense(new Expense{category = "Groceries", amount = 150});addExpense(new Expense{category = "Gas", amount = 80});addExpense(new Expense{category = "Utilities", amount = 110});addExpense(new Expense{category = "Entertainment", amount = 50});end

end

Related tasks

“Lesson 5: Add code for the BudgetService functions” on page 19The functions in the BudgetService part perform the create, read, update, anddelete (CRUD) tasks for the database.

Finished code for ExpenseGrid.eglThe following is the complete text (including tabs, comments, and blank lines) ofthe ExpenseGrid.egl file. If you see errors in your source file, compare your codewith this version.package widgets;

import com.ibm.egl.rui.widgets.Grid;import com.ibm.egl.rui.widgets.GridBehaviors;import com.ibm.egl.rui.widgets.GridColumn;import com.ibm.egl.rui.widgets.GridSelector;import com.ibm.egl.rui.widgets.HTML;import egl.ui.rui.Widget;import records.Expense;

handler ExpenseGrid type RUIWidget {targetWidget = innerGrid,

56 Database access with EGL Rich UI

Page 61: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

cssFile = "css/BudgetEGLProject.css"}

//constants for grid sizes, to simplify adjusting the grid laterconst idWidth int = 50;const categoryWidth int = 150;const amountWidth int = 100;fullWidth int = idWidth + categoryWidth + amountWidth;

innerGrid Grid {margin = 10,headerBehaviors = [boldCells],behaviors = [GridBehaviors.tightCells,expenseSelector.enableSelection,sizeCells,appearLikeMoney],columns = [new GridColumn{name = "ID", width = idWidth },new GridColumn{name = "Category", width = categoryWidth },new GridColumn{name = "Amount", width = amountWidth }

],data = []};

expenseSelector GridSelector{color = "lightblue"};

//behavior to set the title cellsprivate function boldCells(grid Grid in,

td Widget in,row ANY in,rowNumber INT in,column GridColumn in)

td.backgroundColor = "#EEEEEE"; //very light graytd.fontWeight = "bold";end

//behavior to resize the cellsprivate function sizeCells(grid Grid in,

cell Widget in,row ANY in,rowNumber INT in,column GridColumn in)

cell.padding = 5;cell.style = "border-spacing: 0";end

//behavior to make the Amount column have $ to look like moneyprivate function appearLikeMoney(grid Grid in,

cell Widget in,row ANY in,rowNumber INT in,column GridColumn in)

if(column.name == "Amount")html HTML = cell.children[1];html.text = "$" :: html.text;cell.style = "text-align: right";endend

//resets the data in the innerGridfunction setData(data Expense[])innerGrid.data = data as ANY[];end

//gets the data from the innerGridfunction getData(rowNumber INT) returns (Expense)

Access a database with EGL Rich UI 57

Page 62: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

return(innerGrid.data[rowNumber] as Expense);end

//gets all selected rowsfunction getSelectedRows() returns (Expense[])return(expenseSelector.selection as Expense[]);end

//given a cell, gets the column namefunction getColumnName(cell Widget in) returns (STRING)return(innerGrid.getColumn(cell).name);end

end

Related tasks

“Lesson 6: Create a widget to display the Expense record” on page 23At the focal point of the Web page you will use to interact with the database isa grid (table) that displays rows of data.

Finished code for DataViewHandler.egl after Lesson 7The following is the complete text (including tabs, comments, and blank lines) ofthe DataViewHandler.egl file at the end of Lesson 7. If you see errors in yoursource file, compare your code with this version.package handlers;

import com.ibm.egl.rui.mvc.Controller;import com.ibm.egl.rui.mvc.MVC;import com.ibm.egl.rui.widgets.Box;import com.ibm.egl.rui.widgets.Grid;import com.ibm.egl.rui.widgets.GridColumn;import com.ibm.egl.rui.widgets.HTML;import com.ibm.egl.rui.widgets.TextField;import egl.io.sql.Column;import egl.ui.color;import egl.ui.rui.Event;import egl.ui.rui.Widget;import dojo.widgets.DojoButton;import records.Expense;import services.BudgetService;import widgets.ExpenseGrid;

handler DataViewHandler type RUIhandler {initialUI = [ ui ],onConstructionFunction = start, cssFile="css/BudgetEGLProject.css"}

// variable to reference the servicedbService BudgetService{};

// holds the initial UIui Box{columns = 1, children = [descriptionBox, chartBox, labelBox]};

// describes the applicationprivate description STRING = "<h1>Budget file maintenance</h1>" +"<p>This is a sample database application written in EGL.</p>";descriptionBox HTML{text = description};

// buttons for interactionaddRowButton DojoButton{text = "Add", onClick ::= addRowClicked};deleteRowsButton DojoButton{text = "Delete", onClick ::= deleteRowsClicked};refreshButton DojoButton {text = "Refresh", onClick ::= refreshClicked};// box to hold the buttonsbuttonBox Box{columns = 3, children = [addRowButton, deleteRowsButton, refreshButton]};

// holds the db contentsgrid ExpenseGrid{innerGrid.behaviors ::= enableEdit};

58 Database access with EGL Rich UI

Page 63: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

gridBox Box{columns = 1, children = [buttonBox, grid, resetBox]};chartBox Box{columns = 2, children = [gridbox]}; // add pie chart here later

// "load default" linkdefaultLink HTML{text = "<a href=#>Load Default Data</a>", onClick ::= defaultClicked, paddingRight = 10};resetBox Box{columns = 1, alignment = com.ibm.egl.rui.widgets.BoxLib.ALIGN_RIGHT, children = [defaultLink]};

// STATUS AND ERROR MESSAGESstatus STRING = "";statusLabel HTML{width = grid.fullWidth};statusController Controller{@MVC{model = status, view = statusLabel}};

error STRING = "";errorLabel HTML{color = "red", width = grid.fullWidth};errorController Controller{@MVC{model = error, view = errorLabel}};

labelBox Box{columns = 1, margin = 20, children = [statusLabel, errorLabel]};

// publish changes to the textLabel widgetsprivate function setStatus(st STRING in)status = st;statusController.publish();end

private function setError(err STRING in)error = err;errorController.publish();end

// catch-all exception handlerprivate function handleException(ae AnyException in)setError("Error calling service: " :: ae.message);end

// INITIALIZATIONgridEditable BOOLEAN = TRUE;

function start()setStatus("Loading current data.");call dbService.getAllExpenses() returning to refreshTableData onException initException;end

function initException(ae AnyException in)setStatus("Table is missing from database. Creating table with default data.");call dbService.createDefaultTable() returning to refresh onException serviceLib.serviceExceptionHandler;end

function refreshTableData(expenses Expense[] in)grid.setData(expenses);setStatus("");gridEditable = TRUE;// refresh pie chart hereend

// REFRESHING// event listener for the refresh buttonfunction refreshClicked(e Event in)setError("");refresh();end

// get an array of records from the database.function refresh()setStatus("Refreshing.");call dbService.getAllExpenses() returning to refreshTableData onException refreshTableException;end

Access a database with EGL Rich UI 59

Page 64: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

// exception handlerfunction refreshTableException(ae AnyException in)grid.setData([] as Expense[]);setStatus("");setError("There was an error refreshing the data: " :: ae.message ::

"<br>Please try loading the default data." );gridEditable = true;end

// DEFAULT DATA// drop and recreate the Expense tablefunction defaultClicked(e Event in)setError("");setStatus("Restoring default data.");call dbService.createDefaultTable() returning to refresh onException handleException;end

// ADD EXPENSE// add a new recordfunction addRowClicked(e Event in)setError("");setStatus("Adding.");expense Expense{category = "New Category", amount = 0};// service determines ID for new servicecall dbService.addExpense(expense) returning to verifyAddRow onException handleException;end

function verifyAddRow(expense Expense in)refresh();end

//DELETE EXPENSEprivate deleteCount int = 0;

// delete all selected rowsfunction deleteRowsClicked(e Event in)setError("");setStatus("Deleting.");expenses Expense[] = grid.getSelectedRows();deleteCount = expenses.getSize();if ( deleteCount == 0 ) // no rows to deletesetStatus( "" );elsefor (i int from 1 to expenses.getSize())call dbService.deleteExpense(expenses[i]) returning to verifyDeleteRow onException handleException;endendend

// refresh grid only when all rows are deletedfunction verifyDeleteRow(expenses Expense in)deleteCount = deleteCount - 1;if(deleteCount == 0)refresh();endend

// EDIT EXPENSE// if not ID column, add editRow() as onClick listener functionprivate function enableEdit(grid Grid in, cell Widget in, row any in, rowNumber int in, column GridColumn in)if(column.name != "ID")cell.onClick ::= editRow;cell.width = column.width;endend

60 Database access with EGL Rich UI

Page 65: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

// triggered when a cell in the grid is clicked.function editRow(e Event in)cell Widget = e.widget;

//add the text field to this cell only if it isn't already being editedif(cell.children[1].class == "EglRuiHTML" and gridEditable)setError("");setStatus("Editing.");gridEditable = FALSE;html HTML = cell.children[1];text string = html.text;if(StrLib.indexOf(text, "$") == 1)//drop the $ for the amount columntext = text[2:StrLib.characterLen(text)];end

//create a new text field//logicalParent is set to this cell to make changes easier when done editing//stop editing when focus is lost or when enter is pressedtextField TextField{text = text,logicalParent = cell,onFocusLost ::= stopEditRow,onKeyPress ::= editRowKeyPressed};

//adjust the ui and add the text field to the cellcase(grid.getColumnName(cell))when("Category")textField.width = grid.categoryWidth;when("Amount")textField.width = grid.amountWidth;

endcell.padding = 2;cell.children = [textField];textField.focus();endend

// on loss of focus or enter, commit the changesfunction stopEditRow(e Event in)textField TextField = e.widget;cell Widget = textField.logicalParent;

// store the original data for comparison laterrowNumber INT = cell.getAttribute("rowNumber");original Expense = grid.getData(rowNumber);updated Expense = original;commitChanges BOOLEAN = FALSE;

//figure out which cell was updatedcase(grid.getColumnName(cell))when("Category")updated.category = textField.text;commitChanges = (original.category != updated.category);when("Amount")tryupdated.amount = textField.text as INT;textField.text = "$" :: updated.amount;// don't commit if no changescommitChanges = (original.amount != updated.amount);onException(exception TypeCastException) // found non-numeric charscommitChanges = FALSE;textField.text = "$" :: original.amount; // restore original valuesetError("This field must be set to an integer value.");end

end

Access a database with EGL Rich UI 61

Page 66: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

if(commitChanges)setStatus("Updating.");call dbService.editExpense(updated) returning to verifyEditRow onException editException;else//reset the grid formattinggridEditable = TRUE;cell.padding = 5;cell.children = [new HTML{text = textField.text}];setStatus("");endend

// enter key commits changesfunction editRowKeyPressed(e Event in)if(e.ch == 13) // ENTER keye.widget.onFocusLost.removeAll();stopEditRow(e);endend

function verifyEditRow(updated Expense in)refresh();end

function editException(ae AnyException in)setError("Error calling service: " :: ae.message);refresh();endend

Related tasks

“Lesson 7: Create the DataView Rich UI Handler” on page 26This Rich UI Handler displays the widget that you created to contain thedatabase record.

Finished code for DataViewHandler.egl with pie chartThe following is the complete text (including tabs, comments, and blank lines) ofthe DescriptionHandler.egl file. If you see errors in your source file, compareyour code with this version.package handlers;

import com.ibm.egl.rui.mvc.Controller;import com.ibm.egl.rui.mvc.MVC;import com.ibm.egl.rui.widgets.Box;import com.ibm.egl.rui.widgets.Grid;import com.ibm.egl.rui.widgets.GridColumn;import com.ibm.egl.rui.widgets.HTML;import com.ibm.egl.rui.widgets.TextField;import egl.ui.rui.Event;import egl.ui.rui.Widget;import dojo.widgets.DojoButton;import dojo.widgets.DojoPieChart;import dojo.widgets.PieChartData;import records.Expense;import services.BudgetService;import widgets.ExpenseGrid;

handler DataViewHandler type RUIhandler {initialUI = [ ui ], onConstructionFunction = initialization, cssFile="css/BudgetEGLProject.css"}

// variable to reference the servicedbService BudgetService{};

62 Database access with EGL Rich UI

Page 67: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

// holds the initial UIui Box{columns = 1, children = [descriptionBox, chartBox, labelBox]};

// describes the applicationprivate description STRING = "<h1>Budget file maintenance</h1>" +"<p>This is a sample database application written in EGL.</p>";descriptionBox HTML{text = description};

// buttons for interactionaddRowButton DojoButton{text = "Add", onClick ::= addRowClicked};deleteRowsButton DojoButton{text = "Delete", onClick ::= deleteRowsClicked};refreshButton DojoButton {text = "Refresh", onClick ::= refreshClicked};// box to hold the buttonsbuttonBox Box{columns = 3, paddingLeft = 10, children = [addRowButton, deleteRowsButton, refreshButton]};

// holds the db contentsgrid ExpenseGrid{innerGrid.behaviors ::= enableEdit};gridBox Box{columns = 1, children = [buttonBox, grid, resetBox]};chartBox Box{columns = 2, children = [gridbox, expenseChart]};// chartBox Box{columns = 2, children = [gridbox]}; // add pie chart here

// pie chartexpenseChart DojoPieChart{radius = 150, width = "350", height = "350", labelOffset = 40, fontColor = "white"};

// "load default" linkdefaultLink HTML{text = "<a href=#>Load Default Data</a>", onClick ::= defaultClicked, paddingRight = 10};resetBox Box{columns = 1, alignment = com.ibm.egl.rui.widgets.BoxLib.ALIGN_RIGHT, children = [defaultLink]};

// STATUS AND ERROR MESSAGESstatus STRING = "";statusLabel HTML{width = grid.fullWidth};statusController Controller{@MVC{model = status, view = statusLabel}};

error STRING = "";errorLabel HTML{color = "red", width = grid.fullWidth};errorController Controller{@MVC{model = error, view = errorLabel}};

labelBox Box{columns = 1, margin = 20, children = [errorLabel, statusLabel]};

// publish changes to the textLabel widgetsprivate function setStatus( st string in )status = st;statusController.publish();end

private function setError(err string in)error = err;errorController.publish();end

// catch-all exception handlerprivate function handleException(ae AnyException in)setError("Error calling service: " :: ae.message);end

// INITIALIZATIONgridEditable BOOLEAN = TRUE;

function initialization()setStatus("Loading current data.");call dbService.getAllExpenses() returning to refreshTableData onException initException;end

function initException(ae AnyException in)setStatus("Table is missing from database. Creating table with default data.");call dbService.createDefaultTable() returning to refreshInit onException serviceLib.serviceExceptionHandler;end

Access a database with EGL Rich UI 63

Page 68: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

function refreshTableData(expenses Expense[] in)grid.setData(expenses);setStatus("");gridEditable = TRUE;buildPieChart(); // refresh pie chartend

// REFRESHING// event listener for the refresh buttonfunction refreshClicked(e Event in)setError("");refresh();end

function refreshInit()setStatus("Please make sure the database is set up and configured.");setError("Problem reading database.");refresh();end

// get an array of records from the database.function refresh()setStatus("Refreshing.");call dbService.getAllExpenses() returning to refreshTableData onException refreshTableException;end

// exception handlerfunction refreshTableException(ae AnyException in)grid.setData([] as Expense[]);setStatus("");setError("There was an error refreshing the data: " :: ae.message ::

"<br>Please try loading the default data." );gridEditable = true;end

// DEFAULT DATA// drop and recreate the Expense tablefunction defaultClicked(e Event in)setError("");setStatus("Restoring default data.");call dbService.createDefaultTable() returning to refresh onException handleException;end

// ADD EXPENSE// add a new recordfunction addRowClicked(e Event in)setError("");setStatus("Adding.");expense Expense{category = "New Category", amount = 0};// service determines ID for new servicecall dbService.addExpense(expense) returning to verifyAddRow onException handleException;end

function verifyAddRow( expense Expense in )refresh();end

//DELETE EXPENSEprivate deleteCount int = 0;

// delete all selected rowsfunction deleteRowsClicked(e Event in)setError("");setStatus("Deleting.");

64 Database access with EGL Rich UI

Page 69: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

expenses Expense[] = grid.getSelectedRows();deleteCount = expenses.getSize();if ( deleteCount == 0 ) // no rows to deletesetStatus( "" );elsefor (i int from 1 to expenses.getSize())call dbService.deleteExpense(expenses[i]) returning to verifyDeleteRow onException handleException;endendend

// refresh grid only when all rows are deletedfunction verifyDeleteRow(expenses Expense in)deleteCount = deleteCount - 1;if(deleteCount == 0)refresh();endend

// EDIT EXPENSE// if not ID column, add editRow() as onClick listener functionprivate function enableEdit(grid Grid in, cell Widget in, row any in, rowNumber int in, column GridColumn in)if(column.name != "ID")cell.onClick ::= editRow;cell.width = column.width;endend

// triggered when a cell in the grid is clicked.function editRow(e Event in)cell Widget = e.widget;

//add the text field to this cell only if it isn't already being editedif(cell.children[1].class == "EglRuiHTML" and gridEditable)setError("");setStatus("Editing.");gridEditable = FALSE;html HTML = cell.children[1];text string = html.text;if(StrLib.indexOf(text, "$") == 1)//drop the $ for the amount columntext = text[2:StrLib.characterLen(text)];end

//create a new text field//logicalParent is set to this cell to make changes easier when done editing//stop editing when focus is lost or when enter is pressedtextField TextField{text = text,logicalParent = cell,onFocusLost ::= stopEditRow,onKeyPress ::= editRowKeyPressed};

//adjust the ui and add the text field to the cellcase(grid.getColumnName(cell))when("Category")textField.width = grid.categoryWidth;when("Amount")textField.width = grid.amountWidth;

endcell.padding = 2;cell.children = [textField];textField.focus();endend

// on loss of focus or enter, commit the changes

Access a database with EGL Rich UI 65

Page 70: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

function stopEditRow(e Event in)textField TextField = e.widget;cell Widget = textField.logicalParent;

// store the original data for comparison laterrowNumber INT = cell.getAttribute("rowNumber");original Expense = grid.getData(rowNumber);updated Expense = original;commitChanges BOOLEAN = FALSE;

//figure out which cell was updatedcase(grid.getColumnName(cell))when("Category")updated.category = textField.text;commitChanges = (original.category != updated.category);when("Amount")tryupdated.amount = textField.text as INT;textField.text = "$" :: updated.amount;// don't commit if no changescommitChanges = (original.amount != updated.amount);onException(exception TypeCastException) // found non-numeric charscommitChanges = FALSE;textField.text = "$" :: original.amount; // restore original valuesetError("This field must be set to an integer value.");end

end

if(commitChanges)setStatus("Updating.");call dbService.editExpense(updated) returning to verifyEditRow onException editException;else//reset the grid formattinggridEditable = TRUE;cell.padding = 5;cell.children = [new HTML{text = textField.text}];setStatus("");endend

// enter key commits changesfunction editRowKeyPressed(e Event in)if(e.ch == 13) // ENTER keye.widget.onFocusLost.removeAll();stopEditRow(e);endend

function verifyEditRow(updated Expense in)refresh();end

function editException(ae AnyException in)setError("Error calling service: " :: ae.message);refresh();end

// PIE CHARTfunction buildPieChart()tempPieData PieChartData[0];

colors string[] =["#55eeaa", "#aa88cc", "#341133", "#8844aa", "#77aa33", "#999999", "#888855", "#554444"];

for(i int from 1 to grid.innerGrid.data.getSize() by 1)if(i > 8)setError("No more than 8 chart elements are permitted.");exit for;end

66 Database access with EGL Rich UI

Page 71: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

tempPieData.appendElement(new PieChartData{text = grid.innerGrid.data[i].category, y = grid.innerGrid.data[i].amount, color = colors[i]});end

expenseChart.data = tempPieData;end

end

Related tasks

“Lesson 11: (Optional) Add a pie chart to the Web page” on page 43The pie chart widget is one of many easy additions you can make to enhancethe visual appeal of your Web page.

Finished code for DescriptionHandler.eglThe following is the complete text (including tabs, comments, and blank lines) ofthe DescriptionHandler.egl file. If you see errors in your source file, compareyour code with this version.package handlers;

import com.ibm.egl.rui.widgets.Box;import com.ibm.egl.rui.widgets.HTML;

handler DescriptionHandler type RUIhandler {initialUI = [ ui ], cssFile="css/BudgetEGLProject.css"}

private description STRING = "<h1>Budget file maintenance</h1>" +"<p>This is a sample database application written in EGL.</p>";

ui Box{children = [descriptionHTML]};descriptionHTML HTML{text = description};

end

Related tasks

“Lesson 13: (Optional) Create a separate Rich UI Handler for the description”on page 52Move the description information from the DataViewHandler file to a new RichUI Handler.

Access a database with EGL Rich UI 67

Page 72: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

68 Database access with EGL Rich UI

Page 73: Database access with EGL Rich UI - IBM · Access a database with EGL Rich UI In this tutorial, you create a Rich UI application that you can use to create, display, update, and delete

Index

Aadd statement 19Apache Tomcat Web server

installing 36

BBudgetService.egl

source code 55build descriptor file

editing 14

Cconnecting

to database 10Connector/J driver

and Tomcat 37downloading 10

CRUD tasksfor SQL database 19

Ddatabase connection

creating 10DataViewHandler.egl

source code 58dbService

EGL service variable 27debug mode

running in 35delete statement 20deploying

applications 49services 47

deployment descriptor, EGLediting 38

descriptionHandlerRich UI Handler 52

Design viewoverview 33

Dojo Widget libraryoverview 7

DojoPieChartadding 43

EexpenseGrid widget

overview 23

ExpenseGrid.eglsource code 56, 62, 67

Ggeneratable part

overview 11generated code

running 41get statement 21

HHandler, EGL Rich UI

definition 7

Iimport statement

automatic generation 22Interface part, EGL

creating 46overview 45using 49

MModel-View-Controller

overview 27MySQL database

connecting 10creating 9installing 9

Oorganize imports

EGL feature 22

Ppackage, EGL

creating 12part, EGL

overview 11pie chart widget

adding 43port

changing for Tomcat 47prepare statement 19Preview mode

using 35

Project Interchange Fileoverview 4

project, EGLcreating 12

properties, EGLoverview 15

RRecord part, EGL

creating 15overview 11

replace statement 20REST protocol

definition 3Retrieve SQL

EGL feature 15Rich UI Handler

definition 7deploying 38

running the applicationdebug mode 35from generated code 41

SService part

creating 17sketch

UI 6SOAP protocol

definition 3SQL record

retrieving 15

TtableNames

EGL property 15Tomcat Web server

installing 36tutorials

Format logon page 5

Wwidgets

overview 7WSDL file

overview 47

69