Sei sulla pagina 1di 39

Practical exercises

GeneXus 15
GeneXus 15 Course: Practical exercises

Copyright  GeneXus S.A. 1988-2017.

All rights reserved. This document may not be reproduced without the express consent of GeneXus S.A. The information contained
in this document is for personal use only.

Registered Trade Marks

GeneXus is a registered trade mark of GeneXus S.A. All other trademarks referred to in this document are the property of their
respective owners.

Page 1
GeneXus 15 Course: Practical exercises

1. THE PROBLEM ..................................................................................................................................................................... 3

2. NEW PROJECT, NEW KNOWLEDGE BASE ............................................................................................................................. 3

3. INITIAL TRANSACTIONS ....................................................................................................................................................... 3

“CUSTOMER” TRANSACTION ...................................................................................................................................................................... 4


“ATTRACTION” AND “COUNTRY” TRANSACTIONS, RELATED ....................................................................................................................... 6
Related data: How to maintain integrity ......................................................................................................................................... 8
‘CATEGORY’ TRANSACTION ................................................................................................................................................................. 8
ADDING THE CITIES TO THE ‘COUNTRY’ TRANSACTION ..................................................................................................................... 10
“ATTRACTION” TRANSACTION: ADDING THE CITY. ........................................................................................................................... 12

4. ADDING BEHAVIOR TO TRANSACTIONS (RULES)................................................................................................................ 12

5. PATTERNS: IMPROVING THE INTERFACE TO WORK WITH THE INFORMATION .................................................................. 13

6. “FLIGHT” AND “AIRPORT” TRANSACTIONS AND THE NEED TO DEFINE SUBTYPES ............................................................. 16

7. FORMULAS ........................................................................................................................................................................ 17

8. PDF LISTINGS ..................................................................................................................................................................... 18

9. PASSING PARAMETERS ...................................................................................................................................................... 22

LIST OF ATTRACTIONS IN A GIVEN RANGE ......................................................................................................................................... 22

10. BUSINESS COMPONENTS ................................................................................................................................................... 23

INCREASE OF FLIGHT TICKET PRICES .................................................................................................................................................. 23


SCREEN FOR DELETING ALL FLIGHTS .................................................................................................................................................. 25

11. PROCEDURES FOR UPDATING RECORDS ............................................................................................................................ 26

INCREASE OF FLIGHT TICKET PRICES .................................................................................................................................................. 26


DELETION OF ALL FLIGHTS ................................................................................................................................................................. 27
INITIALIZATION OF INFORMATION IN THE DATABASE [OPTIONAL] ....................................................................................................... 29

12. WEB PANELS...................................................................................................................................................................... 30

13. EXTENDED CONTROLS ....................................................................................................................................................... 31

14. QUERY OBJECT .................................................................................................................................................................. 31

15. WEB SERVICES ................................................................................................................................................................... 32

16. A PART IS REQUIRED FOR SMART DEVICES ........................................................................................................................ 32

17. GENEXUS SERVER .............................................................................................................................................................. 33

18. DEFINITION OF A BUSINESS PROCESS MODEL (BPM) FOR BOOKING AN ATTRACTION [OPTIONAL] ................................. 35

19. TESTING THE APPLICATION WITH GXTEST [OPTIONAL] ..................................................................................................... 37

Page 2
GeneXus 15 Course: Practical exercises

1. The problem
A travel agency hires you to develop a system for storing and handling the information used by the agency in its
business activity. Image that the system includes two modules:

 Backend: part of the application that will be run on a web server so that the agency’s employees are able to
handle the information from any location connected to the internet.

 Simple application for mobile devices: part of the application that will be used for downloading by the
customers of the travel agency, where they will be able to query trips available and the main tourist
attractions available in each city

2. New Project, New Knowledge Base


Access GeneXus and create a knowledge base under the name “TravelAgency” in order to start developing the
application.

Suggestion:

 Select C# as the development environment. Make sure to install everything you will need (including SQL
Server). If you use GeneXus Trial, the generation environment is already predefined with prototyping in the
Amazon cloud.

 Do not create the knowledge base in the “My Documents” folder or in any other folder under “Documents
and Settings” because these folders have special permits granted by Windows.

Take a few minutes to become familiar with the IDE (the Integrated Development Environment of GeneXus).
Try to move windows, view any specific windows you may prefer (View and View/Other Tool Windows) and
pay attention to ‘Folder View’ in the ‘Knowledge Base Navigator’ window, where you will see domains, some
objects, images, and other elements already initialized.

Suggestion: keep the properties window open (F4), for you will be using it constantly. Inside the ‘Knowledge Base
Navigator’ window note the ‘Preferences’ section, where the ‘Environment’ is set up.

3. Initial transactions
At meetings with the travel agency, they inform you the following:

“Our work consists or recording our customers’ data and offering them travels to various cities in different
countries, for which we also record their tourist attractions”.

To build the application we must start by identifying the actors from reality, and then represent them by means of
transactions. What transactions should we then create in the knowledge base (KB)?

Page 3
GeneXus 15 Course: Practical exercises

“Customer” Transaction

We asked the employees of the travel agency the following: what is it that you record about your customers?

If the answer is:

Their name (with not more than 20 characters), surname (also with up to 20 characters), address,
telephone and e-mail address.

You may already create the “Customer” Transaction.

Keep in mind that:

 There are several alternatives to create objects:  If you type dot (“.”) when entering a new attribute,
o From the “Start Page”. it will be initialized with the name of the
o From the menu: File/ New Object transaction.
o Ctrl+N
o We have an icon  Address, Phone and Email are semantic
domains assigned automatically to the attributes
 You will need an attribute to identify each customer que defined containing, respectively in their name,
(CustomerId). the Address, Phone or Email texts.

The structure of the transaction should be as shown:

The next step is to test the application in runtime. Make sure that you have the GeneXus Output window enabled
and visible. (View/Other Tool Windows /Output)
Now test the application in runtime by pressing F5.
What will happen?

SOLUTION

If you decide to create the database and programs locally (this is only possible with full GeneXus), a window
like the one below will open up for you to enter information on the Database, the Server and the connection
method. Remember that if there is no database with the name indicated in that server, then GeneXus will
create it.

Page 4
GeneXus 15 Course: Practical exercises

However, if the database and programs are to be created in the cloud, then the above dialog will not appear
because GeneXus knows the server data in the cloud and will automatically set up the name of the database and all
the connection information for it.
Below is an Impact Analysis with details as to the creation of the database that will take place and the CUSTOMER
table in it:

By pressing the Create button, GeneXus will proceed to execute the program that will carry out these
creations. At the end of the process, the menu with links to execute the objects defined will open up in the
browser set up as the one predetermined. In this case, it will be just one: the Customer transaction.
Enter some customers in the system. Modify some data relative to any of the customers entered previously
and delete any of such customers.

Page 5
GeneXus 15 Course: Practical exercises

You may also use the arrows available to move from one customer record to the next, and between icons,
the image of a magnifying glass provides a “selection list” to view the list of registered customers for
selecting one).

Now let’s identify and create the following transaction. Remember the statement:
“We record all data on our customers, and offer them trips to different cities in various countries, for which
we also record their tourist attractions”.

“ATTRACTION” and “COUNTRY” Transactions, Related

Let’s now create a transaction to record the Tourist attractions and one to record the countries to which they belong.
What data does the travel agency have in relation to each attraction?
Name, country, image of the attraction, category to which it belongs.

The transactions may now be created. Let’s start by “Country”.

Remember that:
 by pressing dot (“.”), when we are about to give a name to an attribute in the structure of the transaction, it
will appear initialized with the name of the transaction.
 An identifier attribute, CountryId, will be required.

When we define the data type of the identifier attribute, instead of using directly Numeric(4.0), we define the ID
domain with that data type.
Set up the Autonumber property of that domain as True, so that all the attributes based on it will be numbered
automatically, without the need for the user to be concerned about that.

Note all the domains already predefined in GeneXus. Specifically, Address, Email and Phone, which appeared
automatically upon creating the CustomerAddress, CustomerEMail and CustomerPhone attributes in the “Customer”
Transaction.

Define the CountryName attribute, with data type, a new domain: Name=Character(50).

Now we create the “ATTRACTION” TRANSACTION. For the time being, we enter only identifier, name and country.

Page 6
GeneXus 15 Course: Practical exercises

Note that when we enter AttractionId, it automatically assumes the ID domain. Likewise, when we enter the
AttractionName attribute it will automatically assume the Name domain.

Why was the CountryName attribute included in “Attraction”, in addition to CountryId?

Execute to test (F5) and the following Impact analysis report will appear:

CountryName?

Page 7
GeneXus 15 Course: Practical exercises

Why does the Attraction table, which GeneXus informs that must be created in the database, not include the
CountryName attribute? In other words, why will the physical table not contain it, if it is part of the structure of the
transaction?

After studying the report, if we agree with it, we press Reorganize in order for what is informed to actually take
place. The navigator will open up with the menu including links to the 3 programs that correspond to each of the
transactions (“Customer”, “Country”, and “Attraction”).
For the countries, enter: Brazil, France, and China. Note that, by leaving a 0 for the identifier value, upon saving,
the number immediately following the last one assigned will be automatically assigned (in fact, it is being
autonumbered).
For tourist attraction, enter: “Louvre Museum”, which is located in France. If you do not remember the system
identifier for France, how should the country be entered then? There is an icon with an arrow next to CountryId, to
open a country “Selection List”, created automatically by GeneXus. This is because CountryId has the role of foreign
key in this transaction, in other words: it is “pointing” to another table.

Related data: How to maintain integrity

“Attraction” and “Country” are related. When we make CountryId part of the structure of Attraction, since it has the exact same
name as the attribute that is primary key in the Country transaction, then GeneXus will understand that, in “Attraction”, CountryId
is foreign key, and it will automatically maintain the integrity of the information. So, by way of example:

 Try to enter an attraction with country ID that is non-existent. Does it allow you to save the tourist attraction?
 Choose a previously entered attraction (such as the Louvre Museum) and change the country, replacing it with one that
does not exist. Were you able to save the change?
 Try to delete a country (using the Country transaction) that has an associated attraction (such as France). Are you
allowed to do it?

Conclusion: the programs corresponding to the transactions ensure data integrity.

‘CATEGORY’ TRANSACTION

We still have to complete the information relative to the “Attraction” transaction. The travel agency employees
described that they record, for each tourist attraction, its category (monument, museum, park, etc.) So, we will
need to create a transaction to record that information, and add the category to the “Attraction” transaction.

But they have also said that recording the category of a given Attraction that is handled is not exactly mandatory. It
may be left empty. If we know that GeneXus automatically controls integrity, how do we do this?

Page 8
GeneXus 15 Course: Practical exercises

Solution:

To conclude the definition of the “Attraction” transaction, add the data still missing: the photograph.
This is done by creating the AttractionPhoto attribute, of the Image data type.
When we request GeneXus to build the application, so it may be tested in runtime. (F5)

Note the contents of the Impact Analysis. The Category table must be created and the existing Attraction table must
be converted, adding three information elements (one for the CategoryId attribute and two for the AttractionPhoto
attribute. We should not be concerned about why the storage of two values per image are required).

Page 9
GeneXus 15 Course: Practical exercises

Reorganize and execute.


Enter categories (as museum and monument) and access the Tourist attractions already entered to complete their
data (category and photo).
Note that, in this case, you may leave the category empty (because the Nullable property was set up as Yes in the
structure of the transaction).
However, if we try to use a value that is non-existent as the CategoryId value for the tourist attraction, it will not be
saved.

ADDING THE CITIES TO THE ‘COUNTRY’ TRANSACTION

In addition to the countries with which the travel agency works, we need to record the data regarding cities.
Therefore, we must add a second level to the “Country” transaction, with the city name and identifier.

Page 10
GeneXus 15 Course: Practical exercises

Remember that:
 Positioned on the CountryName attribute and right clicking / Insert Level the sublevel will be added.
 Once the new level has received a name, by typing quotation marks (“) instead of a dot, the attribute
defined will be initialized with the name of the level
 The cities will be identified with their own ID, in combination with that of the country. This means that it will
not be possible to identify a city without providing the information of the country involved in advance. This
will enable the possibility of having a city 1 Rosario for both Uruguay and Argentina:
Country: 1 (Uruguay) – City: 1 (Rosario)
Country: 2 (Argentina) – City: 1 (Rosario)

 Or it could also be possible that Rosario for Argentina be identified with another number:
Country: 2 (Argentina) – City: 4 (Rosario)

Reorganize and execute (F5).

Note that the Navigation List informs you that:


 The autonumber property will be ignored for the case of CityId. This means that, in runtime, the user must
manually enter the city identifiers. The explanation for this is that the Autonumber property only
autonumbers simple primary keys, and in this case, CityId is the second component of a compound key.
 A new CountryCity table will be created to store the information corresponding to the cities.

Enter cities for the countries you had recorded already.

Page 11
GeneXus 15 Course: Practical exercises

“ATTRACTION” TRANSACTION: ADDING THE CITY.

In the “ATTRACTION” transaction, let us now add the city of the country to which the attraction belongs. What
should you do if the travel agency indicates that such value might not be known or significant for a given attraction
at a given point in time?

Build the application and test it (F5 and Reorganize).

SOLUTION:

Before you move on, open the “Customer” Transaction and modify the data type of CustomerId so that its domain
is Id (and thus it will be autonumbered). Also modify the data types of CustomerName and CustomerLastName
to that they take up the Name domain. Reorganize.

4. ADDING BEHAVIOR TO TRANSACTIONS


(rules)
After they test with us the application that we continue to develop, the people from the travel agency tell us that for
customers, there is a specific behavior that we must ensure is fulfilled when it comes to handling information
through the program (“Customer” Transaction). And what is such behavior?

They tell us that:

 “The system should not allow entering customers without a name or without a surname.”

Page 12
GeneXus 15 Course: Practical exercises

 “Users must be warned when no telephone has been assigned, in case there was an omission.”
 The date of entry of the customer to the system must be recorded (CustomerAddedDate), and today’s date
should be the predefined value proposed for that attribute.

Specify that behavior and test it (F5 and Reorganize).

Remember that:
 Rules end with a semicolon “;”.
 The IsEmpty() method applied to an attribute returns True when the attribute is empty, or otherwise, it
returns False.
 The &today variable is part of the systems and has the value of today’s date loaded.
To write a variable inside the Rules screen, when “&” is typed, all the variables defined to that point for selecting the
one needed will be deployed. Another possibility is to use Insert / Variable.

Try to enter a new customer and leave the name empty. Does it allow you to save or move on to the next field?
Do the same with the surname. Does the same thing happen with the telephone?

If you are later informed that the entry date into the system should not be handled by the user, but only viewed
instead, how would you establish that behavior?
Specify it and test it in runtime.

5. Patterns: improving the interface to work


with the information
When we show the customer what we have done so far, we are informed that the customer would like to handle the
information of countries, categories and tourist attractions in a more powerful and appealing manner (offering
queries, the possibility of filtering, and the insertion, modification and deletion of data, among other things).
To do this we must apply the Work With patterns to the three transactions. Test it a view in runtime.

Note that:
 there is a Work With for Smart Devices as well, but the one we must apply is the one corresponding to the
web application that is being built.
 GeneXus will automatically create several objects per transaction, to implement the “Work With” that entity.

Page 13
GeneXus 15 Course: Practical exercises

SOLUTION:

Why are the Category, Country and Attraction transactions no longer in the Developer menu?

Try:
1. Entering a new country.
2. Modify a pre-existing country (such as by adding a city to it).
3. Delete an existing country.
4. View the information for one country.
5. Make a search by country name.

Page 14
GeneXus 15 Course: Practical exercises

6. Enter a couple of Tourist attractions (Ex.: the Great China wall for China/Beijing, and the Eiffel Tower for
France/Paris)
7. Filter the Tourist attractions with a name starting by F. And if we now want to view all Tourist attractions in
France? This possibility has not been included, so we must customize this transaction’s Work With pattern to
add it. We do this in GeneXus and then test in runtime.

SOLUTION:
To do this, we first note how the existing filter has been specified, by name of the tourist attraction:

8. Now we remove the country, city and category identifiers from the screen of the Work With and we test in
runtime.

Page 15
GeneXus 15 Course: Practical exercises

9. To offer the user the possibility of deciding whether to view the attractions sorted by name of the attraction
or by country name, implement it and then test it.

6. “Flight” and “Airport” Transactions and the


need to define subtypes
We now need to record the flights offered by the travel agency. Each flight has an identifier and it goes from one
airport to another airport. Each flight also has a price. For the Price we create a domain that is Numeric(10.0).

Create a transaction for recording airports. Each airport has an identifier, a name, a country and a city where it is
located.

How do we define that each flight has a departure airport and a destination airport?

Remember

1) That, in the structure of the transaction:


 an icon representing an upward arrow informs that the attribute is foreign key (Foreign Key), meaning
that it points to the other table.
 an icon representing a downward arrow informs that the attribute is inferred from another table.
 an icon representing an indicates that the attribute is a subtype
2) Regarding the groups of subtypes:
 they are defined in the same manner as any type of object.
 each group of subtypes must necessarily contain a subtype of a primary attribute (which is
primary key of a table) or a group of attributes that comprise a primary key.
 for each group of subtypes, we must include all the subtype attributes necessary that belong to
the base and/or the extended table of the group’s primary key.

Page 16
GeneXus 15 Course: Practical exercises

Execute and verify that, upon trying to enter a flight, an error is triggered when the departure airport that is being
assigned to the flight does not exist. And the same applies to the arrival airport.
It should not be allowed to enter a flight with a departure airport being the same as the arrival airport. Implement
that behavior and test it in runtime.

7. Formulas
The current discount applicable to each flight is to be recorded. Define a new attribute in the Flight transaction
to store that data. Name the new attribute as: FlightDiscountPercentage and make its data type a “Percentage”
domain, numeric with a length of 3.

To view the flight’s final price with the discount applied (another requirement), define another attribute, under the
name of FlightFinalPrice, being a global formula that will automatically calculate the final price for the flight:

Press F5, note, in the Impact Analysis, which attribute will be created physically and which will not,
Reorganize, and test the application in runtime.

Create a second level in the “Flight” transaction called: Seat, to record the flight’s seats.

Since flight seats are usually identified by means of a number and a letter, the primary key (or unique identifier) for
the second level, must comprise 2 attributes:

 FlightSeatId: to record the seat number

 FlightSeatChar: to enter the letter

Define the SeatChar domain of the type: character(1), so that the FlightSeatChar attribute belongs to it. Restrict the
letters possible for the domain: they must be valid letters from A to F (by editing the domain’s Enum Values
property).

Create another attribute in the 2nd level of the Flight transaction, called: FlightSeatLocation. Define a “Location”
domain associated with it, of the Character(1) type. In the Domains node, edit the Enum Values property of the
“Location” domain and define the 3 following values:

Page 17
GeneXus 15 Course: Practical exercises

Window (value that will be stored: “W”)

Middle (value that will be stored: “M”)

Aisle (value that will be stored: “A”)

In the form of the Flight transaction you will see that, for each seat, you may indicate its location with a combo
control that will offer values “Window”, “Middle”, and “Aisle”.

Remember that, to define that a given attribute is part of the primary key, we need to right click on the
attribute for the contextual menu to provide the Toggle Key option.

In order to learn about the passenger capacity allowed by the flight, create a new attribute in the first level of the
Flight transaction under the name: FlightCapacity, of the type: Numeric(4), and define it as global formula to count
the number of seats available on the flight.

To view the flight capacity on the web form and control that flights with less than 4 seats are not recorded, this
control must be done after all seats have been entered and after pressing the Confirm button.

8. PDF Listings
Now let’s suppose that, as part of the application, we must implement the possibility to display, upon the user’s
request, PDF Listings with the information required. For instance, suppose that a listing is required to show, in
alphabetical order, the Tourist attractions stored in the database.
If we know that it should appear more or less as follows:

Page 18
GeneXus 15 Course: Practical exercises

Suggestion: Use the Image control from the Toolbox to deploy an image along with the listing’s title.
That image must be included in the knowledge base. To do that, select the Import from File option, search for the
image and assign a name to it.

Page 19
GeneXus 15 Course: Practical exercises

Implement it in GeneXus.

Keep in mind that, in order to view a listing directly from the browser, it should be generated as PDF. To this
end, we must set up the following properties of the object procedure:
 Main program = ‘True’
 Call Protocol = http
 Report output = Only to File

And the following rule:


 Output_file(‘name-archivo.pdf’ , ‘PDF’)

To execute the listing, on the object’s tab: right click / Run with this only

Did you notice what the Navigation List of the procedure informs?

And if now the requirement is that the listing be presented by country name? Implement this, and note what is
informed in the Navigation List and then test it.
And if now the requirement is to have only the list of attractions in France? Try this (observing the navigation list)

In each case, infer what table of the database is being run through to make que query of the For each.

Also a listing like the one below is required (showing each category, and for each of them, its tourist attractions).
Implement it and test what is done.

Suggestion: To reuse part of the recently created listing, right click on the name of the procedure and select the
option Save as... Save it with a different name.

Page 20
GeneXus 15 Course: Practical exercises

Add a new category to the system, for example “Art Gallery”. Execute the listing again and note if that category has
been listed (?)
Modify the previous listing so that it does not contain categories with no tourist attractions associated.
What modifications did you find in the navigation listing?

Another request from the travel agency is a listing to show all country names, and for each of them, the number of
tourist attractions offered:

Page 21
GeneXus 15 Course: Practical exercises

The requirement also calls for the listing to show all countries with more than 2 attractions to visit:

9. PASSING PARAMETERS
We often need an object to receive parameters so that, based on such parameters, it will execute its logic. For
instance, one thing is to define a pdf listing of all tourist attractions in the database, and another thing is to define a
listing of those attractions whose name is within a given range.

LIST OF ATTRACTIONS IN A GIVEN RANGE

Save, with a different name, the procedure created in item 6 to list tourist attractions, and modify it so that now it
only lists the attractions whose name is within a range received by parameter (the initial and end values of the
range will be the parameters received).

Implement a screen to request those range values from the user, and invoke that object, passing those values by
parameter. Test this in runtime.

Remember that:
 When a variable is defined based on an attribute, it will be linked to the data type of the attribute, so,
if the attribute’s data type is modified, the variable’s data type will be modified accordingly.
 The variables used to make an invocation in the object that calls and those used to declare the
parameters received in the object called do not necessarily have the same name, but they must have
compatible data types.

SOLUTION:
To the procedure (let’s call it “AttractionsFromTo”) we add the parm rule (and define both variables in the
procedure):

Page 22
GeneXus 15 Course: Practical exercises

parm( in: &fromName, in: &toName );

And in its Source:

print Title
print ColumnTitles
for each Attraction
where AttractionName>= &fromName
where AttractionName <= &toName
print Attractions
endfor

Then we create a web panel, where we define two variables, that may have any name, such as A and B, but must
have a data type compatible with that of the &fromName and &toName variables. Why? Because it will be in these
variables that the user will enter values that, in the event we will program, will be sent by parameter to the
procedure, as follows:

AttractionsFromTo( &A, &B)

10. Business Components


We will now perform some operations on the database, and we will do it through business components.

INCREASE OF FLIGHT TICKET PRICES

Every now and then, the travel agency requires the application of an increase in prices of flights, in a given
percentage. To do this, we must implement a screen that will enable the user to specify that increase
percentage, and give the order to apply it to all flights in the database. Implement this and test it.

Remember that:
 The web panel object enables the implementation of flexible screens for information input and output.
 For the input of information (for the user to be able to enter values on screen) variable controls are
inserted in the form.
 To edit menu bars, from the upper part in GeneXus, over the bar, you may insert, for example, the
Formatting bar with the right button.
 For the web to perform a given action, you may insert buttons and program the associated “event”.
 Business components are data types created when configuring the property named Business Component
of the transaction object with value Yes. When we do this, to insert, modify or delete records from the
corresponding tables, we may use, in addition to the transaction, a variable of the Business Component
data type in any other object (such as a web panel), and then carry out the same operations with the
Load(), Save() and Delete() methods.
 For the operations done through the business component to remain as permanent, we must execute the
Commit command immediately after.
 To increase an X value by 20%, all we need to do is X = X*(1+20/100) = X*1,20

Page 23
GeneXus 15 Course: Practical exercises

SOLUTION:
One possible solution (try to implement the requirement before seeing what is indicated below): we create a
Web panel, with a &percentage variable of the Numeric(3.0) data type.

When we double click on the button, it takes us to the Events section, editing the associated event upon
defining the button. In our example, this is the “Confirm” event.
There, we program the logic that we want executed when the user presses the button.
We must go through all flights and overwrite the price they had, increasing it by the percentage indicated by the
user in the screen variable.
To go over all flights in the database we use the For each command.
So, how do we edit each flight to modify its FlightPrice value?
For that, we will need a variable with all the structure of the Flight transaction that will also enable us to save in
the database. And what will be the data type of that variable then? The Flight business component (note
that the business component data type has the same name as the transaction). But GeneXus does not create
that data type automatically for each transaction. We have to request that. How? By using the corresponding
property of the transaction.
So, once this is done:

Page 24
GeneXus 15 Course: Practical exercises

Since the operations of saving to or deleting from the database (through the Save() and Delete() methods) may
lead to errors, it is important to know what has occurred. To this end, we have the Success() method that will
return True when there have been no errors, and False when that is not the case.

When we insert, modify or delete records from a table in the database, to the extent that: “everything done
must be permanent” is not indicated, all such modifications will be provisional. So, what must we indicate? That,
for example, in the event of a power failure, those modifications will be lost. The way to indicate “everything
done must be permanent” is by executing the Commit command. If, otherwise, we want to undo what has been
done, then we execute the Rollback command.

SCREEN FOR DELETING ALL FLIGHTS

Save the previous web panel with a different name (to do this all you need is to right click on the tab and do Save
as) and modify the Form for it to only contain a button with the text “Delete all flights”, so that, in runtime, this web
panel will appear like this:

When the user presses the button, all flights should be deleted from the database.
What should the Confirm event programmed modify?

Note: if you go to the button and view its properties, you will see that in the property called Caption you may modify
the text for the button.

Page 25
GeneXus 15 Course: Practical exercises

SOLUTION:

With Msg you will be deploying that message on the web panel screen.

11. PROCEDURES FOR UPDATING RECORDS

INCREASE OF FLIGHT TICKET PRICES

Suppose now that there are thousands of flights for which you must increase their price by a given percentage (go
back to the first exercise in item 9 of the practical exercises). If you know that the price increase is a simple
percentage that will not cause a failure in integrity in any way, try to solve this with a procedure, without using
business components.

Remember that:
 With the For each command within a procedure, you may update the attributes of its extended table
just through simple assignments.
 The “direct” update through procedures will not control information integrity.
 Every object must declare the parameters it receives and the parameters it returns. If it does not
declare them, then it will not receive or return any values.
 Parameters are declared through the parm rule.
 The variables are local in relation to the object where they are used. This means that to receive a value
as parameter in a &X variable, we must declare it in the object.

Page 26
GeneXus 15 Course: Practical exercises

DELETION OF ALL FLIGHTS

And what would you do to delete all flights as we did in item 9 of the practical exercises, but this time through a
procedure?

SOLUTION:
Create a FlightsDeletion procedure that will not receive parameters, with the following code:

for each Flight


for each Flight.Seat
delete
endfor
delete
endfor

Do a “Save as” of the web panel you implemented in item 9 (the one that performed the deletion through Business
Component), and change the Enter event:

Event Enter
FlightsDeletion()
EndEvent

What should be done to delete all the information from the database?

SOLUTION
Create a DeleteAll procedure with Source:

for each Flight


for each Flight.Seat
delete
endfor
delete Remember that procedures do
endfor not validate data consistency but
the database does. This means
for each Airport that the database validates the
delete consistency of inter-related data,
endfor so the order in which we want to
delete data is important. For
for each Attraction example, if we try to delete
countries before attractions,
delete
then the database will not allow
endfor
it and this will not be user-
friendly.
for each Category
delete
endfor
for each Customer
delete
endfor

for each Country

Page 27
GeneXus 15 Course: Practical exercises

for each Country.City


delete
endfor
delete
endfor

In the same web panel used to delete all flights using Business Components, add a new button, which we will
associate with a “user event”, and then we do the call to the procedure.

Drag the button control over the form, and define the new event

Then, by right clicking on the button and selecting Go To Event, once on the event associated with the button,
inside it we define the invocation to the procedure.

 Execute it so that the database will be emptied. .

Page 28
GeneXus 15 Course: Practical exercises

INITIALIZATION OF INFORMATION IN the database [OPTIONAL]

When the application developed starts production (when the travel agency starts using it) all data corresponding to
countries, categories and attractions must be loaded. Initialize those tables with information provided by the travel
agency and test it.

Bear in mind that:

 The new command enters one record in one physical table.


 When no value is assigned to an attribute in the table, then:
o If the attribute is autonumbered, when the record is saved to the database (upon reaching the
“endnew”), the value for that attribute that will remain in memory will be the value given to it
by the database. For example: if a category is being saved:
New
CategoryName = ‘Monument’
Endnew
We know that, after the Endnew, if we use the CategoryId attribute, it will have the value that
the database assigned to the record upon entering it.
The image of the Eiffel Tour is to be entered in the KB in order to use it. A way to do this is to go, in the
Folder View window, to the Customization folder to select Images, where all images currently stored in the
KB are listed, and then insert a new one (from a file) and put a name to it.

Solution
To try different options, we will populate the countries and the categories using the Data Provider property of the
transactions.

 Open the Country transaction and set up the True value for the Data Provider property:

 Load the data desired in Country_DataProvider (you will see it under the Country transaction in the KBExplorer
window). When it is created, the table will be loaded with the data indicated.

Page 29
GeneXus 15 Course: Practical exercises

Remember that:

The DP associated with the transaction will be


triggered again:

 Every time that the corresponding


table is reorganized.

 Every time that the DP's content is


edited.

Therefore, it is necessary to make sure that


the information is not duplicated. This can be
achieved as follows:

 If the primary key is auto numbered,


a unique index can be defined over
the descriptor attribute.

 The auto numbering feature can be


turned off for the primary key. In this
way, its value will be assigned when
creating the DP and it will not be
duplicated.

 In the same manner, load the Monument, Museum and Famous Landmarks categories.

12. Web panels


The travel agency requires a page showing all countries, and the number of cities that may be visited in each.

Remember that the Load even in a web panel with base table is executed just before each line is
loaded on the grid. This event is appropriate for assigning to the variable the calculation returning
the number of cities in each country that is navigated and to be loaded on a grid line.

Now add the web panel defined, two variables (&CountryNameFrom and &CountryNameTo), and define the
conditions necessary to filter the countries included in that range.

Page 30
GeneXus 15 Course: Practical exercises

13. Extended controls

Using the extended control ImageGallery, design a web panel to show the photo gallery of all tourist attractions.

Customize the properties of the extended control by setting Width=1000, Height= 500, and Type=Slider:

14. QUERY OBJECT


Define a query object to return only the cities in France, sorted in alphabetical order and each of them with its
respective number of tourist attractions.

Define a web panel, and using the QueryViewer control, view the previous query as a graph.

Page 31
GeneXus 15 Course: Practical exercises

15. Web services


The travel agency requested a new functionality: they want to offer customers a listing of all countries that will
show, for each country, its capital city, its currency, and its flag:

To solve this, the suggestion is to import and use a specific Web Service: CountryInfoService, that will return that
information and more.

The web service is located at: http://www.oorsprong.org/websamples.countryinfo/CountryInfoService.wso

Remember that by selecting Tools / Application Integration / WSDL Import in the selection menu, a
wizard will be opened that will import all the specifications of the web service, and methods and parameters in
an external object, and SDTs will be defined if necessary. Remember that by defining variables of the external
object type, you will be able to execute the methods provided by the web service.

16. A PART IS REQUIRED FOR SMART DEVICES


At the agency, they also want to offer end users a small app for smart devices.

The idea is to allow anyone to query, from their smart device, all the countries to which the agency is offering trips,
and for each country, the cities and tourist attractions available.

To do this apply the “Work With for Smart Devices” pattern to the Country transaction:

Page 32
GeneXus 15 Course: Practical exercises

Then just save, to later create a Dashboard object to which the name generated by the pattern –
WorkWithDevicesCountry- should be added.

Remember that just because objects for smart devices have been created inside our knowledge base, when F5 is
pressed, the Android emulator will be executed automatically, with the possibility of also accessing our web
application from the Developer menu

17. GeneXus Server

Publish the knowledge base on the http://sandbox.genexusserver.com/v15 server and create a new web panel
(WPCustomers) to show the agency’s list of customers.

Send this new object to the server so that it is included in the centralized knowledge base.

Enter the web console and verify the final status of the KB.

Page 33
GeneXus 15 Course: Practical exercises

Close the previous knowledge base and create a new one synchronizing with the previously published KB. This will
enable you to locally receive a copy of the KB managed by GeneXus Server.

In this new local copy, edit the Country transaction and define the new CountryFlagImage attribute, of the Image
type, and send this change to the server.

Close this KB and open the initial KB again. Perform the Update operation to receive the change done before.

Page 34
GeneXus 15 Course: Practical exercises

18. DEFINITION OF A BUSINESS PROCESS


MODEL (BPM) FOR BOOKING AN ATTRACTION
[OPTIONAL]
The reservation process for a tourist attraction consists of a series of tasks that may be deemed as a business
process.

This process starts when someone goes to the travel agency to book a tour package for a given attraction. The first
thing that the agency employee must do is enter a reservation for that package.

After the reservation has been entered, it should be verified whether the individual requesting the package is a
customer of the agency. If not, that individual must be entered as a customer and then be associated with the
reservation.

With these two steps completed, the availability of packages must be verified for the number of passengers willing
to make that trip.

If there are seats available, then the reservation will be assigned and the business process finalized. Otherwise, the
passenger should be offered an alternative package.

To implement the model, a Business Process Diagram object must be created. But before this, a Reservation
transaction must be created with the following attributes:

 ReservationId - Id

 ReservationDate - Date

 ReservationQty – N(4)

 CustomerId

 CustomerName

 ReservationAvailable – Boolean

The ReservationAvailable attribute is used to indicate whether the tour package is available or not.

For the CustomerId attribute we select the Yes value for its Nullable column. This will indicate that, at the time of
entering a reservation, we might still not have the customer identifier of the individual making the reservation.

Define the business model for the reservation of a tourist attraction and execute it, testing all the cases mentioned
in the description so that the whole diagram is gone through.

SOLUTION
Create the Reservation transaction according to the requirement.

Create a Business Process Diagram object and name it AttractionReservation. From the toolbar, drag a NoneStartEvent symbol to
the diagram.

Find the Reservation transaction in the Folder View window and drag it to the diagram. To connect the Start node to the
transaction, click on the lower section of the green circle and drag the connection until the tip of the arrow has reached the upper
border of the transaction rectangle.

Page 35
GeneXus 15 Course: Practical exercises

To represent the decision in the diagram for verifying whether the individual is a customer of the agency, drag an Exclusive
Gateway node over the diagram and link it from the Reservation transaction.

Now it is necessary to define the condition of the Gateway that will make the flow continue its normal course (downwards) when
the individual need not be added as a customer, or change it to the alternative (to the right) where the individual must be added
as customer. First drag the Customer transaction to the diagram and connect it to the right of the Gateway.

Then double click on the green arrow that connects the Gateway with the Customer transaction and write the expression:
Reservation.CustomerId = 0, to indicate that the flow must take that path when the CustomerId attribute was left with value 0
upon entering the reservation. Note that you must use the name of the transaction to classify the CustomerId attribute, to
distinguish the attribute that is foreign key in the Reservation transaction from the CustomerId attribute that is primary key in the
Customer transaction.

To associate the newly created customer with the reservation you must create a procedure called AssignCustomerToReservation,
and in the rules section write a parm rule, with parameters &ReservationId and &CustomerId.

In its source, write a For each with a Where clause filtering the ReservationId attribute by the ReservationId variable received by
parameter. Then assign the value of the &CustomerId variable to CustomerId and close the For Each.

This will assign the newly created customer to the reservation entered previously.

Now drag the newly created procedure towards the diagram and connect it from the Customer transaction.

To continue with the regular flow (downwards from the Gateway), you must have a screen where to confirm or cancel the
reservation. To do this, you may use the Reservation transaction again, indicating the reservation as available or not, by means of
the ReservationAvailable attribute.

Drag the Reservation transaction from the Folder View window to the diagram. Rename the task as ReservationAvailability and
connect it from the Gateway.

To indicate that the downward flow is the usual flow, select the connection, and in the Properties window assign the ConditionType
property in the Default value. Note that, in the diagram, the flow is indicated with a green line across it. Now use this opportunity
to connect the AssigntCustomerToReservation task to the ReservationAvailability task.

To assess the value entered in the checkbox of the Reservation transaction, insert an Exclusive Gateway from the toolbar, and
connect it from the ReservationAvailability task. Then connect its alternative flow (which we drew to the left) to the Reservation
task to be able to add a new reservation. Double click on that connector and add the condition ReservationAvailable=False. Note
that, in this case, it is not necessary to classify the attribute because it is only in the Reservation transaction.

What remains to be done now is to consider the case where the reservation is confirmed, in which case there will be no more
tasks, and the process will have to be finalized. To indicate that the diagram must end, insert a NoneEndEvent symbol from the
toolbar and connect it from the Gateway.

This downward connection is the Gateway’s regular flow, so that when the reservation is confirmed, the process will be ended.

To indicate this, select the connection and, in the Properties window, assign the ConditionType property with the Default value.

Now the diagram must be executed. Right click on the tab with the name of the diagram and select Run.

A screen will be opened with the GXflow Client. Select the Reservation task, and, to execute it, press the Execute button or double
click on the task. Enter a new reservation but leaving the customer identifier out. Press Confirm and close the window. To go to the
next task press Send.

Since the customer was not entered, the next task pending is the Customer transaction. Execute the task and enter the individual
who made the reservation as a customer. Close the window and press Send.

Note that the following task is ReservationAvailability, because the AssignCustomerToReservation task is not interactive, so it was
executed in batch method. Execute the task, mark the checkbox and press Confirm. Close the window and press Send.

Note that now the input tray appears empty, indicating that there are no more tasks pending execution because the end of the
process has been reached.

Page 36
GeneXus 15 Course: Practical exercises

Execute the diagram again, but this time test the other paths in it, for example, by entering a customer identifier in the
Reservation transaction, or leaving the checkbox unmarked when confirming the reservation.

To view the history of the tasks executed select My Processes in the Navigator window and double click on the
AttractionReservation process of the window on the right. In a window, you will see all the tasks executed.

To view the history as animation, select More Actions, View Diagram and press the Play button.

19. TESTING THE APPLICATION WITH GXTEST


[OPTIONAL]
Note: Download GXtest here. For further information go to http://abstracta.com.uy/

GXtest allows the saving of sequences of operations to test our screens and verify, in the case of new changes, that
the system continues to function properly.

In this case, we will verify that the price on a flight is calculated with no errors.

This price is represented by the FlightFinalPrice attribute defined with a global formula. This formula calculates the
flight’s final price applying the flight discount to the initial price.

With GXtest, define a test case entering a flight with the following values:

Departure airport: 2

Destination airport: 1

Flight price: 5000

Flight discount: 50%

The calculated flight price will be 2500, because the flight discount is 50%, so the formula will apply that discount to
calculate the value of the FlightFinalPrice attribute.

To continue with the example, enter the flight’s seats but do not press Confirm.

In GXtest, define that the correct value for the text showing the flight price value is 2500. Press Confirm and close
the browser.

In GXtest verify that the test case has been correctly created. Verify that the data pool has been created with the
values entered.

Then change the formula of the FlightFinalPrice attribute (for example, change the 100 in the quotient for a value of
10) and execute the test case entered previously.

Verify whether GXtest informs that it detected an error, and see the value that was not calculated correctly on the
flight transaction screen, that is shown in the results window of the test case.

Then correct the formula (using value 100 instead of the 10) and execute the test case again. Verify that, in this
case, GXtest will not find any errors and the results of the test show the value of the flight price calculated correctly.

SOLUTION

Page 37
GeneXus 15 Course: Practical exercises

Open the GXtest Designer application from the desktop direct access. Create a new project and assign a name to it.

Now press the plus sign (green), select the KB from the folder where it is stored, add a description and press OK. When the data
import from the KB is concluded, press OK.

The URL that GXtest is requesting is that of the application to be tested. Return to GeneXus, execute the Flight transaction, copy
its URL and paste it on the URL field of the Gxtest window. Press OK.

On the right section of the window corresponding to the GXtest Designer, right click on Test Cases and select Record Test Case.
Assign a name to the test case, along with a brief description, and check the box so that the set of test data is generated
automatically.

Press the red button on the window’s upper right. You will see that the browser will be opened and the Flight transaction executed.
Enter the new flight with the data specified in the wording of the exercise, including the seats, but do not Confirm to end the entry
of the flight.

Before that, select, with the mouse, the flight price (the one showing value 2500) and press the check symbol in the GXtest
toolbar in the browser. Select VerifyControlText and add a description. Press Accept and then press Accept again.

GXtest will inform that it has successfully added the validation required. Press OK.

Go back to the Flight transaction screen and press Confirm. Close the browser and go back to the GXtest designer.

You will see that a test case has been created. In the diagram, select the component called Flight and you will find that, in the
commands window, there is a detail of all the steps made upon entering the flight in the Flight transaction.

In the Project panel, on the right side of the screen, under DataPools, click on the element of the set of data. In that window,
verify the data used to enter the flight.

Go back to GeneXus, edit the formula of the FlightFinalPrice attribute and, in the division, write a 10 instead of the 100. Press F5
to update the application. To execute the test case defined go back to GXtest, select the test case tab and press the Play button
located in the screen’s upper left.

The browser window will open up, showing the Flight transaction screen, and the automatic execution of the test case will start,
automatically entering the same data you entered previously, as if it were someone entering it.

Note the values and see whether the flight price has been correctly calculated. Now it will show value -20000. Upon the end of the
test case you will note that the GXtest designer window is activated again. Open the designer.

You will see that a tab has been added with the test results. In the Result column you will find the symbol of an insect,
representing a “bug” that has been detected. On the left panel, upon clicking the plus symbol next to the insect, several options
will open up, with the tests performed, on the right.

Upon double clicking on Flight, a screen will be opened where you will see the screen of the Flight transaction, the steps that are
part of the test made, and the time taken by each step, with the results.

If you lower the bar you will see the validation error of the flight price, indicating the value that was expected and the actual value
obtained. By clicking on the error line, the browser screen will be displayed below, with the value calculated incorrectly.

Return to the Flight transaction, leave the formula as it was before (insert 100 again instead of the 10) and go back to GXtest to
execute the test case again.

Now verify that there are no symbol errors and that the result of the flight calculation is correct, showing the value 2500 again.
Verify the value by clicking on the line that shows the validation of that price and verify, in the browser screen shown below, that
the value shown is also 2500.

Page 38

Potrebbero piacerti anche