Learning Book
Learning Book
Learning Book
Appeon PowerBuilder®
2017
DOCUMENT ID: DC00844-01-1700-01
This publication pertains to Appeon software and to any subsequent release until otherwise indicated in new editions or technical notes.
Information in this document is subject to change without notice. The software described herein is furnished under a license agreement,
and it may be used or copied only in accordance with the terms of that agreement.
Upgrades are provided only at regularly scheduled software release dates. No part of this publication may be reproduced, transmitted, or
translated in any form or by any means, electronic, mechanical, manual, optical, or otherwise, without the prior written permission of
Appeon Limited.
Appeon and other Appeon products and services mentioned herein as well as their respective logos are trademarks or registered
trademarks of Appeon Limited.
SAP and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of
SAP and SAP affiliate company.
Java and all Java-based marks are trademarks or registered trademarks of Oracle and/or its affiliates in the U.S. and other countries.
Unicode and the Unicode Logo are registered trademarks of Unicode, Inc.
All other company and product names mentioned may be trademarks of the respective companies with which they are associated.
Use, duplication, or disclosure by the government is subject to the restrictions set forth in subparagraph (c)(1)(ii) of DFARS 52.227-7013
for the DOD and as set forth in FAR 52.227-19(a)-(d) for civilian agencies.
Appeon Limited, 1/F, Shell Industrial Building, 12 Lee Chung Street, Chai Wan District, Hong Kong.
Contents
iv PowerBuilder
Contents
Users Guide v
Contents
vi PowerBuilder
Contents
viii PowerBuilder
Contents
Users Guide ix
Contents
x PowerBuilder
Contents
Users Guide xi
Contents
xii PowerBuilder
Contents
xiv PowerBuilder
Contents
Users Guide xv
Contents
590
Positioning controls in a DataWindow object ............................... 591
Rotating controls in a DataWindow object ................................... 592
xvi PowerBuilder
Contents
xviii PowerBuilder
Contents
Specifying text properties for titles, labels, axes, and legends 744
Specifying overlap and spacing............................................. 747
Specifying axis properties ..................................................... 748
Specifying a pointer............................................................... 751
Using graphs in windows ............................................................. 752
xx PowerBuilder
Contents
PART 8 APPENDIXES
xxii PowerBuilder
Contents
xxiv PowerBuilder
About This Book
Audience This book is for anyone who builds applications with PowerBuilder®. It
assumes that:
• You are familiar with user interface guidelines. If not, consult a book
that covers user interface conventions.
• You have a basic familiarity with SQL. If not, consult a book that
describes SQL statements.
How to use this book This book describes the PowerBuilder development environment. It
shows you how to use PowerBuilder user interface tools to build the
objects you need, including windows, menus, DataWindow® objects, and
user-defined objects, to create client/server and multitier applications.
Related documents Application Techniques presents information about programming
techniques and building multitier applications.
Deploying Components as .NET Assemblies or Web Services explains how
to deploy custom class user objects as .NET assemblies and Web services.
The DataWindow Programmers Guide explains how to use DataWindow
objects in different environments and presents programming techniques
related to DataWindows.
For a description of all the books in the PowerBuilder documentation set,
see the preface of the PowerBuilder Getting Started manual.
Other sources of Use the Appeon Product Manuals web site to learn more about your
information product. The Appeon Product Manuals web site is accessible using a
standard Web browser.
To access the Appeon Product Manuals web site, go to Product Manuals at
https://www.appeon.com/developers/library/product-manuals-for-pb.
Users Guide i
Formatting example Indicates
Retrieve and Update When used in descriptive text, this font indicates:
• Command, function, and method names
• Keywords such as true, false, and null
• Datatypes such as integer and char
• Database column names such as emp_id and
f_name
• User-defined objects such as dw_emp or
w_main
variable or file name When used in descriptive text and syntax
descriptions, oblique font indicates:
• Variables, such as myCounter
• Parts of input text that must be substituted, such
as pblname.pbd
• File and path names
File>Save Menu names and menu items are displayed in plain
text. The greater than symbol (>) shows you how
to navigate menu selections. For example,
File>Save indicates “select Save from the File
menu.”
dw_1.Update() Monospace font indicates:
• Information that you enter in a dialog box or on
a command line
• Sample script fragments
• Sample output fragments
If you need help All customers are entitled to standard technical support for reproducible
software defects. You can open a standard support ticket at the Appeon
support site: https://www.appeon.com/standardsupport/ (login required).
If your organization has purchased a premium support contract for this product,
then the designated authorized support contact(s) may seek assistance with
your technical issue or question at the Appeon support site:
https://support.appeon.com (login required).
ii PowerBuilder
PA RT 1 The PowerBuilder
Environment
About this chapter This chapter describes the basics of working in the PowerBuilder
development environment.
Contents
Topic Page
About PowerBuilder 3
Concepts and terms 4
The PowerBuilder environment 9
Creating and opening workspaces 18
Using wizards 19
Creating a target 20
Target types 22
Managing workspaces 24
Building workspaces 26
Working with tools 28
Using online help 33
Building an application 34
Before you begin If you are new to PowerBuilder, doing the tutorial in Getting Started will
help you become familiar with the development environment. The tutorial
guides you through the process of building a PowerBuilder application.
About PowerBuilder
PowerBuilder is an object-centric graphical application development
environment. Using PowerBuilder, you can easily develop many types of
applications and components. PowerBuilder provides all the tools you
need to build enterprise systems, such as order entry, accounting, and
manufacturing systems.
Users Guide 3
Concepts and terms
4 PowerBuilder
CHAPTER 1 Working with PowerBuilder
For more information about creating a workspace and targets, see Creating and
opening workspaces on page 18 and Creating a target on page 20.
Objects
Your application is a collection of objects. For most targets, PowerBuilder
provides many types of objects, including graphical objects such as windows,
menus, and buttons, and nonvisual objects such as datastore, exception, and
timing objects.
As you work in your application, you create new objects and open existing
objects to continue work on their development.
For more information about creating, opening, and editing objects, see
Working with objects on page 127.
Users Guide 5
Concepts and terms
DataWindow objects
The applications you build are often centered around your organization’s data.
With PowerBuilder you can define DataWindow® objects to retrieve, display,
and manipulate data. For more information about DataWindow objects, see
Chapter 17, Defining DataWindow Objects.
PowerBuilder libraries
As you work in an application, component, or .NET target, the objects you
create are stored in one or more libraries (PBL files) associated with the
application. When you run your application, PowerBuilder retrieves the
objects from the library.
PowerBuilder provides a Library painter for managing your libraries. For
information about creating a new library and working with libraries in the
Library painter, see Chapter 5, Working with Libraries.
6 PowerBuilder
CHAPTER 1 Working with PowerBuilder
For example, buttons have a Clicked event. You write a script for a button’s
Clicked event that specifies what happens when the user clicks the button.
Similarly, edit controls have a Modified event that is triggered each time the
user changes a value in the control.
You write scripts using PowerScript, the PowerBuilder language, in a Script
view in the painter for the object you are working on. Scripts consist of
PowerScript functions, expressions, and statements that perform processing in
response to an event. The script for a button’s Clicked event might retrieve and
display information from the database; the script for an edit control’s Modified
event might evaluate the data and perform processing based on the data.
Scripts can also trigger events. For example, the script for a button’s Clicked
event might open another window, which triggers the Open event in that
window.
Functions
PowerScript provides a rich assortment of built-in functions you use to act
upon the objects and controls in your application. There are functions to open
a window, close a window, enable a button, retrieve data, update a database,
and so on.
You can also build your own functions to define processing unique to your
application.
Properties
All the objects and controls in an application or component have properties,
many of which you set as you develop your application. For example, you
specify a label for a button by setting its text property. You can set these
properties in painters or set them and modify them dynamically in scripts.
Users Guide 7
Concepts and terms
Source control
If you are working with other developers on a large application, you can make
sure you are working with the latest version of a component or object by
synchronizing the copy of the object you are working on with the last version
of the object checked into a source control system. PowerBuilder provides a
basic check in/check out utility as well as a standard application programming
interface to more sophisticated source control systems. For more information,
see Chapter 3, Using Source Control.
PowerBuilder extensions
You can use PowerBuilder extension objects in an application in the same way
as you would built-in PowerBuilder objects, with one difference—you must
import the file that contains the definition of the extension into a library in the
target. Some extensions are provided with PowerBuilder, but you can also
obtain them from third parties or build your own.
For more information about the extensions provided with PowerBuilder, see
the PowerBuilder Extension Reference. For how to build your own extensions,
see the PowerBuilder Native Interface Programmers Guide and Reference.
8 PowerBuilder
CHAPTER 1 Working with PowerBuilder
Users Guide 9
The PowerBuilder environment
When PowerBuilder starts, it opens in a window that contains a menu bar and
the PowerBar at the top and the System Tree and Clip window on the left. The
remaining area will display the painters and editors you open when you start
working with objects.
10 PowerBuilder
CHAPTER 1 Working with PowerBuilder
You can set the root of the Workspace page to your computer’s root directory,
the current selection, or any directory or library, as well as to the current
workspace.
Current target The orders target is bold, indicating it is the current target, which means that it
is the default target used in the New dialog box and for Run and Debug. The
current target is set whenever you:
• Invoke an action in the System Tree, Library painter, or main menu that
affects a target or a child of a target, such as Build, Migrate, Run, or
Debug. Some actions, such as Search and Migrate, display a dialog box. If
you cancel the action by clicking the Cancel button in the dialog box, the
current target is not changed.
• Open an object painter.
• Change the active object painter.
If you prefer to set the current target explicitly using the Set as Current Target
pop-up menu item for the target in the System Tree or the File>Set Current
Target menu item, clear the Automatically Set Current Target check box on the
Workspaces tab page in the System Options dialog box. To open the System
Options dialog box, select Tools>System Options from the main menu.
Users Guide 11
The PowerBuilder environment
Actions in the System You can use the Workspace page as the hub of your PowerBuilder session.
Tree Pop-up menus let you build and deploy targets and open and edit any object.
Double-clicking an event or function in the System Tree opens its script in the
Script view. Events with scripts have a different icon and are listed before
events without scripts.
Table 1-1 lists the actions you can take on each item that displays on the
Workspace page. You can also set properties for each item, choose which
object types display in the tree view, change the root of the Workspace page,
and reset the root to the current workspace.
12 PowerBuilder
CHAPTER 1 Working with PowerBuilder
The PowerBar
Like the System Tree, the PowerBar provides a main control point for building
PowerBuilder applications. From the PowerBar you can create new objects and
applications, open existing objects, and debug and run the current application.
Users Guide 13
The PowerBuilder environment
While you are getting used to using PowerBuilder, you can display a label on
each button in a toolbar to remind you of its purpose. To do so, right-click any
toolbar button and select Show Text from the pop-up menu.
Table 1-2 lists the buttons from left to right on the PowerBar.
Table 1-2: PowerBar buttons and their uses
PowerBar
button What you can use it for
New Create new objects.
Inherit Create new windows, user objects, and menus by inheriting from
an existing object.
Open Open existing objects.
Run/Preview Run windows or preview DataWindows.
System Tree Work in the System Tree window, which can serve as the hub of
your development session. For more information see The System
Tree on page 10.
Output Window Examine the output of a variety of operations (migration, builds,
deployment, project execution, object saves, and searches). See
The Output window on page 16.
Next Error, Navigate through the Output window.
Previous Error
To-Do List Keep track of development tasks you need to do for the current
application and use links to get you quickly to the place where
you complete the tasks.
Browser View information about system objects and objects in your
application, such as their properties, events, functions, and global
variables, and copy, export, or print the information.
Clip Window Store objects or code you use frequently. You can drag or copy
items to the Clip window to be saved and then drag or copy these
items to the appropriate painter view when you want to use them.
See The Clip window on page 15.
Library Manage your libraries using the Library painter.
DB Profile Define and use named sets of parameters to connect to a
particular database.
Database Maintain databases and database tables, control user access to
databases, and manipulate data in databases using the Database
painter.
Edit Edit text files (such as source, resource, and initialization files)
in the file editor.
Incremental Update all the targets and objects in the workspace that have
Build Workspace changed since the last build.
14 PowerBuilder
CHAPTER 1 Working with PowerBuilder
PowerBar
button What you can use it for
Full Build Update all the targets and objects in the workspace.
Workspace
Deploy Deploy all the targets in the workspace.
Workspace
Skip, Stop Interrupt a build, deploy, or search operation. When a series of
operations is in progress, such as a full deploy of the workspace,
the Skip button lets you jump to the next operation. The Stop
button cancels all operations.
Debug Debug the current target. You can set breakpoints and watch
expressions, step through your code, examine and change
variables during execution, and view the call stack and objects in
memory.
Select & Debug Select a target and open the Debugger.
Run Run the current target just as your users would run it. For
standard PowerBuilder application targets, the application runs
in the development environment.
For .NET targets, you must deploy the target before you can run
it for the first time. If you have made changes since you last
deployed, you must redeploy to see those changes when you
click the Run button.
Select & Run Select a target and run it.
Exit Close PowerBuilder.
Customizing the You can customize the PowerBar. For example, you can choose whether to
PowerBar move the PowerBar around, add buttons for operations you perform frequently,
and display text in the buttons.
For more information, see Using toolbars on page 47.
About PowerTips In the PowerBar, when you leave the mouse pointer over a button for a second
or two, PowerBuilder displays a brief description of the button, called a
PowerTip. PowerTips display in PowerBuilder wherever there are toolbar
buttons.
Users Guide 15
The PowerBuilder environment
Using the Clip window The Clip window displays a list of named clips, a preview of the information
contained in the clip, and a description. It provides buttons to move Clip
window contents to the clipboard, copy clipboard contents to the Clip window,
rename a clip, delete a clip, and modify the clip’s description. Clips you save
in one workspace are available in all your workspaces; you might want to use
a naming convention that reflects this.
For example, you might use standard error-checking code when you use the
ConnectToServer function to connect to a server. To copy it to the clipboard,
highlight the code in a Script view and select Copy from the pop-up menu. In
the Clip window, click the Paste icon, and name the clip. The Clip Description
dialog box opens so that you can enter a description. To change the description
later, select the clip’s name and click the Modify button.
You can drag the clip from the Clip window to any script in which you want to
connect to a server. You can also use the Copy icon to copy the clip to the
clipboard.
You can hide or display the Clip window using the Clip Window button on the
PowerBar or by selecting Window>Clip.
16 PowerBuilder
CHAPTER 1 Working with PowerBuilder
Tab Contents
Search Output from search operations
Unsupported features For .NET targets, names and locations of features are not
supported in the target type
Using the Output You can hide or display the Output window with the Output button on the
window PowerBar or by selecting Window>Output.
You control operations in the window using the Skip, Stop, Next Error, and
Previous Error buttons or menu options.
Tabs display in the order in which they are created and remain in the Output
window for the rest of the PowerBuilder session. To clear the output from the
tabs automatically when you start a new build, make sure that the
Automatically Clear Output Window check box on the General page of the
System Options dialog box is selected. You can also clear and close tabs
manually from the pop-up menu.
When appropriate, lines in the Output window provide links that invoke the
correct painter when you double-click on that line. The pop-up menu also
provides the options Edit and Edit Source to open an object in a painter or the
Source editor. You can copy the contents of the current tab to the Windows
clipboard, save its contents to a text file, or print its contents to your default
printer.
Users Guide 17
Creating and opening workspaces
Creating a workspace
To create a new workspace:
1 Do one of the following:
• Click the New button in the PowerBar.
• Select File>New from the menu bar.
• In the Workspace tab of the System Tree, right-click the workspace
name and select New from the pop-up menu.
The New dialog box opens.
2 On the Workspace tab, select Workspace.
The New Workspace dialog box displays.
3 Enter a name for the workspace (.pbw) you want to create and click Save.
The workspace is created and the name of the new workspace displays in
the PowerBuilder title bar.
Opening a workspace
The next time you start PowerBuilder, it opens without opening a workspace.
You can change this behavior by modifying options on the Workspaces page of
the System Options dialog box or on the Welcome to PowerBuilder screen. For
example, you can have PowerBuilder open not only the workspace you used
most recently, but also the objects and scripts you worked on last. See Starting
PowerBuilder with an open workspace on page 37.
When PowerBuilder opens with an open workspace, it displays the name of the
current workspace in the title bar. The current workspace is also displayed in
the Workspace tab page in the System Tree. Although you can create multiple
workspaces, you can have only one workspace open at a time. You can change
workspaces at any time.
18 PowerBuilder
CHAPTER 1 Working with PowerBuilder
To change workspaces:
1 Do one of the following:
• Select File>Open Workspace from the menu bar.
• In the Workspace tab of the System Tree, right-click on the workspace
name and select Open Workspace from the pop-up menu.
The Open Workspace dialog box displays.
2 From the list, select the workspace you want to open.
The workspace is changed and the name of the new workspace displays in
the PowerBuilder title bar.
Using wizards
After you have created a workspace, you can add new or existing targets to it.
The first step in building a new PowerBuilder target is to use a Target wizard
to create the new target and name it.
About wizards
Wizards simplify the initial creation of applications and components. Using
your specifications, wizards can create multiple objects and in some cases
automatically generate complex code that you can modify as needed. The first
page in most wizards explains what the wizard builds. If you need help with the
information you need to give the wizard, click the Help [?] button in the upper
right corner of the window and then click the field you need help with, or click
the field and press F1.
Users Guide 19
Creating a target
You start wizards from the New dialog box, but not all the icons in the New
dialog box represent wizards. On the Project tab page, there are two versions
of some icons: one that starts a wizard, and one that takes you straight to the
Project painter.
Many wizards generate To-Do List entries to guide you through the rest of the
development of the application, object, or component. See Using the To-Do
List on page 30.
Creating a target
When you create a target, you are prompted for the name and location of a
Target (.pbt) file and one or more other objects. Target files are text files that
contain information about the target.
20 PowerBuilder
CHAPTER 1 Working with PowerBuilder
For more information about each type of Target wizard, see the sections
following these instructions.
3 Follow the instructions in the wizard, providing the information the wizard
needs.
In most wizards, you can review your choices on the summary page that
displays when you have finished entering information. This is a summary
page from the Template Application wizard:
Users Guide 21
Target types
Be sure the Generate To-Do List check box is checked if you want the
wizard to add items to the To-Do List to guide and facilitate your
development work.
4 When you are satisfied with your choices in the wizard, click Finish.
The objects are created in the target you specified. If you specified that
items were to be added to the To-Do List, you can see the items by clicking
the To-Do List button in the PowerBar.
As you develop the application, you can use linked items on the To-Do list
to open an object in the specific painter and view where you need to work.
See Using the To-Do List on page 30.
Target types
This section describes each of the targets you can build.
Application targets
There are three wizards for creating application targets:
• Application Target wizard
• Template Application Target wizard
• Existing Application Target wizard
Application Target You use the Application Target wizard to create a new PowerScript-based
wizard Application object and the library containing it. You must create any other
objects you need from scratch.
Template Application You use the Template Application Target wizard to create a PowerScript-based
Target wizard application, the library containing it, and a set of basic objects and scripts. If
the application requires a connection to a SQL database, the wizard
automatically creates a Connection object.
In the Template Application wizard, you can choose one of two application
types: MDI Application and SDI Application.
MDI Application The wizard automatically generates the shell and scripts for
a basic Multiple Document Interface (MDI) application that includes these
objects:
22 PowerBuilder
CHAPTER 1 Working with PowerBuilder
Application object
Frame window
Frame menu
Base sheet window
Sheet menu
Sheet menu service object
Sheet windows
About window
Toolbar window
Connection service object (if database connection is needed)
Project object (optional; can build later using a Project wizard)
You can run the MDI application immediately by clicking the Run button on
the PowerBar. You can open sheets, display an About box, and select items
from menus. The To-Do List can help you use the application as a starting point
for continuing development of an MDI application.
SDI Application In the Template Application wizard, you can also choose to
create a Single Document Interface (SDI) application. An SDI application has
only one main window with a menu and an about window. If the application
requires a connection to a SQL database, the wizard automatically creates a
Connection object.
For information about building MDI and SDI applications, see Application
Techniques.
Existing Application You use the Existing Application Target wizard to add a target to your
Target wizard workspace that uses an application you built in an earlier version of
PowerBuilder. After you complete the wizard, the Migrate Application dialog
box opens so you can migrate the application to this version.
Before you migrate Always make a backup copy of all the PBLs used in an
application before you migrate it to a new version of PowerBuilder.
You can use the Migration Assistant to check for obsolete syntax in your
application before you migrate; then you can make changes in the earlier
version of PowerBuilder and avoid some migration errors. The Migration
Assistant is particularly useful if you are migrating from PowerBuilder 6 or
earlier. Open the Migration Assistant from the Tool tab of the New dialog box,
and press F1 if you need help in the wizard.
You should also check the release notes for the version of PowerBuilder that
you are using to find out if there are any migration issues that might affect you.
For more information about migrating targets, see Migrating targets on page
157.
Users Guide 23
Managing workspaces
.NET targets
.NET Web Service The PowerBuilder .NET Web Service and .NET Assembly wizards build
and .NET Assembly targets that deploy PowerBuilder custom class user objects as .NET Web
wizards
services or assemblies.
The .NET Web Service and .NET Assembly targets require that the
PowerBuilder IDE be run under the administrator mode, because these targets
call external executable files that must be run under the administrator mode.
For more information about .NET targets, see Deploying Components as .NET
Assemblies or Web Services.
Managing workspaces
This section describes how to add and remove targets, and to specify properties
in a workspace.
24 PowerBuilder
CHAPTER 1 Working with PowerBuilder
Users Guide 25
Building workspaces
Building workspaces
You can build and deploy workspaces while you are working in PowerBuilder,
and from a command line.
26 PowerBuilder
CHAPTER 1 Working with PowerBuilder
Users Guide 27
Working with tools
As with other command-line options, you need only use the initial letter or
letters of the option name as long as the option is uniquely identified. The
deploy, fullbuild, and incrementalbuild options can be used only with the
workspace option. You need to create projects and specify build and deploy
options for the workspace in PowerBuilder before you start a build from the
command line. Deploy builds the projects in the target in the order listed on the
Deploy page of the target’s properties dialog box.
Example This example assumes that the location of the PowerBuilder executable file is
in your system path. It opens the workspace called CDShop, builds and deploys
the targets in the workspace according to your specifications in the workspace
and target properties, records the content of the Output window in the file
D:\tmp\cdshop.out, and exits PowerBuilder:
pb170 /w D:\CDShop\CDShop.pbw /d /out D:\tmp\cdshop.out
The output from all the tab pages in the Output window and from all the
projects is included in the output file.
There are additional command-line options you can use to start PowerBuilder.
See Using command line arguments on page 38.
28 PowerBuilder
CHAPTER 1 Working with PowerBuilder
Table 1-5 lists the tools available in the PowerBar. Some of these tools are also
listed on the Tools menu.
Table 1-5: Tools available in the PowerBar
Tool What you use the tool for
To-Do List Keep track of development tasks you need to do for the current
target and create links to get you quickly to the place where you
need to complete the tasks. For information, see Using the To-Do
List on page 30.
Browser View information about system objects and objects in your
target, such as properties, events, functions, and global variables,
and copy, export, or print the information. For information, see
Browsing the class hierarchy on page 305.
Library painter Manage libraries, create a new library, build dynamic libraries,
and use source control.
Database profiles Define and use named sets of parameters to connect to a
particular database. For information, see Connecting to Your
Database.
Database painter For information, see Chapter 15, Managing the Database.
File Editor Edit text files such as source, resource, and initialization files.
For information, see Using the file editor on page 32.
Debugger Set breakpoints and watch expressions, step through your
application, examine and change variables during execution, and
view the call stack and objects in memory. For information, see
Chapter 31, Debugging and Running Applications.
Table 1-6 lists the tools you can launch from the Tool tab page in the New
dialog box. You can also launch the Library painter and File Editor from this
dialog box.
Users Guide 29
Working with tools
30 PowerBuilder
CHAPTER 1 Working with PowerBuilder
Exporting and You can export or import a To-Do List by selecting Export or Import from the
importing lists pop-up menu. Doing this is useful if you want to move from one computer to
another or you need to work with To-Do Lists as part of some other system
such as a project management system.
Linked entries
If you import a list from another workspace or target, or from a previous
version of PowerBuilder, linked entries will display in the list but the links will
not be active.
Working with entries Table 1-7 tells you how to work with entries on the To-Do List.
on the To-Do List
Users Guide 31
Working with tools
32 PowerBuilder
CHAPTER 1 Working with PowerBuilder
Setting file editing The file editor has font properties and an indentation property that you can
properties change to make files easier to read. If you do not change any properties, files
have black text on a white background and a tab stop setting of 3 for
indentation. Select Design>Options from the menu bar to change the tab stop
and font settings.
Dragging and To move text, simply select it, drag it to its new location, and drop it. To copy
dropping text text, press the Ctrl key while you drag and drop the text.
Users Guide 33
Building an application
Building an application
This section describes the basic steps you follow when building a traditional
client/server application. After completing step 1, you can define the objects
used in your application in any order as you need them.
34 PowerBuilder
CHAPTER 1 Working with PowerBuilder
Users Guide 35
Building an application
36 PowerBuilder
C H A P T E R 2 Customizing PowerBuilder
About this chapter This chapter describes how you can customize the PowerBuilder
development environment to suit your needs and get the most out of
PowerBuilder’s productivity features.
Contents
Topic Page
Starting PowerBuilder with an open workspace 37
Changing default layouts 41
Using toolbars 47
Customizing keyboard shortcuts 55
Changing fonts 56
Defining colors 57
How the PowerBuilder environment is managed 58
Users Guide 37
Starting PowerBuilder with an open workspace
Opening the If you want PowerBuilder to open the last workspace you used and the painters
workspace, painters, and editors you were using, check Reopen Workspace on Startup and Reload
and scripts
Painters When Opening Workspace. When you open PowerBuilder, any
painters and editors that were open when you closed PowerBuilder are
reloaded. If you edited a script before closing PowerBuilder, the Script view is
scrolled to show the last line you edited.
Opening with no If you want PowerBuilder to open without loading a workspace, clear Reopen
workspace Workspace on Startup. If you want the painters and editors that were open
when you last used a workspace to be reloaded when you reopen it, clear
Reopen Workspace on Startup and check Reload Painters When Opening
Workspace.
Displaying the If you want to see the Welcome to PowerBuilder dialog box when you start
Welcome dialog box PowerBuilder, check Show Start Dialog at Startup with no Workspace and
clear Reopen Workspace on Startup. The Welcome to PowerBuilder dialog box
is shown in The PowerBuilder environment on page 9.
38 PowerBuilder
CHAPTER 2 Customizing PowerBuilder
Users Guide 39
Starting PowerBuilder with an open workspace
Examples The following examples assume that the location of the PowerBuilder
executable file is in your system path.
This example starts a PowerBuilder session by opening the Window painter in
the Client PBL in the Math workspace. The output of the session is sent to a
file called math.log. The workspace file, the PBL, and the log file are all in the
current directory:
pb170 /w Math.pbw /l Client.pbl /p window /out math.log
40 PowerBuilder
CHAPTER 2 Customizing PowerBuilder
Enter this command to start PowerBuilder and open the DataWindow object
called d_emp_report in the workspace Emp.pbw:
pb170 /w D:\pbws\Emp.pbw /P dataw /O d_emp_report
Users Guide 41
Changing default layouts
Using the full width or Windows docked at the top or bottom of the main window occupy the full
height of the main width of the frame. You can change this default by clearing the Horizontal
window
Dock Windows Dominate check box on the General page System Options
dialog box. The following screen shows the Output window docked at the
bottom of the window. The Horizontal Dock Windows Dominate check box
has been cleared so that the System Tree occupies the full height of the
window:
42 PowerBuilder
CHAPTER 2 Customizing PowerBuilder
Each painter has a default layout, but you can display the views you choose in
as many panes as you want to and save the layouts you like to work with. For
some painters, all available views are included in the default layout; for others,
only a few views are included.
Each pane has:
• A title bar you can display temporarily or permanently
• A handle in the top-left corner you can use to drag the pane to a new
location
• Splitter bars between the pane and each adjacent pane
Users Guide 43
Changing default layouts
To move a pane:
1 Place the pointer anywhere on the title bar of the view at the top of the
stack, hold down the left mouse button, and start moving the pane.
A gray outline appears around the pane:
44 PowerBuilder
CHAPTER 2 Customizing PowerBuilder
3 Release the mouse button to drop the outline in the new location:
To resize a pane:
• Drag the splitter bars between panes.
Users Guide 45
Changing default layouts
Saving a layout
When you have rearranged panes in the painter window, PowerBuilder saves
the layout in the registry. The next time you open the painter window, your last
layout displays. You can also save customized layouts so that you can switch
from one to another for different kinds of activities.
46 PowerBuilder
CHAPTER 2 Customizing PowerBuilder
Using toolbars
Toolbars provide buttons for the most common tasks in PowerBuilder. You can
move (dock) toolbars, customize them, and create your own.
Toolbar basics
PowerBuilder uses three toolbars: the PowerBar, PainterBar, and StyleBar:
This toolbar Has buttons for And (unless hidden) displays
PowerBar Opening painters and tools Always
PainterBar Performing tasks in the In each painter or editor; some
current painter painters have more than one
PainterBar
StyleBar Changing properties of text, In appropriate painters
such as font and alignment
Users Guide 47
Using toolbars
Drop-down toolbars
To reduce the size of toolbars, some toolbar buttons have a down arrow on the
right that you can click to display a drop-down toolbar containing related
buttons.
For example, the down arrow next to the Text button in the DataWindow
painter displays the Controls drop-down toolbar, which has a button for each
control you can place on a DataWindow object.
48 PowerBuilder
CHAPTER 2 Customizing PowerBuilder
2 Click the toolbar you want to work with (the current toolbar is highlighted)
and the options you want.
PowerBuilder saves your toolbar preferences in the registry and the
PowerBuilder initialization file.
Docking toolbars
When you first start PowerBuilder, all the toolbars display one above another
at the top left of the workspace. When you move a toolbar, you can dock
(position) it:
• At the top or bottom of the workspace, at any point from the left edge to
the right edge
• At the left or right of the workspace, at any point from the top edge to the
bottom edge
• To the left or right of, or above or below, another toolbar
Customizing toolbars
You can customize toolbars with PowerBuilder buttons and with buttons that
invoke other applications, such as a clock or text processor.
Adding, moving, and You can add, move, and delete buttons in any toolbar.
deleting buttons
Users Guide 49
Using toolbars
3 Click the palette of buttons you want to use in the Select Palette group box.
4 Choose a button from the Selected Palette box and drag it to the position
you want in the Current Toolbar box.
The function of the button you selected displays in the Description at the
bottom of the dialog box. If you choose a button from the Custom palette,
another dialog box displays so you can define the button.
For more information, see Adding a custom button on page 51.
50 PowerBuilder
CHAPTER 2 Customizing PowerBuilder
2 In the Current toolbar box, select the button and drag it outside the Current
toolbar box.
Resetting a toolbar You can restore the original setup of buttons on a toolbar at any time.
To reset a toolbar:
1 Position the pointer on the toolbar, display the pop-up menu, and select
Customize.
2 Click the Reset button, then Yes to confirm, then OK.
Clearing or deleting a Whenever you want, you can remove all buttons from a toolbar. If you do not
toolbar add new buttons to the empty toolbar, the toolbar is deleted. You can delete
both built-in toolbars and toolbars you have created.
To recreate a toolbar
If you delete one of PowerBuilder’s built-in toolbars, you can recreate it easily.
For example, to recreate the PowerBar, display the pop-up menu, select New,
and then select PowerBar1 in the New Toolbar dialog box.
For information about creating new toolbars and about the meaning of
PowerBar1, see Creating new toolbars on page 54.
Users Guide 51
Using toolbars
4 Fill in the Command Line box using Table 2-2 on page 53.
5 In the Item Text box, specify the text associated with the button in two
parts separated by a comma: the text that displays on the button and text
for the button’s PowerTip:
ButtonText, PowerTip
For example:
Save, Save File
If you specify only one piece of text, it is used for both the button text and
the PowerTip.
6 In the Item MicroHelp box, specify the text to appear as MicroHelp when
the pointer is on the button.
52 PowerBuilder
CHAPTER 2 Customizing PowerBuilder
Users Guide 53
Using toolbars
1 Position the pointer on the toolbar, display the pop-up menu, and select
Customize.
2 Double-click the button in the Current toolbar box.
The Toolbar Item Command dialog box displays.
3 Make your changes, as described in Adding a custom button on page 51.
Where you create You can create a new PowerBar anywhere in PowerBuilder, but to create a new
them PainterBar, you must be in the workspace of the painter for which you want to
define the PainterBar.
54 PowerBuilder
CHAPTER 2 Customizing PowerBuilder
3 One at a time, drag the toolbar buttons you want from the Selected palette
box to the Current toolbar box and then click OK.
Tip
Creating keyboard shortcuts means you can use the keyboard instead of the
mouse in many common situations, including changing workspaces, objects, or
connections. To do this, create shortcuts for the File>Recent menu items.
Users Guide 55
Changing fonts
You can reset keyboard shortcuts to the default shortcuts globally or for the
current painter only.
Changing fonts
Table 2-3 summarizes the various ways you can change the fonts used in
PowerBuilder.
Table 2-3: Changing the fonts used in PowerBuilder
Object, painter, or tool How to change fonts
A table’s data, headings, and In the Database painter, display the Properties view
labels for the table, and change the font properties on the
Data, Heading, and Label Font tabs.
Objects in the User Object, Select objects and then modify settings in the
Window, and DataWindow StyleBar, or, in the Properties view for one or more
painters objects, change the font properties on Font tab page.
Application, Menu, and Select Tools>System Options from the menu bar
Library painters, System and change the font properties on the Editor Font
Tree, Output window, and Printer font tab pages.
Browser, and MicroHelp
Function painter, Script view, Select Design>Options from the menu bar and
Interactive SQL view in the change the font properties on the System Font and
Database painter, Source Printer Font tab pages of the dialog box that
editor, file editor, and Debug displays. In the Debug window, select
window (changes made for Debug>Options.
one of these apply to all)
Use the Printer font tab to set fonts specifically for printing. If you need to print
multilanguage characters, make sure you use a font that is installed on your
printer.
Changes you make in the Tools>System Options dialog box and from the
Design>Options menu selection are used the next time you open
PowerBuilder.
56 PowerBuilder
CHAPTER 2 Customizing PowerBuilder
Defining colors
You can define custom colors to use in most painters and in objects you create.
Area of the
Color dialog box What you do
Basic colors Click the basic color closest to the color you want to
define to move the pointer in the color matrix and slider
on the right.
Custom colors Modify an existing color—click a custom color, then
palette modify the color matrix and slider. Define a new color—
click an empty box, define the color, and click Add to
Custom Colors.
Color matrix Click in the color matrix to pick a color.
Color slider Move the slider on the right to adjust the color's attributes.
Add to Custom After you have designed the color, click this button to add
Colors button the custom color to the Custom colors palette on the left.
Users Guide 57
How the PowerBuilder environment is managed
58 PowerBuilder
CHAPTER 2 Customizing PowerBuilder
Specifying Normally, you do not need to edit PB.INI. You can specify all your preferences
preferences by taking an action, such as resizing a window or opening a new application,
or by selecting Design>Options from one of the painters. If a variable does not
appear by default in the options sheet for the painter, you can use a text editor
to modify the variable in the appropriate section of PB.INI.
Where the PB.INI is installed in the same directory as the PowerBuilder executable file,
initialization file is kept but is copied to the C:\Users\userName\AppData\Local\Appeon\PowerBuilder
17.0 for each PowerBuilder user the first time the user opens PowerBuilder.
PowerBuilder subsequently uses the PB.INI copy each time the same user
starts an instance of PowerBuilder IDE.
Telling PowerBuilder You can keep PB.INI in another location and tell PowerBuilder where to find
where your it by specifying the location in the System Options dialog box. You may want
initialization file is
to do this if you use more than one version of PowerBuilder or if you are
running PowerBuilder over a network.
Users Guide 59
How the PowerBuilder environment is managed
60 PowerBuilder
C H A P T E R 3 Using Source Control
Users Guide 61
About source control systems
Source control You work with a source control system through a source control interface.
interfaces PowerBuilder supports source control interfaces based on the Microsoft
Common Source Code Control Interface Specification, Version 0.99.0823. You
can use the PowerBuilder SCC API with any source control system that
implements features defined in the Microsoft specification.
PowerBuilder institutes source control at the object level. This gives you a finer
grain of control than if you copied your PBLs directly to source control outside
of the PowerBuilder SCC API.
No other interfaces
PowerBuilder does not support working with source control systems through
proprietary interfaces provided by source control vendors. To work with source
control systems from your PowerBuilder workspace, you must use the
PowerBuilder SCC API. PowerBuilder also uses this API to connect to the
PowerBuilder Native check in/check out utility that installs with the product.
62 PowerBuilder
CHAPTER 3 Using Source Control
* You can perform these source control operations from PowerBuilder for some source control
systems.
Using PBNative
PowerBuilder provides minimal in-the-box source control through the
PBNative check in/check out utility. PBNative allows you to lock the current
version of PowerBuilder objects and prevents others from checking out these
objects while you are working on them. It provides minimal versioning
functionality, and does not allow you to add comments or labels to objects that
you add or check in to the PBNative project directory.
Connecting to You connect to PBNative from PowerBuilder in the same way you connect to
PBNative all other source control systems: through the PowerBuilder SCC API. You use
the same menu items to add, check out, check in, or get the latest version of
objects on the source control server. However, any menu item that calls a
source control management tool is unavailable when you select PBNative as
your source control system.
Because there is no separate management tool for PBNative, if you need to edit
project PBG files that get out of sync, you can open them directly on the server
without checking them out of source control.
Users Guide 63
About source control systems
For more information about PBG files, see Editing the PBG file for a source-
controlled target on page 99.
PRP files PBNative creates files with an extra PRP extension for every object registered
in the server storage location. If an object with the same file name (minus the
additional extension) has been checked out, a PRP file provides the user name
of the person who has placed a lock on the object. PRP files are created on the
server, not in the local path.
PowerBuilder also adds a version number to the PRP file for an object in the
PBNative archive directory when you register that object with PBNative
source control. PowerBuilder increments the version number when you check
in a new revision. The version number is visible in the Show History dialog box
that you open from the pop-up menu for the object, or in the Library painter
when you display the object version numbers.
For more information on the Show History dialog box, see Displaying the
source control version history on page 91. For information on displaying the
version number in the Library painter, see Controlling columns that display in
the List view on page 144.
64 PowerBuilder
CHAPTER 3 Using Source Control
This directory becomes the project path in the SCC repository. The local
workspace object (PBW), the offline status cache file (PBC), the source
control log file, and any Orcascript files used to rebuild and refresh the
source-controlled targets should be saved to this top-level directory on
local workstations
• Create a unique subdirectory under the project path for each PBL in the
source-controlled targets
This practice avoids issues that can arise if you copy or move objects from
one PBL to another in the same target.
• Instruct each developer on the team to create a workspace object in the
top-level directory and, on the Source Control tab of the Properties of
Workspace dialog box, assign this directory as the "Local Project Path".
Each developer must also assign the corresponding top-level directory in
the SCC repository in the "Project" text box of the Source Control tab for
the workspace
• Add target files (PBT) to the project path directory or create unique
subdirectories under the project path for each target file
Project manager’s Before developers can start work on PowerBuilder objects in a workspace
tasks under source control, a project manager usually performs the following tasks:
• Sets up source control projects (and archive databases)
• Assigns each developer permission to access the new project
• Sets up the directory structure for all targets in a project
Ideally, the project manager should create a subdirectory for each target.
Whatever directory structure is used, it should be copied to all computers
used to check out source-controlled objects.
• Distributes the initial set of PBLs and target (PBT) files to all developers
working on the project or provides a network location from which these
files and their directory structure can be copied.
PowerScript and .NET targets require that all PBLs listed in a target library list
be present on the local computer. For source control purposes, all PBLs in a
target should be in the same local root path, although they could be saved in
separate subdirectories. PBWs and PBLs are not stored in source control unless
they are added from outside the PowerBuilder SCC API. They cannot be
checked into or out of source control using the PowerBuilder SCC API.
Users Guide 65
About source control systems
If you are sharing PBLs in multiple targets, you can include the shared PBLs
in a workspace and in targets of their own, and create a separate source control
project for the shared objects. After adding (registering) the shared PBL
objects to this project, you can copy the shared targets to other workspaces, but
the shared targets should not be registered with the corresponding projects for
these other workspaces. In this case, the icons indicating source control status
for the shared objects should be different depending on which workspace is the
current workspace.
For small projects, instead of requiring the project manager to distribute PBLs
and target files, developers can create targets in their local workspaces having
the same name as targets under source control. After creating a source control
connection profile for the workspace, a developer can get the latest version of
all objects in the workspace targets from the associated project on the source
control server, overwriting any target and object files in the local root path.
(Unfortunately, this does not work well for large PowerScript or .NET projects
with multiple PBLs and complicated inheritance schemes.)
Ongoing maintenance tasks of a project manager typically include:
• Distributing any target (PBT) files and PBLs that are added to the
workspace during the course of development, or maintaining them on a
network directory in an appropriate hierarchical file structure
• Making sure the PBL mapping files (PBGs) do not get out of sync
For information about the PBG files, see Editing the PBG file for a source-
controlled target on page 99.
Connections from each development computer to the source control project
can be defined on the workspace after the initial setup tasks are performed.
Developers’ tasks Each user can define a local root directory in a workspace connection profile.
Although the local root directory can be anywhere on a local computer, the
directory structure below the root directory must be the same on all computers
that are used to connect to the source control repository. Only relative path
names are used to describe the location of objects in the workspace below the
root directory level.
After copying the directory structure for source-controlled PowerScript or
.NET targets to the local root path, developers can add these targets to their
local workspaces. The target objects can be synchronized in PowerBuilder,
although for certain complex targets, it might be better to do the initial
synchronization through the source control client tool or on a nightly build
computer before adding the targets to PowerBuilder. (Otherwise, the target
PBLs may need to be manually rebuilt and regenerated.)
66 PowerBuilder
CHAPTER 3 Using Source Control
For more information about getting the latest version of objects in source
control, see Synchronizing objects with the source control server on page 85.
Users Guide 67
Using a source control system with PowerBuilder
68 PowerBuilder
CHAPTER 3 Using Source Control
Users Guide 69
Using a source control system with PowerBuilder
Advanced connection
70 PowerBuilder
CHAPTER 3 Using Source Control
options Advanced connection options depend on the source control system you are
using to store your workspace objects. Different options exist for different
source control systems.
Users Guide 71
Using a source control system with PowerBuilder
6 Fill in the information required by your source control system and click
OK.
The Project field on the Source Control page of the Workspace Properties
dialog box is typically populated with the project name from the source
control system you selected. However, some source control systems (such
as Perforce or Vertical Sky) do not return a project name. For these
systems, you can leave this field blank.
7 Type or select a path for the local root directory.
All the files that you check into and out of source control must reside in
this path or in a subdirectory of this path.
8 (Option) Select the options you want for your local workspace connection
to the source control server.
9 (Option) Click the Advanced button and make any changes you want to
have apply to advanced options defined for your source control system.
The Advanced button might be grayed if you are not first connected to a
source control server. If Advanced options are not supported for your
source control system, you see only a splash screen for the system you
selected and an OK button that you can click to return to the Workspace
Properties dialog box.
10 Click Apply or click OK.
72 PowerBuilder
CHAPTER 3 Using Source Control
Source control icons The icons and their meanings are described in Table 3-3 and Table 3-4.
Table 3-3: Source control status icons in PowerBuilder
Icon Source control status of object displaying icon
The object resides only locally and is not under source control.
The object is under source control and is not checked out by anyone. The
object on the local computer is in sync with the object on the server unless
the icon for indeterminate status also appears next to the same object.
The object is checked out by the current user.
The object is checked out by another user.
The current status of an object under source control has not been
determined. You are likely to see this icon only if the Perform Diff On
Status Update check box is not selected and if diffs are not performed for
your source control system based on version number. This icon can appear
only in conjunction with the icon for a registered object (green dot icon)
or for an object checked out by another user (red x icon).
The object on the local computer is registered to source control, but is out
of sync with the object on the server. This icon can also appear with the
icon for an object checked out by another user. The Perform Diff On Status
Update check box must be selected for this icon to display.
Compound icons with a red check mark can display only if your SCC provider
permits multiple user checkouts. These icons are described in the following
table:
Table 3-4: Source control status icons with multiple checkouts enabled
Icon Source control status of object displaying icon
The object is under source control and is checked out nonexclusively by
another user. PowerBuilder allows a concurrent checkout by the current
user.
The object is checked out by both the current user and another user.
The object is checked out nonexclusively by another user and the version
in the current user’s local path is out of sync.
Users Guide 73
Using a source control system with PowerBuilder
Pop-up menus Pop-up menus for each object in the workspace change dynamically to reflect
the source control status of the object. For example, if the object is included in
a source-controlled workspace but has not been registered to source control,
the Add To Source Control menu item is visible and enabled in the object’s
pop-up menu. However, other source control menu items such as Check In and
Show Differences are not visible until the object is added to source control.
Library painter Entry Additional status functionality is available from the Entry menu of the Library
menu painter. Depending on the source control system you are using, you can see the
owner of an object and the name of the user who has the object checked out.
For most source control systems, you can see the list of revisions, including any
branch revisions, as well as version labels for each revision.
74 PowerBuilder
CHAPTER 3 Using Source Control
Users Guide 75
Using a source control system with PowerBuilder
76 PowerBuilder
CHAPTER 3 Using Source Control
Typically, the source control server files are stored in a database but preserve
the file system structure. Files in any deployment configuration directories can
be regenerated automatically by building and deploying the files in the Source
directory.
Users Guide 77
Source control operations in PowerBuilder
78 PowerBuilder
CHAPTER 3 Using Source Control
Adding multiple If the object you select is a PowerBuilder workspace, a dialog box displays
objects to source listing all the objects for that workspace that are not currently under source
control
control (although the workspace PBW and target PBLs are not included in the
list). If the object you select is a PowerBuilder target, and at least one of the
objects in that target has not been registered with the current source control
project, PowerBuilder displays a dialog box that prompts you to:
• Select multiple files contained in the target
• Register the target file only
If you select the multiple files radio button, another dialog box displays with a
list of objects to add to source control. A check box next to each object lets you
select which objects you want to add to source control. By default, check boxes
are selected for all objects that are not in your source control project. They are
not selected for any object already under source control.
You can resize all source control dialog boxes listing multiple files by placing
a cursor over the edge of a dialog box until a two-headed arrow displays, then
dragging the edge in the direction of one of the arrow heads.
You can also select multiple objects to add to source control from the List view
of the Library painter (without selecting a workspace, target, or PBL).
Users Guide 79
Source control operations in PowerBuilder
The Add To Source Control menu item is disabled for all objects that are
registered in source control except workspaces and targets. If you select the
Add To Source Control menu item for a workspace or target in which all the
objects are already registered to source control, PowerBuilder displays the Add
To Source Control dialog box with an empty list of files. You cannot add
objects to your source control project that are already registered with that
project.
Creating a mapping When you add a target or an object (in a target that is not under source control)
file for target PBLs to source control, PowerBuilder creates a PBG file. A PBG file maps objects
in a target to a particular PBL in a PowerScript or .NET target. One PBG file
is created per PBL, so there can be multiple PBG files for these types of target.
If a PBG file already exists for a target PBL containing the object you are
adding to source control, PowerBuilder checks the PBG file out of source
control and adds the name of the object to the names of objects already listed
in the PBG file. It then checks the PBG file back into source control.
The PBG files are used by PowerBuilder to make sure that objects are
distributed to the correct PBLs and targets when you check the objects out (or
get the latest versions of the objects) from source control.
If your source control system requires comments on registration and check-in,
you get separate message boxes for the PBG file and the objects that you are
adding to source control. If your source control system gives you the option of
adding the same comments to all the objects you are registering, you can still
get additional message boxes for PBG files, since PBG files are checked in
separately.
Because it is possible for PBG files to get out of sync, it is important that the
project manager monitor these files to make sure they map all objects to the
correct PBLs and contain references to all objects in the source control project.
However, you cannot explicitly check in or check out PBG files through the
PowerBuilder SCC API.
For more information on modifying PBG files, see Editing the PBG file for a
source-controlled target on page 99.
80 PowerBuilder
CHAPTER 3 Using Source Control
• Copies the object to the directory for the target to which it belongs
• For a PowerScript object, compiles the object and regenerates it in the
target PBL to which it is mapped
• Displays a check mark icon next to the object in your System Tree and in
your Library painter to show that the object has been checked out
Checking out multiple If you select the Check Out menu item for a PowerBuilder target that is not
objects already checked out, and at least one of the objects in that target is available for
checkout, PowerBuilder displays a dialog box that prompts you to:
• Select multiple files contained in the target
• Check out the target file only
If you select the multiple file option, or if the target file is already checked out,
the Check Out dialog box displays the list of objects from that target that are
available for checkout. A check box next to each object in the list lets you
choose which objects you want to check out. By default, check boxes are
selected for all objects that are not currently checked out of source control.
The Deselect All button in the Check Out dialog box lets you clear all the check
boxes with a single click. When none of the objects in the list is selected, the
button text becomes Select All, and you can click the button to select all the
objects in the list.
You can also select multiple objects (without selecting a target) in the List view
of the Library painter. The PowerBuilder SCC API does not let you check out
an object that you or someone else has already checked out or that is not yet
registered with source control. If you use multiple object selection to select an
object that is already checked out, PowerBuilder does not include this object in
the list view of the Check Out dialog box.
Multiple user checkout Checking out an object from a source control system usually prevents other
users from checking in modified versions of the same object. Some source
control systems, such as Serena Version Manager (formerly Merant PVCS) and
MKS Source Integrity, permit multiple user checkouts. In these systems, you
can allow shared checkouts of the same object.
By default, PowerBuilder recognizes shared checkouts from SCC providers
that support multiple user checkouts. PowerBuilder shows a red check mark as
part of a compound icon to indicate that an object is checked out to another user
in a shared (nonexclusive) mode. You can check out an object in shared mode
even though another user has already checked the object out.
Users Guide 81
Source control operations in PowerBuilder
If your SCC provider permits multiple user checkouts, you can still ensure that
an item checked out by a user is exclusively reserved for that user until the
object is checked back in, but only if you add the following instruction to the
Library section of the PB.INI file:
[Library]
SccMultiCheckout=0
After you add this PB.INI setting, or if your SCC provider does not support
multiple user checkouts, you will not see the compound icons with red check
marks, and all items will be checked out exclusively to a single user. For source
control systems that support multiple user checkouts, you can re-enable shared
checkouts by setting the SccMultiCheckout value to 1 or -1.
Creating a source If your source control system supports branching and its SCC API lets you
control branch check out a version of an object that is not the most recent version in source
control, you can select the version you want in the Advanced Check Out dialog
box (that you access by clicking the Advanced button in the Check Out dialog
box). When you select an earlier version, PowerBuilder displays a message box
telling you it will create a branch when you check the object back in. You can
click Yes to continue checking out the object or No to leave the object unlocked
in the source control project. If this is part of a multiple object checkout, you
can select Yes To All or No To All.
82 PowerBuilder
CHAPTER 3 Using Source Control
Checking in multiple If you select the Check In menu item for a workspace, PowerBuilder lists all
objects the objects in the workspace that are available for check-in. If you select the
Check In menu item for a PowerBuilder target that is currently checked out to
you, and at least one of the objects in that target is also checked out to you,
PowerBuilder displays a dialog box that prompts you to:
• Select multiple files contained in the target
• Check in the target file only
If you select the multiple file option, or if the target file is not currently checked
out to you, the Check In dialog box displays the list of objects from that target
that are available for you to check in. A check box next to each object in the
list lets you choose which objects you want to check in. By default, check
boxes are selected for all objects that you currently have checked out of source
control.
Users Guide 83
Source control operations in PowerBuilder
The Deselect All button in the Check In dialog box lets you clear all the check
boxes with a single click. When none of the objects in the list is selected, the
button text becomes Select All, and you can click the button to select all the
objects in the list.
You can also select multiple objects (without selecting a workspace or target)
in the List view of the Library painter. The PowerBuilder SCC API does not let
you check in an object that you have not checked out of source control. If you
use multiple object selection to select an object that is not checked out to you,
PowerBuilder does not include this object in the list view of the Check In
dialog box.
84 PowerBuilder
CHAPTER 3 Using Source Control
If you select the multiple file option, or if the target file is not currently checked
out to you, the Undo Check Out dialog box displays the list of objects from that
target that are locked by you in source control. A check box next to each object
in the list lets you choose the objects for which you want to undo the
checked-out status. By default, check boxes are selected for all objects that are
currently checked out to you from source control.
You can also select multiple objects (without selecting a target) in the List view
of the Library painter. The PowerBuilder SCC API does not let you undo the
checked-out status of an object that you have not checked out of source control.
If you use multiple object selection to select an object that is not checked out
to you, PowerBuilder does not include this object in the list view of the Undo
Check Out dialog box.
Users Guide 85
Source control operations in PowerBuilder
86 PowerBuilder
CHAPTER 3 Using Source Control
Users Guide 87
Source control operations in PowerBuilder
88 PowerBuilder
CHAPTER 3 Using Source Control
Users Guide 89
Source control operations in PowerBuilder
5 (Optional) Select any or all of the check box options in the PBNative
Command Options dialog box for your object comparisons.
6 Click OK twice.
You are now set to use your visual difference utility to compare objects on
the local computer and the server.
Using Show You can select Show Differences from a pop-up menu or from the Library
Differences to painter menu bar. If the object you want to compare has not been added to the
compare objects
source control project defined for your workspace, the Show Differences menu
item is not available.
PBNative connections
Skip the next step if you are using a visual difference utility with
PBNative. The difference utility displays the files directly or indicates that
there are no differences between the files.
2 Select the source control comparison options you want and click OK.
90 PowerBuilder
CHAPTER 3 Using Source Control
Users Guide 91
Initialization settings that affect source control
92 PowerBuilder
CHAPTER 3 Using Source Control
Users Guide 93
Initialization settings that affect source control
Permitted values for Table 3-7 describes the effect of permitted values for the SccCOImport,
Import parameters SccUCImport, SccGLImport, and SccRBImport parameters in the PB.INI
initialization file. You can also add an import parameter without assigning it a
value. This has the same effect as the default behavior during checkout, undo
checkout, get latest version, and rollback operations.
94 PowerBuilder
CHAPTER 3 Using Source Control
Table 3-7: Permitted values for import parameters in the PB.INI file
Permitted
value Description
full Forces a full build of the target after the requested source control
operation is completed.
For SccCOImport and SccUCImport, you can combine the “full”
value with the “outofdate” value to reduce the number of objects
imported from the local project path to the target PBLs before a full
rebuild. You combine the values by separating them with a single
space, as shown in the following example: SccUCImport= full
outofdate.
For SccRBImport, if rollback fails for any reason, the build
operation is not performed.
inc Examines the entire target for additional objects that are
descendants of objects or have dependencies on the objects that are
included in the initial source control request. The dependent objects
are compiled and regenerated as part of an incremental build, along
with the objects in the initial request.
For SccCOImport and SccUCImport, you can combine the “inc”
value with the “outofdate” value to reduce the number of objects
imported from the local project path to the target PBLs before an
incremental rebuild. You combine the values by separating them
with a single space, as shown in the following example:
SccUCImport= inc outofdate.
For SccRBImport, if rollback fails for any reason, the build
operation is not performed.
outofdate Compares the exported object images to the source code in target
PBLs after an initial checkout or undo checkout operation. If the
code in the PBLs is identical to the object images, the object images
are not imported. The source code for identical PBL objects is also
not compiled unless you also assign “full” or “inc” to the
SccCOImport or SccUCImport parameters.
The “outofdate” value is not available for the SccGLImport and
SccRBImport parameters. Typically GetLatestVersion calls are
made for objects that are assumed to be out of sync, in which case
the out-of-date comparison is not expected to be useful. Also,
object images that have been rolled back should always be
reimported and compiled to assure the integrity of the target PBLs.
Settings for In addition to the initialization parameters that can help with managing source
troubleshooting control operations, there are also parameters you can use to troubleshoot
problems with source
control problems with source control. These parameters should not be used in normal
operations. They should be used only for diagnosing a problem with source
control. Table 3-8 describes these parameters.
Users Guide 95
Initialization settings that affect source control
Comparison strategies By default, PowerBuilder uses the SCCQueryInfoEx API extension command
to compare objects in target PBLs with object files in a source control
repository.
For more information on the SCCQueryInfoEx API extension command, see
Extension to the SCC API on page 67.
96 PowerBuilder
CHAPTER 3 Using Source Control
A backup strategy is set for SCC providers that do not support the API
extension. The default backup strategy for all SCC providers except ClearCase
and Perforce is to issue an SccDiff command. For ClearCase, the backup
strategy compares the PBL object with the local project path object file. For
Perforce versions earlier than 2008, the strategy for comparing differences first
examines the SCC_STATUS_OUTOFDATE bit returned by the SccQueryInfo
command and then compares the PBL object with the local project page object
file.
You can override the default comparison strategy by adding the
SccDiffStrategy parameter to the initialization file and assigning a value to it
from Table 3-9. You can also add the values together to use multiple
comparison strategies, as long as those strategies are supported by your SCC
provider.
Users Guide 97
Modifying source-controlled targets and objects
98 PowerBuilder
CHAPTER 3 Using Source Control
Moving an object that is not under source control to a destination PBL having
a source-controlled object with the same name is permitted only when the
second object is checked out of source control.
You cannot move an object from a source PBL if the object is under source
control, even when the object has been checked out. The right way to move an
object under source control is described below.
Users Guide 99
Migrating existing projects under source control
You cannot see the PBG files in the System Tree or Library painter unless you
set the root for these views to the file system. To edit PBG files manually, you
should check them out of source control using the source control manager and
open them in a text editor. (If you are using PBNative, you can edit PBG files
directly in the server storage location, without checking them out of source
control.)
You can manually add objects to the PBG file for a PowerBuilder library by
including a new line for each object after the @begin Objects line. The
following is an example of the contents of a PBG file for a PBL that is saved
to a subdirectory (target1) of the workspace associated with the source control
project:
100 PowerBuilder
CHAPTER 3 Using Source Control
Removing PowerBuilder 8
If you remove PowerBuilder 8 from a computer where you have already
installed a later version of PowerBuilder, the setup program deletes the
PBNative registry entry. Subsequently, if you want to use PBNative source
control with PowerBuilder 2017, you must reregister PBNAT170.DLL.
Attempting to use PBNative before reregistering the DLL produces an error
message that points out the problem and the solution. You can reregister the
DLL by opening a DOS command box, changing to the
Appeon\Shared\PowerBuilder directory, and entering the command
REGSVR32 PBNAT170.DLL.
Removing PowerBuilder 9 or later does not remove the DLL or the registry
entry for PBNative source control.
102 PowerBuilder
CHAPTER 3 Using Source Control
You can keep all the libraries in the same directory if you want, but it can
be advantageous to create separate subdirectories for each library in the
list. If you plan to share libraries among different targets, you should
structure the directories so that the common libraries are in the local root
path of every target that uses them.
3 Create a new workspace in the new version of PowerBuilder, or open an
existing workspace in the new version of PowerBuilder.
4 Create a new target using the Existing Application wizard.
In the wizard, point to the PBL with an Application object and add all the
helper PBLs to the library search path.
PowerBuilder prompts you to migrate the PBLs.
5 Click Yes to migrate each library in the path.
6 Create a source connection profile for the workspace that points to the old
source control project or to a new project.
7 Check in the migrated objects to source control if you are using the old
source control project, or add the migrated objects to source control if you
are using a new source control project.
8 Delete the work PBL whenever you want.
104 PowerBuilder
PA RT 2 Working with Targets
About this chapter This chapter describes working with application, component, and .NET
targets in the development environment. For more detailed information
about .NET targets, see Deploying Components as .NET Assemblies or
Web Services.
Contents
Topic Page
About targets 107
Working in painters 108
About the Application painter 115
Specifying application properties 116
Writing application-level scripts 120
Specifying target properties 122
Looking at an application's structure 125
Working with objects 127
Using the Source editor 134
About targets
A target can be used to create:
• An executable application A collection of PowerBuilder windows
that perform related activities and that you deliver to users.
An executable application can be a traditional client/server
application that accesses a database server or an application that acts
as a client in a distributed application and requests services from a
server application.
• A .NET assembly or Web service A custom class user object to be
deployed to the .NET Framework.
The first step in creating a new application or component is to use a Target
wizard, described in Chapter 1, Working with PowerBuilder.
Depending on the type of target you choose to create, the target can include
only an Application object or it can include additional objects. If the target
requires connection to a server or a SQL database, the Template Application
wizard also creates a Connection object.
The Application object All application, component, and .NET targets include an Application object. It
is a discrete object that is saved in a PowerBuilder library, just like a window,
menu, function, or DataWindow object. When a user runs the application, the
scripts you write for events are triggered in the Application object.
When you open an Application object in PowerBuilder, you enter the
Application painter.
After you create the new target, you can open the Application object and work
in the Application painter to define application-level properties (such as which
fonts are used by default for text) and application-level behavior (such as what
processing should occur when the application begins and ends).
Working in painters
In PowerBuilder, you edit objects such as applications, windows, menus,
DataWindow objects, and user objects in painters. In addition to painters that
edit objects, other painters such as the Library painter and the Database painter
provide you with the ability to work with libraries and databases.
Opening painters
Painters that edit There are several ways to open painters that edit objects:
objects
From here You can
PowerBar Click New or Inherit (to create new objects) or Open (to open
existing objects)
Library painter Double-click an object or select Edit from the object’s pop-up
menu
System Tree Double-click an object or select Edit from the object’s pop-up
menu
Browser Select edit from an object’s pop-up menu
Other painters Most other painters are accessible from the New dialog box. Some are also
available on the PowerBar and from the Tools menu.
108 PowerBuilder
CHAPTER 4 Working with Targets
Painter summary
The PowerBuilder painters are:
Painter What you do
Application painter Specify application-level properties and scripts.
Database painter Maintain databases, control user access to databases,
manipulate data in databases, and create tables.
DataWindow painter Build intelligent objects called DataWindow objects that
present information from the database.
Data Pipeline painter Transfer data from one data source to another and save a
pipeline object for reuse.
Function painter Build global functions to perform processing specific to
your application.
Library painter Manage libraries, create a new library, and build dynamic
libraries.
Menu painter Build menus to be used in windows.
Project painter Create executable files, dynamic libraries, components,
and proxies.
Query painter Graphically define and save SQL SELECT statements for
reuse with DataWindow objects and pipelines.
SQLSelect painter Graphically define SQL SELECT statements for
DataWindow objects and pipelines.
Structure painter Define global structures (groups of variables) for use in
your application.
User Object painter Build custom visual objects that you can save and use
(visual) repeatedly in your application. A visual user object is a
reusable control or set of controls that has a certain
behavior.
Painter features
Painters that edit Most painters that edit PowerBuilder objects have these features:
objects
Feature Notes
Painter window with views See Views in painters that edit objects on page 110.
Unlimited undo/redo Undo and redo apply to all changes.
Drag-and-drop operations Most drag-and-drop operations change context or
copy objects.
To-Do List support When you are working in a painter, a linked item you
add to the To-Do list can take you to the specific
location. See Using the To-Do List on page 30.
Save needed indicator When you make a change, PowerBuilder displays an
asterisk after the object’s name in the painter’s Title
bar to remind you that the object needs to be saved.
Other painters Most of the painters that do not edit PowerBuilder objects have views and some
drag-and-drop operations.
110 PowerBuilder
CHAPTER 4 Working with Targets
Many views are shared by some painters, but some views are specific to a
single painter. For example, the Layout, Properties, and Control List views are
shared by the Window, Visual User Object, and Application painters, but the
Design, Column Specifications, Data, Preview, Export/Import Template for
XML, and Export Template for XHTML views are specific to the DataWindow
painter. The WYSIWYG Menu and Tree Menu views are specific to the Menu
painter.
The following sections describe the views you see in many painters. Views that
are specific to a single object type are described in the chapter for that object.
Layout view The Layout view shows a representation of the object and its controls. It is
where you place controls on an object and design the layout and appearance of
the object.
If the Properties view is displayed and you select a control in the Layout view
or the Control List view, the properties for that control display in the Properties
view. If you select several controls in the Layout view or the Control List view,
the properties common to the selected controls display in the Properties view.
Properties view The Properties view displays properties for the object itself or for the currently
selected controls or nonvisual objects in the object. You can see and change the
values of properties in this view.
The Properties view dynamically changes when you change selected objects or
controls in the Layout, Control List, and Non-Visual Object List views.
If you select several controls in the Layout view or the Control List view, the
Properties view says group selected in the title bar and displays the properties
common to the selected controls.
In the Properties view pop-up menu, you can select Labels On Top or Labels
On Left to specify where the labels for the properties display. For help on
properties, select Help from the pop-up menu.
If the Properties view is displayed and you select a nonvisual object in the
Non-Visual Object List view, the properties for that nonvisual object display in
the Properties view. If you select several nonvisual objects in the Non-Visual
Object List view, the properties common to the selected nonvisual objects
display in the Properties view.
112 PowerBuilder
CHAPTER 4 Working with Targets
Script view The Script view is where you edit the scripts for events and functions, define
and modify user events and functions, declare variables and external functions,
and view the scripts for ancestor objects.
You can open the default script for an object or control by double-clicking it in
the System Tree or the Layout, Control List, or Non-Visual Object List views,
and you can insert the name of an object, control, property, or function in a
script by dragging it from the System Tree.
For information about the Script view, see Chapter 6, Writing Scripts.
Control List view The Control List view lists the visual controls on the object. You can click the
Control column to sort the controls by control name or by hierarchy.
If you select one or more controls in the Control List view, the controls are also
selected in the Layout view. Selecting a control changes the Properties view
and double-clicking a control changes the Script view.
Event List view The Event List view displays the full event prototype of both the default and
user-defined events mapped to an object. Icons identify whether an event has a
script, is a descendent event with a script, or is a descendent event with an
ancestor script and a script of its own.
Non-Visual Object List The Non-Visual Object List view is a list of nonvisual objects that have been
view inserted in an Application object, window, or user object of any type. You can
sort controls by control name or ancestor.
Function List view The Function List view lists the system-defined functions and the object-level
functions you defined for the object. Icons identify whether a function has a
script, is a descendant of a function with a script, or is a descendant of a
function with an ancestor script and script of its own.
114 PowerBuilder
CHAPTER 4 Working with Targets
Note that although the half-colored icon identifies the myfunc user-defined
function as having both an ancestor script and a script of its own, for a function
this means that the function is overridden. This is different from the meaning
of a half-colored icon in the Event List view.
Structure List view The Structure List view lists the object-level structures defined for the object.
Inserting nonvisual You can automatically create nonvisual objects in an application by inserting a
objects nonvisual object in the Application object. You do this if you want the services
of a nonvisual object available to your application. The nonvisual object you
insert can be a custom class or standard class user object.
You insert a nonvisual object in an Application object in the same way you
insert one in a user object. For more information, see Using class user objects
on page 373.
116 PowerBuilder
CHAPTER 4 Working with Targets
These sections have information about how you specify the following
application properties in the Application painter:
• Specifying default text properties on page 117
• Specifying an icon on page 118
• Specifying default global objects on page 119
The tab you choose displays the current settings for the font, size, style,
and color. The text in the Sample box illustrates text with the current
settings.
2 Review the settings and make any necessary changes:
• To change the font, select a font from the Font list.
• To change the size, select a size from the Size list or type a valid size
in the list.
• To change the style, select a style (Regular, Italic, Bold, or Bold Italic)
from the Font styles list.
• To change font effects, select one or more from the Effects group box
(Strikeout and Underline).
• To change the text color, select a color from the Text Color list. (You
do not specify colors for data, headings, and labels here; instead, you
do that in the DataWindow painter.)
• To change the background color, select a color from the Background
list.
Specifying an icon
Users can minimize your application at runtime. If you specify an icon in the
application painter, the icon will display when the application is minimized.
118 PowerBuilder
CHAPTER 4 Working with Targets
You can create your own versions of these objects by creating a standard class
user object inherited from one of the built-in global objects. You can add
instance variables and functions to enhance the behavior of the global objects.
For more information, see Chapter 14, Working with User Objects.
After you do this, you can specify that you want to use your version of the
object in your application as the default, instead of the built-in version.
For example, if you defined a user object named mytrans that is inherited
from the built-in Transaction object, type mytrans in the box
corresponding to SQLCA.
3 Click OK.
When you run your application, it will use the specified standard class user
objects as the default objects instead of the built-in global objects.
120 PowerBuilder
CHAPTER 4 Working with Targets
Batch applications
If your application performs only batch processing, all processing takes place
in the script for the application Open event.
Table 4-1 lists all events that can occur in the Application object. The only
event that requires a script is Open.
Table 4-1: Events in the Application object
Event Occurs when
Open The user starts the application.
Close The user closes the application. Typically, you write a script for
this event that shuts everything down (such as closing the
database connection).
SystemError A serious error occurs at runtime (such as trying to open a
nonexistent window). If there is no script for this event,
PowerBuilder displays a message box with the PowerBuilder
error number and message text. If there is a script,
PowerBuilder executes the script.
For more about error handling, see Handling errors at runtime
on page 908.
Idle The Idle PowerScript function has been called and the
specified number of seconds has elapsed with no mouse or
keyboard activity.
For a complete list of the properties of the Application object, see Objects and
Controls.
All target types have Library List and Deploy tabs. If there is more than one
project in the target, you can use the Deploy tab page to specify which projects
should be deployed and in which order. For more information about setting
deploy properties for workspaces and targets, see Building workspaces on
page 26.
.NET targets have a Run tab, where you select the project to be used for running
and debugging the target. .NET targets also have a .NET Assemblies tab that
you use to import .NET assemblies into the target.
122 PowerBuilder
CHAPTER 4 Working with Targets
On the Library List tab page of the Target Properties dialog box, you can
modify the libraries associated with the current target.
3 Click OK.
PowerBuilder updates the search path for the target.
124 PowerBuilder
CHAPTER 4 Working with Targets
• If a menu item script refers to the global function f_calc, f_calc displays
when the menu is expanded:
f_calc(EnteredValue)
• If a window uses a pop-up menu through the following statements, m_new
displays when the window is expanded:
m_new mymenu
mymenu = create m_new
mymenu.m_file.PopMenu(PointerX(), PointerY())
126 PowerBuilder
CHAPTER 4 Working with Targets
Objects referenced These are examples of objects referenced through instance variables or
through instance properties:
variables or properties
• If w_go has this statement (and no other statement referencing w_emp),
w_emp does not display as a reference for w_go:
w_emp.Title = "Managers"
Objects referenced These are examples of objects referenced dynamically through string
dynamically through variables:
string variables
• If a window script has the following statements, the window w_go does not
display when the window is expanded. The window w_go is named only
in a string:
window mywin
string winname = "w_go"
Open(mywin,winname)
• If the DataWindow object d_emp is associated with a DataWindow control
dynamically through the following statement, d_emp does not display
when the window containing the DataWindow control is expanded:
dw_info.DataObject = "d_emp"
128 PowerBuilder
CHAPTER 4 Working with Targets
2 In the Inherit From Object dialog box, select the object type (menu, user
object, or window) from the Object Type drop-down list. Then select the
target as well as the library or libraries you want to look in. Finally, select
the object from which you want to inherit the new object.
3 Click OK.
The new object, which is a descendant of the object you chose to inherit
from, opens in the appropriate painter.
For more information about inheritance, see Chapter 12, Understanding
Inheritance.
Naming conventions
As you use PowerBuilder to develop your application, you create many
different components that require names. These components include objects
such as windows and menus, controls that go into your windows, and variables
for your event and function scripts.
You should devise a set of naming conventions and follow them throughout
your project. When you are working in a team, this is critical to enforcing
consistency and enabling others to understand your code. This section provides
tables of common naming conventions. PowerBuilder does not require you to
use these conventions, but they are followed in many PowerBuilder books and
examples.
All identifiers in PowerBuilder can be up to 255 characters long. The first few
characters are typically used to specify a prefix that identifies the kind of object
or variable, followed by an underscore character, followed by a string of
characters that uniquely describes this particular object or variable.
Object naming Table 4-2 shows common prefixes for objects that you create in PowerBuilder.
conventions
Table 4-2: Common prefixes for objects
Prefix Description
w_ Window
m_ Menu
d_ DataWindow
pipe_ Data Pipeline
q_ Query
n_ or Standard class user object, where standardobject represents
n_standardobject_ the type of object; for example, n_trans
n_ or n_cst Custom class user object
u_ or Standard visual user object, where standardobject
u_standardobject_ represents the type of object; for example, u_cb
u_ Custom visual user object
f_ Global function
of_ Object-level function
s_ Global structure
str_ Object-level structure
ue_ User event
Variable naming The prefix for variables typically combines a letter that represents the scope of
conventions the variable and a letter or letters that represent its datatype. Table 4-3 lists the
prefixes used to indicate a variable’s scope. Table 4-4 lists the prefixes for
standard datatypes, such as integer or string.
The variable might also be a PowerBuilder object or control. Table 4-5 lists
prefixes for some common PowerBuilder system objects. For controls, you can
use the standard prefix that PowerBuilder uses when you add a control to a
window or visual user object. To see these prefixes, open the Window painter,
select Design>Options, and look at the Prefixes 1 and Prefixes 2 pages.
130 PowerBuilder
CHAPTER 4 Working with Targets
Prefix Description
lvi ListViewItem
mfd MailFileDescription
mm MailMessage
mr MailRecipient
ms MailSession
msg Message
nvo NonVisualObject
tr Transaction
tvi TreeViewItem
132 PowerBuilder
CHAPTER 4 Working with Targets
2 In the Open dialog box, select the object type from the Object Type
drop-down list. Then select the target as well as the library or libraries you
want to look in. Finally select the object you want to open.
3 Click OK.
The object opens in the appropriate painter.
Accessing recently You can quickly open recently opened objects by selecting File>Recent
opened objects Objects from the menu bar. The Recent Objects list includes the eight most
recently opened objects by default, but you can include up to 36 objects on the
list.
134 PowerBuilder
CHAPTER 4 Working with Targets
You can open an object in the Source editor in one of several ways:
• Use the Open dialog box
• Select the Edit Source menu item in the System Tree or Library painter
• Select the Edit Source menu item in the Output window for a line that
contains an error
Unlike the file editor, the Source editor cannot be opened independently. It can
only be used in conjunction with an object defined within a target in the current
workspace. You cannot open an object in the Source editor that is already open
in a painter.
When you export an object and view the exported file in the file editor, a
PBExportHeader line displays at the beginning of the file. If you saved the
object with a comment from the object’s painter, a PBExportComment also
displays. The Source editor display is identical to the display in the file editor
except that the PBExport lines are not present in the Source editor.
For more information on exporting objects, see Exporting and importing
entries on page 161.
136 PowerBuilder
C H A P T E R 5 Working with Libraries
About this chapter PowerBuilder stores all the PowerScript objects you create in libraries.
This chapter describes how to work with your libraries.
Contents
Topic Page
About libraries 137
Opening the Library painter 139
About the Library painter 140
Working with libraries 143
Searching targets, libraries, and objects 152
Optimizing libraries 154
Regenerating library entries 154
Rebuilding workspaces and targets 156
Migrating targets 157
Exporting and importing entries 161
Creating runtime libraries 164
Creating reports on library contents 165
About libraries
Whenever you save an object, such as a window or menu, in a painter,
PowerBuilder stores the object in a library (a PBL file). Similarly,
whenever you open an object in a painter, PowerBuilder retrieves the
object from the library.
Assigning libraries Application and .NET targets can use as many libraries as you want.
Libraries can be on your own computer or on a server. When you create a
target, you specify which libraries it uses. You can also change the library
search path for a target at any time during development.
For information about specifying the library search path, see Specifying
the target's library search path on page 122.
Using libraries
It is hard to predict the needs of a particular application, so the organization of
a target’s libraries generally evolves over the development cycle.
PowerBuilder lets you reorganize your libraries easily at any time.
About library size For small applications, you might use only one library, but for larger
applications, you should split the application into different libraries.
There are no limits to how large libraries can be, but for performance and
convenience, you should follow these guidelines:
• Number of objects It is a good idea not to have more than 50 or 60
objects saved in a library. This is strictly for your convenience; the number
of objects does not affect performance. If you have many objects in a
library, list boxes that list library objects become unmanageable and the
System Tree and Library painter become more difficult to use.
• Balance Managing a large number of libraries with only a few objects
makes the library search path too long and can slow performance by
forcing PowerBuilder to look through many libraries to find an object. Try
to maintain a balance between the size and number of libraries.
Organizing libraries
You can organize your libraries any way you want. For example, you might put
all objects of one type in their own library, or divide your target into subsystems
and place each subsystem in its own library.
Sharing objects with PowerBuilder provides basic source control using the PBNative check
others in/check out utility. PBNative allows you to lock the current version of
PowerBuilder objects and prevents others from checking out these objects and
modifying them while you are working on them.
138 PowerBuilder
CHAPTER 5 Working with Libraries
The project administrator must design a directory hierarchy for the project’s
workspace. The administrator might create a separate subdirectory for each
target in the workspace, or for each PBL in the workspace. After the
administrator sets up the project and registers every object in the workspace,
individual developers copy a template workspace to their own computers, open
the workspace, and connect to source control.
PowerBuilder also provides a direct connection to external SCC-compliant
source control systems.
For more about using PBNative and other source control systems, see Using a
source control system with PowerBuilder on page 68.
Using the System The Workspace tab page in the System Tree works like a Tree view in the
Tree Library painter. You can perform most tasks in either the System Tree or the
Library painter Tree view, using the pop-up menu in the System Tree and the
pop-up menu, PainterBar, or menu bar in the Library painter. When you have
the System Tree and a Library painter open at the same time, remember that the
PainterBar and menu bar apply only to the Library painter.
Each time you click the Library painter button on the PowerBar, PowerBuilder
opens a new instance of the Library painter. One advantage of using the System
Tree is that there is only one instance of it that you can display or hide by
clicking the System Tree button on the PowerBar.
About the Tree view The Tree view in the Library painter displays the drives and folders on the
computer and the workspaces, targets, libraries, objects, and files they contain.
You can expand drives, folders, and libraries to display their contents.
140 PowerBuilder
CHAPTER 5 Working with Libraries
About the List view The List view in the Library painter displays the contents of a selected drive,
folder, or library and has columns with headers that provide extra information.
For libraries, the comment column displays any comment associated with the
library. For objects in libraries, the columns display the object name,
modification date, size, and any comment associated with the object. You can
resize columns by moving the splitter bar between columns, and you can sort
a column’s contents by clicking the column header.
Displaying items in the Most of the time, you select a library in the Tree view and display the objects
Tree view and the List in that library in the List view, but at any time, you can set a new root or move
view
back and forward in the history of your actions in the List view and the Tree
view to display libraries or other items. For more information, see Setting the
root on page 150 and Moving back, forward, and up one level on page 151.
Using custom layouts You might find that having more than one Tree view or List view makes your
work easier. Using the View menu, you can display as many Tree views and
List views as you need.
The following screen shows the Library painter with one Tree view and three
List views.
You can filter the objects in each of the List views so that one List view shows
menus, another windows, and another user objects. For information about
filtering objects in a view, see Filtering the display of objects on page 145.
To get this layout in the Library painter, use the View menu to display two more
List views and then manipulate the views to fit this layout. For information
about opening and closing views, manipulating views, returning to the default
view layout, or saving your favorite layouts, see Using views in painters on
page 42.
View synchronization Tree and List views are synchronized with each other. When you are using
more than one Tree view or List view, changes you make in one type of view
are reflected in the last view you touched of the other type. For example, when
an item is selected in a Tree view, the contents of that item display in the List
view that you last touched. When you display new contents in a List view by
double-clicking an item, that item is selected in the Tree view you last touched
(if it can be done without resetting the root).
Each List view in the previous screen displays the contents of a different library
because three libraries were dragged from the Tree view and dropped in
different List views. For information about drag and drop, see Displaying
libraries and objects on page 143.
142 PowerBuilder
CHAPTER 5 Working with Libraries
The actions available from an object’s pop-up menu depend on the object type.
For PowerBuilder objects that you can work with in painters, you can edit the
object in a painter or in the Source editor, copy, move, or delete the object,
export it to a text file, search it, regenerate it, or send it to a printer. You can
also preview and inherit from some objects. For most of these actions, the
object must be in a library in your current workspace.
Actions available from the pop-up menus are also available on the Entry menu
on the menu bar.
Selecting objects
In the List view, you can select one or more libraries or objects to act on.
144 PowerBuilder
CHAPTER 5 Working with Libraries
Specifying which In the Tree and List views, the Library painter displays all objects in libraries
objects display in all that you expand, as well as targets, workspaces, folders, and files. You can
libraries
specify that the Library painter display only specific kinds of objects and/or
objects whose names match a specific pattern. For example, you can limit the
display to only DataWindow objects, or limit the display to windows that begin
with w_emp.
Overriding the choices In either the Tree view or the List view, you can override your choice of objects
you made for a that display in all libraries by selecting a library, displaying the library’s pop-up
specific view
menu, and then clearing or selecting items on the list of objects.
To create a library:
1 Click the Create button or select Entry>Library>Create from the menu bar.
The Create Library dialog box displays showing the current directory and
listing the libraries it contains.
2 Enter the name of the library you are creating and specify the directory in
which you want to store it.
The file is given the extension .PBL.
3 Click Save.
The library properties dialog box displays.
4 Enter any comments you want to associate with the library.
Adding comments to describe the purpose of a library is important if you
are working on a large project with other developers.
5 Click OK.
PowerBuilder creates the library.
To delete a library:
1 In either the Tree view or the List view, select the library you want to
delete.
2 Select Entry>Delete from the menu bar or select Delete from the pop-up
menu.
Restriction
You cannot delete a library that is in the current target’s library search path.
The Delete Library dialog box displays showing the library you selected.
3 Click Yes to delete the library.
146 PowerBuilder
CHAPTER 5 Working with Libraries
The library and all its entries are deleted from the file system.
Opening PowerBuilder PowerBuilder objects, such as windows and menus, are opened only if they are
objects in a PBL in the current workspace.
To open an object:
• In either the Tree view or the List view, double-click the object, or select
Edit from the object’s pop-up menu.
PowerBuilder takes you to the painter for that object and opens the object.
You can work on the object and save it as you work. When you close it,
you return to the Library painter.
Opening other objects The Library painter allows you to open most of the different file types it
displays. When you double-click on an object, PowerBuilder attempts to open
it using the following algorithm:
1 PowerBuilder determines if the object can be opened in the File editor. For
example, files with the extensions .txt, .ini, and .sr* open in the File editor.
2 PowerBuilder determines if the object can be opened in a painter or HTML
editor.
3 PowerBuilder checks to see if the object is associated with a program in
the HKEY_CLASSES_ROOT section of the Windows registry and, if so,
launches the application.
Previewing You can run windows and preview DataWindow objects from the Library
PowerBuilder objects painter.
148 PowerBuilder
CHAPTER 5 Working with Libraries
PowerBuilder copies the objects. If an object with the same name already
exists, PowerBuilder prompts you and if you allow it, replaces it with the
copied object.
To delete objects:
1 Select the objects you want to delete.
2 Do one of the following:
• Click the Delete button.
• Select Delete from the pop-up menu.
• Select Entry>Delete from the menu bar.
You are asked to confirm the first deletion.
3 Click Yes to delete the entry or Yes To All to delete all entries. Click No
to skip the current entry and go on to the next selected entry.
2 If you want the root to be a directory or library, type the path or browse to
the path.
Setting the root to the In the System Tree, the default root is the current workspace. If you prefer to
current workspace work in the Library painter, you may find it convenient to set the root to the
current workspace. Using the current workspace as your root is particularly
helpful if you are using many libraries in various locations, because they are all
displayed in the same tree.
150 PowerBuilder
CHAPTER 5 Working with Libraries
Modifying comments
You can use comments to document your objects and libraries. For example,
you might use comments to describe how a window is used, specify the
differences between descendent objects, or identify a PowerBuilder library.
You can associate comments with an object or library when you first save it in
a painter and add or modify comments in the System Tree or Library painter.
If you want to modify comments for a set of objects, you can do so quickly in
the List view.
If you want to stop working on comments before you finish with the
objects you selected, click Cancel. The comments you have entered until
the most recent OK are retained and display in the List view.
Searching selected You can also select a library or one or more PowerBuilder objects to search.
libraries and objects The following procedure applies whatever the scope of your search is.
152 PowerBuilder
CHAPTER 5 Working with Libraries
3 Enter the string you want to locate (the search string) in the Search For
box.
The string can be all or part of a word or phrase used in a property, script,
or variable. You cannot use wildcards in the search string.
4 In the Display group box, select the information you want to display in the
results of the search.
5 In the Search In group box, select the parts of the object that you want
PowerBuilder to inspect: properties, scripts, and/or variables.
6 Click OK.
PowerBuilder searches the libraries for matching entries. When the search
is complete, PowerBuilder displays the matching entries in the Output
window.
For example, the following screen displays the results of a search for the string
garbagecollect:
Optimizing libraries
You should optimize your libraries regularly. Optimizing removes gaps in
libraries and defragments the storage of objects, thus improving performance.
Optimizing affects only layout on disk; it does not affect the contents of the
objects. Objects are not recompiled when you optimize a library.
Once a week
For the best performance, you should optimize libraries you are actively
working on about once a week.
To optimize a library:
1 In either Tree view or List view, choose the library you want to optimize.
2 Select Entry>Library>Optimize from the menu bar or select Optimize
from the library’s pop-up menu.
PowerBuilder reorganizes the library structure to optimize object and data
storage and index locations. Note that PowerBuilder does not change the
modification date for the library entries. PowerBuilder saves the
unoptimized version as a backup file in the same directory.
The optimized file is created with the default permissions for the drive
where it is stored. On some systems new files are not shareable by default.
If you see “save of object failed” or “link error messages after optimizing,”
check the permissions assigned to the PBL.
154 PowerBuilder
CHAPTER 5 Working with Libraries
To regenerate descendants:
1 Click the Browser button in the PowerBar.
The Browser displays.
2 Select the tab for the object type you want to regenerate.
For example, if you want to regenerate all descendants of window
w_frame, click the Window tab.
3 Select the ancestor object and choose Show Hierarchy from its pop-up
menu.
Regenerate limitations
If you regenerate a group of objects, PowerBuilder will regenerate them in the
order in which they appear in the library, which might cause an error if an
object is generated before its ancestor. For this reason, you should use a full or
incremental build to update more than one object at a time.
156 PowerBuilder
CHAPTER 5 Working with Libraries
There are two methods to use when you rebuild a workspace or target:
• Incremental rebuild Updates all the objects and libraries that reference
objects that have been changed since the last time you built the workspace
or target
• Full rebuild Updates all the objects and libraries in your workspace or
target
To rebuild a workspace:
• Do one of the following:
• Select Incremental Build Workspace or Full Build Workspace from
the PowerBar.
• Select the Workspace in the System Tree or Library painter and select
Incremental Build or Full Build from the pop-up menu.
To rebuild a target:
• Do one of the following:
• Select the target in the Library painter and select
Entry>Target>Incremental Build or Entry>Target>Full Build from
the menu bar.
• Select the target in the System Tree or Library painter and select
Incremental Build or Full Build from the pop-up menu.
Migrating targets
When you upgrade to a new version of PowerBuilder, your existing targets
need to be migrated to the new version. Typically, when you open a workspace
that contains targets that need to be migrated, or add a target that needs to be
migrated to your workspace, PowerBuilder prompts you to migrate the targets.
However, there are some situations when you need to migrate a target
manually. For example, if you add a library that has not been migrated to a
target’s library list, you will not be able to open objects in that library until the
target has been migrated.
You cannot migrate a target that is not in your current workspace and you must
set the root of the System Tree or the view in the Library painter to the current
workspace.
Before you migrate There are some steps you should take before you migrate a target:
• Use the Migration Assistant to check for obsolete syntax or the use of
reserved words in your code
• Check the release notes for migration issues
• Make backup copies of the target and libraries
• Make sure that the libraries you will migrate are writable
The Migration Assistant is available on the Tool page of the New dialog box.
For help using the Migration Assistant, click the Help (?) button in the
upper-right corner of the window and click the field you need help with, or
click the field and press F1. If the Migration Assistant finds obsolete code, you
can fix it in an earlier version of PowerBuilder to avoid errors when you
migrate to the current version.
PowerBuilder libraries PowerBuilder libraries (PBLs) contain a header, source code for the objects in
and migration the PBL, and binary code. There are two differences between PowerBuilder 10
and later PBLs and PBLs developed in earlier versions of PowerBuilder:
• The source code in PowerBuilder 10 and later PBLs is encoded in Unicode
(UTF-16LE, where LE stands for little endian) instead of DBCS (versions
7, 8, and 9) or ANSI (version 6 and earlier).
• The format of the header lets PowerBuilder determine whether it uses
Unicode encoding. The header format for PowerBuilder 10 is the same as
that used for PUL files in PowerBuilder 6.5 and for PKL files in
PocketBuilder. These files do not need to be converted to Unicode when
they are migrated to PowerBuilder 10 or later.
When PBLs are Before opening a PBL, PowerBuilder checks its header to determine whether
migrated or not it uses Unicode encoding. PBLs are not converted to Unicode unless you
specifically request that they be migrated.
You cannot expand the icon for a PBL from PowerBuilder 9 or earlier in the
Library painter. To examine its contents, you must migrate it to PowerBuilder
10 or later.
158 PowerBuilder
CHAPTER 5 Working with Libraries
When you attempt to open a workspace that contains targets from a previous
release in PowerBuilder, the Targets to be Migrated dialog box displays. You
can migrate targets from this dialog box, or clear the No Prompting check box
to open the Migrate Application dialog box.
The Migrate The Migrate Application dialog box lists each PBL that will be migrated and
Application dialog box lets you choose the type of messages that display during the migration process.
If you click OK, each PBL is first migrated to the new version of PowerBuilder.
If necessary, PowerBuilder converts source code from DBCS to Unicode.
PowerBuilder performs a full build and saves the source code back to the same
PBL files. Changes to scripts display in informational messages in the Output
window and are written to a log file for each PBL so that you can examine the
changes later. Recommended changes are also written to the log file.
The following two lines from a log file indicate that the FromAnsi function is
obsolete and was replaced with the String function, and that an encoding
parameter should be added to an existing instance of the String function:
2006/01/27 08:20:11test.pbl(w_main).cb_1.clicked.4:
Information C0205: Function 'FromAnsi' is replaced with
function 'String'.
2006/01/27 08:20:11test.pbl(w_main).cb_2.clicked.4:
Information C0206: Append extra argument
'EncodingAnsi!' to function 'String' for backward
compatibility.
The log file has the same name as the PBL with the string _mig appended and
the extension .log and is created in the same directory as the PBL. If no changes
are made, PowerBuilder creates an empty log file. If the PBL is migrated more
than once, output is appended to the existing file.
PowerBuilder makes the following changes:
• The FromUnicode function is replaced with the String function and the
second argument EncodingUTF16LE! is added
• The ToUnicode function is replaced with the Blob function and the second
argument EncodingUTF16LE! is added
• The FromAnsi function is replaced with the String function and the second
argument EncodingAnsi! is added
• The ToAnsi function is replaced with the Blob function and the second
argument EncodingAnsi! is added
• An Alias For clause with the following format is appended to declarations
of external functions that take strings, chars, or structures as arguments or
return any of these datatypes:
ALIAS FOR “functionname;ansi”
160 PowerBuilder
CHAPTER 5 Working with Libraries
If the declaration already has an Alias For clause, only the string ;ansi is
appended.
Adding PBLs to a When you add PBLs from a previous release to a PowerBuilder target’s library
PowerBuilder target list, the PBLs display in the System Tree. The PBLs are not migrated when you
add them to the library list. Their contents do not display because they have not
yet been converted. To display their contents, you must migrate the target.
You can migrate a target from the Workspace tab of the System Tree by
selecting Migrate from the pop-up menu for the target. You can also migrate
targets in the Library painter if they are in your current workspace.
Caution
The primary use of the Export feature is exporting source code, modifying the
source. You can use the Source editor to modify the source code of an object
directly, but modifying source in an ASCII text file is not recommended for
most users. See Using the Source editor on page 134.
162 PowerBuilder
CHAPTER 5 Working with Libraries
3 Select the files you want to import. Use Shift+click or Ctrl+click to select
multiple files.
4 Click Open.
Caution
When you import an entry with the same name as an existing entry, the old
entry is deleted before the import takes place. If an import fails, the old
object will already be deleted.
164 PowerBuilder
CHAPTER 5 Working with Libraries
4 Click OK.
166 PowerBuilder
CHAPTER 5 Working with Libraries
PowerBuilder generates the selected reports and sends them to the printer
specified in Printer Setup in the File menu.
168 PowerBuilder
PA RT 3 Coding Fundamentals
About this chapter PowerBuilder applications are event driven. You specify the processing
that takes place when an event occurs by writing a script. This chapter
describes how to use the Script view to write scripts using the PowerScript
language.
Contents
Topic Page
About the Script view 171
Opening Script views 173
Modifying Script view properties 174
Editing scripts 174
Using AutoScript 180
Getting context-sensitive Help 186
Compiling the script 187
Declaring variables and external functions 190
For more information For complete information about the PowerScript language, see the
PowerScript Reference.
Title bar The Script view’s title bar shows the name and return type of the current event
or function, as well as the name of the current control for events and the
argument list for functions. If the Script view is being used to declare variables
or functions, the titlebar shows the type of declaration.
Drop-down lists There are three drop-down lists at the top of the Script view:
In the first list, you can select the object, control, or menu item for which you
want to write a script. You can also select Functions to edit function scripts or
Declare to declare variables and external functions.
The second list lets you select the event or function you want to edit or the kind
of declaration you want to make. A script icon next to an event name indicates
there is a script for that event, and the icon’s appearance tells you more about
the script:
Table 6-1: Script icons in the Script view
If there is a script The script icon displays
For the current object or control With text
In an ancestor object or control only In color
In an ancestor as well as in the object or control you Half in color
are working with
172 PowerBuilder
CHAPTER 6 Writing Scripts
Toggle buttons for A Prototype window displays at the top of the Script view when you define a
Prototype and Error new function or event. An Error window displays at the bottom of the view
windows
when there are compilation errors. You can toggle the display of these windows
with the two toggle buttons to the right of the lists.
For more information about the Prototype window, see Chapter 7, Working
with User-Defined Functions, and Chapter 8, Working with User Events.
Editing scripts
You can perform standard editing tasks in the Script view using the Edit menu,
the pop-up menu in the Script view, or the PainterBars. There are shortcuts for
many editing actions.
174 PowerBuilder
CHAPTER 6 Writing Scripts
Setting up shortcuts
In a painter with a Script view, select Tools>Keyboard Shortcuts. Expand the
Edit menu to view existing shortcuts and set up your own shortcuts.
Printing scripts
You can print a description of the object you are editing, including all its
scripts, by selecting FilePrint from the menu bar. To print a specific script,
select FilePrint Script.
Undoing a paste
If you paste information into your script by mistake, click the Undo button or
select Edit>Undo from the menu bar.
176 PowerBuilder
CHAPTER 6 Writing Scripts
The left pane displays a single type of object, such as a window or menu. The
right pane displays the properties, events, functions, external functions,
instance variables, shared variables, and structures associated with the object.
Pasting statements You can paste a template for all basic forms of the following PowerScript
statements:
• IF...THEN
• DO...LOOP
• FOR...NEXT
• CHOOSE CASE
• TRY...CATCH... FINALLY
When you paste these statements into a script, prototype values display in the
syntax to indicate conditions or actions. By default, the statements are pasted
in lowercase. To paste statements in uppercase, add the following line to the
[PB] section of the PB.INI file:
PasteLowercase=0
This setting also affects AutoScript.
178 PowerBuilder
CHAPTER 6 Writing Scripts
The appropriate dialog box displays so that you can create the SQL
statement.
4 Create the statement, then return to the Script view.
The statement displays at the insertion point in the workspace.
For more about embedding SQL in scripts, see the PowerScript Reference.
Pasting functions You can paste any function into a script.
Using AutoScript
AutoScript is a tool designed to help you write PowerScript code more quickly
by providing a lookup and paste service inside the Script view. It is an
alternative to using the paste toolbar buttons or the Browser—you do not need
to move your hands away from the keyboard to paste functions, events,
variables, properties, and templates for PowerBuilder TRY, DO, FOR, IF, and
CHOOSE statements into your script.
If you are not sure what the name or syntax of a function is or what the names
of certain variables are, AutoScript can show you a list to choose from and
paste what you need right into the script. If you can remember part of the name,
start typing and select Edit>Activate AutoScript (or do nothing if automatic
pop-up is turned on). If you cannot remember the name at all, turn atomatic
pop-up on, place your cursor in white space, and select Edit>Activate
AutoScript.
Where you use You can use AutoScript in three different contexts:
AutoScript
• When you can remember part of the name and you want AutoScript to
finish typing it for you or show you a list of alternatives.
180 PowerBuilder
CHAPTER 6 Writing Scripts
• When you cannot remember the name or you just want a list. AutoScript
options can help you narrow the list if you do not know the name but you
do know the type you are looking for. For example, you can choose to see
a list showing all variables, or only all local variables.
• When you want a list of the properties and/or functions and events that
apply to an identifier followed by a dot.
For how to use AutoScript options, see Customizing AutoScript on page 182.
Two ways to use AutoScript can pop up a list automatically when you pause while typing, or
AutoScript when you request it:
• Turn automatic pop-up on to have AutoScript pop up the list or complete
what you are typing when you pause for a few seconds after typing one or
more characters or an identifier followed by a dot. See Using automatic
pop-up on page 185.
• Invoke AutoScript when you need it by pressing the shortcut key you
assigned to the Edit>Activate AutoScript menu item when you have typed
one or more characters or an identifier followed by a dot. Pressing the
shortcut key activates AutoScript only once. It does not turn automatic
pop-up on.
For how to paste an item from the pop-up window into a script, see Using the
AutoScript pop-up window next.
Case sensitivity If you have set the PasteLowerCase PB.INI variable to 0 as described in
Pasting statements on page 178, AutoScript always pastes uppercase
characters. Otherwise, AutoScript always pastes lowercase characters.
The case of any characters you have already typed is preserved. For example,
if you are using AutoScript to complete a function name and you want to use
mixed case, you can type up to the last uppercase letter before invoking
AutoScript. AutoScript completes the function name in lowercase characters
and pastes an argument template.
Pasting an item into To paste an item into the script, press Tab or Enter or double-click the item. Use
the script the arrow and page up and page down keys to scroll through the list. If the item
is a function, event, or statement, the template that is pasted includes
descriptive comments that you replace with argument names, conditions, and
so forth. The first commented argument or statement is selected so that it is
easy to replace. You can jump to the next comment by selecting
Edit>Go To>Next Marker.
Go to next marker
You can use Edit>Go To>Next Marker to jump to the next comment enclosed
by /* and */ anywhere in the Script view, not just in AutoScript templates. For
the steps to create a shortcut for this menu item, see Customizing AutoScript
next.
If you do not want to Press the Backspace key or click anywhere outside the pop-up window to
paste from the list dismiss it without pasting into the script.
If nothing displays AutoScript does not pop up a list if the cursor is in a comment or string literal
or if an identifier is complete. If neither of these conditions applies and nothing
displays when you select Edit>Activate AutoScript, there may be no
appropriate completions in the current context. Check that the options you need
are selected on the AutoScript options page as described in Customizing
AutoScript next.
Customizing AutoScript
There are four ways to customize AutoScript:
• Creating shortcut keys
• Specifying what displays in the list
• Using automatic pop-up
182 PowerBuilder
CHAPTER 6 Writing Scripts
Turning options off reduces the length of the list that displays when you invoke
AutoScript so that it is faster and easier to paste a completion or insert code into
the script:
• To show all variables and methods when typing, check all the boxes except
Statement Templates in the Partial Name Resolution Include group box.
When you pause or press the Activate AutoScript shortcut key, the list
shows variables and methods that begin with the string you typed.
• To quickly find functions on an object, clear all the boxes except Methods
in the After A Dot Include group box. When you type an instance name
followed by a dot, only function and event names for the instance display.
• To see a list of arguments and local variables when the cursor is in white
space, check the Arguments and Local Variables boxes in the When No
Context Include group box. When you press the Activate AutoScript
shortcut key, the list shows only arguments and local variables.
184 PowerBuilder
CHAPTER 6 Writing Scripts
Using automatic Most of the time you will probably use a shortcut key to invoke AutoScript, but
pop-up you can also have AutoScript pop up a list or paste a selection automatically
whenever you pause for several seconds while typing. To do so, check the
Automatic Popup box on the AutoScript options page. Automatic pop-up does
not operate when the cursor is at the beginning of a line or in white space.
This feature is most useful when you are entering new code. You can customize
the options in the Partial Name Resolution Include and After A Dot Include
group boxes to reduce the number of times AutoScript pops up.
When you are editing existing code, it is easier to work with automatic pop-up
off. AutoScript might pop up a list or paste a template for a function when you
do not want it to. Using only the shortcut key to invoke AutoScript gives you
complete control.
Using AutoScript only If you want AutoScript to work only when you have typed an identifier
with dot notation followed by a dot, check the Activate Only After a Dot box on the AutoScript
options page. The effect of checking this box applies whether or not you have
checked Automatic Popup. You might find it most useful when you have
checked Automatic Popup, because it provides another way to limit the number
of times AutoScript pops up automatically.
Example
The following simple example illustrates how AutoScript works with
automatic pop-up turned off and different settings for each context. The
example assumes that you have set up F8 as the Activate AutoScript shortcut
key. To set up the example:
• Create a new window and place on it a DataWindow control and a
CommandButton control.
• Select all the boxes in the Partial Name Resolution Include group box.
• Clear all the boxes in the After A Dot Include group box except Methods.
• Clear all the boxes in the When No Context Include group box except
Arguments and Local Variables.
• Clear both boxes in the Options group box.
Table 6-4: AutoScript example
Context Do this What happens
Partial name In the Clicked event script AutoScript pastes the local variable
resolution for cb_1, type long ll_rtn into the script because it is the
ll_rtn. On a new line, only completion that begins with ll.
type ll and press F8.
Type = d and press F8. The list displays all properties, events,
functions, variables, and statements that
begin with d.
Type w and press Tab or The list scrolls to dw_1 and AutoScript
Enter. pastes it into the script when you press
Tab or Enter.
After a dot Type a dot after dw_1 and The list shows all the functions and
press F8. events for a DataWindow control.
Type GetNextM and press AutoScript pastes the rest of the
Tab or Enter. GetNextModified function name and
template into the script, retaining your
capitalization.
Select Edit>Go To>Next AutoScript selects the next function
Marker. argument so you can replace it.
Complete or comment out the
statement.
No context In the empty ItemChanged The list displays the local variables and
event for dw_1, declare the arguments for the ItemChanged
some local variables, press event.
Tab or Enter, and then press
F8.
186 PowerBuilder
CHAPTER 6 Writing Scripts
To compile a script:
• Click the Compile button, or select Edit>Compile from the menu bar.
PowerBuilder compiles the script and reports any problems it finds, as
described in Handling problems next.
Handling problems
If problems occur when a script is compiled, PowerBuilder displays messages
in a Message window below the script.
188 PowerBuilder
CHAPTER 6 Writing Scripts
Disabling database When PowerBuilder compiles an application that contains embedded SQL, it
connection when connects to the database profile last used in order to check for database access
compiling and building
errors during the build process. For applications that use multiple databases,
this can result in spurious warnings during the build since the embedded SQL
can be validated only against that single last-used database and not against the
databases actually used by the application. In addition, an unattended build,
such as a lengthy overnight rebuild, can stall if the database connection cannot
be made.
To avoid these issues, you can select the Disable Database Connection When
Compiling and Building check box on the General page of the System Options
dialog box.
Caution
Select the check box only when you want to compile without signing on to the
database. Compiling without connecting to a database prevents the build
process from checking for database errors and may therefore result in runtime
errors later.
190 PowerBuilder
C H A P T E R 7 Working with User-Defined
Functions
About this chapter This chapter describes how to build and use user-defined functions.
Contents
Topic Page
About user-defined functions 191
Defining user-defined functions 193
Modifying user-defined functions 200
Using your functions 201
Object-level functions Object-level functions are defined for a window, menu, user object, or
application object. These functions are part of the object’s definition and can
always be used in scripts for the object itself. You can choose to make these
functions accessible to other scripts as well.
These functions correspond to built-in functions that are defined for specific
PowerBuilder objects such as windows or controls. You define object-level
functions in a Script view for the object.
192 PowerBuilder
CHAPTER 7 Working with User-Defined Functions
The following sections describe each of the steps required to define and code a
new function:
1 Opening a Prototype window to add a new function.
2 Defining the access level (for object-level functions).
3 Defining a return type.
4 Naming the function.
5 Defining arguments.
6 Defining a THROWS clause.
7 Coding the function.
8 Compiling and saving the function.
194 PowerBuilder
CHAPTER 7 Working with User-Defined Functions
// object-level functions
of_refreshwindow
of_checkparent
Built-in functions do not usually have underscores in their names, so this
convention makes it easy for you to identify functions as user defined.
196 PowerBuilder
CHAPTER 7 Working with User-Defined Functions
Defining arguments
Like built-in functions, user-defined functions can have any number of
arguments, including none. You declare the arguments and their types when
you define a function.
Passing arguments In user-defined functions, you can pass arguments by reference, by value, or
read-only. You specify this for each argument in the Pass By list.
By reference When you pass an argument by reference, the function has
access to the original argument and can change it directly.
By value When you pass by value, you are passing the function a temporary
local copy of the argument. The function can alter the value of the local copy
within the function, but the value of the argument is not changed in the calling
script or function.
Read-only When you pass as read-only, the variable’s value is available to
the function but it is treated as a constant. Read-only provides a performance
advantage over passing by value for string, blob, date, time, and datetime
arguments, because it does not create a copy of the data.
To define arguments:
1 Declare whether the first argument is passed by reference, by value, or
read-only.
The order in which you specify arguments here is the order you use when
calling the function.
2 Declare the argument’s type. You can specify any datatype, including:
• Built-in datatypes, such as integer and real
• Object types, such as window, or specific objects, such as w_emp
• User objects
• Controls, such as CommandButtons
3 Name the argument.
4 If you want to add another argument, press the Tab key or select Add
Parameter from the pop-up menu and repeat steps 1 to 3.
Passing arrays
You must include the square brackets in the array definition, for example,
price[ ]or price[50], and the datatype of the array must be the datatype of
the argument. For information on arrays, see the PowerScript Reference.
198 PowerBuilder
CHAPTER 7 Working with User-Defined Functions
200 PowerBuilder
CHAPTER 7 Working with User-Defined Functions
Recompiling other Changing arguments and the return type of a function affect scripts and other
scripts functions that call the function. You should recompile any script in which the
function is used. This guarantees that the scripts and functions work correctly
during execution.
Seeing where a PowerBuilder provides browsing facilities to help you find where you have
function is used referenced your functions. In the System Tree or Library painter, select a target,
library, or object and select Search from the pop-up menu. You can also search
multiple entries in the Library painter:
Pasting user-defined When you build a script in the Script view, you can type the call to the
functions user-defined function. You can also paste the function into the script. There are
four ways to paste a user-defined function into a script:
• Drag the function from the System Tree to the Script view.
• Select Edit>Paste Special>Function>User-defined from the menu bar.
• Enable AutoScript, select the function’s signature in the list that displays
when you pause, and press Tab or Enter.
• Select the function in the Browser and copy and paste it into the script.
Using the System Tree, AutoScript, or the Browser pastes the function’s
prototype arguments as well as its name into the script.
For more information about AutoScript, see Using AutoScript on page 180.
202 PowerBuilder
C H A P T E R 8 Working with User Events
About this chapter This chapter introduces user events, describes how to define them, and
discusses how to use them in an application.
Contents
Topic Page
About user events 203
Defining user events 206
Using a user event 209
Event ID names
The PowerBuilder naming convention for user event IDs is similar to the
convention Windows uses to name messages. All PowerBuilder event IDs
begin with pbm_.
Event IDs associated Several Windows messages and notifications map to PowerBuilder event IDs.
with Windows
messages For Windows messages that begin with wm_, the PowerBuilder event ID
typically has the same name with pbm_ substituted for wm_. For messages from
controls, the PowerBuilder event ID typically has the same name but begins
with pbm_ and has the Windows prefix for the control added to the message
name. For example:
• wm_keydown maps to pbm_keydown
To see a list of event IDs to which you can map a user-defined event, select
Insert>Event and display the Event ID drop-down list in the Prototype window
that displays.
Windows messages that are not mapped to a PowerBuilder event ID map to the
pbm_other event ID. The PowerBuilder Message object is populated with
information about system events that are not mapped to PowerBuilder event
IDs. For more information about the Message object, see Objects and Controls
or Application Techniques.
204 PowerBuilder
CHAPTER 8 Working with User Events
For more information about Windows messages and notifications, see the
information about Windows controls and Windows management in the section
on user interface design and development in the Microsoft MSDN Library at
http://msdn.microsoft.com/library/default.aspx.
Event IDs associated PowerBuilder has its own events, each of which has an event ID. For example,
with PowerBuilder the PowerBuilder event DragDrop has the event ID pbm_dragdrop. The event
events
name and event ID of the predefined PowerBuilder events are protected; they
cannot be modified. The event IDs for predefined events are shown in the
Event List view:
Custom event IDs The list of event IDs that displays in the Event ID drop-down list in the
Prototype window includes custom event IDs. Custom user events can be
mapped from Windows wm_user message numbers to pbm_customxx event
IDs.
Obsolete technique
This technique is not recommended and is considered to be obsolete. The
ability to use this technique has been retained for backward compatibility. If
you do not want to map a user event to a named pbm_ code, use an unmapped
user event as described in Unmapped user events on page 207.
These event IDs were intended for use with DataWindow controls, windows,
and user objects other than standard visual user objects, which behave like the
built-in controls they inherit from. They were not intended for use with
standard controls.
Defining custom user events for standard controls can cause unexpected
behavior because all standard controls respond to standard events in the range
0 to 1023. Most controls also define their own range of custom events beyond
1023, corresponding to wm_user messages, and some controls have custom
events that overlap with the PowerBuilder custom events. The pbm_custom01
event ID maps to wm_user+0, pbm_custom02 maps to wm_user+1, and so on,
through pbm_custom75, which maps to wm_user+74.
The Prototype window for user events has an additional field that you use if
you want to map the user event to an event ID.
206 PowerBuilder
CHAPTER 8 Working with User Events
Mapped user events When a system message occurs, PowerBuilder triggers any user event that has
been mapped to the message and passes the appropriate values to the event
script as arguments. When you define a user event and map it to an event ID,
you must use the return value and arguments that are associated with the event
ID.
Unmapped user Unmapped user events are associated with a PowerBuilder activity and do not
events have an event ID. When you define an unmapped user event, you specify the
arguments and return datatype; only your application scripts can trigger the
user event. For example, if you create an event called ue_update that updates a
database, you might trigger or post the event in the Clicked event of an Update
command button.
The Prototype window opens in the Script view. If you display the Script
view’s title bar, you see (Untitled) because you have not named the
event yet. If there is no open Script view, a new view opens.
4 Select a return type and tab to the next field.
Defining return types for events is similar to defining them for functions.
See Defining a return type on page 195.
208 PowerBuilder
CHAPTER 8 Working with User Events
210 PowerBuilder
CHAPTER 8 Working with User Events
You can use this window as the ancestor of any sheet window in your
application that does not have database update capability. When the window is
active, the Add, Delete, Undelete, and Update menu items are grayed out.
When it is not active, the Close item is grayed out.
For windows that have database update capability, you can create a second
ancestor window that inherits from the ancestor window in which you defined
ue_ct_menu_enable. In the second ancestor window, you can override the
ue_ct_menu_enable event script so that the appropriate menu options are
enabled.
212 PowerBuilder
C H A P T E R 9 Working with Structures
About this chapter This chapter describes how to build and use structures.
Contents
Topic Page
About structures 213
Defining structures 214
Modifying structures 217
Using structures 217
About structures
A structure is a collection of one or more related variables of the same or
different datatypes grouped under a single name. In some languages, such
as Pascal and COBOL, structures are called records.
Structures allow you to refer to related entities as a unit rather than
individually. For example, if you define the user’s ID, address, access
level, and a picture (bitmap) of the employee as a structure called
s_employee, you can then refer to this collection of variables as
s_employee.
Two kinds There are two kinds of structures:
• Global structures, which are not associated with any object in your
application. You can declare an instance of the structure and reference
the instance in any script in your application.
• Object-level structures, which are associated with a particular type of
window, menu, or user object, or with the Application object. These
structures can always be used in scripts for the object itself. You can
also choose to make the structures accessible from other scripts.
Defining structures
Although you define object-level structures in the painter for a specific object
and global structures in the Structure painter, in both cases you define the
structure in a Structure view. The following sections describe each of the steps
you take to define a new structure:
1 Open a Structure view.
2 For object-level structures, name the structure.
3 Define the variables that make up the structure.
4 Save the structure.
Opening a Structure How you open the Structure view depends on whether you are defining an
view object-level structure or a global structure.
214 PowerBuilder
CHAPTER 9 Working with Structures
A structure as a variable
A variable in a structure can itself be a structure. Specify the structure’s
name as the variable's datatype.
216 PowerBuilder
CHAPTER 9 Working with Structures
Modifying structures
To modify a structure:
1 Do one of the following:
• In the Open dialog box, select the global structure you want to modify.
• Open the painter for the object that contains the object-level structure
and select the structure from the Structure List view.
If the Structure List view is not open, select it from the View menu.
2 Review the variable information displayed in the Structure view and
modify the structure as necessary.
To insert a variable before an existing variable, highlight it and select
Insert>Row from the menu bar or Insert Row from the pop-up menu.
To delete a variable, select Delete Row from the pop-up menu.
3 Save the modified structure.
Building a similar If you want to create a structure that is similar to one that already exists, you
structure can use the existing structure as a starting point and modify it.
Using structures
After you define the structure, you can:
• Reference an instance of the structure in scripts and functions
Referencing structures
When you define a structure, you are defining a new datatype. You can use this
new datatype in scripts and user-defined functions as long as the structure
definition is stored in a library in the application's library search path.
218 PowerBuilder
CHAPTER 9 Working with Structures
Example Assume that the structure str_custdata is defined for the window
w_history and you are writing a script for a CommandButton in the window. To
use the structure definition in the script, you write:
str_custdata lstr_cust1
lstr_cust1.name = "Joe"
Copying structures
To copy the values of a structure to another structure of the same type:
• Assign the structure to be copied to the other structure using this syntax:
struct1 = struct2
PowerBuilder copies all the variable values from struct2 to struct1.
Example These statements copy the values in lstr_emp2 to lstr_emp1:
str_empdata lstr_emp1, lstr_emp2
...
lstr_emp1 = lstr_emp2
220 PowerBuilder
PA RT 4 Working with Windows
About this chapter This chapter describes how to build windows in the Window painter.
Contents
Topic Page
About windows 223
Types of windows 225
About the Window painter 228
Building a new window 229
Viewing your work 238
Writing scripts in windows 239
Running a window 242
Using inheritance to build a window 243
About windows
Windows form the interface between the user and a PowerBuilder
application. Windows can display information, request information from
a user, and respond to the user’s mouse or keyboard actions.
A window consists of:
• Properties that define the window’s appearance and behavior
For example, a window might have a title bar or a minimize box.
• Events
Windows have events like other PowerBuilder objects.
• Controls placed in the window
At the window level When you create a window, you specify its properties in the Window
painter’s Properties view. You can also dynamically change window
properties in scripts during execution.
You can write scripts for window events that specify what happens when a
window is manipulated. For example, you can connect to a database when a
window is opened by coding the appropriate statements in the script for the
window’s Open event.
At the control level You place PowerBuilder controls, such as CheckBox, CommandButton, or
MultiLineEdit controls, in the window to request and receive information from
the user and to present information to the user.
After you place a control in the window, you can define the style of the control,
move and resize it, and build scripts to determine how the control responds to
events.
Designing windows
The Microsoft Windows operating environment has certain standards that
graphical applications are expected to conform to. Windows, menus, and
controls are supposed to look and behave in predictable ways from application
to application.
This chapter describes some of the guidelines you should follow when
designing windows and applications, but a full discussion is beyond the scope
of this book. You should acquire a book that specifically addresses design
guidelines for applications on the Windows platform and apply the rules when
you use PowerBuilder to create your application.
Building windows
When you build a window, you:
• Specify the appearance and behavior of the window by setting its
properties
• Add controls to the window
• Build scripts that determine how to respond to events in the window and
its controls
To support these scripts, you can define new events for the window and its
controls, and declare functions, structures, and variables for the window.
Two ways There are two ways to build a window. You can:
• Build a new window from scratch
224 PowerBuilder
CHAPTER 10 Working with Windows
You use this technique to create windows that are not based on existing
windows.
• Build a window that inherits its style, events, functions, structures,
variables, and scripts from an existing window
You use inheritance to create windows that are derived from existing
windows, thereby saving you time and coding.
For more information For information on building windows from scratch, see Building a new
window on page 229.
For information on using inheritance to build a window, see Using inheritance
to build a window on page 243.
Types of windows
PowerBuilder provides the following types of windows: main, pop-up, child,
response, Multiple Document Interface (MDI) frame, and MDI frame with
MicroHelp.
Main windows
Main windows are standalone windows that are independent of all other
windows. They can overlap other windows and can be overlapped by other
windows.
You use a main window as the anchor for your application. The first window
your application opens is a main window unless you are building a Multiple
Document Interface (MDI) application, in which case the first window is an
MDI frame.
For more on building MDI applications, see Application Techniques.
Using main windows Define your independent windows as main windows. For example, assume that
your application contains a calculator or scratch pad window that you want to
have always available to the user. Make it a main window, which can be
displayed at any time anywhere on the screen. As a main window, it can
overlap other windows on the screen.
Pop-up windows
Pop-up windows are typically opened from another window, which in most
cases becomes the pop-up window’s parent.
A pop-up window can display outside its parent window. It cannot be overlaid
by its parent. A pop-up window is hidden when its parent is minimized and
when its parent is closed. When you minimize a pop-up window, the icon for
the window displays at the bottom of the desktop.
Using pop-up Pop-up windows are often used as supporting windows. For example, say you
windows have a window containing master information, such as film listings. You can
use a pop-up window to allow a user to see details of a particular entry.
Explicitly naming a In most cases, the window that opens a pop-up window becomes that window's
parent parent. For example, if a script in w_go has this statement, w_go is the parent
of w_popup:
Open(w_popup)
You can also explicitly name a pop-up window’s parent when you use Open in
this way:
Open (popupwindow, parentwindow)
For example, the following statement opens w_popup and makes w_parent its
parent:
Open(w_popup, w_parent)
However, there are also other considerations regarding which window
becomes the parent of an opened window.
For more information, see the Open function in the PowerScript Reference.
Child windows
Child windows are always opened from within a main or pop-up window,
which becomes the child window’s parent.
226 PowerBuilder
CHAPTER 10 Working with Windows
A child window exists only within its parent. You can move the child window
within the parent window, but not outside the parent. When you move a portion
of a child window beyond the parent, PowerBuilder clips the child so that only
the portion within the parent window is visible. When you move the parent
window, the child window moves with the parent and maintains the same
position relative to the parent.
Child windows cannot have menus and are never considered the active
window. They can have title bars and can be minimizable, maximizable, and
resizable. When they are maximized, they fill the space of their parent; when
they are minimized, their icon displays at the bottom of their parent.
The initial position of the child is relative to the parent and not to the entire
screen. A child window closes when you close its parent.
You will probably not use child windows very often. Typically, if you want to
display windows inside other windows, you will write MDI applications,
where much of the window management happens automatically.
For more on building MDI applications, see Application Techniques.
Response windows
Response windows request information from the user. They are always opened
from within another window (its parent). Typically, a response window is
opened after some event occurs in the parent window.
Response windows are application modal. That is, when a response window
displays, it is the active window (it has focus) and no other window in the
application is accessible until the user responds to the response window. The
user can go to other applications, but when the user returns to the application,
the response window is still active. Response windows act like modal pop-up
windows.
Using response For example, if you want to display a confirmation window when a user tries
windows to close a window with unsaved changes, use a response window. The user is
not allowed to proceed until the response window is closed.
Using message boxes PowerBuilder also provides message boxes, which are predefined windows
that act like response windows in that they are application modal. You open
message boxes using the PowerScript MessageBox function.
For more information, see MessageBox in the PowerScript Reference.
MDI frames
An MDI window is a frame window in which you can open multiple document
windows (sheets) and move among the sheets. There are two types of MDI
frame windows: MDI frame and MDI frame with MicroHelp.
For more on building MDI applications, see Application Techniques.
228 PowerBuilder
CHAPTER 10 Working with Windows
This illustration shows the Layout view at the top of one of the stacks.
The Window painter opens. The new window displays in the Window
painter’s Layout view and its default properties display in the Properties
view.
230 PowerBuilder
CHAPTER 10 Working with Windows
Choosing a window You can change the background color of your window.
color
232 PowerBuilder
CHAPTER 10 Working with Windows
Choosing the window If the window can be minimized, you can specify an icon to represent the
icon minimized window. If you do not choose an icon, PowerBuilder uses the
application icon for the minimized window.
Specifying the You can specify a value between 1 and 100% for the Transparency property of
window’s a window. This property is useful if you want a non-modal dialog box to remain
transparency
visible but become semi-transparent when it loses focus.
Opening and closing You can use a special effect when a window opens or closes. Effects include
windows with an fading in or out, opening from the center, and sliding or rolling from the top,
animated effect
bottom, left, or right. You specify animation effects with the OpenAnimation,
CloseAnimation, and AnimationTime properties. Set the AnimationTime
property to between 1 and 5000 milliseconds to specify how long the animation
effect takes to complete.
For example, if your application displays a splash screen while the
application’s main window is initializing, you can set the splash screen’s
CloseAnimation property to have the window fade out rather than just
disappearing when the application is initialized or after a timeout by setting the
CloseAnimation property to FadeAnimation!.
234 PowerBuilder
CHAPTER 10 Working with Windows
Option Meaning
UnitsPerLine The number of PowerBuilder units to scroll up or down
when the user clicks the up or down arrow in the vertical
scroll bar. When the value is 0 (the default), it scrolls 1/100
the height of the window.
UnitsPerColumn The number of PowerBuilder units to scroll right or left
when the user clicks the right or left arrow in the horizontal
scroll bar. When the value is 0 (the default), it scrolls 1/100
the width of the window.
ColumnsPerPage The number of columns to scroll when the user clicks the
horizontal scroll bar itself. When the value is 0 (the
default), it scrolls 10 columns.
Option Meaning
LinesPerPage The number of lines to scroll when the user clicks the
vertical scroll bar itself. When the value is 0 (the default),
it scrolls 10 lines.
Adding controls
When you build a window, you place controls, such as CheckBox,
CommandButton, and MultiLineEdit controls, in the window to request and
receive information from the user and to present information to the user.
After you place a control in the window, you can define its style, move and
resize it, and write scripts to determine how the control responds to events.
For more information, see Chapter 11, Working with Controls.
236 PowerBuilder
CHAPTER 10 Working with Windows
To save a window:
1 Select File>Save from the menu bar.
If you have previously saved the window, PowerBuilder saves the new
version in the same library and returns you to the Window painter
workspace.
If you have not previously saved the window, PowerBuilder displays the
Save Window dialog box.
2 Name the window in the Windows text box (see below).
3 Type comments in the Comments text box to describe the window.
These comments display in the Select Window window and in the Library
painter. It is a good idea to use comments so you and others can easily
remember the purpose of the window later.
4 Specify the library where you want to save the window.
5 Click OK.
Naming the window The window name can be any valid PowerBuilder identifier of up to 40
characters. For information about PowerBuilder identifiers, see the
PowerScript Reference.
A commonly used convention is to preface all window names with w_ and use
a suffix that helps you identify the particular window. For example, you might
name a window that displays employee data w_empdata.
Previewing a window
As you develop a window, you can preview its appearance from the Window
painter. By previewing the window, you get a good idea of how it will look
during execution.
To preview a window:
• Click the Preview button in the PainterBar (not the PowerBar), or select
Design>Preview from the menu bar.
PowerBuilder minimizes and the window displays with the properties you
have defined, such as title bar, menu, Minimize box, and so on.
What you can do While previewing the window, you can get a sense of its look and feel. You can:
• Move the window
• Resize it (if it is resizable)
• Maximize, minimize, and restore it (if these properties were enabled)
• Tab from control to control
• Select controls
What you cannot do You cannot:
• Change properties of the window
Changes you make while previewing the window, such as resizing it, are
not saved.
• Trigger events
238 PowerBuilder
CHAPTER 10 Working with Windows
Print settings
You can view and change the print settings in the Library painter. Select
any PowerBuilder object, then select Entry>Library Item>Print from the
menu bar.
240 PowerBuilder
CHAPTER 10 Working with Windows
All properties, events, and built-in functions for all PowerBuilder objects,
including windows, and each type of control are described in Objects and
Controls.
Examples of statements
The following assignment statement in the script for the Clicked event for a
CommandButton changes the text in the StaticText object st_greeting when the
button is clicked:
st_greeting.Text = "Hello User"
The following statement tests the value entered in the SingleLineEdit sle_state
and displays the window w_state1 if the text is "AL":
if sle_State.Text= "AL" then Open(w_state1)
Running a window
During development, you can test a window without running the whole
application.
You can preview a window from the Window painter using the Preview button
on the PainterBar or run the window by clicking the Preview button on the
PowerBar. The PowerTip text for this button is Run/Preview Object. For
information about previewing using the PainterBar button, see Previewing a
window on page 238.
242 PowerBuilder
CHAPTER 10 Working with Windows
When you run the window using the PowerBar button, you must save the
window first. You can also trigger events and open other windows because the
window is functional.
To run a window:
1 Click the Preview button in the PowerBar (not the PainterBar).
2 In the Run/Preview dialog box, select Windows as the Objects of Type.
3 Select the target that includes the window you want to run.
4 Select the library that includes the window.
5 Select the window you want to run and click OK.
You must save your work before running a window. If you have not saved
your work, PowerBuilder prompts you to do so.
PowerBuilder runs the window.
You can trigger events, open other windows, connect to a database, and so on
when running a window. The window is fully functional. It has access to global
variables that you have defined for the application and to built-in global
variables, such as SQLCA. The SystemError event is not triggered if there is
an error, because SystemError is an Application object event.
The only differences in the second window, w_customer, are that the title is
Customer Data, the drop-down list displays customer files instead of employee
files, and there is a Delete button so the user can delete files.
Your choices To build these windows, you have three choices:
244 PowerBuilder
CHAPTER 10 Working with Windows
Note You cannot inherit a window from an existing window when the
existing window is open, and you cannot open a window when its ancestor
or descendant is open.
2 Select File>Inherit, select w_ancestor in the Inherit From dialog box, and
click OK.
3 Add the Employee Data title, specify that the DropDownListBox control
displays employee files, and save the window as w_employee.
4 Select File>Inherit, select w_ancestor in the Inherit From dialog box, and
click OK.
5 Add the Customer Data title, specify that the DropDownListBox control
displays customer files, add the Delete button, and save the window as
w_customer.
All public instance variables with simple datatypes such as integer, boolean,
character, date, string, and so on display. Instance variables with the any or blob
data type or instance variables that are objects or arrays do not display.
246 PowerBuilder
CHAPTER 10 Working with Windows
248 PowerBuilder
C H A P T E R 11 Working with Controls
About this chapter Users run your application primarily by interacting with the controls you
place in windows. This chapter describes the use of controls.
Contents
Topic Page
About controls 249
Inserting controls in a window 250
Selecting controls 251
Defining a control's properties 252
Naming controls 252
Changing text 255
Moving and resizing controls 256
Copying controls 259
Defining the tab order 260
Defining accelerator keys 262
Specifying accessibility of controls 263
Choosing colors 264
Using the 3D look 266
Using the individual controls 267
About controls
About window controls You place controls in a window to request and receive information from
the user and to present information to the user. For a complete list of
standard window controls, open a window in the Window painter and
select Insert>Control.
If you often use a control or set of controls with certain properties, such as
a group of related radio buttons, you can create a visual user object that
contains the control or set of controls. For more about user objects, see
Chapter 14, Working with User Objects.
About events All window controls have events so that users can act on the controls. You write
scripts that determine the processing that takes place when an event occurs in
the control.
Drawing controls are usually used only to make your window more attractive
or to group controls. Only constructor and destructor events are defined for
them, but you can define your own events if needed. The drawing controls are
Line, Oval, Rectangle, and RoundRectangle.
250 PowerBuilder
CHAPTER 11 Working with Controls
Placing OLE controls You can place objects from applications that support OLE, such as Excel
worksheets and Visio drawings, in your windows. For information about using
OLE with PowerBuilder, see Application Techniques.
Selecting controls
You select controls so that you can change their properties or write scripts using
the Layout view or the Control List view.
To select a control:
• Click the control in the Layout view, or click the control in the Control List
view.
In the Layout view, the control displays with handles on it. Previously
selected controls are no longer selected.
Acting on multiple You can act on all or multiple selected controls as a unit. For example, you can
controls move all of them or change the fonts for all the text displayed in the controls.
Information displayed The name, x and y coordinates, width, and height of the selected control are
in the MicroHelp bar displayed in the MicroHelp bar. If you select multiple objects, Group
Selected displays in the Name area and the coordinates and size do not
display.
Naming controls
When you place a control in a window, PowerBuilder assigns it a unique name.
The name is the concatenation of the default prefix for the control name and
the lowest 1- to 4-digit number that makes the name unique.
For example, assume the prefix for ListBoxes is lb_ and you add a ListBox to
the window:
• If the names lb_1, lb_2, and lb_3 are currently used, the default name is lb_4
• If lb_1 and lb_3 are currently used but lb_2 is not, the default name is lb_2
252 PowerBuilder
CHAPTER 11 Working with Controls
Control Prefix
StaticHyperLink shl_
Tab tab_
TreeView tv_
User Object uo_
VProgressBar vpb_
VScrollBar vsb_
VTrackBar vtb_
254 PowerBuilder
CHAPTER 11 Working with Controls
Changing text
You can specify the text and text display characteristics for a control in the
Properties view for the control. You can also use the Window painter StyleBar
to change:
• The text itself
• The font, point size, and characteristics such as bold
• The alignment of text within the control
CommandButton text
Text in CommandButtons is always center aligned.
The default text for most controls that have a text property is none. To display
an empty StaticText or SingleLineEdit control, clear the Text box in the
Properties view or the StyleBar.
When you add text to a control’s text property, the width of the control changes
automatically to accommodate the text as you type it in the StyleBar, or when
you tab off the Text box in the Properties view.
You can specify text size in pixels if you want, by using positive numbers. The
following statement sets the text size to be 14 pixels:
st_prompt.TextSize = 14
256 PowerBuilder
CHAPTER 11 Working with Controls
To align controls:
1 Select the control whose position you want to use to align the others.
PowerBuilder displays handles around the selected control.
2 Press and hold the Ctrl key and click the controls you want to align with
the first one.
All the selected controls have handles on them.
3 Select Format>Align from the menu bar, or select the Layout drop-down
toolbar in PainterBar3.
4 Select the dimension along which you want to align the controls.
PowerBuilder aligns all the selected controls with the first control
selected.
258 PowerBuilder
CHAPTER 11 Working with Controls
4 Select the size for width, height, or both width and height.
Copying controls
You can copy controls within a window or to other windows. All properties of
the control, as well as all of its scripts, are copied. You can use this technique
to make a copy of an existing control and change what you want in the copy.
To copy a control:
1 Select the control.
2 Select Edit>Copy from the menu bar or press Ctrl+C.
The control is copied to a private PowerBuilder clipboard.
3 Do one of the following:
• To copy the control within the same window, select Edit>Paste
Controls from the menu bar or press Ctrl+V.
• To copy the control to another window, click the Open button in the
PowerBar and open the window in another instance of the Window
painter. Make that window active and select Edit>Paste Controls from
the menu bar or press Ctrl+V.
If the control you are pasting has the same name as a control that
already exists in the window, the Paste Control Name Conflict dialog
box displays.
4 If prompted, change the name of the pasted control to be unique.
PowerBuilder pastes the control in the destination window at the same
location as in the source window. If you are pasting into the same window,
move the pasted control so it does not overlay the original control. You can
make whatever changes you want to the copy; the source control will be
unaffected.
When you add a control to the window, PowerBuilder obtains the tab value of
the control that precedes the new control in the tab order and assigns the new
control the next number.
For example, if the tab values for controls A, B, and C are 30, 10, and 20
respectively and you add control D between controls A and B, PowerBuilder
assigns control D the tab value 40.
260 PowerBuilder
CHAPTER 11 Working with Controls
2 Use the mouse or the Tab key to move the pointer to the tab value you want
to change.
3 Enter a new tab value from 0 to 9999.
The value 0 removes the control from the tab order. It does not matter
exactly what value you use, other than 0. Only the relative value is
significant. For example, if you want the user to tab to control B after
control A but before control C, set the tab value for control B so it is
between the value for control A and the value for control C.
Tab tips
A tab order value of 0 does not prevent a control from being selected or
activated or from receiving keyboard events. To prevent a user from
activating a control with the mouse, clear the Enabled check box on its
General property page.
To permit tabbing in a group box, change the tab value of the GroupBox
control to 0, then assign nonzero tab values to the controls in the group
box.
4 Repeat the procedure until you have the tab order you want.
5 Select Format>Tab Order or the Tab Order button again.
PowerBuilder saves the tab order.
Each time you select Tab Order, PowerBuilder renumbers the tab order values
to include any controls that have been added to the window and to allow space
to insert new controls in the tab order. For example, if the original tab values
for controls A, B, and C were 10, 20, and 30, and you insert control D between
A and B and give it a tab value of 15, when you select tab order again, the
controls A, B, and C will have the tab values 10, 30, and 40, and control D will
have the tab value 20.
Displaying an ampersand
If you want to display an ampersand character in the text of a control, type
a double ampersand. The first ampersand acts as an escape character.
262 PowerBuilder
CHAPTER 11 Working with Controls
2 In the General tab page, type the letter of the accelerator key in the
Accelerator box.
For example, if the control contains a user’s name and you want to make
Alt+N the accelerator for the control, type n in the Accelerator box.
At this point you have defined the accelerator key, but the user has no way
of knowing it, so you need to label the control.
3 Place a StaticText control next to the control that was assigned the
accelerator key.
4 Click the StaticText control to display its properties in the Properties view.
5 In the Text box on the General page, precede the letter that you want to use
as the accelerator key with an ampersand character (&).
For example, if the StaticText control will display the label Name, type
&Name in the Text box so that the letter N is underlined. Now your user
knows that there is an accelerator key associated with the control.
Choosing colors
The Window painter has two Color drop-down toolbars on PainterBar3 that
display colors that you can use for the background and foreground of
components of the window. Initially, the drop-down toolbars display these
color selections:
• 20 predefined colors
• 16 custom colors (labeled C)
• The full set of Windows system colors
Windows system The Windows system colors display in the same order as in the TextColor and
colors BackColor lists in the Properties view for a control. They are labeled with
letters that indicate the type of display element they represent:
• W for windows
• T for text in windows, title bars, menus, buttons, and so on
• A for the application workspace
• B for button face, highlight, shadows, and borders
• S for scroll bars
• D for the desktop
• M for menu bars
• F for window frames
• H for highlight
264 PowerBuilder
CHAPTER 11 Working with Controls
• L for links
The Windows system colors are those defined by the user in the Windows
Control Panel, so if you use these colors in your window, the window colors
will change to match the user’s settings at runtime.
Defining custom You can define your own custom colors for use in windows, user objects, and
colors DataWindow objects.
Specifying foreground You can assign colors to controls using the Painterbar or the Properties view.
and background The page in the Properties view that you use depends on the control. For some
colors
controls you can change only the background color, and for others you can
change neither the foreground nor the background color. These controls
include CommandButton, PictureButton, PictureHyperLink, Picture,
ScrollBar, TrackBar, ProgressBar, and OLE controls.
266 PowerBuilder
CHAPTER 11 Working with Controls
Use this feature if you want to place a control containing a picture on a window
and have the picture blend in with the background color of the window when
the window's background is using Button Face for a 3D effect. The control’s
picture takes on the 3D colors the user has selected.
The window’s background must be set to Button Face. To make the image
blend in with the window, give it a background color in the range between
RGB(160,160,160) and RGB(223,223,223), such as silver. Lighter shades of
gray map to the button highlight color and darker shades to the button shadow
color.
This option can affect other colors used in the bitmap. It does not affect the
control’s border settings, and it has no effect if there is no image associated
with the control.
How to use the You should use the controls only for the purpose shown in the table. For
controls example, users expect radio buttons for selecting an option. Do not use a radio
button also to invoke an action, such as opening a window or printing. Use a
command button for that.
There are, however, several exceptions: user objects can be created for any
purpose, and ListBoxes, ListViews, TreeViews, and Tabs are often used both
to display data and to invoke actions. For example, double-clicking a ListBox
item often causes some action to occur.
Individual controls The following sections describe some features that are unique to individual
controls. The controls are listed in the order in which they display on the
Insert>Control menu and the drop-down controls palette:
• CommandButton on page 269
• PictureButton on page 270
• CheckBox on page 271
• RadioButton on page 271
• StaticText on page 272
• StaticHyperLink on page 273
• Picture on page 274
• PictureHyperLink on page 274
• GroupBox on page 275
• Drawing controls on page 275
• SingleLineEdit and MultiLineEdit on page 276
• EditMask on page 276
• HScrollBar and VScrollBar on page 279
• HTrackBar and VTrackBar on page 279
• HProgressBar and VProgressBar on page 280
• DropDownListBox on page 280
• DropDownPictureListBox on page 281
• ListBox on page 282
• PictureListBox on page 283
• ListView on page 286
• TreeView on page 289
• Tab on page 292
• MonthCalendar on page 296
• DatePicker on page 297
• Animation on page 300
• InkEdit and InkPicture on page 301
268 PowerBuilder
CHAPTER 11 Working with Controls
CommandButton
CommandButtons are used to carry out actions. For example, you can use an
OK button to confirm a deletion or a Cancel button to cancel a requested
deletion. If there are many related CommandButtons, place them along the
right side of the window; otherwise, place them along the bottom of the
window.
You cannot change the color or alignment of text in a CommandButton.
If clicking the button opens a window that requires user interaction before any
other action takes place, use ellipsis points in the button text; for example,
“Print...”.
A bold border is placed around the default CommandButton (or the button with
focus if the user explicitly tabs to a CommandButton).
You can define a CommandButton as being the cancel button by selecting
Cancel in the General property page in the button’s Properties view. If you
define a cancel CommandButton, the cancel button’s Clicked event is triggered
when the user presses the Esc key.
PictureButton
PictureButtons are identical to CommandButtons in their functionality. The
only difference is that you can specify a picture to display on the button. The
picture can be a bitmap (BMP) file, a GIF or animated GIF file, a JPEG file, a
PNG file, a run-length encoded (RLE) file, or an Aldus-style Windows
metafile (WMF).
You can choose to display one picture if the button is enabled and a different
picture if the button is disabled.
Use these controls when you want to be able to represent the purpose of a
button by using a picture instead of text.
To specify a picture:
1 Select the PictureButton to display its properties in the Properties view.
2 On the General tab page, enter the name of the image file you want to
display when the button is enabled, or use the Browse button and choose
a file.
3 Enter the name of the image file you want to display when the button is
disabled, or use the Browse Disabled button and choose a file.
If the PictureButton is defined as initially enabled, the enabled picture
displays in the Layout view. If the PictureButton is defined as initially
disabled, the disabled picture displays in the Layout view.
270 PowerBuilder
CHAPTER 11 Working with Controls
CheckBox
CheckBoxes are square boxes used to set independent options. When they are
selected, they contain a check mark; when they are not selected, they are empty.
CheckBoxes are independent of each other. You can group them in a GroupBox
or rectangle to make the window easier to understand and use, but that does not
affect the CheckBoxes’ behavior; they are still independent.
Using three states CheckBoxes usually have two states: on and off. But sometimes you need to
represent a third state, such as Unknown. The third state displays as a grayed
box with a check mark.
RadioButton
RadioButtons are round buttons that represent mutually exclusive options.
They always exist in groups. Exactly one RadioButton is selected in each
group.
When a RadioButton is selected, it has a dark center; when it is not selected,
the center is blank.
In the following example, the text can be either plain, bold, or italic (plain is
selected):
When the user clicks a RadioButton, it becomes selected and the previously
selected RadioButton in the group becomes deselected.
Use RadioButtons to represent the state of an option. Do not use them to invoke
actions.
When a window opens, one RadioButton in a group must be selected. You
specify which is the initially selected RadioButton by selecting the Checked
property in the General property page in the RadioButton’s Properties view.
Grouping By default, all RadioButtons in a window are in one group, no matter what their
RadioButtons location in the window. Only one RadioButton can be selected at a time.
You use a GroupBox control to group related RadioButtons. All RadioButtons
inside a GroupBox are considered to be in one group. One button can be
selected in each group.
The Automatic When a window contains several RadioButtons that are outside of a GroupBox,
property the window acts as a GroupBox. Only one RadioButton can be active at a time
unless the check box for the Automatic property on the RadioButton’s General
property page is cleared.
When the Automatic property is not set, you must use scripts to control when
a button is selected. Multiple RadioButtons can be selected outside of a group.
The Automatic property does not change how RadioButtons are processed
inside a GroupBox.
StaticText
You use a StaticText control to display text to the user or to describe a control
that does not have text associated with it, such as a list box or edit control.
272 PowerBuilder
CHAPTER 11 Working with Controls
The user cannot change the text, but you can change the text for a StaticText
control in a script by assigning a string to the control's Text property.
StaticText controls have events associated with them, but you will probably
seldom write scripts for them because users do not expect to interact with static
text.
Indicating accelerator One use of a StaticText control is to label a list box or edit control. If you assign
keys an accelerator key to a list box or edit control, you need to indicate the
accelerator key in the text that labels the control. Otherwise, the user would
have no way of knowing that an accelerator key is defined for the control. This
technique is described in Defining accelerator keys on page 262.
Indicating a border You can select a border style using the BorderStyle property on the General
style property page.
StaticHyperLink
A StaticHyperLink is display text that provides a hot link to a specified Web
page. When a user clicks the StaticHyperLink in a window, the user’s Web
browser opens to display the page.
The StaticHyperLink control has a URL property that specifies the target of the
link. You specify the text and URL on the StaticHyperLink control’s General
tab page in the Properties view.
If you know that your users have browsers that support URL completion, you
can enter a partial address—for example, appeon.com instead of the complete
address, https://www.appeon.com.
When the StaticHyperLink control is in an MDI Frame window with
MicroHelp, the URL you specify displays in the status bar when the user’s
pointer is over the control.
A hand is the default pointer and blue underlined text is the default font. To
change the pointer, use the Other property page. To change the font, use the
Font property page.
Picture
Pictures are PowerBuilder-specific controls that display a bitmap (BMP) file,
a GIF or animated GIF file, a JPEG file, a PNG file, a run-length encoded
(.RLE) file, or an Aldus-style Windows metafile (WMF).
To display a picture:
1 Place a picture control in the window.
2 In the General tab page in the Properties view, enter in the PictureName
text box the name of the file you want to display, or browse to select a file.
The picture displays.
You can choose to resize or invert the image.
If you try to insert a very large image into a picture control, the image may fail
to display. The maximum size that will display depends on the version of
Windows, the graphics card and driver, and the available memory. Compressed
files must be decompressed to display. Failure to display is most likely to occur
with JPEG files because the JPEG standard supports very high compression
and the decompressed content may be many times larger than the size of the
JPEG file.
Be careful about how you use picture controls. They can serve almost any
purpose. They have events, so users can click on them, but you can also use
them simply to display images. Be consistent in their use so users know what
they can do with them.
PictureHyperLink
A PictureHyperLink is a picture that provides a hot link to a specified Web
page. When a user clicks the PictureHyperLink in a window, the user’s Web
browser opens to display the page.
The PictureHyperLink control has a URL property that specifies the target of
the link. You specify the picture and URL in the PictureHyperLink control’s
Properties view in the General tab page. If you know that your users have
browsers that support URL completion, you can enter a partial address—for
example, appeon.com—instead of the complete address,
https://www.appeon.com.
274 PowerBuilder
CHAPTER 11 Working with Controls
A hand is the default pointer. To change the pointer, use the Other property
page.
The PictureHyperLink control is a descendant of the Picture control. Like a
Picture control, a PictureHyperLink control can display a bitmap (BMP) file, a
GIF or animated GIF file, a JPEG file, a PNG file, a run-length encoded (RLE)
file, or an Aldus-style Windows metafile (WMF).
You display a picture in a PictureHyperLink control in the same way you
display a picture in a picture control. For more information, see Picture on page
274.
GroupBox
You use a GroupBox to group a set of related controls. When a user tabs from
another control to a GroupBox, or selects a GroupBox, the first control in the
GroupBox gets focus. To tab between controls in a GroupBox, set the tab value
of the GroupBox to 0 and assign a tab value to each control within it.
All RadioButtons in a GroupBox are considered to be in a group. For more
information about using RadioButtons in GroupBoxes, see RadioButton on
page 271.
Drawing controls
PowerBuilder provides the following drawing controls: Line, Oval, Rectangle,
and RoundRectangle. Drawing controls are usually used only to enhance the
appearance of a window or to group controls. However, constructor and
destructor events are available, and you can define your own unmapped events
for a drawing control. A drawing control does not receive Windows messages,
so a mapped event would not be useful.
You can use the following functions to manipulate drawing controls at runtime:
Hide
Move
Resize
Show
In addition, each drawing control has a set of properties that define its
appearance. You can assign values to the properties in a script to change the
appearance of a drawing control.
Never in front
You cannot place a drawing control on top of another control that is not a
drawing control, such as a GroupBox. Drawing controls always appear behind
other controls whether or not the Bring to Front or Send to Back items on the
pop-up menu are set. However, drawing controls can be on top of or behind
other drawing controls.
EditMask
Sometimes users need to enter data that has a fixed format. For example, U.S.
and Canadian phone numbers have a three-digit area code, followed by three
digits, followed by four digits. You can use an EditMask control that specifies
that format to make it easier for users to enter values. Think of an EditMask
control as a smart SingleLineEdit: it knows the format of the data that can be
entered.
276 PowerBuilder
CHAPTER 11 Working with Controls
An edit mask consists of special characters that determine what can be entered
in the box. An edit mask can also contain punctuation characters to aid the user.
For example, to make it easier for users to enter phone numbers in the proper
format, you can specify the following mask, where # indicates a number:
(###) ###-####
At runtime, the punctuation characters (the parentheses and dash) display in the
box and the cursor jumps over them as the user types.
Masks in EditMask controls in windows work in a similar way to masks in
display formats and in the EditMask edit style in DataWindow objects. For
more information about specifying masks, see the discussion of display
formats in Chapter 21, Displaying and Validating Data.
Validation for The EditMask control checks the validity of a date when you enter it, but if you
EditMask controls change a date so that it is no longer valid, its validity is not checked when you
tab away from the control. For example, if you enter the date 12/31/2016 in an
EditMask control with the mask mm/dd/yyyy, you can delete the 1 in 12, so that
the date becomes 02/31/2016. To catch problems like this, add validation code
to the LoseFocus event for the control.
Keyboard behavior Some keystrokes have special behavior in EditMask controls. For more
information, see The EditMask edit style on page 630.
Using a drop-down You can use a drop-down calendar that is similar to the DatePicker control in
calendar EditMask controls that have a Date or DateTime edit mask. The user can
choose to edit the date in the control or to select a date from a drop-down
calendar.
To specify that an EditMask control uses a drop-down calendar to display and
set dates, select the Drop-down Calendar check box on the Mask page in the
Properties view. You can set display properties for the calendar on the Calendar
page. Users navigate and select dates within the calendar as they do in the
calendar in a DatePicker control.
Using spin controls You can define an EditMask as a spin control, which is an edit control that
contains up and down arrows that users can click to cycle through fixed values.
For example, assume you want to allow your users to select how many copies
of a report to print. You could define an EditMask as a spin control that allows
users to select from a range of values.
278 PowerBuilder
CHAPTER 11 Working with Controls
Use a trackbar when you want the user to select a discrete value. For example,
you might use a trackbar to enable a user to select a timer interval or the size
of a window.
You can set properties such as minimum and maximum values, the frequency
of tick marks, and the location where tick marks display.
You can highlight a range of values in the trackbar with the SelectionRange
function. The range you select is indicated by a black fill in the channel and an
arrow at each end of the range. This is useful if you want to indicate a range of
preferred values. In a scheduling application, the selection range could indicate
a block of time that is unavailable. Setting a selection range does not prevent
the user from selecting a value either inside or outside the range.
You can see an example of a window with a trackbar in the PowerBuilder Code
Examples sample application in the Examples subdirectory in your
PowerBuilder directory. See the w_trackbars window in PBEXAMW3.PBL.
DropDownListBox
DropDownListBoxes combine the features of a SingleLineEdit and a ListBox.
280 PowerBuilder
CHAPTER 11 Working with Controls
• Type a character. The ListBox scrolls to the first entry in the list that begins
with the typed character. Typing the character again scrolls to the next
entry that begins with the character, unless the character can be combined
with the first to match an entry.
• Click the down arrow to the right of the edit control to display the list, then
select the one you want.
Editable boxes If you want to give users the option of specifying a value that is not in the list,
make the DropDownListBox editable by selecting the AllowEdit check box on
the General tab page.
With editable DropDownListBoxes, you can choose to have the list always
display or not. For the latter type, the user can display the list by clicking the
down arrow.
Populating the list You specify the list in a DropDownListBox the same way as for a ListBox. For
information, see ListBox on page 282.
Specifying the size of To indicate the size of the box that drops down, size the control in the Window
the drop-down box painter using the mouse. When the control is selected in the painter, the full
size—including the drop-down box—is shown.
Other properties As with ListBoxes, you can specify whether the list is sorted and whether the
edit control is scrollable.
For more information, right-click in any tab page in the Properties view and
select Help from the pop-up menu.
DropDownPictureListBox
DropDownPictureListBoxes are similar to DropDownListBoxes in the way
they present information. They differ in that DropDownListBoxes use only text
to present information, whereas DropDownPictureListBoxes add images to the
information.
Adding images to a You can choose from a group of stock images provided by PowerBuilder, or
DropDownPictureList use any bitmap (BMP), icon (ICO), GIF, JPEG, or PNG file when you add
Box
images to a DropDownPictureListBox. You use the same technique that you
use to add pictures to a PictureListBox. For more information, see Adding
images to a PictureListBox on page 284.
ListBox
A ListBox displays available choices. You can specify that ListBoxes have
scroll bars if more choices exist than can be displayed in the ListBox at one
time.
ListBoxes are an exception to the rule that a control should either invoke an
action or be used for viewing and entering data. ListBoxes can do both.
ListBoxes display data, but can also invoke actions. Typically in Windows
applications, clicking an item in the ListBox selects the item. Double-clicking
an item acts upon the item.
For example, in the PowerBuilder Open dialog box, clicking an object name in
a ListBox selects the object. Double-clicking a name opens the object’s painter.
PowerBuilder automatically selects (highlights) an item when a user selects it
at runtime. If you want something to happen when users double-click an item,
you must code a script for the control’s DoubleClicked event. The Clicked
event is always triggered before the DoubleClicked event.
Populating the list To add items to a ListBox, select the ListBox to display its properties in the
Properties view, select the Items tab, and enter the values for the list. Press tab
to go to the next line.
In the Items tab page, you can work with rows in this way:
To do this Do this
Select a row Click the row button on the left or with the cursor in the edit box,
press Shift+Space
Delete a row Select the row and press Delete
Move a row Click the row button and drag the row where you want it or press
Shift+Space to select the row and then press Ctrl+Up Arrow or
Ctrl+Down Arrow to move the row
Delete text Click the text and select Delete from the pop-up menu
282 PowerBuilder
CHAPTER 11 Working with Controls
Setting tab stops You can set tab stops for text in ListBoxes (and in MultiLineEdits) by setting
the TabStop property on the General property page. You can define up to 16 tab
stops. The default is a tab stop every eight characters.
You can also define tab stops in a script. Here is an example that defines two
tab stops and populates a ListBox:
// lb_1 is the name of the ListBox.
string f1, f2, f3
f1 = "1"
f2 = "Emily"
f3 = "Foulkes"
// Define 1st tab stop at character 5.
lb_1.tabstop[1] = 5
// Define 2nd tab stop 10 characters after the 1st.
lb_1.tabstop[2] = 10
// Add an item, separated by tabs.
// Note that the ~t must have a space on either side
// and must be lowercase.
lb_1.AddItem(f1 + " ~t " + f2 + " ~t " + f3)
Note that this script will not work if it is in the window’s Open event, because
the controls have not yet been created. The best way to specify this is in a user
event that is posted in the window’s Open event using the PostEvent function.
Other properties For ListBoxes, you can specify whether:
• Items in the ListBox are displayed in sorted order
• The ListBox allows the user to select multiple items
• The ListBox displays scroll bars if needed
For more information, right-click in any tab page in the Properties view for a
ListBox and select Help from the pop-up menu.
PictureListBox
A PictureListBox, like a ListBox, displays available choices in both text and
images. You can specify that PictureListBoxes have scroll bars if more choices
exist than can be displayed in the PictureListBox at one time.
Adding images to a You can choose from a group of stock images provided by PowerBuilder, or
PictureListBox use any bitmap (BMP), icon (ICO), GIF, JPEG, or PNG file when you add
images to a PictureListBox.
Keep in mind, however, that the images should add meaning to the list of
choices. If you use a large number of images in a list, they become
meaningless.
You could, for example, use images in a long list of employees to show the
department to which each employee belongs, so you might have a list with 20
or 30 employees, each associated with one of five images.
3 Specify a picture mask color (the color that will be transparent for the
picture).
4 Specify the height and width for the image in pixels or accept the defaults.
284 PowerBuilder
CHAPTER 11 Working with Controls
5 Repeat the procedure for the number of images you plan to use in your
PictureListBox.
6 Select the Items tab and change the Picture Index for each item to the
appropriate number.
7 Click OK.
On the Items tab page, you can work with rows in this way:
To Do this
Select a row Click the row button on the left, or with the cursor in the edit box,
press Shift+Space
Delete a row Select the row and press Delete
Move a row Click the row button and drag the row where you want it or press
Shift+Space to select the row and then press Ctrl+Up Arrow or
Ctrl+Down Arrow to move the row
Delete text Click the text and select Delete from the pop-up menu
On the Pictures tab page, you can work with rows in the same way, and also:
To Do this
Browse for a Select the row and click the Browse button or press F2
picture
For information about other properties, right-click in any tab page in the
Properties view and select Help from the pop-up menu.
ListView
A ListView control lets you display items and icons in a variety of
arrangements. You can display large or small icons in free-form lists. You can
add columns, pictures, and items to the ListView, and modify column
properties, using PowerScript functions such as AddColumn, AddLargePicture,
SetItem, SetColumn, and so on. For information about ListView functions, see
the online Help.
The following illustration from the Code Examples application shows a
ListView control used in a sales order application.
Adding ListView items Adding images to a ListView control is the same as adding images to a
and pictures PictureListBox. The ListView control’s Properties view has two tab pages for
adding pictures: Large Picture (default size 32 by 32 pixels) and Small Picture
(16 by 16 pixels).
For more information, see Adding images to a PictureListBox on page 284.
286 PowerBuilder
CHAPTER 11 Working with Controls
To Do this
Move a row Click the row button and drag the row where you want it, or
press Shift+Space to select the row and then press Ctrl+Up
Arrow or Ctrl+Down Arrow to move the row
Delete text Click the text and select Delete from the pop-up menu
Note Setting the picture index for the first item to zero clears all the
settings on the tab page.
3 Set properties for the item on the Large Picture, Small Picture, and/or State
tab pages as you did on the Items tab page.
On these pages, you can also browse for a picture. To do so, click the
browse button or press F2.
4 Repeat until all the items are added to the ListView.
Choosing a ListView You can display a ListView in four styles:
style
• Large icon
• Small icon
• List
• Report
Choose
To specify this tab
The border style General
Choose
To specify this tab
Whether the user can delete items General
The images for ListView items in Large Icon view Large Picture
The images for ListView items in Small Icon, list, and report Small Picture
views
The state images for ListView items State
The names and associated picture index for ListView items Items
The font size, family, and color for ListView items Font
The size and position of the ListView Other
The icon for the mouse pointer in the ListView Other
The icon for a drag item, and whether the drag-and-drop must Other
be performed programmatically
For more information on the ListView control, see Application Techniques. For
information about its properties, see Objects and Controls.
288 PowerBuilder
CHAPTER 11 Working with Controls
TreeView
You can use TreeView controls in your application to represent relationships
among hierarchical data. An example of a TreeView implementation is
PowerBuilder’s Browser. The tab pages in the Browser contain TreeView
controls.
Adding TreeView A TreeView consists of TreeView items that are associated with one or more
items and pictures pictures. You add images to a TreeView in the same way that you add images
to a PictureListBox.
For more information, see Adding images to a PictureListBox on page 284.
Working in the Properties view with the rows in the State or Pictures tab page
is the same as working with them in a ListView control. For information, see
ListView on page 286.
ll_tvi = tv_foo.finditem(currenttreeitem! , 0)
tv_foo.getitem(ll_tvi , tvi)
tvi.statepictureindex = 1
290 PowerBuilder
CHAPTER 11 Working with Controls
tv_foo.setitem(ll_tvi, tvi)
For more information on the TreeView control, see Application
Techniques.
Setting other
properties
Tab
A Tab control is a container for tab pages that display other controls. You can
add a Tab control to a window in your application to present information that
can logically be grouped together but may also be divided into distinct
categories. An example is the use of tab pages in the Properties view for objects
in PowerBuilder. Each tab page has a tab that displays the label for the tab page
and is always visible, whichever tab page is selected.
When you add a Tab control to a window, PowerBuilder creates a Tab control
with one tab page labeled “none”. The control is rectangular.
Selecting Tab controls You may find that you select the control when you want to select the page and
and tab pages vice versa. This Tab control has three tab pages. The TabPosition setting is
tabsontopandbottom!, so that the tab for the selected tab page and pages that
precede it in the tab order display at the top of the Tab control.
To select the Tab control, click any of the tabs where the label displays, or in
the area adjacent to the tabs, shown in gray here.
To select a tab page, click its tab and then click anywhere on the tab page except
the tab itself. The handles at the corners of the white area indicate that the tab
page is selected, not the Tab control.
Adding tab pages to a To add a new Tab control to a window, select Insert>Control>Tab and click in
Tab control the window. The control has one tab page when it is created. Use the following
procedure to add additional tab pages to the tab control.
292 PowerBuilder
CHAPTER 11 Working with Controls
Adding a reusable tab Once you have created a user object that can be used as a tab page, you can add
page to a Tab control it to a Tab control. You cannot add the user object to a Tab control if the user
object is open, and, after you have added the user object to the control, you
cannot open the user object and the window that contains the Tab control at the
same time.
294 PowerBuilder
CHAPTER 11 Working with Controls
The Tab control and all tab pages are moved as a group.
You can add controls only to a tab page created within the Tab control. To
add controls to an independent tab page, open it in the User Object painter.
To move a control between a tab page and the window containing the
Tab control:
• Cut or copy the control and paste it on the destination window or tab page.
Moving the control between a tab page and the window changes the control’s
parent, which affects scripts that refer to the control.
For more information on the Tab control, see the chapter on using tabs in a
window in Application Techniques.
MonthCalendar
A MonthCalendar control lets you display a calendar to your users to make it
easy for them to view and set date information. You can size the calendar to
show from one to twelve months. The following illustration shows a calendar
with three months. Today’s date is September 3, 2009, and the date November
28 has been selected.
If a user selects a date or a range of dates in the calendar, you can use the
GetSelectedDate or GetSelectedRange functions to obtain them. You use the
SetSelectedDate and SetSelectedRange functions to select dates
programmatically.
You can also:
• Set and get minimum and maximum dates that can be displayed in the
calendar
296 PowerBuilder
CHAPTER 11 Working with Controls
DatePicker
The DatePicker control provides an easy way for a user to select a single date.
The user can choose to edit the date in the control or to select a date from a
drop-down calendar. The calendar is similar to the MonthCalendar control,
which can be used to select a range of dates. As an alternative to the drop-down
calendar, you can set the ShowUpDown property to display up and down
arrows that allow users to specify one element of the date at a time.
The drop-down calendar can only be used to select a date. The up and down
arrows lets users specify a time as well as a date. The following illustration
shows three DatePicker controls. The controls on the left have the
ShowUpDown property set. One uses the standard date format, and the other
uses a custom format that displays the date and time. The control on the right
uses the default drop-down calendar option and the standard long date format.
You can set initial properties for the appearance and behavior of the control in
the Properties view. Properties that apply to the drop-down calendar portion of
the control are similar to the properties that apply to the MonthCalendar control
and display on the Calendar page in the Properties view. For example, you can
choose which day of the week displays as the first day in the week, whether the
current date is circled, and whether a “Today Section” showing the current date
displays at the bottom of the calendar.
Specifying a format You can choose to display the date in the DatePicker control as a long date, a
short date, a time, or with a custom format. To set a custom format in the
painter, select dtfCustom! from the Format list and type the format in the
Custom Format field. For example, the second control on the left in the
previous illustration uses the custom format yyyy/MM/dd HH:mm:ss. The
uppercase H for the hour format specifies a 24-hour clock. The following
statements set the Format property to use a custom format and set the
CustomFormat property to show the full name of the month, the day of the
month followed by a comma, and the four-digit year:
dp_1.Format = dtfCustom!
dp_1.CustomFormat = "MMMM dd, yyyy"
For a complete list of formats you can use, see the description of the
CustomFormat property in the online Help.
Specifying maximum The MaxDate and MinDate properties determine the range of dates that a user
and minimum dates can enter or pick in the control. If you set a restricted range, the calendar
displays only the months in the range you set, and if users type a date outside
the range into the control, the date reverts to its previous value.
Editing modes When a user tabs into a DatePicker control, the control is in normal editing
mode and behaves in much the same way as an EditMask control with a Date
or DateTime mask. Users can edit the part of the date (year, month, day, hour,
minutes, or seconds) that has focus using the up/down arrow keys on the
keyboard or, for numeric fields, the number keys. Use the left/right arrow keys
to move between parts of the date.
If the control has a drop-down calendar, users can navigate from one month or
year to another using the controls in the calendar and click to select a date. If
the ShowUpDown option is set, users can change the selected part of the date
or time with the up and down keys in the control. To navigate in the drop-down
calendar, a user can:
• Click the arrows in the top corners to move from month to month
• Click the month to display a list of months, then click a month to select it
298 PowerBuilder
CHAPTER 11 Working with Controls
• Click the year to display a spin control, then use the spin control’s arrows
to select a year
• Click a date to select the date and close the calendar
• Press the Esc key to close the calendar without changing the selection
Allowing users to edit You can give users a third way to change the date by setting the AllowEdit
the date directly property to “true”. The user can then press F2 or click in the control to select
all the text in the control for editing. When the control loses focus, the control
returns to normal editing mode and the UserString event is fired. The
UserString event lets you test whether the text the user entered in the control is
a valid date and set the value to the new date if it is valid. If it is valid, you can
use the event’s dtm by reference argument to set the value to the new date. This
code in the UserString event tests whether the date is valid and within range:
Date d
DateTime dt
IF IsDate(userstr) THEN
d = Date(usrstr)
IF (this.maxdate >= d and this.mindate <= d) THEN
dtm = DateTime(dt)
ELSE
MessageBox("Date is out of range", userstr)
END IF
ELSE
MessageBox("Date is invalid", userstr)
END IF
The Value property The Value property contains the date and time to which the control is set. If you
do not specify a date, the Value property defaults to the current date and time.
You can set the property in the painter or in a script. If you change the value at
runtime, the display is updated automatically. The Value property has two parts
that can be obtained from the DateValue and TimeValue properties. These
properties should be used only to obtain the date and time parts of the Value
property; they cannot be used to set a date or time. The Text property and the
GetText function return the Value property as a string formatted according to
your format property settings.
You can use the SetValue function to set the Value property in a control using
separate date and time values or a single DateTime value. This example sets the
property control using separate date and time values:
date d
time t
d=date("2016/12/27")
t=time("12:00:00")
dp_1.SetValue(d, t)
This example sets the Value property using a DateTime value:
date d
time t
datetime dt
dt = DateTime(d, t)
dp_1.SetValue(dt)
Localizing the The DatePicker control is designed to work in different locales. The string
DatePicker control values in the DatePicker control support non-English characters and the names
of months and days of the week in the calendar display in the local language.
You can set the FirstDayOfWeek property on the Calendar page in the
Properties view to have the drop-down calendar use Monday or any other day
of the week as the first day.
The MaxDate and MinDate properties and the date part of the Value property
use the Short Date format specified in the regional settings in the Windows
control panel of the local computer, and the time part uses the local computer’s
time format. The three predefined display formats—long date, short date, and
time—also depend on the local computer’s regional settings.
Animation
Animation controls can display Audio-Video Interleaved (AVI) clips. An AVI
clip is a series of bitmap frames that can be played like a movie. The clip can
come from an uncompressed AVI file or from an AVI file compressed using
run-length encoding (BI_RLE8). If you use an AVI file that has a sound
channel, the sound is not played.
You might display an AVI clip to show the user that some activity is occurring
while a lengthy operation such as a search or full build is completing. To
specify which AVI clip to use, specify the AVI file name in the control’s
AnimationName property. If you want the control to display only when an
event in your application starts to play the application, set its Border and
Visible properties to “false” and its Transparent property to “true”.
300 PowerBuilder
CHAPTER 11 Working with Controls
302 PowerBuilder
C H A P T E R 1 2 Understanding Inheritance
About this chapter This chapter describes how to use inheritance to build PowerBuilder
objects.
Contents
Topic Page
About inheritance 303
Creating new objects using inheritance 304
The inheritance hierarchy 305
Browsing the class hierarchy 305
Working with inherited objects 307
Using inherited scripts 308
About inheritance
One of the most powerful features of PowerBuilder is inheritance. It
enables you to build windows, user objects, and menus that derive from
existing objects.
Using inheritance has a number of advantages:
• When you change an ancestor object, the changes are reflected in all
the descendants. You do not have to make manual changes in the
descendants, as you would in a copy. This saves you coding time and
makes the application easier to maintain.
• The descendant inherits the ancestor’s scripts, so you do not have to
re-enter the code to add to the script.
• You gain consistency in the code and objects in your applications.
This chapter describes how inheritance works in PowerBuilder and how
to use it to maximize your productivity.
3 Click OK.
The new object, which is a descendant of the object you chose to inherit
from, opens in the appropriate painter.
304 PowerBuilder
CHAPTER 12 Understanding Inheritance
Regenerating objects
The Browser also provides a convenient way to regenerate objects and their
descendants. For more information, see Regenerating library entries on page
154.
306 PowerBuilder
CHAPTER 12 Understanding Inheritance
2 In the left pane, select an object and choose Show Hierarchy from its
pop-up menu.
3 Select an object and choose Expand All from its pop-up menu.
PowerBuilder shows the selected object in the current application.
Descendent objects are shown indented under their ancestors.
For example, if your application uses the PBDOM PowerBuilder extension
object, the pbdom_object displays on the User Object page. You can select
Show Hierarchy and Expand All from its pop-up menu to display its
descendent objects.
Working in an When you use inheritance to build an object, the descendant is dependent on
ancestor object the definition of the ancestor. Therefore you should not delete the ancestor
without deleting the descendants. You should also be careful when you change
the definition of an ancestor object. You may want to regenerate descendent
objects if you do any of the following:
• Delete or change the name of an instance variable in the ancestor
• Modify a user-defined function in the ancestor
• Delete a user event in an ancestor
• Rename or delete a control in an ancestor
When you regenerate the descendants, the compiler will flag any references it
cannot resolve so you can fix them. For information about regenerating objects,
see Chapter 5, Working with Libraries.
308 PowerBuilder
CHAPTER 12 Understanding Inheritance
Extending or The Extend Ancestor Script item on the Edit menu or the pop-up menu in the
overriding a script Script view determines whether the script is extended or overridden. If the
menu item is selected (a check mark displays next to it), the ancestor script is
extended. If there is no check mark, the ancestor script is overridden.
When there is no script for the descendant, the Extend Ancestor Script menu
item is selected and disabled. You cannot clear the menu item unless you add
a script to the descendant. When you have added a script, the menu item is
enabled and you can choose to override the ancestor script by clearing the
menu item, or to extend it by leaving the menu item selected.
Executing code before To write a script that executes before the ancestor script, first override the
the ancestor script ancestor script and then in the descendent script explicitly call the ancestor
script at the appropriate place. For more information, see Calling an ancestor
script on page 312.
Getting the return To get the return value of an ancestor script, you can use the
value of the ancestor AncestorReturnValue variable. This variable is always available in descendent
script
scripts that extend an ancestor script. It is also available if you override the
ancestor script and use the CALL syntax to call the ancestor event script. For
more information, see Application Techniques.
Script icons in the The third drop-down list in the Script view shows the current object followed
third drop-down list by each of its ancestors in ascending order. The icons next to object names
indicate whether the object has a script for the event selected in the second
drop-down list as follows:
• If an object is the highest class in the hierarchy to have a script, a
transparent script icon displays next to its name. No icon displays next to
the names of any of its ancestors.
• If an object does not have a script for the event but it has an ancestor that
has a script for the event, the script icon next to its name is displayed in
color.
• If an object has a script for the event, and it has an ancestor that also has a
script for the event, the script icon next to its name is displayed half in
color.
Extending a script
When you extend an ancestor script for an event, PowerBuilder executes the
ancestor script, then executes the script for the descendant when the event is
triggered.
310 PowerBuilder
CHAPTER 12 Understanding Inheritance
Overriding a script
To override an ancestor script:
1 In the first drop-down list in the Script view, select the object or a control,
and in the second drop-down list, select the event for which you want to
override the script.
2 Code a script for the event in the descendant.
You can call the script for any event in any ancestor as well as call any
user-defined functions that have been defined for the ancestor.
For information about calling an ancestor script or function, see Calling an
ancestor script on page 312 and Calling an ancestor function on page 312.
3 Select Extend Ancestor Script on the Edit menu or the pop-up menu to
clear the check mark.
Clearing the Extend Ancestor Script item means that you are overriding
the script.
312 PowerBuilder
CHAPTER 12 Understanding Inheritance
For more information about calling an ancestor function, see the PowerScript
Reference.
314 PowerBuilder
C H A P T E R 1 3 Working with Menus and
Toolbars
About this chapter By adding customized menus and toolbars to your applications, you can
make it easy and intuitive for your users to select commands and options.
This chapter describes how to define and use menus and toolbars.
Contents
Topic Page
Menus and menu items 315
Using the Menu painter 316
Building a new menu 321
Defining the appearance and behavior of menu items 329
Providing toolbars 334
Writing scripts for menu items 344
Using inheritance to build a menu 348
Using menus in your applications 353
Using menus You can use menus you build in PowerBuilder in two ways:
• In the menu bar of windows Menu bar menus are associated with a
window in the Window painter and display whenever the window is
opened.
• As pop-up menus Pop-up menus display only when a script executes
the PopMenu function.
Both uses are described in this chapter.
Designing menus PowerBuilder gives you complete freedom in designing menus, but you should
follow conventions to make your applications easy to use. For example, you
should keep menus simple and consistent; group related items in a drop-down
menu; make sparing use of cascading menus and restrict them to one or two
levels.
This chapter describes some guidelines you should follow when designing
menus. A full discussion of menu design is beyond the scope of this book. You
should acquire a book that specifically addresses design guidelines for
graphical applications and apply the rules when you use PowerBuilder to create
your menus.
Building menus When you build a menu, you:
• Specify the appearance and behavior of the menu items by setting their
properties.
• Build scripts that determine how to respond to events in the menu items.
To support these scripts, you can declare functions, structures, and
variables for the menu.
There are two ways to build a menu. You can:
• Build a new menu from scratch. See Building a new menu on page 321.
• Build a menu that inherits its style, functions, structures, variables, and
scripts from an existing menu. You use inheritance to create menus that are
derived from existing menus, thereby saving yourself coding and time. See
Using inheritance to build a menu on page 348.
316 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
In addition to customizing the style of a menu in the Menu painter, you can also
customize the style of a toolbar associated with a menu. For information, see
Providing toolbars on page 334.
The Tree Menu view and the WYSIWYG Menu view are equivalent. You can
use either view to insert new menu items on the menu bar or on drop-down or
cascading menus, or to modify existing menu items. The menus in both views
change when you make a change in either view.
You specify menu properties in two views:
Table 13-2: Views in the Menu painter
This view Displays
Properties view General and Appearance tab pages for setting menu-wide
(for the top-level properties
menu object)
Properties view General and Toolbar tab pages for setting properties for
(for submenu submenu items and toolbars
items)
Views for the top level This Menu painter layout is for the top level menu object, m_main. The Tree
menu object Menu view is in the top left and the WYSIWYG Menu view is in the top
middle. The General and Appearance tab pages display in the Properties view
on the right. For more information about these properties, see Setting menu
style properties for contemporary menus on page 332.
318 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
Views for submenu This Menu painter layout is for a menu item under the top level, in this case the
items Exit menu item. The Tree Menu view is in the top left and the WYSIWYG
Menu view is in the top middle. The General and Toolbar tab pages display in
the Properties view on the right. For more information about these properties,
see Setting General properties for menu items on page 329.
Menu styles
A menu can have a contemporary or traditional style.
Menu style Description
Contemporary A 3D-style menu similar to Microsoft Office 2003 and Visual
Studio 2005 menus
Traditional Window default menu style which has a flat appearance
Menus that you import or migrate from earlier versions of PowerBuilder have
the traditional style, and new menus use the traditional menu style by default.
The new contemporary menu style has a three-dimensional menu appearance
that can include images and menu title bands. With a contemporary menu, you
can set the MenuAnimation, MenuImage, and MenuTitleText at runtime using
scripts.
You select a menu style on the Appearance tab of the Properties view for the
top-level menu object in the Menu painter. You must select the top-level menu
object in the Tree Menu view of the Menu painter to display its Properties view.
If you select contemporarymenu! in the Menu Style drop-down list, you can
customize the display properties for that style and have them apply to all menu
items in the current menu. If you select traditionalmenu! the rest of the
menu style properties are grayed.
Images for menus and Contemporary menus can include images. You can use icons, bitmaps, GIF
toolbars files, and JPEG files for both contemporary menus and traditional and
contemporary toolbars.
All stock icons have a transparent background. Other icon and GIF files with
transparent backgrounds are always displayed with a transparent background.
If you want a bitmap to display with a transparent background, the bitmap must
use button face as its background color. This applies whatever the background
color of the menu or toolbar is set to. There is currently no property that allows
you to specify that an image has a transparent background.
320 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
When an icon file With the contemporary menu style and toolbar style, when an icon file includes
includes several several images, PowerBuilder uses the following image selection rules:
images
If the images . . . PowerBuilder displays . . .
Are all the same size 8 bit, 16 bit, 24 bit, 32 bit, and 4 bit images in that
order.
Include 16 bit*16 bit images 16 bit*16 bit images.
and also other sized images
Do not include 16 bit*16 bit The image with the image size closest to 16 bit. For
images example, if one icon file contains 24*24 bit images
and another icon file contains 32*32 bit images, then
PowerBuilder selects the 24*24 bit images.
Are greater than 16 bit The image as 16*16 bit or 32*32 bit. If the icon
images image is 16*16, then it displays as 16*16. If the icon
image is larger than 16*16, it will be displayed as
32*32.
Because you are creating a new menu and have not added menu items yet, the
only content in the Tree Menu view and the WYSIWYG view is an untitled
top-level tree view item in the TreeMenu view.
322 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
The complete menu item name (prefix and suffix) can be up to 79 characters.
If the prefix and suffix exceed this size, PowerBuilder uses only the first 79
characters without displaying a warning message.
Duplicate menu item Menu items in the Tree Menu view and WYSIWYG Menu view can have the
names same names, but they cannot have the same name in the Properties view. If you
try to add a menu item using the same name as an existing menu item,
PowerBuilder displays a dialog box that suggests a unique name for the menu
item. For example, you might already have an Options item on the Edit menu
with the default name m_options. If you add an Options item to another menu,
PowerBuilder cannot give it the name m_options.
Menu item names are After you add a menu item, the name that PowerBuilder assigns to the menu
locked by default item is locked. Even if you later change the text that displays for the menu item,
PowerBuilder does not rename the menu item. This allows you to change the
text that displays in a menu without having to revise all your scripts that
reference the menu item. (Remember, you reference a menu item through the
name that PowerBuilder assigns to it.)
To rename a menu item after changing the text that displays for it, you can
unlock the name.
324 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
• Select a menu bar item and select Insert>Menu Item to add a menu bar
item before the selected menu bar item.
2 Type the text you want for the menu bar item, and then press Enter.
326 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
Dragging to copy
To copy a menu item by dragging it, press and hold the Ctrl key while you drag
and drop the item. A copied menu item has the same properties and scripts as
the original menu item.
You can also copy or move a menu item by selecting the item and using the Cut,
Copy, and Paste items on the Edit menu or the pop-up menu.
To save a menu:
1 Select File>Save from the menu bar.
328 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
If you have previously saved the menu, PowerBuilder saves the new
version in the same library and returns you to the Menu painter. If you have
not previously saved the menu, PowerBuilder displays the Save Menu
dialog box.
2 Name the menu in the Menus box (see Naming the menu next).
3 Write comments to describe the menu.
These comments display in the Select Menu dialog box and in the Library
painter. It is a good idea to use comments so you and others can easily
remember the purpose of the menu later.
4 Specify the library in which to save the menu and click OK.
Naming the menu The menu name can be any valid PowerBuilder identifier of up to 40
characters. For information about PowerBuilder identifiers, see the
PowerScript Reference.
A common convention is to use m_ as a standard prefix, and a suffix that helps
you identify the particular menu. For example, you might name a menu used in
a sales application m_sales.
A tag is a text string that you can associate with an object and use in any way
you want.
For information about defining MicroHelp text and tag properties, see the
chapter on building MDI applications in Application Techniques.
Setting the On the General tab page in the Properties view, you can also specify how a
appearance of a menu menu item appears at runtime.
item
Table 13-3: Setting display properties for menu items
Property Meaning
Visible Whether the menu item is visible. An invisible menu item still
displays in the WYSIWYG and Tree Menu views, but at runtime,
it will not display. In WYSIWYG Menu view, an invisible item
has faded and dotted text.
Enabled Whether the menu item can be selected.
Checked Whether the menu item displays with a check mark next to it.
Default Whether the menu item text is bold. In a pop-up menu, Default
indicates what action occurs if the user double-clicks instead of
right-clicks on an item. In dragging, Default indicates what
happens when an item is dragged with the left mouse button
instead of the right mouse button.
ShiftToRight Whether the menu item shifts to the right (or down for a
drop-down or cascading menu) when you add menu items in a
menu that is inherited from this menu. Selecting this property
allows you to insert menu items in descendent menus, instead of
being able to add them only to the end.
For more information, see Inserting menu items in a descendent
menu on page 350.
MergeOption The way menus are modified when an OLE object is activated.
Options are: File, Edit, Window, Help, Merge, Exclude.
For more information, see the chapter about using OLE in an
application in Application Techniques.
MenuItemType Whether the menu item you are creating is Normal, About, Exit,
or Help type.
The settings you specify here determine how the menu items display by
default. You can change the values of the properties in scripts at runtime.
Assigning accelerator Every menu item should have an accelerator key, also called a mnemonic
and shortcut keys access key, which allows users to select the item from the keyboard by pressing
Alt+key when the menu is displayed. Accelerator keys display with an
underline in the menu item text.
330 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
You can also define shortcut keys, which are combinations of keys that a user
can press to select a menu item whether or not the menu is displayed.
For example, in the following menu all menu items have accelerator keys: the
accelerator key is U for Undo, T for Cut, and so on. New, Undo, Cut, Copy,
Paste, and Clear each have shortcut keys: the Ctrl key in combination with
another key or keys.
You should adopt conventions for using accelerator and shortcut keys in your
applications. All menu items should have accelerator keys, and commonly
used menu items should have shortcut keys.
If you specify the same shortcut for more than one MenuItem, the command
that occurs later in the menu hierarchy is executed.
Some shortcut key combinations, such as Ctrl+C, Ctrl+V, and Ctrl+X, are
commonly used by many applications. Avoid using these combinations when
you assign shortcut keys for your application.
4 Select Shortcut Alt, Shortcut Ctrl, and/or Shortcut Shift to create a key
combination.
PowerBuilder displays the shortcut key next to the menu item name.
After you select the contemporary style, you can modify other menu style
properties on the top-level menu object and on all lower-level menu items.
Since it is important to maintain a consistent look across each menu and
toolbar, very few style properties are modifiable at the menu item level.
You can modify menu style properties only at design time. After you select the
contemporary menu style for a top-level menu object, you can select values for
other style properties to manipulate a menu’s visual appearance. The following
properties are modifiable for the top-level menu object only; you cannot
modify them for individual menu items:
Property Datatype Use to assign
MenuStyle Enumerated Overall menu style. Values are:
contemporarymenu! and traditionalmenu!
332 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
You select or enter values for the menu item style properties on the General tab
of the Properties view for each menu item. You can make selections for the
MenuAnimation and MenuImage properties only if the MenuBitmaps check
box for the current menu object is selected. The MenuBitmaps check box is
selected by default for the contemporary menu style.
You can enter text for the MenuTitleText property only if the MenuTitles check
box for the current menu object is selected.
Providing toolbars
To make your application easier to use, you can add toolbars with buttons that
users can click as a shortcut for choosing an item from a menu. In
PowerBuilder, you can associate a toolbar with the window types listed in
Table 13-4.
334 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
Creating windows in You can create a main window, an MDI window, or an MDI Help window in
PowerBuilder PowerBuilder by clicking the New button in the PowerBar and selecting
Window on the PB Object tab page. The new window’s type is Main by default.
To change it to MDI or MDI Help, select the window type on the General page
in the Properties view.
In MDI windows, you can associate a toolbar with the MDI frame and a toolbar
with the active sheet. This screen shows New, Print, and Exit buttons on the
toolbar associated with the MDI Frame, and window management buttons on
the toolbar associated with the sheet. The toolbar associated with the MDI
frame is called the FrameBar. The toolbar associated with the active sheet is
called the SheetBar.
This section provides you with the information you need to create and use
toolbars. For information about customizing toolbar behavior and saving and
restoring toolbar settings, see Application Techniques.
336 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
• Toolbars work only in MDI frame, MDI sheet, and Main windows. If you
open a pop-up window with a menu that has a toolbar, the toolbar does not
display.
• If both the MDI sheet and the frame have toolbars and the sheet is open,
then the menu that is displayed is the menu for the sheet, but both toolbars
appear and are operative.
• If the currently active sheet does not have a menu, then the menu and
toolbar for the frame remain in place and are operative. This can be
confusing to your user, because the displayed menu is not for the active
sheet. If any sheet has a menu, then all sheets should probably have menus.
Menus with multiple A single menu can have more than one toolbar. When you associate a menu that
toolbars has multiple toolbars with a window, PowerBuilder displays all the toolbars
when you open the window. This screen shows a sheet open in an MDI frame,
with one FrameBar and two SheetBars:
You can work with the toolbars independently. For example, you can float any
of the toolbars, move them around the window, and dock them at different
locations within the window.
The button associated with a menu item can appear on only one toolbar at a
time. To indicate which toolbar a menu item’s button belongs to, you set the
ToolbarItemBarIndex property for the menu item. All items that have the same
index number appear on the same toolbar.
338 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
2 At the bottom of the Appearance tab page, select the toolbar style you
want, contemporarytoolbar! or traditionaltoolbar!
Toolbar style properties Toolbars have style properties that you can change
at design time on the top-level menu object. You can modify these properties
only if you select contemporarytoolbar! as the toolbar style for the
top-level menu object.
Property Datatype Use to assign
ToolbarBackColor Long Background color of the menu toolbar.
ToolbarGradient Boolean Gradient of the menu toolbar background.
ToolbarHighlightColor Long Highlight color for the toolbar buttons when
they are selected.
ToolbarStyle Enumerated Overall style of the menu toolbar. Values
are: contemporarytoolbar! and
traditionaltoolbar!
ToolbarTextColor Long Color of the text in the menu toolbar.
Toolbar item style property You can select the ToolbarAnimation property
for a menu item toolbar button. This property offsets the button image by two
pixels to the upper left when a user positions the cursor over the button. You
cannot assign this property at the menu object or toolbar level. You must assign
it to individual toolbar items (buttons) at design time. This property has a
Boolean datatype. You can select it on the Toolbar tab for each menu item
below the top-level menu object. With a contemporary menu, you can set the
ToolbarAnimation property at runtime at runtime using scripts.
The customizable menu and toolbar styles can be used for MDI and main
windows. Pop-up menus can also use menu style properties. The styles do not
affect existing PowerBuilder applications that use a traditional style. You can,
however, update an existing PowerBuilder application to use the new style
properties.
340 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
Menu items can have A menu item can have a toolbar button associated with it that displays a
drop-down toolbars drop-down toolbar. When the user clicks on the button, PowerBuilder displays
a drop-down toolbar that shows all of the toolbar buttons for menu items
defined at the next level. For example, if you define a drop-down toolbar for
the File menu item, the drop-down toolbar will show the buttons defined for
the items on the File menu (such as New, Open, Close, and Exit).
PowerBuilder displays a drop-down toolbar at runtime by default if the Object
Type of the menu item is MenuCascade. You can specify programmatically
whether submenu items display in a drop-down toolbar or as normal toolbar
items by setting the DropDown property of the menu item. For example, if you
want a descendent menu item to have a drop-down toolbar, but not its ancestor,
clear the DropDown check box on the ancestor’s Toolbar property page, and
set the DropDown property of the descendent menu item to “true” in a script.
342 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
Specifying the text in By default, PowerBuilder provides a pop-up menu for the toolbar, which users
the toolbar’s pop-up can use to manipulate the toolbar. It is similar to the pop-up menu you use to
menu
manipulate the PowerBar and PainterBar.
You can change the text that displays in this menu, but you cannot change the
functionality of the menu items in the menu. Typically, you do this when you
are building an application in a language other than English.
You change the text as follows:
• The first two items in the pop-up menu display the titles set in
ToolbarFrameTitle and ToolbarSheetTitle (defaults: FrameBar and
SheetBar).
• The remaining text items are specified by the property
ToolbarPopMenuText. To specify values for this property, use a
comma-delimited list of values to replace the text “Left,” “Top,” “Right,”
“Bottom,” “Floating,” “Show Text,” and “Show PowerTips”:
ToolbarPopMenuText = "left, top, right, bottom, floating, showText,
showPowerTips"
For example, to change the text for the toolbar pop-up menu to German and
have hot keys underlined for each, you would specify the following:
ToolbarPopMenuText = "&Links, &Oben, &Rechts, " + &
"&Unten, &Frei positionierbar, &Text anzeigen, " &
+ "&PowerTips anzeigen"
344 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
• Help You can provide Help on a menu item when a user presses the F1
key, or when the user clicks the context Help button [?] on the title bar of
the window with which the menu is associated, and then clicks on a menu
item.
• Selected You will probably use few Selected scripts since users do not
expect things to happen when they simply highlight a menu item. One use
of Selected scripts is to change MicroHelp displayed in an MDI
application as the user scrolls through a menu.
About the Clicked The Clicked event is triggered whenever:
event
• The user clicks the menu item
• The user selects (highlights) the menu item using the keyboard and then
presses ENTER
• The user presses the shortcut key for the menu item
• The menu containing the menu item is displayed and the user presses the
accelerator key Alt+key
• A script executes the PopMenu function and displays a pop-up menu
A menu item responds to a mouse-click or the keyboard only if both its Visible
and Enabled properties are set to “true”.
If the menu item has a drop-down or cascading menu under it, the script for its
Clicked event (if any) is executed when the mouse button is pressed, and then
the drop-down or cascading menu displays. If the menu item does not have a
menu under it, the script for the Clicked event is executed when the mouse
button is released.
About the Help event The Help event is triggered when the user presses F1 or clicks the context Help
button [?] on a window’s title bar and then points and clicks on a menu item.
About the Selected The Selected event is triggered when the user selects a menu item.
event
Using variables Scripts for menu items have access to all global variables declared for the
application. You can also declare local variables, which are accessible only in
the script where they are declared.
You can declare instance variables for the menu when you have data that needs
to be accessible to scripts in several menu items in a menu. Instance variables
are accessible to all menu items in the menu.
For a complete description of variables and how to declare them, see the
PowerScript Reference.
Defining menu-level If you need to manipulate a collection of related variables, you can define
structures menu-level structures using the Structure view. You do this by displaying the
Structure List view and then selecting Add from the pop-up menu. The
Structure and Structure List views are not part of the default layout.
For more information, see Chapter 9, Working with Structures.
346 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
For example, this statement moves the window w_cust from within a menu
item script:
w_cust.Move(300, 300)
This statement minimizes w_cust:
w_cust.WindowState = Minimized!
You can use the reserved word ParentWindow to refer to the window that the
menu is associated with at runtime. For example, the following statement
closes the window the menu is associated with:
Close(ParentWindow)
You can also use ParentWindow to refer to properties of the window a menu is
associated with, but not to refer to properties of controls or user objects in the
window.
For example, the following statement is valid, because it refers to properties of
the window itself:
ParentWindow.Height = ParentWindow.Height/2
But the following statement is invalid, because it refers to a control in the
window:
ParentWindow.sle_result.Text = "Statement invalid"
Referring to controls When referring to a control or user object, you must always qualify the control
and user objects in or user object with the name of the window:
windows
window.control.property
window.userobject.property
For example, this statement enables a CommandButton in window w_cust from
a menu item script:
w_cust.cb_print.Enabled = TRUE
Referring to menu When referring to a menu item, use this syntax:
items
menu.menu item
menu.menu item.property
The selected menu displays in the WYSIWYG Menu view and the Tree
Menu view in the Menu painter. The title in the painter’s title bar indicates
that the menu is a descendant.
3 Make the changes you want to the descendent menu as described in the
next section.
4 Save the menu under a new name.
348 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
About menu item PowerBuilder uses the following syntax to show names of inherited menu
names in a items:
descendant
AncestorMenuName::MenuItemName
For example, in a menu inherited from m_update_file, you see
m_update_file::m_file for the m_file menu item, which is defined in
m_update_file.
The inherited menu item name is also locked, so you cannot change it.
Understanding The issues concerning inheritance with menus are similar to the issues
inheritance concerning inheritance with windows and user objects. For information, see
Chapter 12, Understanding Inheritance.
350 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
The Example with no ShiftToRight in ancestor on page 351 and the Example
with ShiftToRight in ancestor on page 353 demonstrate some of these rules.
How to insert menu If you can insert a menu item in a descendent menu, the Insert Menu Item
items in a descendent option on the Insert menu and the pop-up menu is enabled. The Insert Menu
menu
Item is enabled if ShiftToRight is set in the selected item that will follow the
item you are inserting and all menu items following it.
To insert a menu item in a descendant, you use the same method you use to
insert an item in a new menu, whether the menu item is on the menu bar or on
a drop-down or cascading menu. For information about inserting menu items,
see Working with menu items on page 322.
The following examples illustrate where you can insert menu items in a
descendent menu and demonstrate the rules that govern where you can insert
them.
Example with no Suppose you have a menu with File, Edit, Window, and Help items on the menu
ShiftToRight in bar. The menu is inherited from an ancestor frame menu with no items set as
ancestor
ShiftToRight in the ancestor.
Here is how you might add some new menu items. Since ShiftToRight is not
set anywhere at first, you can add a menu item only to the end.
1 Select any item in the menu bar and select Insert>Menu Item At End.
2 Name the new menu item New1 and press Enter.
The New1 menu item is added to the right of the Help menu.
Now add a new Menu item before the New1 menu item. You can do this
without setting ShiftToRight on New1, because New1 is a new menu item
in the inherited menu.
3 Select Insert Menu Item from the pop-up menu for New1.
4 Name the new menu item New2 and press Enter.
Now add a new Menu item before the Help menu item. You cannot do this
unless you set ShiftToRight on the Help menu item, the New2 Menu item,
and the New1 menu item, because Help is an inherited menu item without
ShiftToRight set in the ancestor menu. For Help to shift right, New2 and
New1 must also be able to shift right.
5 Select the Help menu item and in the Properties view, select the
ShiftToRight property, and then do the same for New1 and New2.
Now you can add a new menu item before the Help menu item.
6 Select the Help menu item, then select Insert New Item from the pop-up
menu, name the new item New3, and then press Enter.
If you want to add a new Menu item before the New3 menu item, you can
do it without setting ShiftToRight on New3, because New3 is a new menu
item and ShiftToRight is set in all items that follow.
However, if you want to add a new menu item before the Window menu
item, you cannot do this by working only in the descendent menu because
the Window menu item is an ancestor menu item and ShiftToRight is not
set in the ancestor. To be able to do this, you must set Window as
ShiftToRight in the ancestor.
352 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
Example with In this example, the inherited menu has the same four menu bar items, but
ShiftToRight in ShiftToRight has been set in the Window and Help menu items in the ancestor
ancestor
menu. Suppose you want to insert a new menu item before the Help menu item
and the Window menu item.
1 Select the Help menu item and display the pop-up menu.
The Insert Menu Item option is disabled because the Help item is not the
first item in a group of ancestor menu items (Window and Help) with
ShiftToRight set in the ancestor.
2 Select the Window menu item and display the pop-up menu.
The Insert Menu Item option is enabled because the Window item is the
first item in a group of ancestor menu items with ShiftToRight set in the
ancestor.
3 Select Insert Menu Item At End from the pop-up menu to insert a new
menu item after Help, name it New1, and press Enter.
The New1 item’s ShiftToRight property is set automatically.
Now the Window, Help, and New1 items are set ShiftToRight. You can
insert a new item before Window and New1, but not before Help. This is
because the Window and Help menu items are a group for which
ShiftToRight is set in the ancestor.
You cannot insert a new item before the Edit menu item because Edit is in
a group (File and Edit) that are inherited items with no ShiftToRight set in
the ancestor.
4 Select the Edit menu item, select ShiftToRight in the Properties view, and
then add a new menu item.
You could also have set the ShiftToRight property in the ancestor menu,
but it is easier to work just in the descendant.
354 PowerBuilder
CHAPTER 13 Working with Menus and Toolbars
356 PowerBuilder
C H A P T E R 1 4 Working with User Objects
About this chapter One of the features of object-oriented programming is reusability: you
define a component once, then reuse it as many times as you need to
without any additional work. User objects are one of the best ways to take
advantage of reusability in PowerBuilder. This chapter describes how to
define and use user objects.
Contents
Topic Page
About user objects 357
About the User Object painter 360
Building a new user object 362
Using inheritance to build user objects 369
Using user objects 371
Communicating between a window and a user object 376
There are two main types of user objects: class and visual. Class user objects
are also called nonvisual objects.
358 PowerBuilder
CHAPTER 14 Working with User Objects
Standard class user A standard class user object inherits its definition from one built-in, nonvisual
objects PowerBuilder object, such as the Transaction object or Error object. You
modify the definition to make the object specific to your application, and
optionally add instance variables and functions to enhance the behavior of the
built-in object. Once you define a standard class user object, you can go to the
Application painter and specify that you want to use it instead of the
corresponding built-in system object in your application.
One important use of a standard class user object is employing one inherited
from the built-in Transaction object to do database remote procedure calls from
within an application.
Standard visual user A standard visual user object inherits its definition from one standard
objects PowerBuilder control. You modify the definition to make the control specific
to your applications.
Assume you frequently use a CommandButton named Close to display a
message box and then close the parent window. If you build a standard visual
user object that derives from a CommandButton to perform this processing,
you can use the user object whenever you want to display a message box and
then close a window.
360 PowerBuilder
CHAPTER 14 Working with User Objects
Views for visual user In this User Object painter for a custom visual user object, the Layout view and
objects Script view have been arranged to display at the same time:
Most of your work in the User Object painter for visual objects is done in three
views:
• The Layout view, where you design the appearance of the user object
• The Properties view, where you set user object properties and control
properties
• The Script view, where you modify behavior by coding user object and
control scripts
In the Layout view, you add controls to a visual user object in the same way
you add controls to a window.
For information about specifying user object properties, see Building a new
user object on page 362. For information about using the Script view, see
Chapter 6, Writing Scripts.
Views for nonvisual You do not need the Layout and Control List views for nonvisual user objects,
user objects but otherwise, you use all the views that you use for visual objects.
Nonvisual user objects require no layout design work, but working in the User
Object painter on the behavior of a nonvisual object is otherwise similar to
working on the behavior of a visual user object.
3 Click OK.
What you do next depends on the type of user object you selected. For all
user objects except Standard Class and Standard Visual, the User Object
painter opens.
The remainder of this section describes how to build each type of user
object.
362 PowerBuilder
CHAPTER 14 Working with User Objects
364 PowerBuilder
CHAPTER 14 Working with User Objects
366 PowerBuilder
CHAPTER 14 Working with User Objects
Standard class user objects have the same events as the PowerBuilder system
object from which they inherit.
Events in visual user Standard visual user objects have the same events as the PowerBuilder control
objects from which they inherit. Custom and external visual user objects have a
common set of events.
Table 14-2: Events for custom and external visual user objects
Event Occurs when
Constructor Immediately before the Open event of the window and when the
user object is dynamically placed in a window
Destructor Immediately after the Close event of the window and when the
user object is dynamically removed from a window
DragDrop A dragged object is dropped on the user object
DragEnter A dragged object enters the user object
DragLeave A dragged object leaves the user object
DragWithin A dragged object is moved within the user object
Help A user presses the F1 key or clicks the context Help button [?] on
the title bar of the window with which the menu is associated and
then points and clicks on a menu item
Other A Windows message occurs that is not a PowerBuilder event
RButtonDown The right mouse button is pressed
368 PowerBuilder
CHAPTER 14 Working with User Objects
2 In the Inherit From Object dialog box, select User Objects from the
Objects of Type drop-down list.
3 Select the target as well as the library or libraries you want to look in.
4 Select the user object you want to use to create the descendant, and click
OK.
The selected object displays in the User Object painter and the title bar
indicates that the object is a descendant.
5 Make any changes you want to the user object.
6 Save the user object with a new name.
370 PowerBuilder
CHAPTER 14 Working with User Objects
What you can do After you place a user object in a window or a custom visual user object, you
can name it, size it, position it, write scripts for it, and do anything else you can
do with a control.
When you place the user object in a window, PowerBuilder assigns it a unique
name, just as it does when you place a control. The name is a concatenation of
the default prefix for a user object control (initially, uo_) and a default suffix,
which is a number that makes the name unique.
You should change the default suffix to a suffix that has meaning for the user
object in your application.
For more information about naming, see Naming controls on page 252.
Writing scripts When you place a user object in a window or a custom user object, you are
actually creating a descendant of the user object. All scripts defined for the
ancestor user object are inherited. You can choose to override or extend those
scripts.
For more information, see Using inherited scripts on page 308.
You place a user object as a unit in a window (or another user object). You
cannot write scripts for individual controls in a custom user object after placing
it in a window or custom user object; you do that only when you are defining
the user object itself.
Placing a user object You can add a user object to a window at runtime using the PowerScript
at runtime functions OpenUserObject and OpenUserObjectWithParm in a script. You can
remove a user object from a window using the CloseUserObject function.
372 PowerBuilder
CHAPTER 14 Working with User Objects
If you select Autoinstantiate in the properties of the class user object, you
cannot use the CREATE and DESTROY statements.
Using the Non-Visual You can use the same technique to insert standard class user objects. Since all
Object List view class user objects are nonvisual, you cannot see them, but if you look at the
Non-Visual Object List view, you see all the class user objects that exist in your
user object.
Using the Non-Visual Object List view’s pop-up menu, you can display a class
user object’s properties in the Properties view, display the Script view for the
object to code its behavior, or delete the object.
To replace the built-in global object with a standard class user object:
1 Open the Application object.
2 In the Properties view, click the Additional Properties button on the
General tab page.
3 In the Application properties dialog box, select the Variable Types tab.
374 PowerBuilder
CHAPTER 14 Working with User Objects
4 Specify the standard class user object you defined in the corresponding
field and click OK.
After you have specified your user object as the default global object, it
replaces the built-in object and is created automatically when the application
starts up. You do not create it (or destroy it) yourself.
The properties and functions defined in the user object are available anywhere
in the application. Reference them using dot notation, just as you access those
of other PowerBuilder objects such as windows.
Supplementing the You can use a user object inherited from one of these global objects by
built-in global object inserting one in your user object as described in Using class user objects on
page 373. If you do, your user object is used in addition to the built-in global
object variable. Typically you use this technique with user objects inherited
from the Transaction object. You now have access to two Transaction objects:
the built-in SQLCA and the one you defined.
For more information For more information about using the Error object, see Using the Error object
on page 908.
For information about using the Message object, and about creating your own
Transaction object to support database remote procedure calls, see Application
Techniques.
376 PowerBuilder
CHAPTER 14 Working with User Objects
Directly referencing Instead of using functions or user events, it is possible to reference properties
properties of a user object directly. If you have a user object control, uo_1, associated with
a custom user object that has a SingleLineEdit, sle_1, you can use the following
in a script for the window:
uo_1.sle_1.Text = "new text"
However, it is better to communicate with user objects through functions and
user events, as described below, in order to maintain a clean interface between
your user object and the rest of your application.
The functions Exchanging information using functions is straightforward. After a user object
technique calls a function, any return value is available to any control within that object.
For how to use this technique, see Example 1: using functions on page 379.
For more information about user events, see Chapter 8, Working with User
Events, and Application Techniques. For instructions for using this technique,
see Example 2: using user events on page 380.
378 PowerBuilder
CHAPTER 14 Working with User Objects
If the user clicks the Maximize button in an application window containing this
user object, the current window becomes maximized. If the user clicks
Minimize, the window closes to an icon.
Because the user object can be associated with any window, the scripts for the
buttons cannot reference the window that has the user object. The user object
must get the name of the window so that the buttons can reference the window.
Example 1: using functions next shows how PowerBuilder uses functions to
pass a window name to a user object, allowing controls in the user object to
affect the window the user object is in.
Example 2: using user events on page 380 shows how PowerBuilder uses
unmapped user events to allow controls in a user object to affect the window
the user object is in.
Example 1: using 1 In the Script view in the User Object painter, define an instance variable,
functions mywin, of type window.
window mywin
This variable will hold the name of the window that has the user object.
2 Define a user object-level function, f_setwin, with:
• Public access
• No return value
• One argument, win_param, of type window and passed by value
3 Type the following script for the function:
mywin = win_param
When f_setwin is called, the window name passed in win_param will be
assigned to mywin, where user object controls can reference the window
that has the user object.
4 Write scripts for the two buttons:
• cb_max: mywin.WindowState = Maximized!
5 Save the user object as uo_minmax and close the User Object painter.
6 Open the window, drag uo_minmax onto the window in the Layout view,
and name it uo_func in the Properties view.
7 In the Open event for the window, call the user object-level function,
passing the name of the window:
uo_func.f_setwin(This)
The pronoun This refers to the window’s name, which will be passed to the
user object's f_setwin function.
What happens When the window opens, it calls the user object-level
function f_setwin, which passes the window name to the user object. The user
object stores the name in its instance variable mywin. When the user clicks a
button control in the user object, the control references the window through
mywin.
Example 2: using user 1 In the Script view in the User Object painter, define two unmapped user
events events for the user object: Max_requested and Min_requested.
Leave the Event ID fields blank to define them as unmapped.
2 Trigger user events of the user object in the scripts for the Clicked event
of each CommandButton:
• cb_max: Parent.Event Max_requested()
3 Save the user object and name it uo_event and close the User Object
painter.
4 Open the window and in the Window painter, select Insert>Object from
the menu bar and then place uo_event in the window.
5 Double-click uo_event to display its Script view.
The two new user events display in the second drop-down list in the Script
view.
6 Write scripts for the two user events:
• max_requested: Parent.WindowState = Maximized!
These scripts reference the window containing the user object with the
pronoun Parent.
380 PowerBuilder
CHAPTER 14 Working with User Objects
What happens When a user clicks a button, the Clicked event script for that
button triggers a user event in its parent, the user object. The user object script
for that event modifies its parent, the window.
382 PowerBuilder
PA RT 5 Working with Databases
About this chapter This chapter describes how to manage a database from within
PowerBuilder.
Contents
Topic Page
Working with database components 385
Managing databases 389
Using the Database painter 390
Creating and deleting a SQL Anywhere database 395
Working with tables 396
Working with keys 410
Working with indexes 414
Working with database views 416
Manipulating data 421
Creating and executing SQL statements 428
Controlling access to the current database 432
Using the ASA MobiLink synchronization wizard 433
Managing MobiLink synchronization on the server 438
Before you begin You work with relational databases in PowerBuilder. If you are not
familiar with relational databases, you might want to consult an
introductory text.
How you work with You can use PowerBuilder to work with the following database components:
databases in
PowerBuilder • Tables and columns
• Keys
• Indexes
• Database views
• Extended attributes
• Additional database components
Tables and columns A database usually has many tables, each of which contains rows and columns
of data. Each row in a table has the same columns, but a column’s value for a
particular row could be empty or NULL if the column’s definition allows it.
Tables often have relationships with other tables. For example, in the PB Demo
DB included with PowerBuilder, the Department table has a Dept_id column,
and the Employee table also has a Dept_id column that identifies the department
in which the employee works. When you work with the Department table and
the Employee table, the relationship between them is specified by a join of the
two tables.
Keys Relational databases use keys to ensure database integrity.
Primary keys A primary key is a column or set of columns that uniquely
identifies each row in a table. For example, two employees may have the same
first and last names, but they have unique ID numbers. The Emp_id column in
the Employee table is the primary key column.
Foreign keys A foreign key is a column or set of columns that contains
primary key values from another table. For example, the Dept_id column is the
primary key column in the Department table and a foreign key in the Employee
table.
Key icons In PowerBuilder, columns defined as keys are displayed with key
icons that use different shapes and colors for primary and foreign.
PowerBuilder automatically joins tables that have a primary/foreign key
relationship, with the join on the key columns.
386 PowerBuilder
CHAPTER 15 Managing the Database
Database administrators often create database views for security purposes. For
example, a database view of an Employee table that is available to users who
are not in Human Resources might show all columns except Salary.
For more information, see Working with database views on page 416.
Extended attributes Extended attributes enable you to store information about a table’s columns in
special system tables. Unlike tables, keys, indexes, and database views (which
are DBMS-specific), extended attributes are PowerBuilder-specific. The most
powerful extended attributes determine the edit style, display format, and
validation rules for the column.
For more information about extended attributes, see Specifying column
extended attributes on page 400. For more information about the extended
attribute system tables, see Appendix A, The Extended Attribute System
Tables.
Additional database Depending on the database to which you are connected and on your user
components privileges, you may be able to view or work with a variety of additional
database components through PowerBuilder. These components might
include:
Driver information
Groups
Metadata types
Procedures and functions
Users
Logins
Triggers
Events
Web services
For example, driver information is relevant to ODBC connections. It lists all
the ODBC options associated with the ODBC driver, allowing you to
determine how the ODBC interface will behave for a given connection. Login
information is listed for Adaptive Server® Enterprise database connections.
Information about groups and users is listed for several of the databases and
allows you to add new users and groups and maintain passwords for existing
users.
You can drag most items in these folders to the Object Details view to display
their properties. You can also drag procedures, functions, triggers, and events
to the ISQL view.
388 PowerBuilder
CHAPTER 15 Managing the Database
Managing databases
PowerBuilder supports many database management systems (DBMSs). For the
most part, you work the same way in PowerBuilder for each DBMS, but
because each DBMS provides some unique features (which PowerBuilder
makes use of), there are some issues that are specific to a particular DBMS. For
complete information about using your DBMS, see Connecting to Your
Database.
What you can do Using the Database painter, you can do the following in any DBMS to which
you have been given access by the database administrator:
• Modify local table and column properties
• Retrieve, change, and insert data
• Create new local tables or modify existing tables
Setting the database When you open a painter that communicates with the database (such as the
connection Database painter or DataWindow painter), PowerBuilder connects you to the
database you used last if you are not already connected. If the connection to the
default database fails, the painter still opens.
If you do not want to connect to the database you used last, you can deselect
the Connect to Default Profile option in the Database Preferences dialog box.
Changing the You can change to a different database at any time. You can have several
database connection database connections open at a time, although only one connection can be
active. The database components for each open connection are listed in the
Objects view.
The Database painter title bar displays the number of open connections and
which is active. The title bar for each view displays the connection with which
it is currently associated. You can change the connection associated with a view
by dragging the profile name for a different connection onto the view.
For more about changing the database you are connected to, see Connecting to
Your Database.
Creating and deleting When you are connected to SQL Anywhere, you can create a new database or
databases delete an existing database using the Database painter.
For all other DBMSs, creating and deleting a database is an administrative task
that you cannot do within PowerBuilder.
390 PowerBuilder
CHAPTER 15 Managing the Database
Views in the Database Table 15-1 lists the views available in the Database painter.
painter
Table 15-1: Database painter views
View Description
Activity Log Displays the SQL syntax generated by the actions you
execute.
Columns Used to create and/or modify a table’s columns.
Extended Attributes Lists the display formats, edit styles, and validation rules
defined for the selected database connection.
Interactive SQL Used to build, execute, or explain SQL.
Object Details Displays an object’s properties. For some objects, its
properties are read-only; for others, properties can be
modified. This view is analogous to the Properties view in
other painters.
Object Layout Displays a graphical representation of tables and their
relationships.
Objects Lists database interfaces and profiles. For an active database
connection, might also list all or some of the following
objects associated with that database: groups, metadata
types, procedures and functions, tables, columns, primary
and foreign keys, indexes, users, views, driver information,
events, triggers, and utilities (the database components
listed depend on the database and your user privileges).
Results Displays data in a grid, table, or freeform format.
Dragging and You can select certain database objects from the Objects view and drag them
dropping to the Object Details, Object Layout, Columns, and/or ISQL views. Position
the pointer on the database object’s icon and drag it to the appropriate view.
Table 15-2: Using drag and drop in the Database painter
Object Can be dragged to
Driver, group, metadata type, procedure or function, Object Details view
table, column, user, primary or foreign key, index, event
trigger
Table or view Object Layout view
Table or column Columns view
Procedure or view ISQL view
Database painter Table 15-3 describes how to do some basic tasks in the Database painter. Most
tasks of these tasks begin in the Objects view. Many can be accomplished by
dragging and dropping objects into different views. If you prefer, you can use
buttons or menu selections from the menu bar or from pop-up menus.
392 PowerBuilder
CHAPTER 15 Managing the Database
Preferences on the You can set colors separately for each component of the Database painter’s
Object Colors property graphical table representation: the table header, columns, indexes, primary key,
page
foreign keys, and joins. Set a color preference by selecting a color from a
drop-down list.
You can design custom colors that you can use when you select color
preferences. To design custom colors, select Design>Custom Colors from the
menu bar and work in the Custom Colors dialog box.
394 PowerBuilder
CHAPTER 15 Managing the Database
396 PowerBuilder
CHAPTER 15 Managing the Database
For what to enter in each field, see Specifying column definitions on page
398.
As you enter information, use the Tab key to move from place to place in
the column definition. After defining the last item in the column
definition, press the Tab key to display the work area for the next column.
3 Repeat step 2 for each additional column in your table.
4 (Optional) Select Object>Pending Syntax from the menu bar or select
Pending Syntax from the pop-up menu to see the pending SQL syntax.
If you have not already named the table, you must provide a name in the
dialog box that displays. To hide the SQL syntax and return to the table
columns, select Object>Pending Syntax from the menu bar.
5 Click the Save button or select Save from the File or pop-up menu, then
enter a name for the table in the Create New Table dialog box.
PowerBuilder submits the pending SQL syntax statements it generated to
the DBMS, and the table is created. The new table is displayed in the
Object Layout view.
2 Right-click in the Columns view and select Save Table As from the pop-up
menu.
3 Enter a name for the new table and then the owner’s name, and click OK.
The new table appears in the Object Layout view and the Columns view.
4 Make whatever changes you want to the table definition.
5 Save the table.
6 Make changes to the table’s properties in the Object Details view.
For more information about modifying table properties, see Specifying
table and column properties on page 399.
398 PowerBuilder
CHAPTER 15 Managing the Database
The properties for the table display in the Object Details view.
2 Select a tab and specify properties:
Select this tab To modify this property
General Comments associated with the table
Data Font Font for data retrieved from the database and displayed in
the Results view by clicking a Data Manipulation button
Heading Font Font for column identifiers used in grid, tabular, and n-up
DataWindow objects displayed in the Results view by
clicking a Data Manipulation button
Label Font Font for column identifiers used in freeform
DataWindow objects displayed in the Results view by
clicking a Data Manipulation button
3 Right-click on the Object Details view and select Save Changes from the
pop-up menu.
Any changes you made in the Object Details view are immediately saved
to the table definition.
400 PowerBuilder
CHAPTER 15 Managing the Database
3 Right-click on the Column property sheet and select Save Changes from
the pop-up menu.
Any changes you made in the property sheet are immediately saved to the
table definition.
Overriding definitions
In the DataWindow painter, you can override the extended attributes specified
in the Database painter for a particular DataWindow object.
How the information is Extended attributes are stored in the PowerBuilder system tables in the
stored database. PowerBuilder uses the information to display, present, and validate
data in the Database painter and in DataWindow objects. When you create a
view in the Database painter, the extended attributes of the table columns used
in the view are used by default.
About display formats, In the Database painter, you create display formats, edit styles, and validation
edit styles, and rules. Whatever you create is then available for use with columns in tables in
validation rules
the database. You can see all the display formats, edit styles, and validation
rules defined for the database in the Extended Attributes view.
For more information about defining, maintaining, and using these extended
attributes, see Chapter 21, Displaying and Validating Data.
About headings and By default, PowerBuilder uses the column names as labels and headings,
labels replacing any underscore characters with spaces and capitalizing each word in
the name. For example, the default heading for the column Dept_name is Dept
Name. To define multiple-line headings, press Ctrl+Enter to begin a new line.
Value Meaning
Any Characters are displayed as they are entered
UPPER Characters are converted to uppercase
lower Characters are converted to lowercase
Specifying a column You can specify that a character column can contain names of picture files.
as a picture
Altering a table
After a table is created, how you can alter the table depends on your DBMS.
You can always:
• Add or modify PowerBuilder-specific extended attributes for columns
402 PowerBuilder
CHAPTER 15 Managing the Database
For complete information about what you can and cannot do when you modify
a table in your DBMS, see your DBMS documentation.
To alter a table:
1 Highlight the table and select Alter Table from the pop-up menu.
The table definition displays in the Columns view (this screen shows the
Employee table).
2 Make the changes you want in the Columns view or in the Object Details
view.
3 Select Save Table or Save Changes.
PowerBuilder submits the pending SQL syntax statements it generated to
the DBMS, and the table is modified.
404 PowerBuilder
CHAPTER 15 Managing the Database
Closing a table
You can remove a table from a view by selecting Close or Reset View from its
pop-up menu. This action only removes the table from the Database painter
view. It does not drop (remove) the table from the database.
Dropping a table
Dropping removes the table from the database.
To drop a table:
1 Select Drop Table from the table’s pop-up menu or select Object>Delete
from the menu bar.
2 Click Yes.
Deleting orphaned If you drop a table outside PowerBuilder, information remains in the system
table information tables about the table, including extended attributes for the columns.
The SQL statements execute only when you save the table definition or
reset the view and then tell PowerBuilder to save changes.
Copying, saving, and When you are viewing pending SQL changes, you can:
printing pending SQL
changes • Copy pending changes to the clipboard
• Save pending changes to a file
• Print pending changes
406 PowerBuilder
CHAPTER 15 Managing the Database
Opening and You can open system tables like other tables in the Database painter.
displaying system
tables
408 PowerBuilder
CHAPTER 15 Managing the Database
To enforce this kind of relationship, you define a foreign key for Dept_Head_ID
that points to the Employee table. With this key in place, the DBMS disallows
any value for Dept_Head_ID that does not match an Emp_ID in the Employee
table.
For more about primary and foreign keys, consult a book about relational
database design or your DBMS documentation.
What you can do in You can work with keys in the following ways:
the Database painter
410 PowerBuilder
CHAPTER 15 Managing the Database
Opening related When working with tables containing keys, you can easily open related tables.
tables
412 PowerBuilder
CHAPTER 15 Managing the Database
Any changes you made in the view are immediately saved to the table
definition.
Defining foreign keys If your DBMS supports foreign keys, you can define them in PowerBuilder.
5 On the Rules tab page, specify any information required by your DBMS.
For example, you might need to specify a delete rule by selecting one of
the rules listed for On Delete of Primary Table Row.
For DBMS-specific information, see your DBMS documentation.
6 Right-click on the Object Details view and select Save Changes from the
pop-up menu.
Any changes you make in the view are immediately saved to the table
definition.
Modifying keys You can modify a primary key in PowerBuilder.
To drop a key:
1 Highlight the key in the expanded tree view for the table in the Objects
view or right-click the key icon for the table in the Object Layout view.
2 Select Drop Primary Key or Drop Foreign Key from the key’s pop-up
menu.
3 Click Yes.
414 PowerBuilder
CHAPTER 15 Managing the Database
Update limitation
You can update a table in a DataWindow object only if it has a unique index or
primary key.
To create an index:
1 Do one of the following:
• Highlight the table for which you want to create an index and click the
Create Index drop-down toolbar button in PainterBar1.
• Select Object>Insert>Index from the main menu or New>Index from
the pop-up menu.
• Expand the table’s tree view, right-click on Indexes, and select New
Index from the pop-up menu.
The Index’s properties display in the Object Details view.
2 Enter a name for the index in the Index box.
3 Select whether or not to allow duplicate values for the index.
4 Specify any other information required for your database.
For example, in Adaptive Server Enterprise specify whether the index is
clustered, and in SQL Anywhere specify the order of the index.
5 Click the names of the columns that make up the index.
6 Select Save Changes from the pop-up menu.
7 Right-click on the Object Details view and select Save Changes from the
pop-up menu.
Any changes you made in the view are immediately saved to the table
definition.
Modifying an index You can modify an index.
To modify an index:
1 Do one of the following:
• Highlight the index listed in the table’s expanded tree view and click
the Properties button.
• Select Properties from the Object or pop-up menu.
• Drag the index icon and drop it in the Object Details view.
2 In the Object Details view, select or deselect columns as needed.
3 Right-click on the Object Details view and select Save Changes from the
pop-up menu.
Any changes you made in the view are immediately saved to the table
definition.
Dropping an index Dropping an index removes it from the database.
416 PowerBuilder
CHAPTER 15 Managing the Database
3 Select the columns to include in the view and include computed columns
as needed.
4 Join the tables if there is more than one table in the view.
For information, see Joining tables on page 419.
5 Specify criteria to limit rows retrieved (Where tab), group retrieved rows
(Group tab), and limit the retrieved groups (Having tab), if appropriate.
For information, see the section on using the SQL Select painter in
Selecting a data source on page 476. The View painter and the SQL Select
painter are similar.
6 When you have completed the view, click the Return button.
7 Name the view.
Include view or some other identifier in the view’s name so that you will
be able to distinguish it from a table in the Select Tables dialog box.
8 Click the Create button.
PowerBuilder generates a CREATE VIEW statement and submits it to the
DBMS. The view definition is created in the database. You return to the
Database painter workspace with the new view displayed in the
workspace.
418 PowerBuilder
CHAPTER 15 Managing the Database
Displaying a database You can display the SQL statement that defines a database view. How you do
view’s SQL statement it depends on whether you are creating a new view in the View painter or want
to look at the definition of an existing view.
Joining tables If the database view contains more than one table, you should join the tables on
their common columns. When the View painter is first opened for a database
view containing more than one table, PowerBuilder makes its best guess as to
the join columns, as follows:
• If there is a primary/foreign key relationship between the tables,
PowerBuilder automatically joins them.
To join tables:
1 Click the Join button.
2 Click the columns on which you want to join the tables.
In the following screen, the Employee and Department tables are joined on
the dept_id column:
3 To create a join other than the equality join, click the join representation in
the workspace.
The Join dialog box displays:
4 Select the join operator you want from the Join dialog box.
If your DBMS supports outer joins, outer join options also display in the
Join dialog box. For example, in the preceding dialog box (which uses the
Employee and Department tables), you can choose to include rows from
the Employee table where there are no matching departments, or rows
from the Department table where there are no matching employees.
For more about outer joins, see Using ANSI outer joins on page 494.
420 PowerBuilder
CHAPTER 15 Managing the Database
Dropping a database Dropping a database view removes its definition from the database.
view
To drop a view:
1 In the Objects view, select the database view you want to drop.
2 Click the Drop Object button or select Drop View from the pop-up menu.
PowerBuilder prompts you to confirm the drop, then generates a DROP
VIEW statement and submits it to the DBMS.
Exporting view syntax You can export the syntax for a view to the log. This feature is useful when you
want to create a backup definition of the view before you alter it or when you
want to create the same view in another DBMS.
Manipulating data
As you work on the database, you often want to look at existing data or create
some data for testing purposes. You might also want to test display formats,
validation rules, and edit styles on real data.
PowerBuilder provides data manipulation for such purposes. With data
manipulation, you can:
• Retrieve and manipulate database information
• Save the contents of the database in a variety of formats (such as Excel,
PDF, or XML)
Retrieving data
To retrieve data:
1 In the Database painter, select the table or database view whose data you
want to manipulate.
Only a few rows of data display at a time. You can use the First, Prior, Next,
and Last buttons or the pop-up menu to move from page to page.
Modifying data
You can add, modify, or delete rows. When you have finished manipulating the
data, you can apply the changes to the database.
422 PowerBuilder
CHAPTER 15 Managing the Database
To modify data:
1 Do one of the following:
• To modify existing data, tab to a field and enter a new value.
• To add a row, click the Insert Row button and enter data in the new
row.
• To delete a row, click the Delete Row button.
When you add or modify data, the data uses the validation rules, display
formats, and edit styles that you or others have defined for the table in the
Database painter.
2 Click the Save Changes button or select Rows>Update to apply changes
to the database.
Sorting rows
You can sort the data, but any sort criteria you define are for testing only and
are not saved with the table or passed to the DataWindow painter.
2 Drag the columns you want to sort on from the Source Data box to the
Columns box:
A check box with a check mark in it displays under the Ascending heading
to indicate that the values will be sorted in ascending order. To sort in
descending order, clear the check box.
Precedence of sorting
The order in which the columns display in the Columns box determines the
precedence of the sorting. For example, in the preceding dialog box, rows
would be sorted by department ID. Within department ID, rows would be
sorted by state.
To change the precedence order, drag the column names in the Column
box into the order you want.
6 When you have specified all the sort columns and expressions, click OK.
424 PowerBuilder
CHAPTER 15 Managing the Database
Filtering rows
You can limit which rows are displayed by defining a filter.
The filters you define are for testing only and are not saved with the table or
passed to the DataWindow painter.
If the expression evaluates to TRUE, the row is displayed. You can paste
functions, columns, and operators in the expression.
3 Click OK.
PowerBuilder filters the data. Only rows meeting the filter criteria are
displayed.
Importing data
You can import data from an external source and then save the imported data
in the database.
To import data:
1 Select Rows>Import from the menu bar.
The Select Import File dialog box displays.
2 Specify the file from which you want to import the data.
The types of files you can import into the Database painter are shown in
the Files of Type drop-down list.
3 Click Open.
PowerBuilder reads the data from the file. You can click the Save Changes
button or select Rows>Update to add the new rows to the database.
426 PowerBuilder
CHAPTER 15 Managing the Database
Printing data
You can print the data displayed by selecting File>Print from the menu bar.
Before printing, you can also preview the output on the screen.
Saving data
You can save the displayed data in an external file.
428 PowerBuilder
CHAPTER 15 Managing the Database
Controlling comments
By default, PowerBuilder strips off comments when it sends SQL to the
DBMS. You can have comments included by clearing the check mark next to
Strip Comments in the pop-up menu of the Interactive SQL view.
Entering SQL
You can enter a SQL statement in four ways:
• Pasting the statement
• Typing the statement in the view
• Opening a text file containing the SQL
• Dragging a procedure or function from the Objects view
Pasting SQL You can paste SELECT, INSERT, UPDATE, and DELETE statements to the view.
Depending on which kind of statement you want to paste, PowerBuilder
displays dialog boxes that guide you through painting the full statement.
• For an INSERT statement, type the values to insert into each column.
You can insert as many rows as you want.
• For an UPDATE statement, specify the new values for the columns in
the Update Column Values dialog box. Then specify the WHERE
criteria to indicate which rows to update.
• For a DELETE statement, specify the WHERE criteria to indicate
which rows to delete.
4 When you have finished creating the SQL statement, click the Return
button in the PainterBar in the Select, Insert, Update, or Delete painter.
You return to the Database painter with the SQL statement pasted into the
ISQL view.
Typing SQL Rather than paste, you can simply type one or more SQL statements directly in
the ISQL view.
You can enter most statements supported by your DBMS. This includes
statements you can paint as well as statements you cannot paint, such as a
database stored procedure or CREATE TRIGGER statement.
You cannot enter certain statements that could destabilize the PowerBuilder
development environment. These include the SET statement and the USE
database statement. However, you might want to use a SET statement to
change a default setting in the development environment, such as SET
NOCOUNT ON or SET ANSI_WARNINGS OFF. You can enable SET commands
in the ISQL view for database interfaces that support them by adding the
following line to the [Database] section in your PB.INI file:
EnableSet=1
Importing SQL from a You can import SQL that has been saved in a text file into the Database painter.
text file
430 PowerBuilder
CHAPTER 15 Managing the Database
Explaining SQL
Sometimes there is more than one way to code SQL statements to obtain the
results you want. If you connect to an SAP database using an SAP native
driver, or to a SQL Anywhere database using the ODBC driver, you can select
Explain SQL on the Design menu to help you choose the most efficient coding
method. Explain SQL displays information about the path that PowerBuilder
will use to execute the statements in the SQL Statement Execution Plan dialog
box. This is most useful when you are retrieving or updating data in an indexed
column or using multiple tables.
DBMS-specific information
The information displayed in the SQL Statement Execution Plan dialog box
depends on your DBMS. For more about the SQL execution plan, see your
DBMS documentation.
Executing SQL
When you have the SQL statements you want in the workspace, you can submit
them to the DBMS.
Setting Coloring You can set the text color and background color for SQL styles (such as
properties datatypes and keywords) so that the style will stand out and the SQL code will
be more readable. You set Coloring properties on the Coloring tab page.
432 PowerBuilder
CHAPTER 15 Managing the Database
Using a desktop Some information that you enter in the wizard is optional, but other
database profile information is required. The wizard prompts you for a database profile, which
it uses to establish a connection to a remote database on the development
computer. If you are not testing a connection on the desktop, you can select the
option to proceed without a database connection and ignore the database
profile field.
A database profile is required for automatic retrieval of publication names in
the database. A publication is a database object describing data to be
synchronized. A publication, along with a synchronization user name and a
synchronization subscription, is required for MobiLink synchronization.
Selecting publication The wizard lets you select multiple publication names if they exist in the
names remote database defined by the connection profile. There must be subscriptions
associated with the publication in order for them to display in the publication
selection list.
If you selected the option to proceed without a database connection, the wizard
prompts you to type a publication name (or a comma-separated list of
publication names) in the MobiLink Client Publication wizard page instead of
prompting you to select publication names retrieved from the database.
For more information about publications, see MobiLink - Client Administration
on the SQL Anywhere online Help.
434 PowerBuilder
CHAPTER 15 Managing the Database
Overriding registry By default, information you enter in the wizard is saved in properties of the
settings on the client nvo_appname_mlsync user object that the wizard generates. This information
computer
includes values that you select for MobiLink logging and command line
options and the MobiLink server and port. Prior to synchronization, the values
of these properties can be modified with values entered by an application user
in the w_appname_sync_options Options window.
The first time synchronization is run, user object property values are entered
into the client computer registry. The next time the application is run, this
information is available for retrieval from the registry.
The ASA MobiLink Synchronization wizard has an optional Override Registry
Settings screen that allows you to override client registry settings. When you
enable runtime overrides to the client registry settings, you must assign a build
number to the objects generated by the wizard.
The build number you assign can be any positive numeric value. To override
the registry settings, the build number you assign must be higher than the build
number in the registry, if there is one. Registry settings will be used if the build
number in the registry is equal to or lower than the build number in the
ObjectRevision property of the nvo_appname_mlsync user object that the
wizard generates.
Security measure
For security reasons, the MobiLink user name and password, and the
authentication parameters and encryption key database settings are never saved
to the registry.
The Override Registry Settings page of the wizard displays only if you do not
change the radio button option to prompt the application user for password and
runtime changes on the previous wizard page (Optional Runtime
Configuration Objects). If, however, you change the radio button selection to
disallow runtime overrides to the synchronization, the wizard does not display
the Override Registry Settings page and does not generate the
w_appname_sync_options Options window.
Wizard options
Except for the object name settings, Table 15-8 lists the ASA MobiLink
Synchronization wizard options.
436 PowerBuilder
CHAPTER 15 Managing the Database
template application. You do not need to create a SQL database connection, but
you do need to create a project.
Before you use the wizard to generate objects for the application, you need to
set up a remote database and add at least one publication, user, and subscription
to it, and create a PowerBuilder database profile for the remote database. To
test the synchronization objects from your application, you need to set up a
consolidated database. You can create your own remote and consolidated
databases, as described in the chapter on MobiLink synchronization in
Application Techniques.
To test the synchronization objects, complete the following steps:
1 Run the wizard.
2 Call synchronization objects from your application.
3 Deploy the application and database files.
4 Start the MobiLink server.
5 Run the application.
Run the wizard You start the wizard from the Database tab of the New dialog box. The wizard
prompts you for a database profile and a publication, although you can enter
this information at a later time after you generate synchronization objects.
Call synchronization Open a menu for your application in the Menu painter and add two submenu
objects from your items to the File menu, called Synchronize and Sync Options. Add the following
application
code to the Clicked event of the Synchronize menu item (appname is the name
of your application):
syncparm s_opt
gf_appname_sync(s_opt)
Add the following code to the Clicked event of the Sync Options menu item:
gf_appname_configure_sync()
Deploy the application Use the Project painter to deploy the application to the desktop and copy this
and database files to all computers that will be connecting remotely to the MobiLink server. You
need to copy the remote database to all end-user computers, and either register
the database as an ODBC database or include connection parameters in a data
source name (DSN) file.
For information on additional files and registry entries required on end-user
computers, see the chapter on MobiLink synchronization in Application
Techniques.
Start the MobiLink Select MobiLink Synchronization Server from the Utilities folder in the
server Database painter. Fill in the required information and click OK to start the
server.
For more information, see Starting the MobiLink synchronization server next.
Run the application Run the application on the remote computer and select the File>Synchronize
and File>Sync Options menu items to test their operation.
438 PowerBuilder
CHAPTER 15 Managing the Database
440 PowerBuilder
C H A P T E R 1 6 Working with Data Pipelines
About this chapter This chapter describes how to use the Data Pipeline painter to create data
pipelines, which let you reproduce database data in various ways.
Contents
Topic Page
About data pipelines 441
Creating a data pipeline 444
Modifying the data pipeline definition 447
Correcting pipeline errors 456
Saving a pipeline 457
Using an existing pipeline 458
Pipeline examples 458
Source and You can use the Data Pipeline painter to pipe data from one or more tables in a
destination databases source database to one table in a destination database.
You can pipe all data or selected data in one or more tables. For example, you
can pipe a few columns of data from one table or data selected from a
multitable join. You can also pipe from a view or a stored procedure result set
to a table.
When you pipe data, the data in the source database remains in the source
database and is reproduced in a new or existing table in the destination
database.
Although the source and destination can be the same database, they are usually
different ones, and they can even have different DBMSs. For example, you can
pipe data from an Adaptive Server Enterprise database to a SQL Anywhere
database on your computer.
442 PowerBuilder
CHAPTER 16 Working with Data Pipelines
Datatype support Each DBMS supports certain datatypes. When you pipe data from one DBMS
to another, PowerBuilder makes a best guess at the appropriate destination
datatypes. You can correct PowerBuilder’s best guess in your pipeline
definition as needed.
The Data Pipeline painter supports the piping of columns of any datatype,
including columns with blob data. For information about piping a column that
has a blob datatype, see Piping blob data on page 454.
When the Extended Attributes check box is selected, the extended attributes
associated with the source database’s selected columns automatically go into
the extended attribute system tables of the destination database, with one
exception. When you pipe a column that has an edit style, display format, or
validation rule associated with it, the style, rule, or format is not piped if one
with the same name exists in the extended attribute system tables of the
destination database. In this situation, the column uses the style, rule, or format
already present in the destination database.
For example, for the Phone column in the Employee table, the display format
with the name Phone_format would be piped unless a display format with the
name Phone_format already exists in the destination database. If such a display
format exists, the Phone column would use the Phone_format display format in
the destination database.
Piping the extended Selecting the Extended Attributes check box never results in the piping of
attribute system tables named display formats, edit styles, and validation rules that are stored in the
extended attribute system tables but are not associated with columns in tables
you are piping. If you want such extended attribute definitions from one
database to exist in another database, you can pipe the appropriate extended
attribute system table or a selected row or rows from the table.
Piping an entire If you want to reproduce an entire database, you can pipe all database tables
database and extended attribute system tables, one table at a time.
444 PowerBuilder
CHAPTER 16 Working with Data Pipelines
446 PowerBuilder
CHAPTER 16 Working with Data Pipelines
PowerBuilder retrieves the source data and executes the pipeline. If you
specified retrieval arguments in the Select painter, PowerBuilder first
prompts you to supply them.
At runtime, the number of rows read and written, the elapsed execution
time, and the number of errors display in MicroHelp. You can stop
execution yourself or PowerBuilder might stop execution if errors occur.
For information about execution and how rows are committed to the
destination table, see When execution stops on page 452.
9 Save the pipeline definition if appropriate.
For information, see Saving a pipeline on page 457.
Table 16-2 lists properties that you can modify that apply to the destination
table’s columns and keys. These properties display under the properties that
apply to the table itself and most can be modified only for the Create and
Replace pipeline operations.
Table 16-2: Pipeline properties for the destination table’s columns and
keys
Item Description Default How to edit
Destination Column name Source column name. Enter a name.
Name
Type Column datatype If the DBMS is unchanged, Select a type from the
source column datatype. If the drop-down list.
DBMS is different, a
best-guess datatype.
Key Whether the column is a key Source table’s key columns (if Select or clear check boxes.
column (check means yes) the source is only one table and
all key columns were selected).
Width Column width Source column width. Enter a number.
Dec Decimal places for the column Source column decimal places. Enter a number.
Nulls Whether NULL is allowed for Source column value. Select or clear check boxes.
the column (check means yes)
448 PowerBuilder
CHAPTER 16 Working with Data Pipelines
450 PowerBuilder
CHAPTER 16 Working with Data Pipelines
If you try to use the Create option, but a table with the specified name already
exists in the destination database, PowerBuilder tells you, and you must select
another option or change the table name.
When you use the Replace option, PowerBuilder warns you that you are
deleting a table, and you can choose another option if needed.
When using Refresh For the Refresh - Delete/Insert Rows or Append - Insert Rows options, the
and Append destination table must already exist. You can:
• Select an existing table from the Table drop-down list.
• Modify the Commit and Max Errors values.
• Change the initial value for a column.
When using Update For the Update - Update/Insert Rows option, the destination table must already
exist. You can:
• Select an existing table from the Table drop-down list.
• Modify the Commit and Max Errors values.
• Change the Key columns in the destination table’s primary key or unique
index, depending on what the DBMS supports. Key columns must be
selected; the key determines the UPDATE statement’s WHERE clause.
• Change the initial value for a column.
452 PowerBuilder
CHAPTER 16 Working with Data Pipelines
For example, if an error occurs when the 24th row is piped and the Commit
value is 10 and the Max Errors value is 1, then:
1 10 rows are piped and committed.
2 10 rows are piped and committed.
3 3 rows are piped and committed.
4 Piping stops.
If the Commit value is All or None, 23 rows are rolled back.
About transactions A transaction is a logical unit of work done by a DBMS, within which either
all the work in the unit must be completed or none of the work in the unit must
be completed. If the destination DBMS does not support transactions or is not
in the scope of a transaction, each row that is inserted or updated is committed.
About the All and In the Data Pipeline painter, the Commit values All and None have the same
None commit values meaning.
The None commit value is most useful at runtime. For example, some
PowerBuilder applications require either all piped rows to be committed or no
piped rows to be committed if an error occurs. Specifying None allows the
application to control the committing and rolling back of piped rows by means
of explicit transaction processing, such as the issuing of commits and rollbacks
in pipeline scripts using COMMIT and ROLLBACK statements.
For information about the datatype that supports blob data in your DBMS, see
your DBMS documentation.
Adding blob columns When you select data to pipe, you cannot select a blob column as part of the
to a pipeline definition data source because blobs cannot be handled in a SELECT statement. After the
pipeline definition is created, you add blob columns, one at a time, to the
definition.
The Database Binary/Text Large Object dialog box displays. The Table
box has a drop-down list of tables in the pipeline source that have a
primary key and contain blob columns.
454 PowerBuilder
CHAPTER 16 Working with Data Pipelines
2 In the Table box, select the table that contains the blob column you want
to add to the pipeline definition.
For example, in the PB Demo DB, the ole table contains a blob column
named Object with the large binary datatype.
3 In the Large Binary/Text Column box, select a column that has a blob
datatype.
4 In the Destination Column box, change the name of the destination column
for the blob if you want to.
If you want to add the column and see changes you make without closing
the dialog box, click Apply after each change.
5 When you have specified the blob source and destination as needed, click
OK.
To edit the source or destination name of the blob column in the pipeline
definition:
• Display the blob column’s pop-up menu and select Properties.
Changing the source Normally you would not change the source database, because your pipeline
definition is dependent on it, but if you need to (perhaps because you are no
longer connected to that source), you can.
Working with At any time in the Data Pipeline painter, you can edit an existing database
database profiles profile or create a new one.
456 PowerBuilder
CHAPTER 16 Working with Data Pipelines
Saving a pipeline
When you have generated a pipeline definition in the Data Pipeline painter
workspace, you should save the pipeline. You can then reuse it later.
To save a pipeline:
• Click the Save button, or select File>Save from the menu bar.
For a new pipeline When you save a pipeline for the first time, you must specify a name. The name
can be any valid identifier with up to 80 characters. A common convention is
to prefix the name with the string pipe_. You can also specify the library in
which the pipeline is saved.
Pipeline examples
Updating data in a You might want to pipe data and then update the data often.
destination table
458 PowerBuilder
CHAPTER 16 Working with Data Pipelines
460 PowerBuilder
PA RT 6 Working with
DataWindows
About this chapter The applications you build are centered around your organization’s data.
This chapter describes how to define DataWindow objects to display and
manipulate the data.
Contents
Topic Page
About DataWindow objects 463
Choosing a presentation style 466
Building a DataWindow object 475
Selecting a data source 476
Using Quick Select 478
Using SQL Select 488
Using Query 503
Using External 503
Using Stored Procedure 504
Using a Web service data source 507
Using the OData Service 507
Choosing DataWindow object-wide options 511
Generating and saving a DataWindow object 512
Defining queries 515
What's next 517
Display formats If a column displays phone numbers, salaries, or dates, you can specify the
format appropriate to the data.
Validation rules If a column can take numbers only in a specific range, you can specify a simple
validation rule for the data, without writing any code, to make sure users enter
valid data.
Enhancing If you want to enhance the presentation and manipulation of data in a
DataWindow objects DataWindow object, you can include computed fields, pictures, and graphs that
are tied directly to the data retrieved by the object.
464 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Reports versus Reports and DataWindow objects are the same objects. You can open and
DataWindow objects modify both in the DataWindow painter. However, a report is not updatable and
can only be used to present data. For information about how you can specify
whether users can update the data in a DataWindow object, see Chapter 20,
Controlling Updates in DataWindow objects.
466 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
reorganize the default layout any way you want by moving columns and text:
468 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Grid report with This grid report was created from the original one by decreasing the width of
modified column some columns:
widths
Mailing labels
Business cards
Name tags
Specifying label If you choose the Label style, you are asked to specify the properties for the
properties label after specifying the data source. You can choose from a list of predefined
label types or enter your own specifications manually.
Where label PowerBuilder gets the information about the predefined label formats from a
definitions come from preferences file called pblab170.ini.
470 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
472 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
For more about the Group presentation style, see Chapter 22, Filtering,
Sorting, and Grouping Rows.
For more about the Composite presentation style, see Chapter 24, Using
Nested Reports.
For more information about these two presentation styles, see Chapter 25,
Working with Graphs, and Chapter 26, Working with Crosstabs.
474 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
For more about the TreeView presentation style, see Chapter 27, Working with
TreeViews.
Column limit
There is a limit of 1000 on the number of columns in a DataWindow object.
476 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
If the data is in the If the data for the DataWindow object will be retrieved from a database, choose
database one of the data sources from Table 17-2.
Table 17-2: Data source choices for data from a database
Data source Use when
Quick Select The data is from a single table (or from tables that are related
through foreign keys) and you need only to choose columns,
selection criteria, and sorting.
SQL Select You want more control over the SQL SELECT statement
generated for the data source or your data is from tables that
are not connected through a key. For example, you need to
specify grouping, computed columns, or retrieval arguments
within the SQL SELECT statement.
Query The data has been defined as a query.
Stored Procedure The data is defined in a stored procedure.
If the data is not in a Web Service data source Select the Web Service data source if you want to
database populate the DataWindow object with data you obtain from a Web service.
For more information, see Using a Web service data source on page 507.
External data source Select the External data source if:
• The DataWindow object will be populated programmatically.
• Data will be imported from a DDE application.
• Data will be imported from an external file, such as an XML,
comma-separated values (CSV), tab-separated text (TXT), or dBASE
(DBF) file.
You can also use an ODBC driver to access data from a file.
For more information, see Connecting to Your Database.
After you choose a data source in the various DataWindow wizards, you
specify the data. The data source you choose determines what displays in the
wizards and how you define the data.
Why use a Even when the data is not coming from the database, there are many times
DataWindow if the when you want to take advantage of the intelligence of a DataWindow object:
data is not from a
DBMS • Data Validation You have full access to validation rules for data
• Display Formats You can use any existing display formats to present the
data, or create your own
• Edit Styles You can use any existing edit styles, such as radio buttons
and edit masks, to present the data, or create your own
478 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
To use these options when you create a DataWindow object, choose SQL
Select as your data source. If you decide later that you want to use retrieval
arguments, you can define them by modifying the data source. For more
information, see Chapter 18, Enhancing DataWindow Objects.
Selecting a table
When you choose Quick Select, the Quick Select dialog box displays. The
Tables box lists tables and views in the current database.
Which tables and The DBMS determines what tables and views display. For some DBMSs, all
views display? tables and views display, whether or not you have authorization. If you select
a table or view you are not authorized to access, the DBMS issues a message.
For ODBC databases, the tables and views that display depend on the driver for
the data source. SQL Anywhere does not restrict the display, so all tables and
views display, whether or not you have authorization.
Tables with key When you select a table, the table’s column names display in the Columns box,
relationships and any tables having a key relationship with the selected table display in the
Tables box. These tables are indented and marked with an arrow to show their
relationship to the selected table. You can select any of these related tables if
you want to include columns from them in the DataWindow object.
Meaning of the up and An arrow displays next to a table to indicate its relationship to the selected
down arrows table. The arrow always points in the many direction of the relationship—
toward the selected table (up) if the selected table contains a foreign key in the
relationship and away from the selected table (down) if the selected table
contains a primary key in the relationship:
480 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Selecting columns
You can select columns from the primary table and from its related tables.
Select the table whose columns you want to use in the Tables box, and add
columns from the Columns box:
• To add a column, select it in the Columns box.
• To add all the columns that display in the Columns box, click Add All.
• To remove a column, deselect it in the Columns box.
• To view comments that describe a table or column, position the pointer on
a table or column name, and press and hold the right mouse button.
As you select columns, they display in the grid at the bottom of the dialog box
in the order in which you select them. If you want the columns to display in a
different order in the DataWindow object, select a column name you want to
move in the grid and drag it to the new location.
482 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
SQL operators You can use these SQL relational operators in the retrieval criteria:
supported in Quick
Select Table 17-3: SQL relational operators used in retrieval criteria
Operator Meaning
= Is equal to (default operator)
> Is greater than
< Is less than
<> Is not equal to
>= Is greater than or equal to
<= Is less than or equal to
LIKE Matches this pattern
NOT LIKE Does not match this pattern
IN Is in this set of values
NOT IN Is not in this set of values
Because = is the default operator, you can enter the value 100 instead of = 100,
or the value New Hampshire instead of = New Hampshire.
Comparison operators You can use the LIKE, NOT LIKE, IN, and NOT IN operators to compare
expressions.
Use LIKE to search for strings that match a predetermined pattern. Use NOT
LIKE to find strings that do not match a predetermined pattern. When you use
LIKE or NOT LIKE, you can use wildcards:
• The percent sign (%), like the wildcard asterisk (*) used in many
applications, matches multiple characters. For example, Good% matches all
names that begin with Good.
• The underscore character (_) matches a single character. For example,
Good _ _ _ matches all seven-letter names that begin with Good.
Use IN to compare and include a value that is in a set of values. Use NOT IN to
compare and include values that are not in a set of values. For example, the
following clause selects all employees in department 100, 200, or 500:
SELECT * from employee
WHERE dept_id IN (100, 200, 500)
484 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Example 2 The expression 100 in the Criteria row in the DeptId column in the grid
retrieves information for employees who belong to department 100.
486 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
employee.salary
FROM employee
WHERE (((employee.emp_id >='500') AND
(employee.salary >='30000') AND
(employee.emp_id <='1000') AND
(employee.salary <='50000')))
Example 7 In a grid with three columns: emp_last_name, emp_first_name, and salary, the
expressions LIKE C% in the Criteria row and LIKE G% in the Or row in the
emp_last_name column retrieve information for employees who have last
names that begin with C or G.
488 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Below the Table Layout view, several tabbed views also display by default.
You use the views (for example, Compute, Having, Group) to specify the SQL
SELECT statement in more detail. You can turn the views on and off from the
View menu on the menu bar.
Specifying what is You can display the label and datatype of each column in the tables (the label
displayed information comes from the extended attribute system tables). If you need
more space, you can choose to hide this information.
You can also remove individual tables and views from the Table Layout view,
or clear them all at once and begin selecting a new set of tables.
How PowerBuilder If you select more than one table in the SQL Select painter, PowerBuilder joins
joins tables columns based on their key relationship.
490 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Selecting columns
You can click each column you want to include from the table representations
in the Table Layout view. PowerBuilder highlights selected columns and places
them in the Selection List at the top of the SQL Select painter.
3 Press the Tab key to get to the next row to define another computed
column, or click another tab to make additional specifications.
PowerBuilder adds the computed columns to the list of columns you have
selected.
About computed Computed columns you define in the SQL Select painter are added to the SQL
columns and statement and used by the DBMS to retrieve the data. The expression you
computed fields
define here follows your DBMS’s rules.
You can also choose to define computed fields, which are created and
processed dynamically by PowerBuilder after the data has been retrieved from
the DBMS. There are advantages to doing this. For example, work is offloaded
from the database server, and the computed fields update dynamically as data
changes in the DataWindow object. (If you have many rows, however, this
updating can result in slower performance.) For more information, see Chapter
18, Enhancing DataWindow Objects.
492 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Joining tables
If the DataWindow object will contain data from more than one table, you
should join the tables on their common columns. If you have selected more
than one table, PowerBuilder joins columns according to whether they have a
key relationship:
• Columns with a primary/foreign key relationship are joined automatically.
• Columns with no key relationship are joined, if possible, based on
common column names and types.
PowerBuilder links joined tables in the SQL Select painter Table Layout view.
PowerBuilder joins can differ depending on the order in which you select the
tables, and sometimes the PowerBuilder best-guess join is incorrect, so you
may need to delete a join and manually define a join.
To delete a join:
1 Click the join operator connecting the tables.
The Join dialog box displays.
2 Click Delete.
To join tables:
1 Click the Join button in the PainterBar.
2 Click the columns on which you want to join the tables.
3 To create a join other than an equality join, click the join operator in the
Table Layout view.
The Join dialog box displays:
table-reference ::=
table_view_name [correlation_name] | OUTER-join
494 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Order of evaluation In ANSI SQL-92, when nesting joins, the result of the first outer join
and nesting (determined by order of ON conditions) is the operand of the outer join that
follows it. In PowerBuilder, an outer join is considered to be nested if the
table-reference on the left of the JOIN has been used before within the same
outer join nested sequence.
The order of evaluation for ANSI syntax nested outer joins is determined by
the order of the ON search conditions. This means that you must create the
outer joins in the intended evaluation order and add nested outer joins to the
end of the existing sequence, so that the second table-reference in the outer join
BNF above will always be a table_view_name.
Nesting example For example, if you create a left outer join between a column in Table1 and a
column in Table2, then join the column in Table2 to a column in Table3, the
product of the outer join between Table1 and Table2 is the operand for the outer
join with Table3.
For standard database connections, the default generated syntax encloses the
outer joins in escape notation {oj ...} that is parsed by the driver and
replaced with DBMS-specific grammar:
SELECT Table1.col1, Table2.col1, Table3.col1
FROM {oj {oj Table1 LEFT OUTER JOIN Table2 ON Table1.col1 =
Table2.col1}
LEFT OUTER JOIN Table3 ON Table2.col1 = Table3.col1}
Table references Table references are considered equal when the table names are equal and there
is either no alias (correlation name) or the same alias for both. Reusing the
operand on the right is not allowed, because ANSI does not allow referencing
the table_view_name twice in the same statement without an alias.
Determining left and When you create a join condition, the table you select first in the painter is the
right outer joins left operand of the outer join. The table that you select second is the right
operand. The condition you select from the Joins dialog box determines
whether the join is a left or right outer join.
For example, suppose you select the dept_id column in the employee table, then
select the dept_id column in the department table, then choose the following
condition:
employee.dept_id = department.dept_id and rows from
department that have no employee
The syntax generated is:
SELECT employee.dept_id, department.dept_id
FROM {oj "employee" RIGHT OUTER JOIN "department" ON
"employee"."dept_id" = "department"."dept_id"}
Equivalent statements
The syntax generated when you select table A then table B and create a left
outer join is equivalent to the syntax generated when you select table B then
table A and create a right outer join.
If you want the user to be prompted to identify which rows to retrieve, you can
define retrieval arguments when defining the SQL SELECT statement. For
example, consider these situations:
• Retrieving the row in the Employee table for an employee ID entered into
a text box. You must pass that information to the SELECT statement as an
argument at runtime.
• Retrieving all rows from a table for a department selected from a
drop-down list. The department is passed as an argument at runtime.
496 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Referencing retrieval If you have defined retrieval arguments, you reference them in the WHERE or
arguments HAVING clause. In SQL statements, variables (called host variables) are always
prefaced with a colon to distinguish them from column names.
For example, if the DataWindow object is retrieving all rows from the
Department table where the dept_id matches a value provided by the user at
runtime, your WHERE clause will look something like this:
WHERE dept_id = :Entered_id
where Entered_id was defined previously as an argument in the Specify
Retrieval Arguments dialog box.
Referencing arrays
Use the IN operator and reference the retrieval argument in the WHERE or
HAVING clause.
498 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Defining WHERE You can limit the rows that are retrieved into the DataWindow object by
criteria specifying selection criteria that correspond to the WHERE clause in the
SELECT statement.
For example, if you are retrieving information about employees, you can limit
the employees to those in Sales and Marketing, or to those in Sales and
Marketing who make more than $50,000.
• Paste a value from the database by selecting Value from the pop-up
menu, then selecting a value from the list of values retrieved from the
database. (It may take some time to display values if the column has
many values in the database.)
• Define a nested SELECT statement by selecting Select from the pop-
up menu. In the Nested Select dialog box, you can define a nested
SELECT statement. Click Return when you have finished.
500 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
You can change the sorting order by dragging the selected column names
up or down. With the following sorting specification, rows will be sorted
first by department ID, then by employee ID:
The columns in the tables you selected display in the left side of the Group
view. You might need to scroll to see your selections.
2 Drag the first column you want to group onto the right side of the Group
view.
This specifies the column for grouping. Columns are grouped in the order
in which they are displayed in the right side of the Group view.
3 Continue to specify additional columns for grouping within the first
grouping column as needed.
To change the grouping order, drag the column names in the right side to
the positions you want.
4 Define sorting (Sort view), limiting (Where view), and limiting groups
(Having view) criteria as appropriate.
5 Click the Return button to return to the DataWindow painter.
Defining HAVING If you have defined groups, you can define HAVING criteria to restrict the
criteria retrieved groups. For example, if you group employees by department, you can
restrict the retrieved groups to departments whose employees have an average
salary of less than $50,000. This corresponds to:
SELECT dept_id, sum(salary), avg(salary)
FROM employee
GROUP BY dept_id
HAVING avg(salary) < 50000
If you specify this with the Employee table in the PB Demo DB, you will get
three rows back, because there are three departments that have average salaries
less than $50,000.
502 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Using Query
When you choose Query as the data source, you select a predefined SQL
SELECT statement (a query) as specifying the data for your DataWindow
object.
Using External
If the data for the DataWindow object does not come from a database (either
through a native SAP database interface or through a standard database
interface), specify External as the data source. You then specify the data
columns and their types so PowerBuilder can build the appropriate
DataWindow object to hold the data. These columns make up the result set.
PowerBuilder places the columns you specified in the result set in the
DataWindow object.
3 Click Add to enter the name and type of any additional columns you want
in the result set.
4 Click Next when you have added all the columns you want.
What you do next In code, you need to tell PowerBuilder how to get data into the DataWindow
object in your application. Typically, you import data at runtime using a
method (such as IimportFile or IimportString) or do some data manipulation and
use the SetItem method to populate the DataWindow.
For more about these methods, see the online help.
You can also import data values from an external file into the DataWindow
object or report.
504 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
When you have finished interacting with the wizard, you go to the
DataWindow painter with the columns specified in the result set placed in
the DataWindow object.
For information about defining retrieval arguments for DataWindow
objects, see Chapter 18, Enhancing DataWindow Objects.
For information about using a stored procedure to update the database, see
Using stored procedures to update the database on page 602.
Editing a result set After you create a result set that uses a stored procedure, you can edit the result
description set description from the DataWindow painter.
506 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Support for a Web service data source is not available for RichText and OLE
presentation styles.
Using the After you select a supported DataWindow presentation style from the
DataWindow wizard DataWindow tab of the New dialog box, you select a data source for the
DataWindow.
When you select Web Service as the data source and click Next, the
DataWindow wizard opens a page that prompts you to select a WSDL file. The
file you select should be in a publicly accessible location for all members of the
development team. You can enter the URL to a WSDL, ASMX, or XML file,
or you can browse a mapped drive for these types of files.
The Choose WSDL File page of the DataWindow wizard also lets you name
the assembly file that the wizard will create. The assembly file serves as an
interface between the DataWindow and the Web service. If you do not name
the assembly file, the wizard will select a name for you based on the name of
the WSDL file entry.
The next step to access a Web service data source is to select a service
described in the WSDL, and then one of its public methods. You must then
select a parameter for the DataWindow to use as the result set for the method.
A DataWindow typically obtains its data from an array of structures. Because
a Web service method can pass an array of structures in one of its arguments
rather than in a return value, the wizard prompts you to select one of the
method’s arguments or its return value as the designated result set for the
method. If you want data for a single row and column only, you can select a
parameter that has a simple datatype. You can also select a parameter that is an
array of simple datatypes rather than an array of structures.
You complete the wizard as you would when using any other type of data
source for your DataWindow. After you complete the wizard, the DataWindow
displays in the DataWindow painter. However, there is no equivalent to the
SQL painter for a DataWindow with a Web service data source. For this type
of DataWindow, you cannot select Design>Data Source from the DataWindow
painter menu to change selected columns or modify the DataWindow syntax.
The DataWindow can also use a Web service data source that has structures for
parameters, as long as the structures are composed of the simple datatypes that
can be mapped to DataWindow datatypes. An array of structures can be
mapped to n rows with x columns where n is the size of the array and x is the
number of members in the structure. Nested structures are not supported.
508 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Using parameters by For a Web service that you create from a PowerBuilder nonvisual object, a
reference result set must be passed by reference, but it cannot be passed in a method
return value. You must use a method argument to pass the result set and then
select that argument in any DataWindow object that uses the method as its data
source.
A parameter passed by reference is a bidirectional [IN,OUT] parameter by
definition. The Web Service DataWindow wizard lets you select a Web service
method [OUT] or [IN,OUT] parameter, instead of the method return value, to
pass a result set to a DataWindow object. However, the parameter you select
cannot be used for both a return value and a retrieval argument by the same
DataWindow object.
Database-related In the Web Service DataWindow, some database or transaction-related
functions and events functions and events are not supported and meaningless because the Web
Service DataWindow has no direct relation to the database. The following
functions cannot be used with the Web Service DataWindow: GetSQLPreview,
GetSQLSelect, SetSQLPreview, SetSQLSelect, SetTrans, and SetTransObject.
The DBError event is also not supported for the Web Service DataWindow.
Instead, you can use the WSError error event to handle errors during retrieve,
insert, or update operations.
Using the Some Web services support or require a user ID and password, and other
WSConnection object session-related properties like firewall settings. The WSConnection object can
provide this information for your DataWindow connections.
You use an instance of the WSConnection object to connect to a Web service
by calling the SetWSObject method.
The following code instantiates a WSConnection object with user-related and
authentication information, then sets the object as the connection object for a
Web service data source:
int ii_return
wsconnection ws_1
ws_1 = create wsconnection
ws_1.username = "johndoe"
ws_1.password = "mypassword"
ws_1.endpoint = "myendpoint"
ws_1.authenticationmode = "basic"
ws_1.usewindowsintegratedauthentication = true
ii_return = dw_1.setwsobject (ws_1)
For more information about setting properties for a Web service connection,
see WSConnection and SetWSObject in the online Help.
For more information about updating the database with a Web service
DataWindow, see Using a Web service to update the database on page 604.
510 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
The values for properties shown on the page are for the currently selected
presentation style.
4 Change one or more of the following properties:
Property Meaning for the DataWindow object
Background color The default color for the background.
Text border and color The default border and color used for labels and
headings.
Column border and color The default border and color used for data values.
Wrap Height (Freeform The height of the detail band.
only) When the value is None, the number of columns
selected determines the height of the detail band.
The columns display in a single vertical line.
When the value is set to a number, the detail band
height is set to the number specified and columns
wrap within the detail band.
5 Click OK.
Your choices are PowerBuilder saves your generation option choices as the defaults to use when
saved creating a DataWindow object with the same presentation style.
512 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
514 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Defining queries
A query is a SQL SELECT statement created in the Query painter and saved
with a name so that it can be used repeatedly as the data source for a
DataWindow object.
Queries save time, because you specify all the data requirements just once. For
example, you can specify the columns, which rows to retrieve, and the sorting
order in a query. Whenever you want to create a DataWindow object using that
data, simply specify the query as the data source.
To define a query:
1 Select File>New from the menu bar.
2 In the New dialog box, select the Database tab.
3 Select the Query icon and click OK.
4 Select tables in the Select Tables dialog box and click Open.
You can select columns, define sorting and grouping criteria, define
computed columns, and so on, exactly as you do when creating a
DataWindow object using the SQL Select data source.
For more about defining the SELECT statement, see Using SQL Select on page
488.
To preview a query:
1 Select DesignPreview from the menu bar.
PowerBuilder retrieves the rows satisfying the currently defined query in
a grid-style DataWindow object.
2 Manipulate the retrieved data as you do in the Database painter in the
Output view.
You can sort and filter the data, but you cannot insert or delete a row or
apply changes to the database. For more about manipulating data, see
Chapter 15, Managing the Database.
3 When you have finished previewing the query, click the Close button in
the PainterBar to return to the Query painter.
516 PowerBuilder
CHAPTER 17 Defining DataWindow Objects
Modifying a query
To modify a query:
1 Select File>Open from the menu bar.
2 Select the Queries object type and then the query you want to modify, and
click OK.
3 Modify the query as needed.
What's next
After you have generated your DataWindow object, you will probably want to
preview it to see how it looks. After that, you might want to enhance the
DataWindow object in the DataWindow painter before using it. PowerBuilder
provides many ways for you to make a DataWindow object easier to use and
more informative for users. See Chapter 18, Enhancing DataWindow Objects,
next.
518 PowerBuilder
C H A P T E R 1 8 Enhancing DataWindow Objects
About this chapter Before you put a DataWindow object into production, you can enhance it
to make it easier to use and interpret data. You do that in the DataWindow
painter. This chapter describes basic enhancements you can make to a
DataWindow object.
Contents
Topic Page
Working in the DataWindow painter 520
Using the Preview view of a DataWindow object 528
Saving data in an external file 538
Modifying general DataWindow object properties 546
Storing data in a DataWindow object using the Data view 563
Retrieving data 564
Related topics Other ways to enhance DataWindow objects are covered in later chapters:
Chapter Explains how to
Chapter 19, Working with Controls Add controls to a DataWindow object
in DataWindow Objects and reorganize, position, and rotate them
Chapter 21, Displaying and Specify display formats, edit styles, and
Validating Data validation rules for column data
Chapter 22, Filtering, Sorting, and Limit which rows are displayed, the
Grouping Rows order in which they are displayed, and
whether they are divided into groups
Chapter 23, Highlighting Highlight data by using conditional
Information in DataWindow expressions to modify the properties of
Objects controls in DataWindow objects
Chapter 24, Using Nested Reports Place reports inside DataWindow
objects
Chapter 25, Working with Graphs Use graphs to visually present
information retrieved in a DataWindow
object
Chapter 26, Working with Use crosstabs to present analyses of data
Crosstabs retrieved in a DataWindow object
Design view The Design view at the top left shows a representation of the DataWindow
object and its controls. You use this view to design the layout and appearance
of the DataWindow object. Changes you make are immediately shown in the
Preview view and the Properties view.
520 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
Preview view The Preview view in the middle on the left shows the DataWindow object with
data as it will appear at runtime. If the Print Preview toggle (File>Print
Preview) is selected, you see the DataWindow object as it would appear when
printed with an optional blue outline that shows where the page margins are
located.
Export/Import The Export/Import Template view for XML at the bottom left shows a default
Template view for template for exporting and importing data in XML format. You can define
XML
custom templates for import and export. The templates are saved with the
DataWindow object. For more information, see Chapter 28, Exporting and
Importing XML Data.
Export Template view The Export Template view for XHTML (not shown; see XHTML tab at the
for XHTML bottom left) shows a default template for exporting data in XHTML format.
You can define custom XHTML export templates for customizing XML Web
DataWindow generation. The templates are saved with the DataWindow
object.
Properties view The Properties view at the top right displays the properties for the currently
selected control(s) in the DataWindow object, for the currently selected band
in the DataWindow object, or for the DataWindow object itself. You can view
and change the values of properties in this view.
Control List view The Control List in the stacked pane at the bottom right view lists all controls
in the DataWindow object. Selecting controls in this view selects them in the
Design view and the Properties view. You can also sort controls by Control
Name, Type, or Tag.
Data view The Data view in the stacked pane at the bottom right displays the data that can
be used to populate a DataWindow object and allows manipulation of that data.
Column Specifications The Column Specifications view in the stacked pane at the bottom right shows
view a list of the columns in the data source. For the columns, you can add, modify,
and delete initial values, validation expressions, and validation messages. You
can also specify that you want a column to be included in a prompt for retrieval
criteria during data retrieval. To add a column to the DataWindow object, you
can drag and drop the column from the Column Specifications view to the
Design view. For external or stored procedure data sources, you can add,
delete, and edit columns (column name, type, and length).
522 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
You can specify additional heading information (such as a date) in the header
band and you can include pictures, graphic controls, and color to enhance the
appearance of the band.
When you design the detail band of a DataWindow object, you can specify
display and validation information for each column of the DataWindow object
and add other controls, such as text, pictures, graphs, and drawing controls.
StyleBar The StyleBar includes buttons for applying properties (such as bold) to selected
text elements.
524 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
To use the Properties view to modify the parts of the DataWindow object:
1 Position the mouse over the part you want to modify.
2 Display the part’s pop-up menu and select Properties.
If it is not already displayed, the Properties view displays. The view
displays the properties of the currently selected control(s), the band, or the
DataWindow object itself. The contents of the Properties view change as
different controls are selected (made current).
For example, the Properties view for a column has tabbed property pages of
information that you access by clicking the appropriate tab. If you want to
choose an edit style for the column, you click the Edit tab. This brings the Edit
page to the front of the Properties view.
Lasso selection
Use lasso selection when possible because it is fast and easy. Lasso selection is
another name for the method described below for selecting neighboring
multiple controls.
526 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
Displaying information The name, x and y coordinates, width, and height of the selected control are
about the selected displayed in the MicroHelp bar. If multiple controls are selected, Group
control
Selected displays in the Name area and the coordinates and size do not display.
Retrieving data
Where PowerBuilder PowerBuilder follows this order of precedence to supply the data in your
gets data DataWindow object:
1 If you have saved data in the DataWindow object, PowerBuilder uses the
saved rows from the DataWindow object and does not retrieve data from
the database.
2 PowerBuilder uses the data in the cache, if there is any.
528 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
3 If there is no data in the cache yet, PowerBuilder retrieves data from the
database automatically, with one exception. If the Retrieve on Preview
option is off, you have to request retrieval explicitly, as described next.
Previewing without If you do not want PowerBuilder to retrieve data from the database
retrieving data automatically when the Preview view opens, you can clear the Retrieve on
Preview option. The Preview view shows the DataWindow object without
retrieving data.
PowerBuilder uses When PowerBuilder first retrieves data, it stores the data internally. When it
data caching refreshes the Preview view, PowerBuilder displays the stored data instead of
retrieving rows from the database again. This can save you a lot of time, since
data retrieval can be time consuming.
How using data from Because PowerBuilder accesses the cache and does not automatically retrieve
the cache affects you data every time you preview, you might not have what you want when you
preview. The data you see in preview and the data in the database can be out of
sync.
For example, if you are working with live data that changes frequently or with
statistics based on changing data and you spend time designing the
DataWindow object, the data you are looking at may no longer match the
database. In this case, retrieve again just before printing.
Explicitly retrieving You can explicitly request retrieval at any time.
data
Modifying data
You can add, modify, or delete rows in the Preview view. When you have
finished manipulating the data, you can apply the changes to the database.
Changing input You (and your users) can add or modify data in a DataWindow object in
language multiple input languages. If you use multiple input languages, you can display
a Language bar on your desktop to change the current input language. In a
DataWindow object, the input language in effect the first time a column gets
focus becomes the default input language for that column. If you subsequently
change the input language when that column has focus, the new input language
becomes the default for that column. This behavior does not apply to columns
that have the RightToLeft property set.
530 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
To add a row:
1 Click the Insert Row button.
PowerBuilder creates a blank row.
2 Enter data for a row.
To save the changes to the database, you must apply them, as described below.
Selecting Insert Row is equivalent to calling the insertRow method and then
the scrollToRow method at runtime.
To delete a row:
• Click the Delete Row button.
PowerBuilder removes the row from the display.
To save the changes to the database, you must apply them, as described below.
532 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
The types of files that you can import into the painter display in the List
Files of Type drop-down list.
3 Click Open.
PowerBuilder reads the data from the file into the DataWindow painter.
You can then click the Update Database button in the PainterBar to add the
new rows to the database.
For information about importing XML data, see Chapter 28, Exporting and
Importing XML Data.
Controlling the display You can choose whether to display rulers around page borders.
of rulers
Changing margins You can dynamically change margins while previewing a DataWindow object.
Zooming the page You can reduce or enlarge the amount of the page that displays in the Print
Preview view. This does not affect the printed output.
534 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
Printing data
You can print a DataWindow object while the Preview view is displayed. You
can print all pages, a range of pages, only the current page, or only odd or even
pages. You can also specify whether you want multiple copies, collated copies,
and printing to a file.
Avoiding large rows To avoid multiple blank pages and other anomalies in printed reports, no row
in the DataWindow object should be larger than the size of the target page. The
page boundary is often reached in long text columns with AutoSizeHeight on.
It can also be reached when detail rows are combined with page and group
headers and trailers, or when they contain multiple nested DataWindow objects
or a column that has been resized to be larger than the page.
When a row contains large multiline edit columns, it can be broken into a series
of rows, each containing one text line. These text lines become the source for
a nested DataWindow object. The nested DataWindow object determines how
many of its rows fit in the remaining page space.
Page break before The summary band in a report is always printed on the same page as the last
last row row of data. This means that you sometimes find a page break before the last
row of data even if there is sufficient space to print the row. If you want the last
row to print on the same page as the preceding rows, the summary band must
be made small enough to fit on the page as well.
To change printers or You can choose File>Printer Setup from the menu bar.
settings before
printing
4 Specify all pages, even pages, or odd pages in the Print drop-down list.
5 If you want to print to a file rather than to the printer, select the Print to
File check box.
6 If you want to change the collating option, clear or select the Collate
Copies check box and click OK.
If you specified print to file, the Print to File dialog box displays.
7 Enter a file name and click OK.
The extension PRN indicates that the file is prepared for the printer.
Change the drive, the directory, or both, if you want.
536 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
538 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
Using PDFlib Starting from PowerBuilder 2017, an alternative method is provided to directly
print data to PDF without needing to install any third-party tool or driver or
make any configuration. This method relies on a light-weight software called
PDFlib which is automatically installed with PowerBuilder at no cost. And
PDFlib is automatically packaged into the PowerBuilder application
executable as well without requiring the developer to make any configuration
or selection during the building process.
Using XSL-FO and Building on the ability to save data as XML, PowerBuilder can also save the
Java printing DataWindow object’s data and presentation to PDF by generating XSL
Formatting Objects (XSL-FO). This option provides a platform-independent
solution by rendering the DataWindow using a Java process rather than the
Microsoft GDI. It also offers the possibility of customizing the PDF file at the
XSL-FO stage. Saving as PDF using XSL-FO is particularly useful if you want
to print DataWindow objects on a UNIX operating system by using Java
printing. The Ghostscript method and the PDFlib method are not supported on
UNIX.
The XSL (Extensible Stylesheet Language) W3C Recommendation has two
parts, XSLT and XSL-FO. XSLT provides the transformation typically used to
present XML documents as HTML in a browser. XSL-FO provides extensive
formatting capabilities that are not dependent on the output format.
For more information about XSL, see the latest version of the Extensible
Stylesheet Language (XSL) at http://www.w3.org/TR/xsl/.
Limitations The Ghostscript method currently does not support OLE and RichText
DataWindow objects. The PDFlib method currently does not support OLE
DataWindow objects. The XSL-FO method currently does not support OLE,
RichText, graph, and composite DataWindow objects.
The PDFlib method currently does not support the DataWindow object
background.property.
dw_1.Object.DataWindow.Export.PDF.Method = Distill!
dw_1.Object.DataWindow.Printer = "\\prntsrvr\pr-6"
dw_1.Object.DataWindow.Export.PDF. &
Distill.CustomPostScript="Yes"
540 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
To support saving as PDF using Ghostscript, you must download and install
Ghostscript files on your system as described in the chapter on deploying
applications and components in Application Techniques. You also need to
install PostScript driver files.
If you have installed a PostScript printer on your computer, the PostScript
driver files required to create PDF files, PSCRIPT5.DLL, PS5UI.DLL, and
pscript.ntf, are already installed, typically in
C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_1a216484\Amd
64 on a 64-bit Windows 7 system. You must use the version of these files that
is appropriate to the operating system where the PDF file is created. You should
copy the files to the Appeon\Shared\PowerBuilder\drivers directory.
If you have never installed a PostScript printer, use the Printers and Faxes
option in the Windows control panel to install a generic PostScript printer. If
the Pscript5.dll has never been installed, you may be prompted to insert the
Windows install CD.
Other related files are installed in Appeon\Shared\PowerBuilder\drivers.
When you deploy applications that use the ability to save as PDF with the
distill method, you must make sure your users have installed Ghostscript and
have access to the drivers directory.
See the chapter on deployment in Application Techniques for more information
about redistributing these files.
2 Select PDF from the Format to Configure drop-down list and select
NativePDF! from the Method drop-down list.
3 Save the DataWindow object, then select File>Save Rows As, select PDF
as the Save As Type, specify a file name, and click Save.
In a script In a script, set the Export.PDF.Method property to NativePDF! before saving
the DataWindow object as PDF using the SaveAs method with the SaveAsType
PDF!. To print the PDF file in the portrait mode, set the
Export.PDF.NativePDF.CustomOrientation property to 2 and to print the file
size to A4, set the Export.PDF.NativePDF.CustomSize property to 4:
int li_ret
dw_1.Modify ("DataWindow.Export.PDF.Method =
NativePDF!")
dw_1.Modify
("DataWindow.Export.PDF.NativePDF.CustomOrientation =
2")
dw_1.Modify
("DataWindow.Export.PDF.NativePDF.CustomSize = 4")
542 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
Saving as XSL-FO
You can also save a DataWindow object as XSL-FO, then use the processor of
your choice to convert the XSL-FO string to the format you want, applying
your own customizations to the conversion. Processors such as the Apache
XSL Formatting Objects processor (FOP) can convert XSL-FO documents
into several output formats including PDF, PCL, and AWT.
In the DataWindow painter, select File>Save Rows As and select XSL-FO as
the file type. In a script, you can use the SaveAs method with the SaveAsType
XSLFO!.
For a DataWindow named dwemp, the following command lines show the FOP
syntax for producing a PDF, a print preview rendered on screen (-awt), and
printable output rendered and sent to a printer (-print):
Fop dwemp.fo dwemp.pdf
Fop dwemp.fo -awt
Fop dwemp.fo -print
For more information about using FOP, see the FOP page of the Apache XML
Project Web site at http://xmlgraphics.apache.org/fop/.
544 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
A PSR file contains a DataWindow definition (source and object) as well as the
data contained in the DataWindow object when the PSR file was created.
Figure 18-1: PSR file
About reports
A report is the same as a nonupdatable DataWindow object. For more
information, see Reports versus DataWindow objects on page 466.
You can use a PSR file to save a complete report (report design and data). This
can be especially important if you need to keep a snapshot of data taken against
a database that changes frequently.
PowerBuilder creates a PSR file when you save data in the Powersoft report
file format. See Saving data in an external file on page 538. PSR files are used
primarily by InfoMaker, a reporting tool. When an InfoMaker user opens a
PSR file, InfoMaker displays the report in the Report painter. If InfoMaker is
not already running, opening a PSR file automatically starts InfoMaker.
To open a PSR file in PowerBuilder, open any DataWindow object, then select
File>Open File and select the PSR file.
546 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
548 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
550 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
You can set a pointer for the entire DataWindow object, specific bands,
and specific controls.
2 Select the Pointer tab.
3 Either choose the pointer from the Stock Pointers list or, if you have a file
containing pointer definitions (CUR files), enter a pointer file name.
You can use the Browse button to search for the file.
4 Click OK.
552 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
Setting Description
Override Print Job When you print a series of reports using the PrintOpen,
PrintDataWindow, and PrintClose methods, all the reports
in the print job use the layout, fonts, margins, and other
print specifications defined for the computer. Select this
check box to override the default print job settings and use
the print settings defined for this report.
Collate Copies Select to collate copies when printing. Collating increases
print time because the print operation is repeated to
produce collated sets.
Print Preview Shows Select to display a blue outline to show the location of the
Outline margins.
Print Shows Whether the background settings of the DataWindow and
Background controls are included when the DataWindow is printed.
Preview Shows Whether the background settings of the DataWindow and
Background controls display in the print preview.
Newspaper Columns If you want a multiple-column report where the data fills
Across and Width one column on a page, then the second, and so on, as in a
newspaper, select the number and width of the columns in
the Newspaper Columns boxes. See Printing with
newspaper-style columns next.
554 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
4 Specify the number of columns across the page and the width of columns
in the Newspaper Columns Across and Newspaper Columns Width
properties.
5 For each control in the DataWindow object that you do not want to have
appear multiple times on the page (such as headers), select Properties from
the control’s pop-up menu and select the HideSnaked check box on the
General page in the Properties view.
Example This example describes how to create a newspaper-style DataWindow object
using the Employee table in the PB Demo DB.
1 Create a tabular DataWindow object, selecting the last name, first name,
and phone number columns, and add a title, page number, and date.
The Emp_Fname column and the text control holding a comma are defined
as Slide Left, so they display just to the right of the Emp_Lname column.
The finished DataWindow object has one set of page heading information and
two columns of column header and detail information.
556 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
If the DataWindow If you are defining a DataWindow object with more than one table,
object contains PowerBuilder assigns each column a tab value of 0, meaning the user cannot
columns from more
than one table tab to the column. This is because, by default, multitable DataWindow objects
are not updatable—users cannot modify data in them. You can change the tab
values to nonzero values to allow tabbing in these DataWindow objects.
For more about controlling updates in a DataWindow object, see Chapter 20,
Controlling Updates in DataWindow objects.
2 Use the mouse or the Tab key to move the pointer to the tab value you want
to change.
3 Enter a new tab value in the range 0 to 9999.
0 removes the column from the tab order (the user cannot tab to the
column). It does not matter exactly what value you use (other than 0); all
that matters is relative value. For example, if you want the user to tab to
column B after column A but before column C, set the tab value for
column B so it is between the value for column A and the value for column
C.
4 Repeat the procedure until you have the tab order you want.
5 Select Format>Tab Order from the menu bar or click the Tab Order button
again.
PowerBuilder saves the tab order.
Each time you select Tab Order, PowerBuilder reassigns tab values to include
any columns that have been added to the DataWindow object and to allow
space to insert new columns in the tab order.
558 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
Clipping columns
You can have Autosize Height columns without an Autosize Height detail
band. If such a column expands beyond the size of the detail band in the
Preview view, it is clipped.
560 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
Modifying the retrieval You can add, modify, or delete retrieval arguments when modifying your data
arguments source.
For more information about retrieval arguments, see Chapter 17, Defining
DataWindow Objects.
562 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
Retrieving data
In a DataWindow object, you can prompt for retrieval criteria, retrieve rows as
needed, and save retrieved rows to disk.
564 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
Testing in PowerBuilder
You can test the prompting for criteria by retrieving data in the Preview view
of the DataWindow object.
Using edit styles If a column uses a code table or the RadioButton, CheckBox, or
DropDownListBox edit style, an arrow displays in the column header and users
can select a value from a drop-down list when specifying criteria:
If you do not want the drop-down list used for a column for specifying retrieval
criteria to display, select the Override Edit check box on the General page of
the column’s Properties view.
Forcing the entry of If you have specified prompting for criteria for a column, you can force the
criteria entry of criteria for the column by selecting the Equality Required check box
on the Behavior page of the column’s Properties view. PowerBuilder
underlines the column header in the grid during prompting. Selection criteria
for the specified column must be entered, and the = operator must be used.
For more information The section Using Quick Select on page 478 describes in detail how you and
your users can specify selection criteria in the grid.
The chapter on dynamic DataWindow objects in the DataWindow
Programmers Guide describes how to write code to allow users to specify
retrieval criteria at runtime.
566 PowerBuilder
CHAPTER 18 Enhancing DataWindow Objects
In a multiuser situation, Retrieve Rows As Needed might lock other people out
of the tables.
568 PowerBuilder
C H A P T E R 1 9 Working with Controls in
DataWindow Objects
About this chapter One of the ways you can enhance a DataWindow object is to add controls,
such as columns, drawing objects, buttons, and computed fields. You can
also change the layout of the DataWindow object by reorganizing,
positioning, and rotating controls. This chapter shows you how.
Contents
Topic Page
Adding controls to a DataWindow object 569
Reorganizing controls in a DataWindow object 585
Positioning controls in a DataWindow object 591
Rotating controls in a DataWindow object 592
570 PowerBuilder
CHAPTER 19 Working with Controls in DataWindow Objects
About the default font When you place text in a DataWindow object, PowerBuilder uses the font and
and style style (such as boldface) defined for the application’s text in the Application
painter. You can override the text properties for any text in a DataWindow
object.
For more about changing the application’s default text font and style, see
Chapter 4, Working with Targets.
572 PowerBuilder
CHAPTER 19 Working with Controls in DataWindow Objects
3 Use the Browse button to find the file or enter a file name in the File Name
box. Then click Open.
The picture must be a bitmap (BMP), runlength-encoded (RLE), Windows
metafile (WMF), Graphics Interchange Format (GIF), or Joint
Photographic Experts Group (JPEG) file.
4 Display the pop-up menu and select Original Size to display the image in
its original size.
You can use the mouse to change the size of the image in the DataWindow
painter.
5 Select the Invert Image check box on the Appearance page in the
Properties view to display the picture with its colors inverted.
Tips for using pictures To display a different picture for each row of data, retrieve a column containing
picture file names from the database. For more information, see Specifying
additional properties for character columns on page 402.
To compute a picture name at runtime, use the Bitmap function in the
expression defining a computed field. If you change the image in the Picture
control in a DataWindow object, you need to reset the original size property.
The property automatically reverts to the default setting when you change the
image.
To use a picture to indicate that a row has focus at runtime, use the
SetRowFocusIndicator function.
• Concatenated fields
If you retrieve first name and last name, you can define a computed field
that concatenates the values so they appear with only one space between
them: Fname + " " + Lname.
• System information
You can place the current date and time in a DataWindow object’s header
using the built-in functions Today() and Now() in computed fields.
If Cost is defined as a computed column in the SQL Select painter, the SELECT
statement is as follows:
SELECT part.part_num,
part.part_qty,
part.part_price,
part.part_qty * part.part_price
FROM part;
574 PowerBuilder
CHAPTER 19 Working with Controls in DataWindow Objects
If the user changes the price of a part in the DataWindow object in this
scenario, the cost does not change in the DataWindow object until the database
is updated and the data is retrieved again. The user sees a display with the
changed price but the unchanged, incorrect cost.
Part # Quantity Price Cost
101 100 2.50 125.00
In this scenario, if the user changes the price of a part in the DataWindow
object, the cost changes immediately.
Part # Quantity Price Cost
101 100 2.50 250.00
Recommendation If you want your DBMS to do the calculations on the server before bringing
data down and you do not need the computed values to be updated dynamically,
define the computed column as part of the SELECT statement.
If you need computed values to change dynamically, define computed fields in
the DataWindow painter Design view, as described next.
DataWindow expressions
You are entering a DataWindow expression, not a SQL expression processed
by the DBMS, so the expression follows the rules for DataWindow
expressions. For complete information about DataWindow expressions, see the
DataWindow Reference.
Referring to next and You can refer to other rows in a computed field. This is particularly useful in
previous rows N-Up DataWindow objects when you want to refer to another row in the detail
band. Use this syntax:
ColumnName[x]
where x is an integer. 0 refers to the current row (or first row in the detail band),
1 refers to the next row, –1 refers to the previous row, and so on.
Examples Table 19-1 shows some examples of computed fields.
576 PowerBuilder
CHAPTER 19 Working with Controls in DataWindow Objects
For complete information about the functions you can use in computed fields
in the DataWindow painter, see the DataWindow Reference.
Menu options and PowerBuilder provides a quick way to create computed fields that summarize
buttons for common values in the detail band, display the current date, or show the current page
functions
number.
To summarize values:
1 Select one or more columns in the DataWindow object’s detail band.
2 Select one of the options at the bottom of the cascading menu: Average,
Count, or Sum.
The same options are available at the bottom of the Controls drop-down
toolbar on the PainterBar.
PowerBuilder places a computed field in the summary band or in the group
trailer band if the DataWindow object is grouped. The band is resized
automatically to hold the computed field. If there is already a computed
field that matches the one being generated, it is skipped.
The same options are available at the bottom of the Controls drop-down
toolbar on the PainterBar.
3 Click anywhere in the DataWindow object.
If you selected Today, PowerBuilder inserts a computed field containing
this expression: Today(). For Page n of n, the computed field contains this
expression: 'Page ' + page() + ' of ' + pageCount().
Adding custom You can add buttons to the PainterBar in the DataWindow painter that place
buttons that place computed fields using any of the aggregate functions, such as Max, Min, and
computed fields
Median.
578 PowerBuilder
CHAPTER 19 Working with Controls in DataWindow Objects
3 With the button still selected, type the text to display on the button in the
PainterBar or on the General page of the Properties view.
4 Select the action you want to assign to the button from the Action
drop-down list on the General page of the Properties view.
For information about actions, see Actions assignable to buttons in
DataWindow objects on page 581.
5 If you want to add a picture to the button, select the Action Default Picture
check box or enter the name of the Picture file to display on the button.
6 If you want to suppress event processing when the button is clicked at
runtime, select the Suppress Event check box.
When this option has been selected for the button and the button is clicked
at runtime, only the action assigned to the button and the Clicked event are
executed. The ButtonClicking and the ButtonClicked events are not
triggered.
What happens if If Suppress Event is off and the button is clicked, the Clicked and
Suppress Event is off ButtonClicking events are fired. Code in the ButtonClicking event (if any) is
executed. Note that the Clicked event is executed before the ButtonClicking
event.
• If the return code from the ButtonClicking event is 0, the action assigned
to the button is executed and then the ButtonClicked event is executed.
• If the return code from the ButtonClicking event is 1, neither the action
assigned to the button nor the ButtonClicked event are executed.
Example For an example of a DataWindow object that uses buttons, see the
d_button_report object in the Code Examples application.
This DataWindow object has several buttons that have default actions, and two
that have user-defined actions. In the Properties view in the DataWindow
painter, these buttons are named cb_help and cb_exit. Suppress Event is off for
all buttons.
In the Window painter, the Clicked and ButtonClicking events for the
DataWindow control that contains d_button_report are not scripted. This is the
ButtonClicked event script:
stringls_Object
stringls_win
ls_Object = String(dwo.name)
580 PowerBuilder
CHAPTER 19 Working with Controls in DataWindow Objects
582 PowerBuilder
CHAPTER 19 Working with Controls in DataWindow Objects
You use an InkPicture control with a table that has a blob column to store the
ink data, and optionally a second blob column to provide a background image.
The InkPicture control behaves like a Picture control that accepts annotation.
You can associate a picture with the control so that the user can draw
annotations on the picture, then save the ink, the picture, or both. If you want
to use the control to capture and save signatures, you usually do not associate
a picture with it.
To add an InkPicture control to a DataWindow object, select
Insert>Control>InkPicture from the menu. A dialog box displays to let you
specify a blob column to store the ink data and another to use as a background
image. After you specify the columns in the dialog box, the InkPicture control
displays in the DataWindow and its Properties view includes a Definition tab
page where you can view or change the column definitions.
If you insert the InkPicture control into a N-Up DataWindow object, you
should specify the Row In Detail so the correct image displays. For example,
if you have three rows in the detail band, you might enter 1 for the ink picture
associated with the first, 2 for the second, and 3 for the third.
InkPicture controls are not supported in Crosstab DataWindows.
584 PowerBuilder
CHAPTER 19 Working with Controls in DataWindow Objects
Option Meaning
Snap to Grid Make controls snap to a grid position when you place them
or move them.
Show Grid Show or hide the grid when the workspace displays.
X Specify the size (width) of the grid cells.
Y Specify the size (height) of the grid cells.
Show Ruler Show a ruler. The ruler uses the units of measurement
specified in the Style dialog box. See Changing the
DataWindow object style on page 546.
Your choices for the grid and the ruler are saved and used the next time you
start PowerBuilder.
586 PowerBuilder
CHAPTER 19 Working with Controls in DataWindow Objects
588 PowerBuilder
CHAPTER 19 Working with Controls in DataWindow Objects
4 From the cascading menu, select the dimension whose size you want to
equalize.
You can also use the Layout drop-down toolbar on PainterBar2 to size
controls.
Option Description
Slide Left Slide the column or control to the left if there is nothing
to the left. Be sure the control does not overlap the
control to the left. Sliding left will not work if the
controls overlap.
Slide Up - All Above Slide the column or control up if there is nothing in the
row above. The row above must be completely empty
for the column or control to slide up.
Slide Up - Directly Slide the column or control up if there is nothing
Above directly above it in the row above.
You can also use the drop-down toolbar on PainterBar2 to slide controls.
590 PowerBuilder
CHAPTER 19 Working with Controls in DataWindow Objects
Example In a mailing label that includes first and last names, as well as address
information, you can use sliding to combine the columns appropriately.
In the following label, emp_lname, the comma, state, and zip_code are
specified as slide left. Edges are shown to indicate the spacing between the
columns. Notice that there is a small amount of space between controls. This
space is necessary for Slide Left to work properly:
When you preview (run) the DataWindow object, the last name, comma, state,
and zip code slide left to remove the blank space:
Default positioning PowerBuilder uses the defaults shown in Table 19-4 when you place a new
control in a DataWindow object.
Table 19-4: Default position properties for controls in a DataWindow
object
Control Default positioning
Graph Foreground, movable, resizable
All other controls Band, not movable, not resizable
592 PowerBuilder
CHAPTER 19 Working with Controls in DataWindow Objects
Several other properties of a rotated control affect its final placement when the
DataWindow object runs. The location of the control in Design view, the
amount of rotation specified for it, and the location of the text within the
control (for example, centered text as opposed to left-aligned text) all
contribute to what you see in the DataWindow object Preview view.
The following procedure includes design practices that help ensure that you get
the final results you want. As you become more experienced, you can drop or
alter some of the steps. The procedure recommends making the control
movable in the Preview view, which is often helpful.
If the box that contains the text overlaps the border of the page or the
border of a label in a DataWindow object with the Label presentation style,
the origin of rotation is the center of the portion of the top border that is
within the page or label, and the portion that is outside the page or label is
cut off. This can cause the text in the box to run to a second line when it is
rotated. If you want the text to display close to the border, you can add one
or more line breaks (“~r~n”) before the text and adjust the size of the box.
6 To display the current rotation in Preview, close the Preview view and
reopen it (View>Preview on the menu bar).
7 Drag and drop the control in the Design view until it is where you want it.
8 In the Design view, select the control that is being rotated and deselect the
Moveable check box.
594 PowerBuilder
C H A P T E R 2 0 Controlling Updates in
DataWindow objects
About this chapter When PowerBuilder generates the basic DataWindow object, it defines
whether the data is updatable. This chapter describes the default settings
and how you can modify them.
Contents
Topic Page
About controlling updates 595
Specifying the table to update 597
Specifying the unique key columns 597
Specifying an identity column 598
Specifying updatable columns 598
Specifying the WHERE clause for update/delete 599
Specifying update when key is modified 601
Using stored procedures to update the database 602
Using a Web service to update the database 604
Updatability of views
Some views are logically updatable; some are not. For the rules your DBMS
follows for updating views, see your DBMS documentation.
596 PowerBuilder
CHAPTER 20 Controlling Updates in DataWindow objects
Changing tab values PowerBuilder does not change the tab values associated with columns after you
change the update characteristics of the DataWindow object. If you have
allowed updates to a table in a multitable DataWindow object, you should
change the tab values for the updatable columns so that users can tab to them.
For more information, see Defining the tab order in a DataWindow object on
page 557.
The key columns you select here must uniquely identify a row in the table.
They can be the table’s primary key, though they don’t have to be.
598 PowerBuilder
CHAPTER 20 Controlling Updates in DataWindow objects
DELETE
FROM table
WHERE col1 = value1
AND col2 = value2 ...
Using timestamps
Some DBMSs maintain timestamps so you can ensure that users are working
with the most current data. If the SELECT statement for the DataWindow object
contains a timestamp column, PowerBuilder includes the key column and the
timestamp column in the WHERE clause for an UPDATE or DELETE statement
regardless of which columns you specify in the Where Clause for
Update/Delete box.
If the value in the timestamp column changes (possibly due to another user
modifying the row), the update fails.
To see whether you can use timestamps with your DBMS, see Connecting to
Your Database.
Choose one of the options in Table 20-1 in the Where Clause for Update/Delete
box. The results are illustrated by an example following the table.
Table 20-1: Specifying the WHERE clause for UPDATE and DELETE
Option Result
Key Columns The WHERE clause includes the key columns only. These are the
columns you specified in the Unique Key Columns box.
The values in the originally retrieved key columns for the row are
compared against the key columns in the database. No other
comparisons are done. If the key values match, the update
succeeds.
Caution
Be very careful when using this option. If you tell PowerBuilder
only to include the key columns in the WHERE clause and someone
else modified the same row after you retrieved it, their changes will
be overwritten when you update the database (see the example
following this table).
Use this option only with a single-user database or if you are using
database locking. In other situations, choose one of the other two
options described in this table.
Key and The WHERE clause includes all key and updatable columns.
Updatable The values in the originally retrieved key columns and the
Columns originally retrieved updatable columns are compared against the
values in the database. If any of the columns have changed in the
database since the row was retrieved, the update fails.
Key and The WHERE clause includes all key and modified columns.
Modified The values in the originally retrieved key columns and the modified
Columns columns are compared against the values in the database. If any of
the columns have changed in the database since the row was
retrieved, the update fails.
Example Consider this situation: a DataWindow object is updating the Employee table,
whose key is Emp_ID; all columns in the table are updatable. Suppose the user
has changed the salary of employee 1001 from $50,000 to $65,000. This is
what happens with the different settings for the WHERE clause columns:
• If you choose Key Columns for the WHERE clause, the UPDATE statement
looks like this:
UPDATE Employee
SET Salary = 65000
WHERE Emp_ID = 1001
600 PowerBuilder
CHAPTER 20 Controlling Updates in DataWindow objects
How to choose a Consider the following when choosing the Key Modification setting:
setting
• If multiple rows are changed, DELETE and INSERT always work. In some
DBMSs, UPDATE fails if the user modifies two keys and sets the value in
one row to the original value of the other row.
• You might choose the setting here based on your DBMS triggers. For
example, if there is an Insert trigger, select Use Delete then Insert.
• If only one row can be modified by the user before the database is updated,
use UPDATE because it is faster.
602 PowerBuilder
CHAPTER 20 Controlling Updates in DataWindow objects
604 PowerBuilder
CHAPTER 20 Controlling Updates in DataWindow objects
Insert, delete, and The insert, delete, and update operations imply different things depending on
update operations the original data source. When you insert a DataWindow row for an RDBMS,
a new row is added to the database; when the data source is an array of
structures, a new structure instance is added to the array; and when the data
source is an array of simple types, a new instance of the simple type is added
to the array. The delete operation removes a database row or an instance in an
array, and the update operation modifies a database row or an instance in an
array.
For each operation, you must map DataWindow column values or expressions
to Web service input parameters. At runtime when performing one of these
operations, the DataWindow binds column or expression values to parameters
as instructed and calls the Web service method. The DataWindow engine does
not know what actually happens in the Web service component (that is, how
the component implements the update), only whether it returns a success or
failure message.
Figure 20-1 displays the Web Service Update dialog box. You use this dialog
box to bind to Web service parameters to DataWindow columns or expressions.
Unlike the retrieve call, DataWindow update operations can handle
bidirectional parameters. However, you can select an expression or computed
column only for an update method input parameter.
Figure 20-1: Web Service Update dialog box
2 Select the tab for the Web service update method (Update, Insert, or
Delete) with which you want to associate a Web service.
3 Click the browse button next to the WSDL Filename text box to browse to
a WSDL file describing the Web service you want to use to update the
DataWindow, and click OK.
You use a WSDL file to generate an assembly that you can deploy with
your Web service DataWindow application. You can override the default
assembly name that will be generated if you enter an existing assembly in
the following step of this procedure.
If you already have an assembly that you want to use to update the
DataWindow, you can skip the current step and select the assembly that
you want in step 4.
You can use the Reset button to clear all entries in the Web Service Update
dialog box.
4 (Optional) Type an assembly name in the Assembly Name text box to
override a default assembly name that you want to generate from a WSDL
file, or browse to an existing assembly file that describes the Web service
you want to use to update the DataWindow, and click OK.
Although you can browse to any mapped directory to find an assembly file
for update operations, you must make sure to copy the assembly under the
current target directory. All assemblies for retrieving and updating a Web
service DataWindow must be deployed to the same directory as the
application executable file, or retrieve and update operations will not be
able to work at runtime.
5 Click Generate if you want to generate and load an assembly file, or click
Load if you entered an existing assembly file name in step 4.
After you click Generate, an assembly file is created with a default name
from the WSDL file or from a name that you entered in the previous step.
After you generate the assembly from a WSDL file or load an existing
assembly, the Web services in that file are added to the Web Service Name
drop-down list and the methods for the Web services are added to the
Method Name drop-down list.
6 Select a Web service name and method name from the list of Web services
and methods.
The parameters used in the Web service method are displayed in the
Argument Name list in the order in which they are defined. Column Name
lists the columns used in your DataWindow object.
606 PowerBuilder
CHAPTER 20 Controlling Updates in DataWindow objects
Argument Description
operation String for the type of operation (Retrieve, Update, Insert,
Delete, Connect, or Disconnect)
rowNumber Int32 for the row number or 0 if not applicable, such as
when an error occurs during connection to the Web service
buffername String for the name of the buffer being accessed while the
error occurred (Primary, Filter, or Delete)
assembly String for the name of the assembly being used
method String for the name of the Web service method invoked
returnCode Int32 for the return code from the Web service
608 PowerBuilder
C H A P T E R 2 1 Displaying and Validating Data
About this chapter This chapter describes how to customize your DataWindow object by
modifying the display values in columns and specifying validation rules.
Contents
Topic Page
About displaying and validating data 609
About display formats 611
Working with display formats 612
Defining display formats 615
About edit styles 622
Working with edit styles 624
Defining edit styles 626
Defining a code table 637
About validation rules 641
Working with validation rules 642
Defining validation rules 643
How to maintain extended attributes 649
610 PowerBuilder
CHAPTER 21 Displaying and Validating Data
Validating data
When data is entered in the Database painter or in a DataWindow object,
PowerBuilder evaluates the data against validation rules defined for that
column. If the data is valid, PowerBuilder accepts the entry; otherwise,
PowerBuilder displays an error message and does not accept the entry.
For more information, see About validation rules on page 641.
612 PowerBuilder
CHAPTER 21 Displaying and Validating Data
614 PowerBuilder
CHAPTER 21 Displaying and Validating Data
Shortcuts
To assign the Currency or Percent display format to a numeric column in a
report, select the column, then click the Currency or Percent button in the
PainterBar or select Format>Currency or Format>Percent from the menu bar.
Customizing the You can add buttons to the PainterBar that assign a specified display format to
toolbar selected columns in reports.
For more information, see Customizing toolbars on page 49.
The following format specifies different displays for positive and negative
numbers—negative numbers are displayed in parentheses:
$#,##0;($#,##0)
Using keywords Enclose display format keywords in square brackets. For example, you can use
the keyword [General] when you want PowerBuilder to determine the
appropriate format for a number.
Using colors You can define a color for each display format section by specifying a color
keyword before the format. The color keyword is the name of the color, or a
number that represents the color, enclosed in square brackets: [RED] or [255].
The number is usually used only when a color is required that is not provided
by name. The named color keywords are:
[BLACK]
[BLUE]
[CYAN]
[GREEN]
[MAGENTA]
[RED]
[WHITE]
[YELLOW]
The formula for combining primary color values into a number is:
256*256*blue + 256*green + red=number
where the amount of each primary color is specified as a value from 0 to 255.
For example, to specify cyan, substitute 255 for blue, 255 for green, and 0 for
red. The result is 16776960.
If you want to add text to a numeric display format and use a color attribute,
you must include the escape character (\) before each literal in the mask. For
example:
[red]\D\e\p\t\: ###
Table 21-1 lists the blue, green, and red values you can use in the formula to
create other colors.
616 PowerBuilder
CHAPTER 21 Displaying and Validating Data
Using special To include a character in a mask that has special meaning in a display format,
characters such as [, precede the character with a backslash (\). For example, to display a
single quotation mark, enter \'.
Setting display In scripts, you can use GetFormat to get the current format for a column and
formats at runtime SetFormat to change the format for a column at runtime.
Percent signs, decimal points, parentheses, and spaces display as entered in the
mask.
Number keywords You can use the following keywords as number display formats when you want
PowerBuilder to determine an appropriate format to use:
• [General]
• [Currency]
Note that [Currency(7)] and [Currency(n)] are legal edit masks, but they are not
legal display formats.
Percentages Use caution when defining an edit mask for a percentage. When you enter a
number in a column with a percent edit mask and tab off the column,
PowerBuilder divides the number by 100 and stores the result in the buffer. For
example, if you enter 23, PowerBuilder passes .23 to the buffer. When you
retrieve from the database, PowerBuilder multiplies the number by 100 and, if
the mask is ##0%, displays 23%.
The datatype for the column must be numeric or decimal to handle the result of
a division by 100. If the column has an integer datatype, a percentage entered
as 333 is retrieved from the database as 300, and 33 is retrieved as 0.
If you use an edit mask with decimals, such as ##0.00%, the datatype must
have enough decimal places to handle the division. For example, if you enter
33.33, the datatype for the column must have at least four decimal places
because the result of the division is .3333. If the datatype has only three
decimal places, the percentage is retrieved as 33.30.
Examples Table 21-3 shows how the values 5, –5, and .5 display when different format
masks are applied.
618 PowerBuilder
CHAPTER 21 Displaying and Validating Data
Date keywords You can use the following keywords as date display formats when you want
PowerBuilder to determine an appropriate format to use:
• [ShortDate]
• [LongDate]
The format used is determined by the regional settings for date in the registry.
Note that [Date] is not a valid display format.
Examples Table 21-5 shows how the date Friday, January 30, 1998, displays when
different format masks are applied.
620 PowerBuilder
CHAPTER 21 Displaying and Validating Data
Time keyword You can use the following keyword as a time display format to specify the
format specified in the Windows control panel:
• [Time]
Examples Table 21-7 shows how the time 9:45:33:234567 PM displays when different
format masks are applied.
Table 21-7: Time display format examples
Format Displays
h:mm AM/PM 9:45 PM
hh:mm A/P 09:45 P
h:mm:ss am/pm 9:45:33 pm
h:mm 21:45
h:mm:ss 21:45:33
h:mm:ss:f 21:45:33:2
h:mm:ss:fff 21:45:33:234
h:mm:ss:ffffff 21:45:33:234567
m/d/yy h:mm 1/30/98 21:45
622 PowerBuilder
CHAPTER 21 Displaying and Validating Data
For example, suppose you have a column Status that takes one of three values:
the letters A, T, and L, each representing a status (Active, Terminated, or On
Leave). If you assign it the RadioButton edit style, userscan simply click a
button instead of having to type A, T, or L. You do not have to create a
validation rule to validate typed input.
624 PowerBuilder
CHAPTER 21 Displaying and Validating Data
2 In the Object Details view, select the edit style type from the Style
drop-down list.
3 Specify the properties of the edit style.
For information, see Defining edit styles on page 626.
You can use the new edit style with any column of the appropriate datatype
in the database.
626 PowerBuilder
CHAPTER 21 Displaying and Validating Data
• To have entered values display as asterisks for sensitive data, check the
Password box.
• To allow users to tab to the column but not change the value, check the
Display Only box.
• To define a code table to determine which values are displayed to users and
which values are stored in the database, check the Use Code Table box and
enter display and data values for the code table.
See Defining a code table on page 637.
Typically, this edit style is used with code tables, where you can specify display
values (which users see) and shorter data values (which are stored in the
database).
In the DropDownListBox edit style, the display values of the code table display
in the ListBox portion of the DropDownListBox. The data values are the values
that are put in the DataWindow buffer (and sent to the database when an Update
is issued) when the user selects an item in the ListBox portion of the drop-down
list.
In the preceding example, when users see the value Business Services, the
corresponding data value could be 200.
628 PowerBuilder
CHAPTER 21 Displaying and Validating Data
3 In the Data Value For boxes, enter the values you want put in the
DataWindow buffer when the CheckBox is checked (on) or unchecked
(off).
If you selected the 3 States box, an optional third state box (other) appears,
for the case when the condition is neither on nor off.
What happens The value you enter in the Text box becomes the display value, and values
entered for On, Off, and Other become the data values.
When users check or clear the check box at runtime, PowerBuilder enters the
appropriate data value in its buffer. When the Update method is called,
PowerBuilder sends the corresponding data values to the database.
Centering check You may find it useful to center check boxes used for columns of information.
boxes without text First make the text control used for the column header and the column control
the same size and left aligned. Then you can center the check boxes and the
column header.
What happens Users select values by clicking a radio button. When the Update method is
issued, the data values are sent to the database.
Edit masks consist of special characters that determine what can be entered in
the column. They can also contain punctuation characters to aid users.
For example, to make it easier for users to enter phone numbers in the proper
format, specify this mask:
(###) ###-####
At runtime, the punctuation characters display in the box and the cursor jumps
over them as the user types:
Special characters Most edit masks use the same special characters as display formats, and there
and keywords are special considerations for using numeric, string, date, and time masks. For
information, see Defining display formats on page 615.
The special characters you can use in string edit masks are different from those
you can use in string display formats.
630 PowerBuilder
CHAPTER 21 Displaying and Validating Data
If you use the “#” or “a” special characters in a mask, Unicode characters,
spaces, and other characters that are not alphanumeric do not display.
Keyboard behavior Note the following about how certain keystrokes behave in edit masks:
• Both Backspace and Shift + Backspace delete the preceding character.
• Delete deletes everything that is selected.
• Non-numeric edit masks treat any characters that do not match the mask
pattern as delimiters.
Also, note certain behavior in Date edit masks:
• Entering zero for the day or month causes the next valid date to be entered.
For example, if the edit mask is DD/MM/YY, typing 00/11/01 results in
01/11/01. You can override this behavior in the development
environment by adding the following lines to your PB.INI file:
[Edit Mask Behaviors]
AutocompleteDates=no
For deployed applications, the date is completed automatically unless you
provide a file called PB.INI in the same directory as the executable file that
contains these lines. Note that this section must be in a file called PB.INI.
Adding the section to a different INI file shipped with the application will
have no effect.
• You cannot use a partial mask, such as dd or mmm, in a date edit mask.
Any mask that does not include any characters representing the year will
be replaced by a mask that does.
• The strings 00/00/00 or 00/00/0000 are interpreted as the NULL value for
the column.
Using the Mask Click the button to the right of the Mask box on the Mask property page to
pop-up menu display a list that contains complete masks that you can click to add to the mask
box, as well as special characters that you can use to construct your own mask.
For example, the menu for a Date edit mask contains complete masks such as
mm/dd/yy and dd/mmm/yyyy. It also has components such as dd and jjj (for a
Julian day). You might use these to construct a mask like dd-mm-yy, typing in
the hyphens as separators.
Using masks with “as You can define a mask that contains “as is” characters that always appear in the
is” characters control or column. For example, you might define a numeric mask such as
Rs0000.00 to represent Indian rupees in a currency column.
632 PowerBuilder
CHAPTER 21 Displaying and Validating Data
For more about code tables, see Defining a code table on page 637.
2 For the column in a second DataWindow getting its data from the
d_dddw_dept DataWindow object, select the DropDownDW edit style.
634 PowerBuilder
CHAPTER 21 Displaying and Validating Data
3 Click the browse button next to the DataWindow box and select the
DataWindow object that contains the data for the column from the list (in
the example, d_dddw_dept). The list includes all the DataWindow objects
in the current target.
4 In the Display Column box, select the column containing the values that
will display in the DataWindow object (in the example, dept_name).
5 In the Data Column box, select the column containing the values that will
be stored in the database (in the example, dept_id).
6 Specify other properties for the edit style.
What happens At runtime, when data is retrieved into the DataWindow object, the column
whose edit style is DropDownDataWindow will itself be populated as data is
retrieved into the DataWindow object serving as the drop-down DataWindow
object.
When the user goes to the column and drops it down, the contents of the
drop-down DataWindow object display. When the user selects a display value,
the corresponding data value is stored in the DataWindow buffer and is stored
in the database when an Update is issued.
By default, whenever a column with the RichText edit style is edited in the
Preview view or at runtime, a font toolbar displays. The font toolbar disappears
when the column loses focus. The following picture shows the default font
toolbar available for columns with the RichText edit style:
636 PowerBuilder
CHAPTER 21 Displaying and Validating Data
638 PowerBuilder
CHAPTER 21 Displaying and Validating Data
Case sensitivity
Code table processing is case sensitive.
If the code table is in a DropDownListBox edit style, and if the column has a
code table that contains duplicate display values, then each value displays only
once. Therefore, if this code table is defined for a column in a DataWindow
object that has a DropDownListBox edit style, Massachusetts and Rhode
Island display in the ListBox portion of the DropDownListBox.
640 PowerBuilder
CHAPTER 21 Displaying and Validating Data
Another technique
You can also perform data validation through code tables, which are
implemented through a column’s edit style.
For more information, see About edit styles on page 622.
For more information, see the chapter on using DataWindow objects in the
DataWindow Programmers Guide.
At runtime
In scripts, you can use the GetValidate method to obtain the validation rule for
a column and the SetValidate method to change the validation rule for a
column.
For information about the GetValidate and SetValidate methods, see the online
help.
642 PowerBuilder
CHAPTER 21 Displaying and Validating Data
You can use this rule with any column of the appropriate datatype in the
database.
644 PowerBuilder
CHAPTER 21 Displaying and Validating Data
646 PowerBuilder
CHAPTER 21 Displaying and Validating Data
Referring to other You can refer to the values in other columns by specifying their names in the
columns validation rule. You can paste the column names in the rule using the Columns
box.
Examples
Here are some examples of validation rules.
Example 1 To check that the data entered in the current column is a positive
integer, use this validation rule:
Integer(GetText( )) > 0
Example 2 If the current column contains the discounted price and the
column named Full_Price contains the full price, you could use the following
validation rule to evaluate the contents of the column using the Full_Price
column:
Match(GetText( ),"^[0-9]+$") AND
Real(GetText( )) < Full_Price
To pass the validation rule, the data must be all digits (must match the text
pattern ^[0-9]+$) and must be less than the amount in the Full_Price column.
Notice that to compare the numeric value in the column with the numeric value
in the Full_Price column, the Real function was used to convert the text to a
number.
Example 3 In your company, a product price and a sales commission are
related in the following way:
• If the price is greater than or equal to $1000, the commission is between
10 percent and 20 percent
• If the price is less than $1000, the commission is between 4 percent and 9
percent
The Sales table has two columns, Price and Commission. The validation rule for
the Commission column is:
(Number(GetText( )) >= If(price >= 1000, .10, .04))
AND
(Number(GetText( )) <= If(price >= 1000, .20, .09))
A customized error message for the Commission column is:
"Price is " + if(price >= 1000,
"greater than or equal to","less than") +
" 1000. Commission must be between " +
If(price >= 1000,".10", ".04") + " and " +
648 PowerBuilder
CHAPTER 21 Displaying and Validating Data
Caution
If you delete a display format, edit style, or validation rule, it is removed
from the extended attribute system tables. Columns in the database are no
longer associated with the entity.
650 PowerBuilder
C H A P T E R 2 2 Filtering, Sorting, and Grouping
Rows
About this chapter This chapter describes how you can customize your DataWindow object
by doing the following in the DataWindow painter:
• Defining filters to limit which of the retrieved rows are displayed in
the DataWindow object
• Sorting rows after they have been retrieved from the database
• Displaying the rows in groups and calculating statistics on each group
Contents
Topic Page
Filtering rows 651
Sorting rows 654
Grouping rows 656
Filtering rows
You can use WHERE and HAVING clauses and retrieval arguments in the
SQL SELECT statement for the DataWindow object to limit the data that
is retrieved from the database. This reduces retrieval time and space
requirements at runtime.
However, you may want to further limit the data that displays in the
DataWindow object. For example, you might want to:
• Retrieve many rows and initially display only a subset (perhaps
allowing the user to specify a different subset of rows to display at
runtime)
• Limit the data that is displayed using DataWindow expression
functions (such as If) that are not valid in the SELECT statement
Using filters In the DataWindow painter, you can define filters to limit the rows that display
at runtime. Filters can use most DataWindow expression functions or user-
defined functions.
Defining a filter
To define a filter:
1 In the DataWindow painter, select Rows>Filter from the menu bar.
The Specify Filter dialog box displays:
International considerations
The formatting that you enter for numbers and currency in filter
expressions display the same way in any country. Changing the regional
settings of the operating system does not modify the formatting displayed
for numbers and currency at runtime.
652 PowerBuilder
CHAPTER 22 Filtering, Sorting, and Grouping Rows
Removing a filter
To remove a filter:
1 Select Rows>Filter from the menu bar.
2 Delete the filter expression from the Specify Filter dialog box, then click
OK.
Examples of filters Assume that a DataWindow object retrieves employee rows and three of the
columns are Salary, Status, and Emp_Lname. Table 22-1 shows some examples
of filters you might use.
Table 22-1: Sample filters
To display these rows Use this filter
Employees with salaries over $50,000 Salary > 50000
Active employees Status = 'A'
Active employees with salaries over Salary > 50000 AND Status = 'A'
$50,000
Employees whose last names begin left(Emp_Lname, 1) = 'H'
with H
Setting filters You can use the SetFilter and Filter methods in a script to dynamically modify
dynamically a filter that was set in the DataWindow painter. For information about SetFilter
and Filter, see the online help.
Sorting rows
You can use an ORDER BY clause in the SQL SELECT statement for the
DataWindow object to sort the data that is retrieved from the database. If you
do this, the DBMS itself does the sorting and the rows are brought into
PowerBuilder already sorted.
However, you might want to sort the rows after they are retrieved. For example,
you might want to:
• Offload the processing from the DBMS
• Sort on an expression, which might not be allowed in the SELECT
statement but is allowed in PowerBuilder
2 Drag to the Columns box the columns on which you want to sort the rows,
and specify whether you want to sort in ascending or descending order.
The order of the columns determines the precedence of the sort. To reorder
the columns, drag them up or down in the list. To delete a column from the
sort columns list, drag the column outside the dialog box.
3 You can also specify expressions to sort on: for example, if you have two
columns, Revenues and Expenses, you can sort on the expression
Revenues – Expenses.
To specify an expression to sort on, double-click a column name in the
Columns box, modify the expression in the Modify Expression dialog box,
and click OK.
You return to the Specify Sort Columns dialog box with the expression
displayed.
654 PowerBuilder
CHAPTER 22 Filtering, Sorting, and Grouping Rows
4 Click OK when you have specified all the sort columns and expressions.
2 Drag the columns whose repeated values you want to suppress from the
Source Data box to the Suppression List box, and click OK.
Grouping rows
You can group related rows together and, optionally, calculate statistics for
each group separately. For example, you might want to group employee
information by department and get total salaries for each department.
How groups are Each group is defined by one or more DataWindow object columns. Each time
defined the value in a grouping column changes, a break occurs and a new section
begins.
For each group, you can:
• Display the rows in each section
• Specify the information you want to display at the beginning and end of
each section
• Specify page breaks after each break in the data
• Reset the page number after each break
Grouping example The following DataWindow object retrieves employee information. It has one
group defined, Dept_ID, so it groups rows into sections according to the value
in the Dept_ID column. In addition, it displays:
656 PowerBuilder
CHAPTER 22 Filtering, Sorting, and Grouping Rows
658 PowerBuilder
CHAPTER 22 Filtering, Sorting, and Grouping Rows
If you want to use an expression, you can define it when you have
completed the wizard. See Using an expression for a group on page 661.
5 Click Next.
PowerBuilder suggests a header based on your data source. For example,
if your data comes from the Employee table, PowerBuilder uses the name
Employee in the suggested header.
6 Specify the Page Header text.
7 If you want a page break each time a grouping value changes, select the
New Page On Group Break box.
660 PowerBuilder
CHAPTER 22 Filtering, Sorting, and Grouping Rows
Using an expression If you want to use an expression for one or more column names in a group, you
for a group can enter an expression as the Group Definition on the General page in the
Properties view after you have finished using the Group wizard.
662 PowerBuilder
CHAPTER 22 Filtering, Sorting, and Grouping Rows
Creating subgroups After defining your first group, you can define subgroups, which are groups
within the group you just defined.
To define subgroups:
1 Select Rows>Create Group from the menu bar and specify the
column/expression for the subgroup.
2 Repeat step 1 to define additional subgroups if you want.
You can specify as many levels of grouping as you need.
How groups are PowerBuilder assigns each group a number (or level) when you create the
identified group. The first group you specify becomes group 1, the primary group. The
second group becomes group 2, a subgroup within group 1, and so on.
For example, suppose you define two groups. The first group uses the dept_id
column and the second group uses the status column.
The rows are grouped first by department (group 1). Within department, rows
are grouped by status (group 2). If you specify page breaks for the groups, a
page break will occur when any of these values changes.
You use the group’s number to identify it when defining summary statistics for
the group. This is described in Adding summary statistics on page 666.
You can also sort on additional rows. For example, if you want to sort by
employee ID within each group, specify emp_id as the third sorting column.
For more information about sorting, see Sorting rows on page 654.
You can include any control in the DataWindow object (such as columns, text,
and computed fields) in the header and trailer bands of a group.
Using the group The contents of the group header band display at the top of each page and after
header band each break in the data.
Typically, you use this band to identify each group. You might move the
grouping column from the detail band to the group header band, since it now
serves to identify one group rather than each row.
664 PowerBuilder
CHAPTER 22 Filtering, Sorting, and Grouping Rows
For example, if you group the rows by department and include the department
in the group header, the department will display before the first line of data
each time the department changes.
At runtime, you see this:
Suppressing group If you do not want a group header to display at the top of each page when you
headers print or display a report, select the Suppress Group Header check box on the
General property page for the header. If none of the headers are suppressed,
they all display at the top of each page. When a page break coincides with a
group break, the group header and any group headers that follow it display
even if the Suppress Group Header property is set, but higher level headers are
suppressed if the property is set for those headers.
For example, suppose a report has three groups: division, sales region, and
sales manager. If all three group headers are suppressed, and a sales region
group break coincides with a page break, the division header is suppressed but
the sales region and sales manager headers display.
Using the group trailer The contents of the group trailer display after the last row for each value that
band causes a break.
In the group trailer band, you specify the information you want displayed after
the last line of identical data for each value in the group. Typically, you include
summary statistics here, as described next.
Specifying the Typically, you use aggregate and other functions in your summary statistic.
expression PowerBuilder lists functions you can use in the Functions box in the Modify
Expression dialog box. When you are defining a computed field in a group
header or trailer band, PowerBuilder automatically lists forms of the functions
that reference the group:
You can paste these templates into the expression, then replace the #x that is
pasted in as the function argument with the appropriate column or expression.
For example, to count the employees in each department (group 1), specify this
expression in the group trailer band:
Count( Emp_Id for group 1 )
To get the average salary of employees in a department, specify:
Avg( Salary for group 1 )
666 PowerBuilder
CHAPTER 22 Filtering, Sorting, and Grouping Rows
At runtime, the average and total salaries are calculated and displayed:
668 PowerBuilder
CHAPTER 22 Filtering, Sorting, and Grouping Rows
For example, if you chose the Salary column, PowerBuilder specifies that
the groups will be sorted by the expression sum(salary for group 1):
670 PowerBuilder
C H A P T E R 2 3 Highlighting Information in
DataWindow Objects
About this chapter This chapter describes how you modify the way information displays in
DataWindow objects and reports based on the conditions you specify. The
conditions are usually related to data values, which are not available until
runtime.
Contents
Topic Page
Highlighting information 671
Modifying properties conditionally at runtime 675
Supplying property values 681
Specifying colors 700
Highlighting information
Every control in a DataWindow object has a set of properties that
determines what the control looks like and where it is located. For
example, the values in a column of data display in a particular font and
color, in a particular location, with or without a border, and so on.
In the following DataWindow object, the Salary Plus Benefits column has a
Shadow box border around every data value in the column. To display the
border, you set the border property for the column:
672 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
In this example the Border property is set to NoBorder in the Properties view.
However, the expression defined for the property overrides that setting at
runtime.
A closer look at the The expression you enter almost always begins with If. Then you specify three
expression things: the condition, what happens if it is true, and what happens if it is false.
Parentheses surround the three things and commas separate them:
If( expression, true, false )
The following expression is used in the example. Because the expression is for
the Border property, the values for true and false indicate particular borders.
The value 1 means Shadow box border and the value 0 means no border:
If(salary_plus_benefits > 60000, 1, 0)
When users run the DataWindow object, PowerBuilder checks the value in the
computed column called salary_plus_benefits to see if it is greater than 60,000.
If it is (true), PowerBuilder displays the value with the Shadow box border. If
not (false), PowerBuilder displays the value with no border.
About specifying Usually you specify a number to indicate what you want for a particular
properties property. For example, the following list shows all of the borders you can
specify and the numbers you use. If you want the border property to be Shadow
box, you specify 1 in the If statement, for either true or false.
0—None
1—Shadow box
2—Box
3—Resize
4—Underline
5—3D Lowered
6—3D Raised
In the Properties view, the list of choices for setting a property includes the
values that correspond to choices in parentheses. This makes it easier to define
an expression for a property; you do not need to look up the values. For
example, if you want to specify the ResizeBorder in your expression, you use
the number 3, as shown in the drop-down list.
For details on the values of properties that can be set using expressions, see
Supplying property values on page 681.
For complete information about what the valid values are for all properties
associated with a DataWindow object, see the discussion of DataWindow
object properties in the DataWindow Reference or online help.
About modifying You can also programmatically modify the properties of controls in a
properties DataWindow object at runtime. For more information, see the DataWindow
programmatically
Reference and the DataWindow Programmers Guide.
674 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
For complete information about what the valid values are for all properties
of controls in the DataWindow object, see the discussion of DataWindow
object properties in the DataWindow Reference or online Help.
7 Replace the f (false) with the value to use for the property if the condition
is false.
8 Click OK.
For examples, see Example 1: creating a gray bar effect next, Example 2:
rotating controls on page 677, Example 3: highlighting rows of data on page
678, and Example 4: changing the size and location of controls on page 680.
676 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
2 To make it easier to see what you are doing in the Design view, select the
General tab and set the Brush Color to White and the Pen Color to Black.
A narrow black line forms a boundary around the rectangle.
3 Select Send to Back from the rectangle’s pop-up menu.
4 To hide the border of the rectangle, set the Pen Style to No Visible Line.
5 Click the button next to the Brush Color property on the General page.
6 In the Modify Expression dialog box, enter the following expression for
the Brush.Color property:
If(mod(getrow(),2 )=1, rgb(255, 255, 255 ), rgb(240,
240, 240 ))
The mod function takes the row number (getrow()), divides it by 2, then
returns the remainder. The remainder can be either 0 or 1. If the row
number is odd, mod returns 1; if the row number is even, mod returns 0.
The expression mod(getrow(),2)=1 distinguishes odd rows from even
rows.
The rgb function specifies maximum amounts of red, green, and blue: rgb
(255, 255, 255). Specifying 255 for red, green, and blue results in the
color white.
If the row number is odd (the condition evaluates as true), the rectangle
displays as white. If the row number is even (the condition evaluates as
false), the rectangle displays as light gray (rgb (240, 240, 240)).
1 Select one of the controls, then use Ctrl + click to select the other two
controls.
The Properties view changes to show the properties that are common to all
selected controls.
2 On the Font page in the Properties view, click the button next to the
Escapement property.
3 Enter the number 450 in the Modify Expression dialog box and click OK.
The value entered for font escapement is in tenths of degrees, so the
number 450 means 45 degrees. You do not have to specify a condition.
Typically, you do not specify a condition for control rotation.
The rotation of the controls does not change in the Design view.
4 To see the change, close and reopen the Preview view.
678 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
To make these controls display in bold with two asterisks if the employee is not
from Massachusetts:
1 Select one of the controls, then use Ctrl + click to select the other three
controls.
The Properties view changes to show the properties that are common to all
selected controls.
2 On the Font page in the Properties view, click the button next to the Bold
property.
3 Enter the following expression in the Modify Expression dialog box and
click OK:
If(state = 'MA', 400, 700)
The expression states that if the value of the state column is MA, use 400
as the font weight. This means employees from Massachusetts display in
the normal font. For any state except MA, use 700 as the font weight. This
means all other employees display in bold font.
4 To insert two asterisks (**) in front of the employee name if the employee
is not from Massachusetts, add a text control to the left of the employee
name with the two asterisks in bold.
5 With the text control selected, click the button next to its Visible property
on the General page in the Properties view.
6 In the Modify Expression dialog box that displays, enter the following
expression and click OK:
If(state = 'MA', 0, 1)
This expression says that if the state of the employee is MA (the true
condition), the Visible property of the ** control is off (indicated by 0). If
the state of the employee is not MA (the false condition), the Visible
property of the ** control is on (indicated by 1). The asterisks are visible
next to that employee’s name.
Tip
You can use underlines, italics, strikethrough, borders, and colors to
highlight information.
This example shows how to move the rectangle and line. The process for
columns is similar.
In the Design view, the rectangle and line display in one location, with a single
set of dimensions. The expressions you specify are used only in Preview view
and at runtime and all have the following syntax:
If ( state='NY', true value, false value )
The false value is the same as the value in Design view. All of the values used
in this example are in PowerBuilder Units (PBUs), the default unit of measure
used for the DataWindow object.
To change properties of the rectangle and the line for rows with the state
column equal to New York:
680 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
1 Select the rectangle, display the Position page in the Properties view, and
specify expressions for the following properties:
Property Expression
X if (state = 'NY', 2890, 1865)
Width if (state = 'NY', 500, 1000)
Height if (state = 'NY', 160, 120)
2 Select the line, display the Position page in the Properties view, and
specify expressions for the following properties:
Property Expression
X1 if (state = 'NY', 2890, 1865)
Y1 if (state = 'NY', 168, 132)
X2 if (state = 'NY', 3400, 2865)
Y2 if (state = 'NY', 168, 132)
3 On the General page for the line, specify this expression for Pen Width:
if (state = 'NY', 10, 4)
At runtime, the rectangle is taller and narrower, and the line is shorter and
has a wider pen width.
Background.Color
Description Setting for the background color of a control.
In the painter Background Color on the Background page or Font page in the Properties view.
682 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
Border
Description The type of border for the control.
In the painter Border on the General page in the Properties view.
Value A number that specifies the type of border. Values are:
0—None
1—Shadow box
2—Box
3—Resize
4—Underline
5—3D Lowered
6—3D Raised
Example The following statement specifies that if the person represented by the current
row has a status of L (on leave), the status column displays with a Shadow box
border:
If(status = 'L', 1, 0)
In this example, the condition is applied to the Border property of the status
column.
The following is a portion of the resulting DataWindow object. Notice that the
status On Leave displays with a Shadow box border:
Brush.Color
Description Setting for the fill color of a graphic control.
In the painter Brush Color on the General page in the Properties view.
Value A number that specifies the color that fills the control.
684 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
Brush.Hatch
Description Setting for the fill pattern of a graphic control.
In the painter Brush Hatch on the General page in the Properties view.
Value A number that specifies the pattern that fills the control. Values are:
0—Horizontal
1—Bdiagonal (lines from lower left to upper right)
2—Vertical
3—Cross
4—Fdiagonal (lines from upper left to lower right)
5—DiagCross
6—Solid
7—Transparent
8—Background (use the values on the Background tab)
Example In this example, statements check the employee’s start date to see if the month
is the current month or the month following the current month. Properties of a
rectangle control placed behind the row of data are changed to highlight
employees with months of hire that match the current month or the month
following the current month.
The Design view includes columns of data and a rectangle behind the data. The
rectangle has been changed to black in the following picture to make it stand
out:
The following statement is for the Brush.Color property of the rectangle. If the
month of the start date matches the current month or the next one, Brush.Color
is set to light gray (12632256). If not, it is set to white (16777215), which
means it will not show:
If(month( start_date ) = month(today())
Color
Description The color of text for text controls, columns, and computed fields; background
color for the DataWindow object; line color for graphs.
In the painter In the Properties view, Text Color on the Font property page; Color on the
Background property page; Line Color on the General property page.
Value A number that specifies the color used for text.
For information on specifying colors, see Specifying colors on page 700.
Example The following statement is for the Color property of the emp_id, emp_fname,
emp_lname, and emp_birth_date columns:
If(month(birth_date) = month (today()), 255, 0)
If the employee has a birthday in the current month, the information for the
employee displays in red (255). Otherwise, the information displays in black
(0).
The Font.Underline property has the same conditional expression defined for
it so that the example shows clearly on paper when printed in black and white.
686 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
Example To enter rotation for a control, select the control in the Design view and click
the button next to the Escapement property in the Properties view. In the dialog
box that displays, enter the number of tenths of degrees.
The following picture shows the Design view with a number of text controls.
Each text control shows the Font.Escapement value entered and the number of
degrees of rotation. In the Design view, you do not see rotation; it looks as if
the controls are all mixed up. Some controls seem to overlie each other:
The next picture shows the same controls at runtime. Each control is rotated
appropriately, based on the Font.Escapement and Alignment values:
Font.Height
Description The height of the text.
In the painter Size on the Font page in the Properties view.
Value An integer in the unit of measure specified for the DataWindow object. Units
of measure include PowerBuilder units, thousandths of an inch (1000 = 1 inch),
thousandths of a centimeter (1000 = 1 centimeter), or pixels. To specify size in
points, specify a negative number.
688 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
Example The following statement is specified for the Font.Height property of a text
control. Note that the DataWindow object is defined as using thousandths of an
inch as its unit of measure. The statement says that if the control is in the first
row, show the text 1/2-inch high (500 1/1000ths of an inch) and if it is not the
first, show the text 1/5-inch high (200 1/1000ths of an inch):
If(GetRow() = 1, 500, 200)
The boundaries of the control might need to be extended to allow for the
increased size of the text. At runtime, the first occurrence of the text control is
big (1/2 inch); subsequent ones are small (1/5 inch).
Font.Italic
Description A number that specifies whether the text should be italic.
In the painter Italic on the Font page in the Properties view.
Value Values are:
0—Not italic
1—Italic
Example The following statements are specified for the Font.Italic, Font.Underline, and
Font.Weight properties, respectively. If the employee has health insurance, the
employee’s information displays in italics. If not, the employee’s information
displays in bold and underlined:
If(bene_health_ins = 'Y', 1, 0)
If(bene_health_ins = 'N', 1, 0)
If(bene_health_ins = 'N', 700, 400)
Statements are specified in this way for four controls: the emp_id column, the
emp_fname column, the emp_lname column, and the emp_salary column. In
the resulting DataWindow object, those with health insurance display in italics.
Those without health insurance are emphasized with bold and underlining:
Font.Strikethrough
Description A number that specifies whether the text should be crossed out.
In the painter Strikeout on the Font page in the Properties view.
Value Values are:
0—Not crossed out
1—Crossed out
Example The following statement is for the Font.Strikethrough property of the emp_id,
emp_fname, emp_lname, and emp_salary columns. The status column must be
included in the data source even though it does not appear in the DataWindow
object itself. The statement says that if the employee's status is L, which means
On Leave, cross out the text in the control:
If(status = 'L', 1, 0)
An extra text control is included to the right of the detail line. It becomes visible
only if the status of the row is L (see Visible on page 697).
690 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
Font.Underline
Description A number that specifies whether the text should be underlined.
In the painter Underline on the Font page in the Properties view.
Value Values are:
0—Not underlined
1—Underlined
Font.Weight
Description The weight of the text.
In the painter Bold on the Font page in the Properties view.
Value Values are:
100—Thin
200—Extra light
300—Light
400—Normal
500—Medium
600—Semibold
700—Bold
800—Extrabold
900—Heavy
Example The following statement, when applied to the Font.Weight property of columns
of employee information, causes the information to be displayed in bold if the
employee does not have health insurance:
If(bene_health_ins = 'N', 700, 400)
For pictures of this example, see Font.Italic on page 689.
Format
Description The display format for a column.
In the painter Format on the Format page in the Properties view.
Values A string specifying the display format.
Example The following statement, when applied to the Format property of the Salary
column, causes the column to display the word Overpaid for any salary
greater than $60,000 and Underpaid for any salary under $60,000:
If(salary>60000, 'Overpaid', 'Underpaid')
692 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
Height
Description The height of the column or other control.
In the painter Height on the Position page in the Properties view.
Value An integer in the unit of measure specified for the DataWindow object. Units
of measure include PowerBuilder units, thousandths of an inch (1000 = 1 inch),
thousandths of a centimeter (1000 = 1 centimeter), or pixels.
Example The following statement causes the height of a rectangle to be 160
PowerBuilder units if the state column for the row has the value NY.
Otherwise, the rectangle is 120 PowerBuilder units high:
if (state = 'NY', 160, 120)
For more details and pictures, see Example 4: changing the size and location
of controls on page 680.
Pen.Color
Description The color of the line or the outline of a graphic control.
In the painter Pen Color on the General page in the Properties view.
Value A number that specifies the color of the line or outline.
For information on specifying colors, see Specifying colors on page 700.
Example See the example for the Pen.Style property, next.
Pen.Style
Description The style of the line or the outline of a graphic control.
In the painter Pen Style on the General page in the Properties view.
Value Values are:
0—Solid
1—Dash
2—Dotted
3—Dash-dot pattern
4—Dash-dot-dot pattern
5—Null (no visible line)
Example In this example, statements check the employee’s start date to see if the month
is the current month or the month following the current month. Properties of a
rectangle control placed behind the row of data are changed to highlight
employees with months of hire that match the current month or the month
following the current month.
The Design view includes columns of data and a rectangle behind the data. The
rectangle has been changed to black in the following picture to make it stand
out:
The following statement is for the Pen.Color property of the line around the
edge of the rectangle. If the month of the start date matches the current month
or the next one, Pen.Color is set to light gray (12632256). If not, it is set to
white (16777215), which means it will not show:
If(month( start_date ) = month(today())
or month( start_date ) = month(today())+1
or (month(today()) = 12 and month(start_date)=1),
12632256, 16777215)
The following statement is for the Pen.Style property of the rectangle. If the
month of the start date matches the current month or the next one, Pen.Style is
set to Solid (0). If not, it is set to NULL (5), which means it will not show:
If(month( start_date ) = month(today())
or month( start_date ) = month(today())+1
or (month(today()) = 12 and month(start_date)=1),
0, 5)
Expressions are also defined for Brush.Color and Brush.Hatch.
For more about these properties, see Brush.Hatch on page 685.
694 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
Pen.Width
Description The width of the line or the outline of a graphic control.
In the painter Pen Width on the General page in the Properties view.
Value An integer in the unit of measure specified for the DataWindow object. Units
of measure include PowerBuilder units, thousandths of an inch (1000 = 1 inch),
thousandths of a centimeter (1000 = 1 centimeter), or pixels.
Example The following statement causes the width of a line to be 10 PowerBuilder units
if the state column for the row has the value NY. Otherwise, the line is 4
PowerBuilder units wide:
If(state = 'NY', 10, 4)
For more details and pictures, see Example 4: changing the size and location
of controls on page 680.
Pointer
Description The image used for the mouse pointer when the pointer is over the specified
control.
In the painter Pointer on the Pointer page in the Properties view.
Value A string that specifies a value of the Pointer enumerated data type or the name
of a cursor file (CUR) used for the pointer.
Values of the Pointer enumerated data type are:
Arrow!
Cross!
HourGlass!
IBeam!
Icon!
Size!
SizeNESW!
SizeNS!
SizeNWSE!
SizeWE!
UpArrow!
Example The following condition, entered for the Pointer property of every control in a
row of expense data, changes the pointer to a column every time the value in
the expense column exceeds $100,000. Note that the pointer has no meaning in
a printed report. The pointer is for use on the screen display of a DataWindow
object:
If(expense 100000, 'pbcolumn.cur', 'arrow!')
Protect
Description The protection setting of a column.
In the painter Protect on the General page in the Properties view.
Value Values are:
0—False, the column is not protected
1—True, the column is protected
696 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
Timer_Interval
In the painter Timer Interval on the General page in the Properties view.
Description The number of milliseconds between the internal timer events.
Value The default is 0 (which is defined to mean 60,000 milliseconds or one minute).
Visible
Description Whether the control is visible in the DataWindow object.
In the painter Visible on the General page in the Properties view.
Value Values are:
0—Not visible
1—Visible
Example The following statement is for the Visible property of a text control with the
words On Leave located to the right of columns of employee information. The
statement says that if the current employee’s status is L, which means On
Leave, the text control is visible. Otherwise, it is invisible:
If(status = 'L', 1, 0)
The Design view includes the text control at the right-hand end of the detail
line. The text control is visible at runtime only if the value of the status column
for the row is L.
In the resulting DataWindow object, the text control is visible only for the two
employees on leave. For a picture, see Font.Strikethrough on page 690.
Width
Description The width of the control.
In the painter Width on the Position page in the Properties view.
Value An integer in the unit of measure specified for the DataWindow object. Units
of measure include PowerBuilder units, thousandths of an inch (1000 = 1 inch),
thousandths of a centimeter (1000 = 1 centimeter), or pixels.
Example The following statement causes the width of a rectangle to be 500
PowerBuilder units if the state column for the row has the value NY.
Otherwise, the rectangle is 1000 PowerBuilder units wide:
if (state = 'NY', 500, 1000)
For more details and pictures, see Example 4: changing the size and location
of controls on page 680.
X
Description The distance of the control from the left edge of the DataWindow object. At
runtime, the distance from the left edge of the DataWindow object is calculated
by adding the margin to the x value.
In the painter X on the Position page in the Properties view.
Value An integer in the unit of measure specified for the DataWindow object. Units
of measure include PowerBuilder units, thousandths of an inch (1000 = 1 inch),
thousandths of a centimeter (1000 = 1 centimeter), or pixels.
Example The following statement causes a rectangle to be located 6.250 inches from the
left if the state column for the row has the value NY. Otherwise, the rectangle
is 4.000 inches from the left:
If(state = 'NY', 6250, 4000)
For more details and pictures, see Example 4: changing the size and location
of controls on page 680.
X1, X2
Description The distance of each end of the line from the left edge of the DataWindow
object as measured in the Design view. At runtime, the distance from the left
edge of the DataWindow object is calculated by adding the margin to the x1
and x2 values.
In the painter X1, X2 on the Position page in the Properties view.
698 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
Value Integers in the unit of measure specified for the DataWindow object. Units of
measure include PowerBuilder units, thousandths of an inch (1000 = 1 inch),
thousandths of a centimeter (1000 = 1 centimeter), or pixels.
Example The following statements for the X1 and X2 properties of a line cause the line
to extend from 6.250 to 7.150 inches from the left if the state column for the
row has the value NY. Otherwise, the line extends from 4.000 to 6.000 inches
from the left:
If(state = 'NY', 6250, 4000)
If(state = 'NY', 7150, 6000)
For more details and pictures, see Example 4: changing the size and location
of controls on page 680.
Y
Description The distance of the control from the top of the band in which the control is
located.
In the painter Y on the Position page in the Properties view.
Value An integer in the unit of measure specified for the DataWindow object. Units
of measure include PowerBuilder units, thousandths of an inch (1000 = 1 inch),
thousandths of a centimeter (1000 = 1 centimeter), or pixels.
Example For information, see Example 4: changing the size and location of controls on
page 680.
Y1, Y2
Description The distance of each end of the specified line from the top of the band in which
the line is located.
In the painter Y1, Y2 on the Position page in the Properties view.
Value Integers in the unit of measure specified for the DataWindow object. Units of
measure include PowerBuilder units, thousandths of an inch (1000 = 1 inch),
thousandths of a centimeter (1000 = 1 centimeter), or pixels.
Example The following statements for the Y1 and Y2 properties of a line cause the line
to be located .400 inches (Y1 and Y2 equal .400 inches) from the top of the
detail band, if the state column for the row has the value NY. Otherwise, the
line is located .250 inches (Y1 and Y2 equal .250 inches) from the top of the
detail band:
If(state = 'NY', 400, 250)
If(state = 'NY', 400, 250)
For more details and pictures, see Example 4: changing the size and location
of controls on page 680.
Specifying colors
You specify a color by specifying a number that represents the color. You can
specify the number explicitly or by using an expression that includes the RGB
(r, g, b) function.
For the numbers and expressions that specify common colors, see Table 23-2
on page 701.
How the number is The formula for combining color values into a number is:
calculated
red + 256*green + 256*256*blue
where the amount of each primary color (red, green, and blue) is specified as a
value from 0 to 255.
The RGB function calculates the number from the amounts of red, green, and
blue specified.
Sample numeric To create cyan, you use blue and green, but no red. If you wanted to create the
calculation most saturated (bright) cyan, you would use maximum amounts of blue and
green in the formula, which is indicated by the number 255 for each. The
following statements show the calculation:
red + 256*green + 256*256*blue
0 + 256*255 + 256*256*255
0 + 65280 + 16711680
16776960
Sample expression The following expression specifies the brightest cyan:
using the RGB
function RGB (0,255,255)
700 PowerBuilder
CHAPTER 23 Highlighting Information in DataWindow Objects
Notice that the expression specifies the maximum for green and blue (255) and
0 for red. The expression returns the value 16776960. To specify cyan, entering
the expression RGB(0, 255, 255) is the same as entering the number 16776960.
Numbers and Table 23-2 shows the numbers and expressions to enter for some common
expressions to enter colors. The number and expression for a color are equivalent. You can use
for the common colors
either.
Table 23-2: Numbers and expressions for common colors
Number
Color Expression to enter to enter How the number is calculated
Black RGB (0, 0, 0) 0 0 (no color)
Blue RGB (0, 0, 255) 16711680 256*256*255 (blue only)
Cyan RGB (0, 255, 255) 16776960 256*255 + 256*256*255 (green and blue)
Dark Green RGB (0, 128, 0) 32768 256*128 (green only)
Green RGB (0, 255, 0) 65280 256*255 (green only)
Light Gray RGB (192, 192, 192) 12632256 192 + 256*192 + 256*256*192
(some red, green, and blue in equal amounts)
Lighter Gray RGB (224, 224, 224) 14737632 224 + 256*224 + 256*256*224
(some red, green, and blue in equal amounts)
Lightest Gray RGB (240, 240, 240) 15790320 240 + 256*240 + 256*256*240
(some red, green, and blue in equal amounts)
Magenta RGB (255, 0, 255) 16711935 255 + 256*256*255 (red and blue)
Red RGB (255, 0, 0) 255 255 (red only)
White RGB (255, 255, 255) 16777215 255 + 256*255 + 256*256*255 (red, green, and blue
in equal amounts at the maximum of 255)
Yellow RGB (255, 255, 0) 65535 255 + 256*255 (red and green)
702 PowerBuilder
C H A P T E R 2 4 Using Nested Reports
About this chapter This chapter provides information about creating reports that have other
reports nested in them.
Contents
Topic Page
About nested reports 703
Creating a report using the Composite presentation style 707
Placing a nested report in another report 709
Working with nested reports 712
Composite report For example, the following composite report consists of three tabular reports.
One of the tabular reports includes a graph:
Composite report in In the Design view, you see three boxes that represent the individual tabular
the Design view reports that are included in the composite report. The only additional controls
in this example are a title, date, and page number:
704 PowerBuilder
CHAPTER 24 Using Nested Reports
About placing a You can place one or more reports within another report. The report you place
nested report within is called the nested report. You can place a nested report in any type of report
another report
except crosstab. Most of the time you will place nested reports in freeform or
tabular reports.
Often, the information in the nested report depends on information in the report
in which it is placed (the base report). The nested report and the base report are
related to each other by some common data. The base report and the nested
report have a master/detail relationship.
Freeform report with a For example, the following freeform report lists all information about a
related nested report customer and then includes a related nested report (which happens to be a
tabular report). The related nested report lists every order that the customer has
ever placed. The base report supplies the customer ID to the nested report,
which requires a customer ID as a retrieval argument. This is an example of a
master/detail relationship—one customer has many orders:
What you see in the In the Design view, you see everything in the base report plus a box that
Design view represents the related nested report:
The difference There are two important differences between nesting using the Composite style
between nested and and nesting a report within a base report.
composite reports
Data sources The composite report does not have a data source—it is just a
container for nested reports. In contrast, a base report with a nested report in it
has a data source. The nested report has its own data source.
Related nesting The composite report cannot be used to relate reports to
each other in the database sense. One report cannot feed a value to another
report, which is what happens in a master/detail report. If you want to relate
reports to each other so that you can create a master/detail report, you need to
place a nested report within a base report.
How retrieval works When you preview (run) a composite report, PowerBuilder retrieves all the
rows for one nested report, and then for another nested report, and so on until
all retrieval is complete. Your computer must have a default printer specified,
because composite reports are actually displayed in print preview mode.
When you preview (run) a report with another related report nested in it,
PowerBuilder retrieves all the rows in the base report first. Then PowerBuilder
retrieves the data for all nested reports related to the first row. Next,
PowerBuilder retrieves data for nested reports related to the second row, and so
on, until all retrieval is complete for all rows in the base report.
For information about efficiency and retrieval, see Supplying retrieval
arguments to relate a nested report to its base report on page 715.
706 PowerBuilder
CHAPTER 24 Using Nested Reports
Limitations on nesting For the most part you can nest the various types of report styles. However,
reports limitations apply to two of them.
Crosstabs You cannot place a crosstab with retrieval arguments within
another report as a related nested report. However, you can include a crosstab
in a Composite report.
RichText reports You cannot nest a RichText report in any way. You cannot
place a RichText report in another report, and you cannot include a RichText
report in a Composite report.
5 Select File>Save from the menu bar and assign a name to the composite
report.
6 Look at the Preview view of the report:
7 Continue to enhance the composite report (for example, add a date and
title).
708 PowerBuilder
CHAPTER 24 Using Nested Reports
The WHERE clause in this example tells the DBMS to retrieve rows where
the value in the column cust_id equals the value of the argument
:customerid:
At this point, when you run the report to retrieve data, you are prompted
to enter a value for :customerid. Later in these steps, you will specify that
the base report supply the values for :customerid instead of prompting for
values.
4 Open or create the report you want to have as the base report.
In the example, the base report is one that lists customers and has a place
for the order history of each customer:
710 PowerBuilder
CHAPTER 24 Using Nested Reports
The Arguments box lists arguments defined for the nested report and
provides a way for you to specify how information from the base report
will be used to supply the values of arguments to the nested report.
9 Supply the base report column or the expression that will supply the
argument’s value. To do this, click the button in the Expression column.
The Modify Expression dialog box displays. In this dialog box, you can
easily select one of the columns or develop an expression. In the example,
the column named id from the base report will supply the value for the
argument :customerid in the nested report.
10 Select File>Save from the menu bar and assign a name to the report.
11 In the Preview view, you can see what your report looks like:
712 PowerBuilder
CHAPTER 24 Using Nested Reports
• Specifying criteria to relate a nested report to its base report on page 716
• Using options for nested reports on page 717
The name of the report that displays in the box in the Design view changes
to the new one.
714 PowerBuilder
CHAPTER 24 Using Nested Reports
To supply a retrieval argument value from the base report to the nested
report:
1 Make sure that the nested report has been set up to take one or more
retrieval arguments.
See Placing a nested report in another report on page 709.
2 Select the nested report and then select the General page of the Properties
view.
The Arguments box lists arguments defined for the nested report and
provides a way for you to specify how information from the base report
will supply the value of the argument to the nested report.
3 Supply the base report column or the expression that will supply the
argument’s value. To do this, click the button in the Expression column.
The Modify Expression dialog box displays. In this dialog box, you can
easily select one of the columns or develop an expression. In the example,
the column named id from the base report will supply the value for the
argument :customerid in the nested report.
When you run the report now, you are not prompted for retrieval argument
values for the nested report. The base report supplies the retrieval
argument values automatically.
716 PowerBuilder
CHAPTER 24 Using Nested Reports
How the DBMS If you use the specify criteria technique, the DBMS repeatedly recompiles the
processes SQL if you SELECT statement and then executes it. The recompilation is necessary for
use the specify criteria
technique each possible variation of the WHERE clause.
When you run the report now, PowerBuilder retrieves rows in the nested
report based on the criteria you have specified. In the example, the
customer ID column in the base report determines which rows from the
sales_order table are included for each customer.
This option is on by default for all nested reports except graphs. Usually there
is no reason to change it. If you do want to force a nested report to have a fixed
height, you can turn this option off.
Note that all bands in the DataWindow also have an Autosize Height option.
The option is off by default and must be on for the Autosize Height option for
the nested report to work properly.
Using the Slide PowerBuilder determines the appropriate Slide options when positioning the
options nested report(s) and assigns default values. Usually, you should not change the
default values:
• The Slide Left option is on by default for grid and crosstab style reports
and off by default for all others. Having Slide Left on for grid and crosstab
ensures that these reports break horizontally on whole columns and not in
the middle of a column.
• The Slide Up All Above and Directly Above options ensure that the nested
report uses just as much vertical space as it needs. One of these options is
on by default for all nested reports.
For more information, see Sliding controls to remove blank space in a
DataWindow object on page 590.
Using the New Page The New Page option forces a new page for a nested report used in a composite
option (composite report. By default, this option is off.
only)
718 PowerBuilder
CHAPTER 24 Using Nested Reports
To specify that the footer should appear at the bottom of the page:
1 In the Design view, select the nested report.
2 In the Properties view, select the General properties page.
3 Clear the Trail Footer check box.
4 The footer appears at the bottom of the page on all pages of the nested
report, including the last page. Note that if another nested report begins on
the same page, the footer from the earlier report might be misleading or
confusing.
720 PowerBuilder
C H A P T E R 2 5 Working with Graphs
About this chapter This chapter describes how to build and use graphs in PowerBuilder.
Contents
Topic Page
About graphs 721
Using graphs in DataWindow objects 729
Using the Graph presentation style 741
Defining a graph's properties 742
Using graphs in windows 752
About graphs
Often the best way to display information is graphically. Instead of
showing users a series of rows and columns of data, you can present
information as a graph in a DataWindow object or window. For example,
in a sales application, you might want to present summary information in
a column graph.
PowerBuilder provides many types of graphs and allows you to customize
your graphs in many ways. Probably most of your use of graphs will be in
a DataWindow object. The source of the data for your graphs will be the
database.
You can also use graphs as standalone controls in windows (and user
objects) and populate the graphs with data through scripts.
The way you define graphs is the same whether you are using them in a
DataWindow object or directly in a window. However, the way you
manipulate graphs in a DataWindow object is different from the way you
manipulate them in a window.
Before using graphs in an application, you need to understand the parts of
a graph and the kinds of graphs that PowerBuilder provides.
Parts of a graph
Here is a column graph created in PowerBuilder that contains most major parts
of a graph. It shows quarterly sales of three products: Stellar, Cosmic, and
Galactic printers:
Organization of a graph
Table 25-2 lists the parts of a typical graph.
722 PowerBuilder
CHAPTER 25 Working with Graphs
Types of graphs
PowerBuilder provides many types of graphs for you to choose from. You
choose the type on the Define Graph Style page in the DataWindow wizard or
724 PowerBuilder
CHAPTER 25 Working with Graphs
Pie graphs
Pie graphs typically show one series of data points with each data point shown
as a percentage of a whole. The following pie graph shows the sales for Stellar
printers for each quarter. You can easily see the relative values in each quarter.
(PowerBuilder automatically calculates the percentages of each slice of the
pie.)
You can have pie graphs with more than one series if you want; the series are
shown in concentric circles. Multiseries pie graphs can be useful in comparing
series of data.
Scatter graphs
Scatter graphs show xy data points. Typically you use scatter graphs to show
the relationship between two sets of numeric values. Non-numeric values, such
as string and DateTime datatypes, do not display correctly.
Scatter graphs do not use categories. Instead, numeric values are plotted along
both axes—as opposed to other graphs, which have values along one axis and
categories along the other axis.
For example, the following data shows the effect of speed on the mileage of a
sedan:
Speed Mileage
10 12
20 18
30 21
40 23
50 26
Speed Mileage
60 26
70 24
80 20
You can have multiple series of data in a scatter graph. You might want to plot
mileage versus speed for several makes of cars in the same graph.
Three-dimensional graphs
Traditional 3D graphs You can also create 3-dimensional (3D) graphs of area, bar, column, line, and
pie graphs. In 3D graphs (except for 3D pie graphs), series are plotted along a
third axis (the Series axis) instead of along the Category axis. You can specify
the perspective to use to show the third dimension:
726 PowerBuilder
CHAPTER 25 Working with Graphs
DirectX 3D graphs DirectX 3D rendering allows you to display the 3D graphs (Pie3D, Bar3D,
Column3D, Line3D, and Area3D) with a more sophisticated look. You can use
data item or series transparency with the DirectX graph styles to improve the
presentation of data.
The DirectX graph rendering style is supported for standalone graph controls
and for graph controls in a DataWindow object. PowerBuilder uses the
following functions to support the DirectX graph styles:
GetDataLabelling SetDataLabelling
GetDataTransparency SetDataTransparency
GetSeriesLabelling SetSeriesLabelling
GetSeriesTransparency SetSeriesTransparency
Stacked graphs
In bar and column graphs, you can choose to stack the bars and columns. In
stacked graphs, each category is represented as one bar or column instead of as
separate bars or columns for each series:
728 PowerBuilder
CHAPTER 25 Working with Graphs
4 Specify which columns contain the data and the type of graph you want,
and click OK.
For more information, see Associating data with a graph on page 732.
The Design view now contains a representation of the graph:
730 PowerBuilder
CHAPTER 25 Working with Graphs
The Properties view for a graph has several property pages in which you
specify information about the graph. Table 25-3 lists the property pages that
contain properties that are specific to graphs, and describes what each property
page specifies.
Table 25-3: Property page for graphs
Property page What it specifies
Axis Labels, scale, information about major and minor divisions for
the category axes.
Data Where to get the graph's data.
General Various general graph properties, including border, graph colors,
whether to size the graph to the full screen display, suppression in
newspaper columns.
Graph type, title, legend location.
For 3D graphs, perspective, rotation, elevation, and render3D.
For bar graphs, overlap, spacing and depth of bars.
Pointer The pointer to use when the mouse is positioned over the graph.
Position The x,y location of the upper left corner of the graph, its width
and height, sliding options, the layer in which the graph is to be
positioned.
Whether the graph can be resized and moved at runtime.
Text Text properties for text controls that display on the graph,
including title, axis text, axis label, and legend.
Text properties include font, font style, font size, alignment,
rotation, color, display expression, display format.
Other Descriptions and label for use by assistive technology tools.
2 Select the settings for the following options on the Position property page:
Table 25-4: Settings on the Position property page for graphs
Setting Meaning
Layer Background — The graph displays behind other elements in
the DataWindow object.
Band — The graph displays in one particular band. If you
choose this setting, you should resize the band to fit the graph.
Often you will want to place a graph in the Footer band. As
users scroll through rows in the DataWindow object, the
graph remains at the bottom of the screen as part of the footer.
Foreground — (Default) The graph displays above all other
elements in the DataWindow object. Typically, if you choose
this setting, you also make the graph movable so it will not
obscure data while users display the DataWindow object.
Moveable The graph can be moved in the Preview view and at runtime.
Resizable The graph can be resized in the Preview view and at runtime.
Slide Left, The graph slides to the left or up to remove extra white space.
Slide Up For more information, see Sliding controls to remove blank
space in a DataWindow object on page 590.
X, Y The location of the upper-left corner of the graph.
Width, Height The width and height of the graph.
3 Select the settings for the following options on the General property page:
Table 25-5: Size and position settings on the General property page
Setting Meaning
Size To Display The graph fills the DataWindow object and resizes when
users resize the DataWindow object. This setting is used with
the Graph presentation style.
HideSnaked Do not repeat graph after the first column in a DataWindow
object using newspaper-style columns.
732 PowerBuilder
CHAPTER 25 Working with Graphs
You can graph data from any columns retrieved into the DataWindow object.
The columns do not have to be displayed.
There is an entry along the Category axis for each different value of the column
or expression you specify.
Select an item from the drop-down list or type an expression (in the Properties
view). For example, if you want to graph the sum of units sold, you can specify:
sum(units for graph)
734 PowerBuilder
CHAPTER 25 Working with Graphs
To graph 110 percent of the sum of units sold, you can specify:
sum(units*1.1 for graph)
There is a set of data points for each different value of the column you specify
here. For example, if you specify a column that has 10 values, then your graph
will have 10 series: one set of data points for each different value of the
column.
Using expressions You can also specify expressions for Series (on the Data page of the Properties
view). For example, you could specify the following for Series:
Units / 1000
In this case, if a table had unit values of 10,000, 20,000, and 30,000, the graph
would show series values of 10, 20, and 30.
Specifying multiple You can specify more than one of the retrieved columns to serve as series.
entries Separate multiple entries by commas.
You must specify the same number of entries in the Value box as you do in the
Series box. The first value in the Value box corresponds to the first series
identified in the Series box, the second value corresponds to the second series,
and so on. The example about graphing actual and projected sales in Examples
on page 736 illustrates this technique.
Examples
This section shows how to specify the data for several different graphs of the
data in the Printer table in the PB Demo DB. The table records quarterly unit
sales of three printers by three sales representatives.
Table 25-7: The Printer table in the PB Demo DB
Rep Quarter Product Units
Simpson Q1 Stellar 12
Jones Q1 Stellar 18
Perez Q1 Stellar 15
Simpson Q1 Cosmic 33
Jones Q1 Cosmic 5
Perez Q1 Cosmic 26
Simpson Q1 Galactic 6
Jones Q1 Galactic 2
Perez Q1 Galactic 1
… … … …
Simpson Q4 Stellar 30
Jones Q4 Stellar 24
Perez Q4 Stellar 36
Simpson Q4 Cosmic 60
Jones Q4 Cosmic 52
Perez Q4 Cosmic 48
Simpson Q4 Galactic 3
Jones Q4 Galactic 3
Perez Q4 Galactic 6
Graphing total sales To graph total sales of printers in each quarter, retrieve all the columns into a
DataWindow object and create a graph with the following settings on the Data
page in the Properties view:
• Set Rows to All
• Set Category to quarter
• Set Value to sum(units for graph)
Leave the Series check box and text box empty.
736 PowerBuilder
CHAPTER 25 Working with Graphs
The Quarter column serves as the category. Because the Quarter column has
four values (Q1, Q2, Q3, and Q4), there will be four categories along the
Category axis. You want only one series (total sales in each quarter), so you can
leave the Series box empty, or type a string literal to identify the series in a
legend. Setting Value to sum(units for graph) graphs total sales in each
quarter.
Here is the resulting column graph. PowerBuilder automatically generates the
category text based on the data in the table:
In the preceding graph, there is one set of data points (one series) across four
quarters (the category values).
The following is a pie graph, which has exactly the same properties as the
preceding column graph except for the type, which is Pie:
Graphing unit sales of To graph total quarterly sales of each printer, retrieve all the columns into a
each printer DataWindow object and create a graph with the following settings on the Data
page in the Properties view:
• Set Rows to All
• Set Category to quarter
• Set Value to sum(units for graph)
• Select the Series check box
• Set Series to product
You want a different series for each printer, so the column Product serves as the
series. Because the Product column has three values (Cosmic, Galactic, and
Stellar), there will be three series in the graph. As in the first example, you want
a value for each quarter, so the Quarter column serves as the category, and you
want to graph total sales in each quarter, so the Value box is specified as
sum(units for graph).
Graphing unit sales by To graph quarterly sales made by each representative, create a graph with the
representative following settings on the Data page in the Properties view:
• Set Rows to All
• Set Category to quarter
• Set Value to sum(units for graph)
• Select the Series check box
• Set Series to rep
738 PowerBuilder
CHAPTER 25 Working with Graphs
Graphing unit sales by To graph quarterly sales made by each representative, plus total sales for each
representative and printer, create a graph with the following settings on the Data page in the
total sales
Properties view:
• Set Rows to All
• Set Category to quarter, "Total"
• Set Value to sum(units for graph), sum(units for graph)
• Select the Series check box
• Set Series to rep, rep
Here you have two types of categories: the first is Quarter, which shows
quarterly sales, as in the previous graph. You also want a category for total
sales. There is no corresponding column in the DataWindow object, so you can
simply type the literal “Total” to identify the category. You separate multiple
entries with a comma.
For each of these category types, you want to graph the sum of units sold for
each representative, so the Value and Series values are repeated.
Notice that PowerBuilder uses the literal “Total” supplied in the Category box
in the Graph Data window as a value in the Category axis.
Graphing actual and To graph total quarterly sales of all printers and projected sales for next year,
projected sales create a graph with the following settings on the Data page in the Properties
view (you assume that sales will increase by 10% next year):
• Set Rows to All
• Set Category to quarter
• Set Value to sum(units for graph), sum(units*1.1 for graph)
• Select the Series check box
• Set Series to 'Actual','Projected'
You are using labels to identify two series, Actual and Projected. Note the
single quotation marks around the literals. For Values, you enter the
expressions that correspond to Actual and Projected sales. For Actual, you use
the same expression as in the examples above, sum(units for graph). For
Projected sales, you multiply each unit sale by 1.1 to get the 10 percent
increase. Therefore, the second expression is sum(units*1.1 for graph).
740 PowerBuilder
CHAPTER 25 Working with Graphs
Here is the resulting graph. PowerBuilder uses the literals you typed for the
series as the series labels in the legend:
Note that when using the Graph presentation style, the graph always
graphs all rows; you cannot specify page or group.
6 On the Define Graph Style page, enter a title for the graph, select a graph
type, and click Next.
7 On the Ready to Create Graph DataWindow page, review your
specifications and click Finish.
A model of the graph displays in the Design view.
8 Specify the properties of the graph, as described in Defining a graph's
properties next.
9 Save the DataWindow object in a library.
10 Associate the graph DataWindow object with a DataWindow control on a
window or user object.
At runtime, the graph fills the entire control and resizes when the control
is resized.
742 PowerBuilder
CHAPTER 25 Working with Graphs
• PowerBuilder uses sample data (not data from your DataWindow object)
to illustrate series, categories, and values.
In Preview view, PowerBuilder displays the graph with data.
Naming a graph You can modify graphs at runtime. To reference a graph in code, you use its
name. By default, the graph is named gr_n.
To name a graph:
• On the General properties page for the graph, assign a meaningful name to
the graph in the Name box.
Defining a graph's title The title displays at the top of the graph.
Multiline titles
You can force a new line in a title by embedding ~n.
For information about specifying properties for the title text, see Specifying
text properties for titles, labels, axes, and legends on page 744.
Specifying the type of You can change the graph type at any time in the development environment.
graph (To change the type at runtime, modify a graph’s GraphType property.)
To specify how to sort the data for series and categories in a graph:
1 Select Properties from the graph’s pop-up menu and then select the Axis
page in the Properties view.
2 Select the axis for which you want to specify sorting.
3 Scroll to Sort, the last option on the Axis page, and select Ascending,
Descending, or Unsorted.
744 PowerBuilder
CHAPTER 25 Working with Graphs
To specify text properties for the title, labels, axis values, and legend of
a graph:
1 Select Properties from the graph’s pop-up menu and then select the Text
page in the Properties view.
2 Select a text element from the list in the Text Object drop-down list.
746 PowerBuilder
CHAPTER 25 Working with Graphs
Example By default, when you generate a pie graph, PowerBuilder puts the title at the
top and labels each slice of the pie with the percentage each slice represents of
the whole. Percentages are accurate to two decimal places.
The following graph has been enhanced as follows:
• The current date displays in the title
• The percentages are rounded to integers
• The raw data for each slice is shown in addition to the percentages
To accomplish this, the display expressions were modified for the title and pie
graph labels:
Element Original expression Modified expression
Title title title + " as of " +
date(today())
Pie graph if(seriescount > 1, if(seriescount > 1, series,
labels series, string string(percentofseries,"0%
(percentofseries, ") + " (" + value + ")" )
"0.00%"))
Table 25-8: Overlap and spacing properties for bar and column charts
Property Meaning
Overlap The percentage by which bars or columns overlap each other.
The default is 0 percent, meaning no overlap.
Spacing The amount of space to leave between bars or columns. The
default is 100 percent, which leaves a space equal to the width of
a bar or column.
For information on specifying properties for the text, see Specifying text
properties for titles, labels, axes, and legends on page 744.
748 PowerBuilder
CHAPTER 25 Working with Graphs
Specifying datatypes The data graphed along the Value, Category, and Series axes has an assigned
datatype. The Series axis always has the datatype String. The Value and
Category axes can have the datatypes listed in Table 25-10.
Table 25-10: Datatypes for Value and Category axes
Axis Possible datatypes
Both axes (for scatter graph) Number, Date, Time
Value (other graph types) Number, Date, DateTime, Time
Category (other graph types) String, Number, Date, DateTime, Time
Scaling axes You can specify the properties listed in Table 25-11 to define the scaling used
along numeric axes.
Using major and You can divide axes into divisions. Each division is identified by a tick mark,
minor divisions which is a short line that intersects an axis. In the Sales by Printer graphs shown
in Examples on page 736, the graph’s Value axis is divided into major divisions
of 50 units each. PowerBuilder divides the axes automatically into major
divisions.
750 PowerBuilder
CHAPTER 25 Working with Graphs
Representing You can specify lines to represent the divisions as described in Table 25-12 and
divisions with grid and illustrated in Figure 25-1.
drop lines
Table 25-12: Representing graph divisions with grid and drop lines
Line Meaning
Grid line A line that extends from a tick mark across the graph. Grid lines make
graphs easier to read.
Drop line A line that extends vertically from a data point to its axis (not available
for all graph types).
Using line styles You can define line styles for the components of a graph listed in Table 25-13.
Table 25-13: Components of a graph that can have line styles
Component Meaning
PrimaryLine The axis itself
SecondaryLine The axis parallel to and opposite the primary axis
OriginLine A grid line that represents the value zero
Frame The frame for the axis in 3D graphs (disabled for 2D graphs)
Specifying a pointer
You can specify a pointer to use when the mouse is over a graph at runtime.
752 PowerBuilder
C H A P T E R 2 6 Working with Crosstabs
About crosstabs
Cross tabulation is a useful technique for analyzing data. By presenting
data in a spreadsheet-like grid, a crosstab lets users view summary data
instead of a long series of rows and columns. For example, in a sales
application you might want to summarize the quarterly unit sales of each
product.
In PowerBuilder, you create crosstabs by using the Crosstab presentation
style. When data is retrieved into the DataWindow object, the crosstab
processes all the data and presents the summary information you have
defined for it.
An example Crosstabs are easiest to understand through an example. Consider the
Printer table in the PB Demo DB. It records quarterly unit sales of printers
made by sales representatives in one year. (This is the same data used to
illustrate graphs in Chapter 25, Working with Graphs.)
754 PowerBuilder
CHAPTER 26 Working with Crosstabs
The first-quarter sales of Cosmic printers displays in the first data cell. (As you
can see from the data in the Printer table shown before the crosstab, in Q1
Simpson sold 33 units, Jones sold 5 units, and Perez sold 26 units—totaling 64
units.) PowerBuilder calculates each of the other data cells the same way.
To create this crosstab, you only have to tell PowerBuilder which database
columns contain the raw data for the crosstab, and PowerBuilder does all the
data summarization automatically.
What crosstabs do Crosstabs perform two-dimensional analysis:
• The first dimension is displayed as columns across the crosstab.
In the preceding crosstab, the first dimension is the quarter, whose values
are in the Quarter column in the database table.
• The second dimension is displayed as rows down the crosstab.
In the preceding crosstab, the second dimension is the type of printer,
whose values are in the Product column in the database table.
Each cell in a crosstab is the intersection of a column (the first dimension) and
a row (the second dimension). The numbers that appear in the cells are
calculations based on both dimensions. In the preceding crosstab, it is the sum
of unit sales for the quarter in the corresponding column and printer in the
corresponding row.
Crosstabs also include summary statistics. The preceding crosstab totals the
sales for each quarter in the last row and the total sales for each printer in the
last column.
How crosstabs are Crosstabs in PowerBuilder are implemented as grid DataWindow objects.
implemented in Because crosstabs are grid DataWindow objects, users can resize and reorder
PowerBuilder
columns at runtime (if you let them).
• Dynamic
• Static
Dynamic crosstabs With dynamic crosstabs, PowerBuilder builds all the columns and rows in the
crosstab dynamically when you run the crosstab. The number of columns and
rows in the crosstab match the data that exists at runtime.
Using the preceding crosstab as an example, if a new printer was added to the
database after the crosstab was saved, there would be an additional row in the
crosstab when it is run. Similarly, if one of the quarter’s results was deleted
from the database after the crosstab was saved, there would be one less column
in the crosstab when it is run.
By default, crosstabs you build are dynamic.
Static crosstabs Static crosstabs are quite different from dynamic crosstabs. With static
crosstabs, PowerBuilder establishes the columns in the crosstab based on the
data in the database when you define the crosstab. (It does this by retrieving
data from the database when you initially define the crosstab.) No matter what
values are in the database when you later run the crosstab, the crosstab always
has the same columns as when you defined it.
Using the preceding crosstab as an example, if there were four quarters in the
database when you defined and saved the crosstab, there would always be four
columns (Q1, Q2, Q3, and Q4) in the crosstab at runtime, even if the number
of columns changed in the database.
Advantages of Dynamic crosstabs are used more often than static crosstabs, for the following
dynamic crosstabs reasons:
• You can define dynamic crosstabs very quickly because no database
access is required at definition time.
• Dynamic crosstabs always use the current data to build the columns and
rows in the crosstab. Static crosstabs show a snapshot of columns as they
were when the crosstab was defined.
• Dynamic crosstabs are easy to modify: all properties for the dynamically
built columns are replicated at runtime automatically. With static
crosstabs, you must work with one column at a time.
756 PowerBuilder
CHAPTER 26 Working with Crosstabs
Creating crosstabs
To create a crosstab:
1 Select File>New from the menu bar.
The New dialog box displays.
2 Select the DataWindow tab.
3 Select the Crosstab presentation style, then click OK.
4 On the Choose Data Source for Crosstab DataWindow page, specify the
data you want retrieved into the DataWindow object.
For more information, see Chapter 17, Defining DataWindow Objects.
5 In the Define Crosstab Rows, Columns, Values page, enter the definitions
for the columns, rows, and cell values in the crosstab.
See Associating data with a crosstab on page 757.
6 Click Next.
7 Choose Color and Border settings and click Next.
8 Review your specifications and click Finish.
PowerBuilder creates the crosstab.
9 (Optional) Specify other properties of the crosstab.
See Enhancing crosstabs on page 764.
10 Save the DataWindow object in a library.
2 Specify the database columns that will populate the columns, rows, and
values in the crosstab, as described below.
3 To build a dynamic crosstab, make sure the Rebuild columns at runtime
check box is selected.
For information about static crosstabs, see Creating static crosstabs on
page 773.
4 Click Next.
758 PowerBuilder
CHAPTER 26 Working with Crosstabs
Dynamic crosstab The process is illustrated using the following dynamic crosstab. The columns
example in the database are Rep, Quarter, Product, and Units. The crosstab shows the
number of printers sold by Quarter:
Specifying the You use the Columns box to specify one or more of the retrieved columns to
columns provide the columns in the crosstab. When users run the crosstab, there is one
column in the crosstab for each unique value of the database column(s) you
specify here.
Specifying the values Each cell in a crosstab holds a value. You specify that value in the Values box.
Typically you specify an aggregate function, such as Sum or Avg, to summarize
the data. At runtime, each cell has a calculated value based on the function you
provide here and the column and row values for the particular cell.
760 PowerBuilder
CHAPTER 26 Working with Crosstabs
Notice that in the Design view, PowerBuilder shows the quarter entries using
the symbolic notation @quarter (with dynamic crosstabs, the actual data
values are not known at definition time). @quarter is resolved into the actual
data values (in this case, Q1, Q2, Q3, and Q4) when the crosstab runs.
The crosstab is generated with summary statistics: the rows and columns are
totaled for you.
At this point, the crosstab looks like this in the Preview view with data
retrieved:
762 PowerBuilder
CHAPTER 26 Working with Crosstabs
For each quarter, the crosstab shows sales of each printer by each sales
representative.
Previewing crosstabs
When you have defined the crosstab, you can see it with data in the Preview
view.
Enhancing crosstabs
When you have provided the data definitions, the crosstab is functional, but
you can enhance it before using it. Because a crosstab is a grid DataWindow
object, you can enhance a crosstab using the same techniques you use in other
DataWindow objects. For example, you can:
• Sort or filter rows
• Change the column headers
• Specify fonts, colors, mouse pointers, and borders
• Specify column display formats
For more on these and the other standard enhancements you can make to
DataWindow objects, see Chapter 18, Enhancing DataWindow Objects.
The rest of this section covers topics either unique to crosstabs or especially
important when working with crosstabs:
• Specifying basic properties next
• Modifying the data associated with the crosstab on page 765
• Changing the names used for the columns and rows on page 766
• Defining summary statistics on page 767
764 PowerBuilder
CHAPTER 26 Working with Crosstabs
766 PowerBuilder
CHAPTER 26 Working with Crosstabs
For example, this is a crosstab that has been enhanced to show averages and
maximum values for each column. This is the Design view:
768 PowerBuilder
CHAPTER 26 Working with Crosstabs
These functions are listed in the Functions box when you define a computed
field in a crosstab:
Each of these functions returns the corresponding statistic about a row in the
crosstab (average, count, maximum value, minimum value, or sum). You place
computed fields using these functions in the detail band in the Design view.
Use the functions with the Dec suffix when you want to return a decimal
datatype.
By default, PowerBuilder places CrosstabSum and CrosstabSumDec in the
detail band, which returns the total for the corresponding row.
How to specify the Each of these functions takes one numeric argument, which refers to the
functions expression defined for Values in the Crosstab Definition dialog box. The first
expression for Values is numbered 1, the second is numbered 2, and so on.
Generally, crosstabs have only one expression for Values, so the argument for
the crosstab functions is 1. So, for example, if you defined sum(units for
crosstab) as your Values expression, PowerBuilder places
CrosstabSum(1) in the detail band.
If you want to cross-tabulate both total unit sales and a projection of future
sales, assuming a 20 percent increase in sales (that is, sales that are 1.2 times
the actual sales), you define two expressions for Values:
sum(units for crosstab)
sum(units * 1.2 for crosstab)
For more information For complete information about defining computed fields, see Chapter 18,
Enhancing DataWindow Objects.
For more about the crosstab functions, see the DataWindow Reference.
770 PowerBuilder
CHAPTER 26 Working with Crosstabs
The first step is to determine the expression that, given a salary, returns the next
smaller salary that is a multiple of $10,000. For example, given a salary of
$34,000, the expression would return $30,000, and given a salary of $47,000,
the expression would return $40,000. You can use the Int function to
accomplish this, as follows:
int(salary/10000) * 10000
That expression divides the salary by 10,000 and takes the integer portion, then
multiplies the result by 10,000. So for $34,000, the expression returns $30,000,
as follows:
34000/10000 = 3.4
int(3.4) = 3
3 * 10000 = 30000
With this information you can build the crosstab. The following uses the
Employee table in the PB Demo DB:
You can see, for example, that 2 people in department 400 and 5 in department
500 earn between $20,000 and $30,000.
Displaying blank In the preceding crosstab, several of the cells in the grid are blank. There are
values as zero no employees in some salary ranges, so the value of those cells is null. To make
the crosstab easier to read, you can add a display format to fields that can have
null values so that they display a zero.
772 PowerBuilder
CHAPTER 26 Working with Crosstabs
For example, in the following screenshot, the four values for Quarter (Q1, Q2,
Q3, and Q4) are displayed in the Design view:
At runtime, no matter what values are in the database for the column, the
crosstab shows only the values that were specified when the crosstab was
defined. In the printer example, the crosstab always has the four columns it had
when it was first defined.
Making changes You can modify the properties of any of the columns in a static crosstab. You
can modify the properties of each column individually, since each column is
displayed in the workspace as part of the crosstab’s definition. For example, in
the printer crosstab you can directly modify the way values are presented in
each individual quarter, since each quarter is represented in the Design view.
(The values are shown as units, units_1, units_2, and units_3.)
774 PowerBuilder
CHAPTER 26 Working with Crosstabs
Example In the following crosstab, an expression has been specified for Units:
776 PowerBuilder
C H A P T E R 2 7 Working with TreeViews
About this chapter This chapter describes how to build and use DataWindow objects in
PowerBuilder using the TreeView presentation style.
Contents
Topic Page
TreeView presentation style 777
Creating a new TreeView DataWindow 779
Adding and deleting TreeView levels 784
Selecting a tree node and navigating the tree 785
Sorting rows in a TreeView DataWindow 786
TreeView DataWindow Design view 787
Setting properties for the TreeView DataWindow 788
TreeView DataWindow examples 792
Similarities to the Creating and using a TreeView DataWindow is similar to creating and using a
Group presentation Group DataWindow. However, with the TreeView DataWindow, you can click
style
the state icon to expand and collapse nodes.
The state icon in a TreeView DataWindow is a plus sign (+) when the node is
collapsed and a minus sign (-) when the node is expanded. When a node is
expanded, connecting lines display by default to show more detail and indicate
how the parent data connects with the child data. When a node is collapsed,
only the parent data displays; the detail data does not.
778 PowerBuilder
CHAPTER 27 Working with TreeViews
3 Choose the TreeView presentation style for the DataWindow and click
OK.
780 PowerBuilder
CHAPTER 27 Working with TreeViews
If you want to use an expression, you can define it when you have
completed the wizard. See Using an expression for a column name on
page 783.
The sample DataWindow shown in Example on page 778 uses the
department and employee tables in the PB Demo DB database.
6 Specify the column or columns that will be at the top level (level 1) of the
TreeView DataWindow.
The sample DataWindow uses the department name as the top level. If you
want to display both the department ID and department name, you specify
that both columns are at the top level.
7 If you want the TreeView DataWindow to display grid lines, select the
Grid Style check box.
When you select the Grid Style check box, the TreeView DataWindow
displays grid lines for rows and columns. You can drag the grid lines to
resize rows and columns.
8 Click Next.
9 Modify the default color and border settings if needed, and then click
Next.
10 Review the TreeView DataWindow characteristics.
11 Click Finish.
The DataWindow painter Design view displays. For information about the
Design view, see TreeView DataWindow Design view on page 787. For
information about adding additional levels, see Adding and deleting TreeView
levels on page 784.
What PowerBuilder As a result of your specifications, PowerBuilder generates a TreeView
does DataWindow object and creates:
• A TreeView header band with controls that include the heading text of the
detail band columns
• The first TreeView level band with the TreeView level columns you chose
in the wizard
• The detail (leaf node) band that includes all the column controls except for
first-level columns you selected in the wizard
• A level 1 trailer band.
• A summary band, and a footer band.
Here is the sample TreeView DataWindow object in the Design view:
If you selected the Grid Style check box, vertical and horizontal grid lines
display:
782 PowerBuilder
CHAPTER 27 Working with TreeViews
Using an expression If you want to use an expression for one or more column names in a TreeView,
for a column name you can enter it as the TreeView definition on the General page in the
Properties view after you finish using the TreeView wizard.
4 Click OK.
The new TreeView level and a Trailer band for that level are created in the
TreeView Design view. For information on how to set properties for a
TreeView level, see Setting TreeView level properties on page 790.
784 PowerBuilder
CHAPTER 27 Working with TreeViews
Other actions you can To reorder the columns, drag them up or down in the list. To delete a column
take from the sort columns list, drag the column outside the dialog box. To specify
an expression to sort on, double-click a column name in the Columns box and
modify the expression in the Modify Expression dialog box.
786 PowerBuilder
CHAPTER 27 Working with TreeViews
The Design view has a header band, a TreeView level band for each added
level, a detail band, a Trailer band for each level, a summary band, and a footer
band.
By default, the controls in the header band are the heading text of the detail
band columns, and the controls in the detail (leaf node) band are all the column
controls except for the first-level columns (in the 1:Treeview level band) that
you selected when you used the TreeView wizard. Columns that you specify as
additional levels remain in the detail band.
The minimum height of each TreeView level band is the height of the tree node
icon.
Icons in the Design There are three icons in the Design view that represent the locations of nodes,
view icons, and connecting lines in the tree to help you design the DataWindow.
Columns must always display to the right of the state and tree node icons:
• A square icon with a plus sign (+) in each TreeView level band represents
the position of the state icon, the icon that indicates whether a node is
expanded or collapsed. On the XP platform, the plus (+) and minus (-)
icons have the Windows XP style.
• A shaded square icon in the detail band and in each TreeView level band
represents the position of the image you specify as a tree node icon.
• When there is no tree node icon specified, a shaded square icon in the
detail band and in each TreeView level band represents where the
connecting line ends.
The position of all the icons changes when you change the indent value.
For more information about specifying icons and the indent value, see Setting
properties for the TreeView DataWindow.
788 PowerBuilder
CHAPTER 27 Working with TreeViews
The properties that are specific to a TreeView DataWindow are the TreeView
properties and the Grid properties. The grid-related properties display only if
you select the Grid Style check box when you define the TreeView
DataWindow.
Property Description
Display On – Grid lines always display.
Off – Grid lines never display (columns cannot be
resized at runtime).
Display Only – Grid lines display only when the
DataWindow object displays online.
Print Only – Grid lines display only when the
contents of the DataWindow object are printed.
Column Moving Columns can be moved at runtime.
Mouse Selection Data can be selected at runtime and, for example,
copied to the clipboard.
Row Resize Rows can be resized at runtime.
Property Description
Indent Value The indent value of the child node from its parent in
the units specified for the DataWindow. The indent
value defines the position of the state icon. The X
position of the state icon is the X position of its parent
plus the indent value.
Expand To Level By Default Expand to TreeView level 1, 2, or 3.
State Icon Align Mode Align the state icon in the middle (0), at the top (1),
or at the bottom (2).
Show Lines Whether lines display that connect parent nodes and
child nodes. If you want to display lines that connect
the rows in the detail band to their parent, select
Connect Leaf Nodes.
Connect Leaf Nodes Whether lines display that connect the leaf nodes in
the detail band rows.
Use Tree Node Icon Whether an icon for the tree node displays. This
applies to icons in the level and detail bands. For how
to specify icon images, see Setting TreeView level
properties and Setting detail band properties next.
Select Node By Mouse Whether a Tree node is selected by clicking the Tree
node with the mouse.
790 PowerBuilder
CHAPTER 27 Working with TreeViews
2 Use the DataWindow TreeView Level properties view that displays to edit
the properties for the level you selected.
The properties that are specific to a TreeView level band are at the bottom of
the Properties view:
Property Description
Tree Node Icon File The file name of the tree node icon in a TreeView
level band when it is in the expanded state.
Collapsed Tree Node Icon The file name of the tree node icon in a TreeView
File level band when it is in the collapsed state.
You set the tree node icon file name separately for each TreeView level band.
You can use a quoted expression for the tree node icon file.
If you want to hide tree nodes in the detail band, set the Height property to 0.
The only property that is specific to the TreeView DataWindow is located at
the bottom of the Properties view:
Property Description
Tree Node Icon File The file name of the tree node icon in the detail
band. You can use a quoted expression.
For more information For reference information about TreeView DataWindow properties, methods
and events, see the DataWindow Reference or the online Help.
792 PowerBuilder
CHAPTER 27 Working with TreeViews
You can click on any TreeView level in the Data Explorer. If you click a
company name in the TreeView DataWindow on the left (for example, Able
Inc., under Catherine Pickett), order information displays on the right.
If you click an order ID in the TreeView DataWindow on the left (for example,
order ID 2400, under Bilhome Industries, under Alison Clark), the customer
order information displays on the right.
794 PowerBuilder
CHAPTER 27 Working with TreeViews
Data Explorer Here is the TreeView DataWindow used in the Data Explorer.
TreeView
DataWindow
Data Explorer code The code in the Clicked event uses GetBandAtPointer to determine which
DataWindow to display. Clicking on some editable items in the detail
DataWindow opens a window in which you can manipulate the data.
The PopMenu menu object has two menu items that call the CollapseAll and
ExpandAll methods to collapse or expand all the nodes in the TreeView.
To use the Data Linker, you first expand an employee name and a company’s
data in the TreeView DataWindow.
Expanding the TreeView displays the company names, the orders for the
company you select, and in the detail band, the icon and name for each item in
the order.
You can click on each of the TreeView levels in order, and then click in the
detail band to display the details in the four DataWindows on the right.
796 PowerBuilder
CHAPTER 27 Working with TreeViews
For example, if you click first on Catherine Pickett, then on Avon Inc., then on
2073, and last on Baseball Cap, the data in each of the related DataWindows
displays on the right. You can also update the data in each of the DataWindows.
Data Linker TreeView Here is the TreeView DataWindow used in the Data Linker sample.
DataWindow
Data Linker code The code in the Clicked event uses GetBandAtPointer to determine which
DataWindow to display.
798 PowerBuilder
C H A P T E R 2 8 Exporting and Importing XML
Data
About this chapter The row data in a DataWindow can be exported and imported in the
Extensible Markup Language (XML). This chapter describes how to
create and use templates that control the export and import of data in XML
format.
Contents
Topic Page
About XML 799
XML support in the DataWindow painter 803
The Export/Import Template view for XML 804
Editing XML templates 811
Exporting to XML 820
Importing XML 830
About XML
Like Hypertext Markup Language (HTML), Extensible Markup
Language (XML) is a subset of Standardized General Markup Language
(SGML) and has been designed specifically for use on the Web. XML is
defined in the W3C Recommendation published by the World Wide Web
Consortium. The latest version of this document is available at
http://www.w3.org/TR/REC-xml.
800 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
XML syntax
There are a few more restrictions on XML than on HTML; they make parsing
of XML simpler.
Tags cannot be Unlike HTML, XML does not allow you to omit tags. This guarantees that
omitted parsers know where elements end.
The following example is acceptable HTML, but not XML:
<table>
<tr>
<td>Dog</td>
<td>Cat
<td>Mouse
</table>
To change this into well-formed XML, you need to add all the missing end
tags:
<table>
<tr>
<td>Dog</td>
<td>Cat</td>
<td>Mouse</td>
</tr>
</table>
Representing empty Empty elements cannot be represented in XML in the same way they are in
elements HTML. An empty element is one that is not used to mark up data, so in HTML,
there is no end tag. There are two ways to handle empty elements:
• Place a dummy tag immediately after the start tag. For example:
<img href="picture.jpg"></img>
• Use a slash character at the end of the initial tag:
<img href="picture.jpg"/>
This tells a parser that the element consists only of one tag.
XML is case sensitive XML is case sensitive, which allows it to be used with non-Latin alphabets.
You must ensure that letter case matches in start and end tags: <MyTag> and
</Mytag> belong to two different elements.
XML parsing
There are two major types of application programming interfaces (APIs) that
can be used to parse XML:
• Tree-based APIs map the XML document to a tree structure. The major
tree-based API is the Document Object Model (DOM) maintained by
W3C. A DOM parser is particularly useful if you are working with a
deeply-nested document that must be traversed multiple times.
For more information about the DOM parser, see the W3C Document
Object Model page at http://www.w3c.org/DOM.
802 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
• Event-based APIs use callbacks to report events, such as the start and end
of elements, to the calling application, and the application handles those
events. These APIs provide faster, lower-level access to the XML and are
most efficient when extracting data from an XML document in a single
traversal.
For more information about the best-known event-driven parser, SAX
(Simple API for XML), see the SAX page at http://sax.sourceforge.net/.
Xerces parser PowerBuilder includes software developed by the Apache Software
Foundation (http://www.apache.org/). The XML services for DataWindow
objects are built on the Apache Xerces-C++ parser, which conforms to both
DOM and SAX specifications and is portable across Windows and UNIX
platforms. For more information about SAX, see the Xerces C++ Parser page
at http://xerces.apache.org/xerces-c/index.html.
XML services
In addition to the support for XML in the DataWindow painter, PowerBuilder
also provides the PowerBuilder Document Object Model (PBDOM). For more
information, see the chapter on XML services in Application Techniques.
Export templates An XML export template lets you customize the XML that is generated.
You can specify optional XML and document type declarations that precede
the root element in the exported XML, as well as the logical structure and
nesting level of iterative DataWindow row data inside the root element. The
children of the root element can contain elements, character references, and
processing instructions as well as the row data, using explicit markup. For
more information, see Header and Detail sections on page 808.
If the exported XML is used by different applications or processes, you can
define a separate export template for each use.
Import templates You need to create an import template if you want to import data that does not
match the DataWindow column definition or is associated with a schema, or if
you want to import attribute values.
Only the mapping of column names to element and attribute names is used for
import. All other information in the template is ignored.
Validating XML XML export and import do not validate the data after export or before import.
You can use the XMLParseFile and XMLParseString functions to validate an
XML file or string against a DTD or XML schema before proceeding with
additional processing.
If no DTD or schema is included or referenced, XMLParseFile and
XMLParseString check whether the content is well-formed XML.
804 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
Creating, opening, From the pop-up menu for the Export/Import Template view (with nothing
and saving templates selected), you can create new templates with or without default contents, open
an existing template, save the current template, or delete the current template.
You can only open and edit templates that are associated with the current
DataWindow object.
Representing tree Each item in the template displays as a single tree view item with an image and
view items font color that denotes its type. The end tags of elements and the markup
delimiters used in an XML document do not display.
Table 28-1 shows the icons used in the Export/Import Template view.
Creating templates
To create a template, select the New menu item or the New Default menu item
from the pop-up menu in the Export/Import Template view.
Creating new base The New menu item creates a template that is empty except for the XML
templates declaration, the root element, and the first element of the row data section,
referred to as the Detail Start element. The name of the root element is the same
as the name of the DataWindow object, and the default name for the Detail
Start element is the name of the root element with _row appended.
For example, if the DataWindow object is named d_name, the default template
has this structure:
<?xml version="1.0"?>
<d_name>
<d_name_row>
</d_name_row>
</d_name>
806 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
Creating new default The New Default menu item creates a template with the same contents as the
templates New menu item, as well as a flat structure of child elements of the Detail Start
element. A child element is created for each DataWindow column name, in the
order in which the columns appear in the SELECT statement, with the
exception of blob and computed columns. The default tag for the element is the
column’s name.
If the names of the column and the control are the same, the content of the child
element displays with a control reference icon. If there is no control name that
matches the column name, the content of the child element displays using the
DataWindow expression icon. For example, consider a DataWindow object in
which the dept_id column is used as a retrieval argument and does not display:
Saving templates
To save a new template, select Save from the pop-up menu in the
Export/Import Template view, and give the template a name and optionally a
comment that identifies its use.
808 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
The Detail section contains the row data, and is generated iteratively for each
row in the DataWindow object.
The Detail Start A line across the Export/Import Template view separates the Header section
element from the Detail section. The first element after this line, d_dept_list_row in the
previous screenshot, is called the Detail Start element.
There can be only one Detail Start element, and it must be inside the
document’s root element. By default, the first child of the root element is the
Detail Start element. It usually wraps a whole row, separating columns across
rows. When the DataWindow is exported to XML, this element and all children
and/or siblings after it are generated iteratively for each row. Any elements in
the root element above the separator line are generated only once, unless the
DataWindow is a group DataWindow and the Iterate Group Headers check box
has been selected.
The Detail Start element can be a nested (or multiply-nested) child of an
element from the Header section, permitting a nested detail. This might be
useful for DataStores being packaged for submission to external processes,
such as B2B, that require company and/or document information, date, or other
master data preceding the detail.
Moving the separator You can change the location of the separator line by selecting the element that
you want as the Detail Start element and selecting Starts Detail from its pop-up
menu. The separator line is redrawn above the new Detail Start element. When
you export the data, the Detail Start element and the children and siblings after
it are generated iteratively for each row.
If no Detail Start element is specified (that is, if the Starts Detail option has
been deselected), the template has only a Header section. When you export the
data, only one iteration of row data is generated.
Header section
The Header section can contain the items listed in Table 28-2. Only the root
element is required:
Detail section
The Detail section, which holds the row data, can contain the items listed in
Table 28-3.
810 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
Every item in the Export/Import Template view has a pop-up menu from which
you can perform actions appropriate to that item, such as editing or deleting the
item, adding or editing attributes, adding child elements or other items, and
inserting elements, processing instructions, CDATA sections, and so forth,
before the current item.
If an element has no attributes, you can edit its tag in the Export/Import
Template view by selecting it and left-clicking the tag or pressing F2. Literal
text nodes can be edited in the same way. You can delete items (and their
children) by pressing the Delete key.
The examples in this section show the delimiters used in the XML document.
When you edit the template in dialog boxes opened from the Export/Import
Template view for XML, you do not need to type these delimiters in text boxes.
The rest of this section describes some of the items in the template. For more
information, see the XML specification at http://www.w3.org/TR/REC-xml.
XML declaration
The XML declaration specifies the version of XML being used. You may need
to change this value for a future version of XML. It can also contain an
encoding declaration and a standalone document declaration. From the pop-up
menu, you can edit the declaration, and, if the document is well-formed, delete
it. If you have deleted the XML declaration, you can insert one from the Insert
Before item on the pop-up menu for the next item in the template.
Encoding declaration The encoding declaration specifies the character-set encoding used in the
document, such as UTF-16 or ISO-10646-UCS-4.
812 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
Public identifiers An external identifier can include a public identifier that an XML processor
can use to generate an alternative URI. If an alternative URI cannot be
generated, the URI provided in the system identifier is used. External
identifiers without a public identifier are preceded by the keyword SYSTEM.
External identifiers with a public identifier are preceded by the keyword
PUBLIC.
Exporting metadata
If you specify a system or public identifier and/or an internal subset in the
Document Type Declaration dialog box, a DTD cannot be generated when the
data is exported to XML. A MetaDataType of XMLDTD! is ignored. For more
information about the properties that control the export of metadata, see
Exporting metadata on page 826.
Root element
You can change the name of the root element, add attributes and children, and
insert comments, instructions, and, if they do not already exist, XML and/or
document type declarations before it.
814 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
Changing the name of the root element changes the name of its start and end
tags. You can change the name using the Edit menu item, or in the Element
Attributes dialog box. Changing the name of the document type declaration, if
it exists, also changes the name of the root element, and vice versa. The root
element name is always the same as the document type declaration name.
You can add the following kinds of children to the root element:
• Elements
• Text
• Control references
• DataWindow expressions (including column references)
• CDATA sections
• Comments
• Processing instructions
Controls
Adding a DataWindow control reference opens a dialog box containing a list
of the columns, computed fields, report controls, and text controls in the
document.
Control references can also be added to empty attribute values or element
contents using drag-and-drop from the Control List view. Column references
can also be added using drag-and-drop from the Column Specifications view.
DataWindow expressions
Adding a DataWindow expression opens the Modify Expression dialog box.
This enables you to create references to columns from the data source of the
DataWindow object. One use of this feature is to return a fragment of XML to
embed, providing another level of dynamic XML generation.
Using Date and If you use a control reference or a DataWindow expression that does not
DateTime with strings include a string to represent Date and DateTime columns in a template, the
XML output conforms to ISO 8601 date and time formats. For example,
consider a date that displays as 12/27/2016 in the DataWindow object, using
the display format mm/dd/yyyy. If the export template does not use an
expression that includes a string, the date is exported to XML as 2016-12-27.
However, if the export template uses an expression that combines a column
with a Date or DateTime datatype with a string, the entire expression is
exported as a string and the regional settings in the Windows registry are used
to format the date and time.
Using the previous example, if the short date format in the registry is
MM/dd/yy, and the DataWindow expression is: "Start Date is " +
start_date, the XML output is Start Date is 12/27/16.
Attributes
Controls or expressions can also be referenced for element attribute values.
Select Edit/Add Attribute from the pop-up menu for elements to edit an
existing attribute or add a new one.
816 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
For each attribute specified, you can select a control reference from the
drop-down list or enter a literal text value. A literal text value takes precedence
over a control reference. You can also use the expression button to the right of
the Text box to enter an expression.
Composite reports For composite reports that use the Composite presentation style, the default
template has elements that reference each of its nested reports.
818 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
CDATA sections
You can export the name of a column in a CDATA section using the syntax
<![CDATA[columnname]]>. You can export the value of a column using the
syntax <![CDATA[~t columnname]]>. The ~t is used to introduce a
DataWindow expression, in the same way that it is used in the Modify method.
You can also use an expression such as ~t columnname*columnname to export
a computed value to the XML.
You can import a value into a column using the syntax <![CDATA[
columnname]]>. Note that this syntax in a template has different results for
import and export: it imports the column value but exports the column name.
You cannot import an XML file that has a ~t expression in a CDATA section.
Everything else inside a CDATA section is ignored by the parser. If text
contains characters such as less than or greater than signs (< or >) or
ampersands (&) that are significant to the parser, it should be defined as a
CDATA section. A CDATA section starts with <![CDATA[ and ends with ]]>.
CDATA sections cannot be nested, and there can be no white space characters
inside the ]]> delimiter—for example, you cannot put a space between the two
square brackets.
Example <![CDATA[
do not parse me
]]>
This syntax in an export template exports the value of the column emp_salary:
<![CDATA[~t emp_salary]]>
This syntax in an import template imports the value of the column emp_salary:
<![CDATA[emp_salary]]>
Comments
Comments can appear anywhere in a document outside other markup. They
can also appear within the document type declaration in specific locations
defined by the XML specification.
Comments begin with <!-- and end with -->. You cannot use the string --
(a double hyphen) in a comment, and parameter entity references are not
recognized in comments.
Example <!-- this is a comment -->
Processing instructions
Processing instructions (PIs) enable you to provide information to the
application that uses the processed XML. Processing instructions are enclosed
in <? and ?> delimiters and must have a name, called the target, followed by
optional data that is processed by the application that uses the XML. Each
application that uses the XML must process the targets that it recognizes and
ignore any other targets.
The XML declaration at the beginning of an XML document is an example of
a processing instruction. You cannot use the string xml as the name of any other
processing instruction target.
Example In this example, usething is the name of the target, and thing=this.thing
is the data to be processed by the receiving application:
<?usething thing=this.thing?>
Exporting to XML
You can export the data in a DataWindow or DataStore object to XML using
any of the techniques used for exporting to other formats such as PSR or
HTML:
• Using the SaveAs method:
ds1.SaveAs("C:\TEMP\Temp.xml", Xml!, true)
• Using PowerScript dot notation or the Describe method:
ls_xmlstring =
dw1.Object.DataWindow.Data.XMLls_xmlstring =
dw1.Describe(DataWindow.Data.XML)
• Using the Save Rows As menu item in the DataWindow painter.
With the Preview view open, select File>Save Rows As, select XML from
the Files of Type drop-down list, provide a file name, and click Save. You
can use this in the development environment to preview the XML that will
be generated at runtime.
When you export data, PowerBuilder uses an export template to specify the
content of the generated XML.
820 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
The template you select from the list is used to conform the XMLgenerated by
any of the methods for saving as XML to the specifications defined in the
named template. Selecting a template from the list box sets the DataWindow
object’s Export.XML.UseTemplate property. You can also modify the value of
the UseTemplate property dynamically in a script. For example, an XML
publishing engine would change templates dynamically to create different
presentations of the same data.
When you open a DataWindow, the Export/Import Template view displays the
template specified in the DataWindow’s Use Template property. (If the view is
not visible in the current layout, select View>Export/Import Template>XML
from the menu bar.) If the property has not been set, the first saved template
displays or, if there are no saved templates, the default structured template
displays as a basis for editing.
Template used when When the DataWindow is saved as XML, PowerBuilder uses the template
saving specified in the Use Template property. If the property has not been set,
PowerBuilder uses the default template.
When you are working on a template, you might want to see the result of your
changes. The template specified in the Use Template property might not be the
template currently displayed in the Export/Import Template view, so you
should check the value of the Use Template property to be sure you get the
results you expect.
822 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
For example, consider a group DataWindow object that includes the columns
sales_order_id and sales_order_order_date. The following screenshot shows
the template for this DataWindow object:
The root element in the Header section of the template, Orders, has a child
element, Order. Order has an id attribute whose value is a control reference to
the column sales_order_id. Order also has a child element, OrderDate, that
contains a column reference to the sales_order_order_date column. These
elements make up the header section that will be iterated for each group.
The Detail Start element, Item, has an id attribute whose value is a control
reference to the column sales_order_items_line_id. It also has three child
elements that contain column references to the line items for product ID,
quantity, and ship date.
When the DataWindow is exported with the Export.XML.HeadGroups
property on, the order ID and date iterate for each group. The following XML
output shows the first three iterations of the group header:
<?xml version="1.0" encoding="UTF-16LE"
standalone="no"?>
<Orders>
<Order id="2001">
<OrderDate>2002-03-14</OrderDate>
<Item id="1">
<Product>300</Product>
<Quantity>12</Quantity>
<ShipDate>2005-09-15</ShipDate>
</Item>
<Item id="2">
<Product>301</Product>
<Quantity>12</Quantity>
<ShipDate>2005-09-14</ShipDate>
</Item>
<Item id="3">
<Product>302</Product>
<Quantity>12</Quantity>
<ShipDate>2005-09-14</ShipDate>
</Item>
</Order>
<Order id="2002">
<OrderDate>2002-03-18</OrderDate>
<Item id="2">
<Product>401</Product>
<Qty>24</Qty>
<ShipDate>2002-09-18</ShipDate>
</Item>
<Item id="1">
<Product>400</Product>
<Qty>24</Qty>
<ShipDate>2002-09-18</ShipDate>
</Item>
</Order>
<Order id="2003">
<OrderDate>2002-03-21</OrderDate>
<Item id="3">
<Product>400</Product>
<Qty>12</Qty>
<ShipDate>2002-09-23</ShipDate>
</Item>
...
For DataWindow objects with more than one group, when you generate a new
default template, each group after the first is identified with a special icon and
a check on the pop-up menu next to the Starts Group Header item.
When the Iterate Header for Groups check box is selected, each XML fragment
in the header section between a Group Header element and the next Group
Header element or Detail Start element is iterated.
824 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
The following XML output shows the first iteration of the customer group
header and the first and second iterations of the order group header:
<?xml version="1.0" encoding="UTF-16LE" standalone="no"?>
<d_customer>
<customer id="101" fname="Michaels" lname="Devlin">
<order id="2001" date="1996-03-14">
<order_item>
<sales_order_items_line_id>1</sales_order_items_line_id>
<sales_order_items_prod_id>300</sales_order_items_prod_id>
<sales_order_items_quantity>12</sales_order_items_quantity>
</order_item>
<order_item>
<sales_order_items_line_id>2</sales_order_items_line_id>
<sales_order_items_prod_id>301</sales_order_items_prod_id>
<sales_order_items_quantity>12</sales_order_items_quantity>
</order_item>
<order_item>
<sales_order_items_line_id>3</sales_order_items_line_id>
<sales_order_items_prod_id>302</sales_order_items_prod_id>
<sales_order_items_quantity>12</sales_order_items_quantity>
</order_item>
</order>
<order id="2005" date="1996-03-24">
<order_item>
<sales_order_items_line_id>1</sales_order_items_line_id>
<sales_order_items_prod_id>700</sales_order_items_prod_id>
<sales_order_items_quantity>12</sales_order_items_quantity>
</order_item>
</order>
Exporting metadata
You can specify that metadata in the form of a DTD or schema should be
exported when you save the DataWindow object. You can choose to save the
metadata with the XML or in a separate file.
If you export metadata as a schema, you can associate it with a namespace. See
Associating a namespace with an exported schema on page 828.
To specify how metadata should be saved, select a value from the Meta Data
Type drop-down list or set the Export.XML.MetaDataType property. The
possible values are:
• XMLNone!—No metadata is generated
• XMLSchema!—An XML schema is generated
• XMLDTD!—A DTD is generated
If the data item for a column is null or an empty string, an empty element is
created. If you select XMLSchema!, child elements with null data items are
created with the content "xsi:nil='true'".
The metadata is saved into the exported XML itself or into an associated file,
depending on the setting in the SaveMeta Data drop-down list or the
Export.XML.SaveMetaData property. The possible values are:
826 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
<dtdexternal>
<dtdexternal_row>
<id>1</id>
<last_name>Hildebrand</last_name>
<first_name>Jane</first_name>
<title>ma</title>
<street>1280 Washington St.</street>
<city>Emeryville</city>
<state>MI</state>
<zip>94608</zip>
<phone>5105551309</phone>
<fax>5105554209</fax>
</dtdexternal_row>
The DTD is in dtdexternal.dtd:
<?xml version="1.0" encoding="UTF-16LE"?><!ELEMENT
dtdexternal (dtdexternal_row*)>
<!ELEMENT dtdexternal_row (id, last_name, first_name,
title, street, city, state, zip, phone, fax)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT last_name (#PCDATA)>
<!ELEMENT first_name (#PCDATA)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT street (#PCDATA)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT state (#PCDATA)>
<!ELEMENT zip (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT fax (#PCDATA)>
Associating a If you export metadata in the form of a schema, you can associate a namespace
namespace with an with the schema. To do so, right-click the root element in the Export/Import
exported schema
template view and select Schema Options from the pop-up menu. In the dialog
box, specify the namespace prefix and URI.
When the Meta Data Type property is XMLSchema! and the Save Meta Data
property is MetaDataInternal!, so that the XML schema is generated inline, you
can specify a name for the root element. If the root element name is specified,
it appears in the generated XML.
828 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
In the following example, the root element name is Contacts, the namespace
prefix is po, and the URI is http://www.example.com/PO1.
The example shows the header and the first row of the generated XML:
<?xml version="1.0" encoding="UTF-16LE"
standalone="no"?>
<Contacts>
<xs:schema xmlns:po="http://www.example.com/PO1"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.com/PO1"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xs:element name="d_contact_list">
<xs:complexType>
<xs:sequence>
<xs:element ref="d_contact_list_row"
maxOccurs="unbounded" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="d_contact_list_row">
<xs:complexType>
<xs:sequence>
<xs:element ref="id"/>
<xs:element ref="last_name"/>
<xs:element ref="first_name"/>
<xs:element ref="city"/>
<xs:element ref="state"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="id" type="xs:int"/>
<xs:element name="last_name" type="xs:string"/>
<xs:element name="first_name" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="state" type="xs:string"/>
</xs:schema>
<po:d_contact_list xmlns:po=
"http://www.example.com/PO1" xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance">
<po:d_contact_list_row>
<po:id>1</po:id>
<po:last_name>Hildebrand</po:last_name>
<po:first_name>Jane</po:first_name>
<po:city>Emeryville</po:city>
<po:state>MI</po:state>
</po:d_contact_list_row>
By default, the generated XML is not associated with a namespace.
ls_template_count=dw_1.Describe
("DataWindow.Export.XML.TemplateCount")
Importing XML
You can select XML as a file type in the dialog box that displays when you
select Rows>Import in the DataWindow painter. (The Preview view must be
open to enable the Rows>Import menu item.)
You can also import data from an XML document or string using the ImportFile,
ImportString, or ImportClipboard methods. These methods have an optional first
parameter that enables you to specify the type of data to be imported.
830 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
Matching template An XML import template must map the XML element and attribute names in
structure to XML the XML document to DataWindow column names, and it must reflect the
nesting of elements and attributes in the XML.
The order of elements and attributes with column reference content in the
template does not have to match the order of columns within the DataWindow,
because import values are located by name match and nesting depth within the
XML. However, the order of elements and attributes in the template must
match the order in which elements and attributes occur in the XML. Each
element or attribute that has column reference content in the template must
occur in each row in the XML document or string. The required elements and
attributes in the XML can be empty.
If an element or attribute does not occur in the XML document, the
DataWindow import column remains empty.
The data for the DataWindow is held in the columns of the data table. Some
data columns, such as those used for computed fields, may not have an
associated control. To import data into a column that has no control reference,
add a child DataWindow expression that contains the column name.
Importing data with For XML import using a template, element and attribute contents in the header
group headers section are ignored. However, if the Starts Detail marker does not exist, all
element and attribute to column mappings within the template are used for
import. This has the following implications for DataWindow objects with
group headers:
• If data is imported to a Group DataWindow using a template that has a
Starts Detail marker, the group header data is not imported because import
starts importing from the Starts Detail location.
• If the Group DataWindow has one group and the import template has no
Starts Detail marker, all the data is imported successfully.
832 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
Restrictions DataWindow columns cannot be referenced twice for import. A second column
reference to a DataWindow column within an XML import template is ignored.
An XML element or attribute name whose content references a DataWindow
column for import must be unique within the level of nesting. It cannot occur
twice in the template at the same nesting level.
Setting the import The names of all templates for the current DataWindow object display in the
template Use Template drop-down list on the Data Import page in the Properties view.
The template you select in the list box is used to conform the XML imported
to the specifications defined in the named template. Selecting a template from
the list sets the DataWindow object’s Import.XML.UseTemplate property. You
can also modify the value of the Import.XML.UseTemplate property
dynamically in a script.
The Data Import page also contains a property that enables you to create a trace
log of the import. See Tracing import on page 839.
Example
This example uses a DataWindow object that includes the columns emp_id,
emp_fname, emp_lname, and dept_id. The template used in this example
includes only these columns. Any other columns in the DataWindow remain
empty when you import using this template.
To illustrate how template import works, create a new template that has one
element in the header section, called before_detail_marker. This element
contains a column reference to the emp_id column.
The Detail Start element, employee, has an attribute, dept_id, whose value is a
control reference to the column dept_id. It also has three children:
• The emp_id element contains a column reference to the emp_id column.
• The emp_fname element contains static text.
• The name element has two children, emp_fname and emp_lname, that
contain column references to those columns.
The template exports and imports the dept_id DataWindow column using the
attribute of the employee element. It exports and imports the emp_id,
emp_fname, and emp_lname columns using the column references in the
elements. The following shows the beginning of the XML exported using this
template:
<?xml version="1.0" encoding="UTF-16LE"
standalone="no"?>
<employee_list>
<before_detail_marker>102</before_detail_marker>
<employee dept_id="100">
<emp_id>102</emp_id>
<emp_fname>static text content</emp_fname>
<name>
<emp_fname>Fran</emp_fname>
<emp_lname>Whitney</emp_lname>
</name>
</employee>
<employee dept_id="100">
<emp_id>105</emp_id>
<emp_fname>static text content</emp_fname>
834 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
<name>
<emp_fname>Matthew</emp_fname>
<emp_lname>Cobb</emp_lname>
</name>
</employee>
...
The exported XML can be reimported into the DataWindow columns dept_id,
emp_id, emp_fname, and emp_lname. Before importing, you must set the
import template on the Data Import page in the Properties view or in a script
using the DataWindow object’s Import.XML.UseTemplate property.
The following items are exported, but ignored on import:
• The before_detail_marker element is ignored because it is in the header
section.
• The first occurrence of the element tag name emp_fname is ignored
because it does not contain a mapping to a DataWindow column name.
If you change the nesting of the emp_fname and emp_lname elements inside
the name element, the import fails because the order of the elements and the
nesting in the XML and the template must match.
Empty elements Empty elements (elements that have no content between the start and end tags)
are imported as empty values into the DataWindow column. If the element text
contains only white space, carriage returns, and new line or tab characters, the
element is treated as an empty element.
Any attributes of empty elements are ignored.
Elements with If the element has no text content, but does contain comments, processing
non-text content instructions, or any other content, it is not regarded as an empty element and is
skipped for import.
Example 1 This example contains two rows, each with five elements that match the
column order, type, and validation requirements for the DataWindow object.
<?xml version="1.0"?>
<d_emp_birth_listing>
<d_emp_birth_row>
<element_1>105</element_1>
<element_2>Matthew</element_2>
<element_3>Cobb</element_3>
<element_4>6175553840</element_4>
<element_5>04/12/1960</element_5>
</d_emp_birth_row>
<d_emp_birth_row>
836 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
<element_1>148</element_1>
<element_2>Julie</element_2>
<element_3>Jordan</element_3>
<element_4>6175557835</element_4>
<element_5>11/12/1951</element_5>
</d_emp_birth_row>
</d_emp_birth_listing>
Example 2 In this example, the elements are not contained in rows, but they still match the
DataWindow object.
<?xml version="1.0"?>
<root_element>
<element_1>105</element_1>
<element_2>Matthew</element_2>
<element_3>Cobb</element_3>
<element_4>6175553840</element_4>
<element_5>04/12/1960</element_5>
<element_6>148</element_6>
<element_7>Julie</element_7>
<element_8>Jordan</element_8>
<element_9>6175557835</element_9>
<element_10>11/12/1951</element_10>
</root_element>
Example 3 The comments and processing instructions in this example are not imported.
The nesting of the <first> and <last> elements within the <Name> element is
ignored.
<?xml version="1.0"?>
<root_element>
<!-- some comment -->
<row_element><?process me="no"?>105<name Title="Mr">
<first>Matthew</first>
<last>Cobb</last>
</name>
<!-- another comment -->
<phone>6175553840</phone>
<birthdate>04/12/1960</birthdate>
</row_element>
<row_element>148<name Title="Ms">
<first>Julie</first>
<last>Jordan</last>
</name>
<phone>6175557835</phone>
<birthdate>11/12/1951</birthdate>
</row_element>
</root_element>
838 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
Tracing import
When you import data from XML with or without a template, you can create a
trace log to verify that the import process worked correctly. The trace log
shows whether a template was used and if so which template, and it shows
which elements and rows were imported.
To create a trace log, select the Trace XML Import check box on in the Data
Import page in the Properties view and specify the name and location of the log
file in the Trace File Name box. If you do not specify a name for the trace file,
PowerBuilder generates a trace file with the name pbxmtrc.log in the current
directory.
You can also use the Import.XML.Trace and Import.XML.TraceFile
DataWindow object properties.
If you use ImportClipboard or ImportStringan import method to import the data,
you must specify XML! as the importtype argument. For example:
ImportString(XML!, ls_xmlstring)
If you omit the importtype argument, the trace file is not created. You do not
need to specify the importtype argument if you use ImportFile.
Example: default The following trace log shows a default import of the department table in the
import PB Demo database:
/*--------------------------------------------------*/
/* 09/10/2005 18:26 */
/*--------------------------------------------------*/
CREATING SAX PARSER.
NO XML IMPORT TEMPLATE SET - STARTING XML DEFAULT
IMPORT.
DATAWINDOW ROWSIZE USED FOR IMPORT: 3
840 PowerBuilder
CHAPTER 28 Exporting and Importing XML Data
842 PowerBuilder
C H A P T E R 2 9 Working with Rich Text
About this chapter This chapter explains how to create DataWindow objects using the
RichText presentation style and how to use the RichTextEdit control.
Contents
Topic Page
About rich text 843
Using the RichText presentation style 844
Using the RichTextEdit control 855
Formatting keys and toolbars 857
The user can use toolbars, editing keys, and a pop-up menu to specify
formatting. A print preview lets users view a reduced image of the document
to see how it fits on the page.
Rich text support in In PowerBuilder you can use rich text as a DataWindow presentation style. You
PowerBuilder can also add a RichTextEdit control to a window or visual user object.
What is not supported PowerBuilder supports version 1.6 of the RTF standard, except for the
following features:
Formatted tables
Drawing objects
Dear {FNAME}:
. . .
In the Preview view, the text is the same, but PowerBuilder replaces the input
fields with values from the database:
Beth Reiser
AMF Corp.
1033 Whippany Road
New York, NY 10154
Dear Beth:
. . .
844 PowerBuilder
CHAPTER 29 Working with Rich Text
Document template The formatted text acts like a document template. There is only one copy of the
text. As the user scrolls from row to row, the data for the current row is inserted
in the input fields and the user sees the document with the current data. If the
user edits the text, the changes show up in every row of data.
Input fields In the RichText presentation style, an input field is associated with a column or
computed field. It gets its value from the retrieved data or from the computed
field’s expression.
If an input field is not a computed field and its name does not match a column,
there is no way to specify data for the input field.
There can be more than one copy of an input field in the rich text. In the sample
above, there are two instances of the field FNAME. Each instance of the field
displays the same data.
Unavailable settings Not all the settings available in other DataWindow styles are available. You
cannot apply code tables and edit styles, such as a DropDownDataWindow or
EditMask, to input fields. You cannot use slide left and slide up settings to
reposition input fields automatically. However, you can set the LineRemove
property at runtime to achieve a similar effect.
Available settings Table 29-1 describes the types of settings you can make for the RichText
DataWindow object in the wizard.
846 PowerBuilder
CHAPTER 29 Working with Rich Text
Editing the content After you click Finish in the wizard, you see input fields with their labels in the
detail band in the Design view:
You can:
• Begin editing text in the detail, header, or footer bands, building a report
around the input fields. You can delete, move, copy, and paste text and
input fields as needed.
• Include a rich text file you have already prepared. If you include a rich text
file created in PowerBuilder that contains input fields, those names should
match the columns selected in the DataWindow object.
For information about creating rich text files, see Application Techniques.
• Add computed fields that will appear as input fields in the report and
whose values come from the computed field expression.
This sample shows how you might rearrange the input fields in a sales letter:
Editing text You can add text by typing directly in the Design view. You do not have to
create text objects as you do for other DataWindow object styles. The
DataWindow painter’s StyleBar lets you apply formatting to selected text. The
RichText toolbars are not available in the painter.
Inserting a file If you have a rich text file, you can include it in the DataWindow object. In the
Design view, you can insert text from a file into the detail, header, or footer
band.
To insert a file:
1 Click in the text in any band to set the insertion point for the file.
2 Right-click in the Design view and select Insert File from the pop-up
menu.
3 In the file selection dialog box, select the file you want to insert.
Only the body of the file is used. If the file has a header or footer, it is ignored.
848 PowerBuilder
CHAPTER 29 Working with Rich Text
Headers and footers You decide whether your RichText DataWindow object has a header and footer
by checking Header/Footer in the wizard or Rich Text Object dialog box
(described in "Formatting for RichText objects within the DataWindow
object" next). The decision to include a header and footer must be made at
design time; it cannot be changed at runtime.
To display a page number or a date in the header or footer, you can insert the
predefined computed fields Page n of n or Today(). You do not need to write
scripts to set the values of these fields for each page, as you do for the
RichTextEdit control.
850 PowerBuilder
CHAPTER 29 Working with Rich Text
Paragraphs There are also settings for selected paragraphs. You can display the Paragraph
dialog box by pressing Ctrl+Shift+S. The user can double-click the ruler bar or
press the key combination to display the same dialog box.
Default font The user can change the default font by double-clicking on the toolbar or
pressing Ctrl+Shift+D. You cannot change the default font in the painter.
Input fields
An input field can be either a column or a computed field. Before you retrieve
data, its value is shown as two question marks (??).
The text can include many copies of a named input field. The same data will
appear in each instance of the input field.
Column input fields The columns you select for the DataWindow object become input fields in the
rich text. Because the input field’s name matches the column name,
PowerBuilder displays the column’s data in the input field.
If an input field exists in the text, you can copy and paste it to create another
copy. If you need to recreate a column input field that you deleted, use this
procedure.
If there are multiple copies of an input field, the validation and format settings
apply to all the copies. Background color on the Font page applies to all input
fields. Other settings on the Font page apply to individual instances.
The user cannot change the format or validation rule. At runtime, these pages
are not available in the dialog box.
Computed field input fields When you display the dialog box for a
computed field, the settings are a little different. You can specify the input field
name and its expression on the Compute page and there is no validation.
Data Value in preview For both columns and computed fields, you see a
value in the Data Value box when you preview the DataWindow object. The
user sees a value in the Data Value box when the current row has a value. For
columns, users can change the value.
Computed fields Computed fields have an expression that specifies the value of the computed
field. In rich text, they are represented as input fields, too. You specify a name
and an expression. The data value comes from evaluating the expression and
cannot be edited.
2 Click in the text where you want the computed field to appear.
852 PowerBuilder
CHAPTER 29 Working with Rich Text
3 On the Compute page, name the computed field and specify its expression.
4 (Optional) On the Font page, specify text formatting.
5 (Optional) On the Format page, specify a display format.
If there are multiple copies of a computed field input field, the expression and
format settings apply to all the copies. Font settings apply to individual
instances. For more about computed field expressions and display formats, see
Chapter 18, Enhancing DataWindow Objects.
Pictures
Inserting a picture You can include bitmaps (BMP, GIF, JPG, RLE, or WMF files) in a RichText
DataWindow.
Specifying picture size A picture is selected when you can see a dashed outline in Design or Preview
view. When the picture is part of a text selection, it displays with inverted
colors.
You can change the size of a picture as a percentage of the original picture size.
The allowable range for a size percent change is between 10 and 250 percent.
Retrieve on Preview
If the RichText definition specifies Retrieve on Preview, data is retrieved
automatically when you open the Preview view or preview the
DataWindow object in preview mode.
Changes in preview Data While previewing the DataWindow object in preview mode, or when
focus is in the Preview view, you can use the scroll buttons in the Preview
toolbar to move from row to row, and you can change data in the input fields.
If you choose the Save Changes button on the toolbar, you will update the data
in the database.
854 PowerBuilder
CHAPTER 29 Working with Rich Text
Text Any changes you make to the rich text in the Preview view will not be
reflected in the Design view. Any changes that you want to keep must be made
in the Design view, not in preview.
If the Display Only setting is checked, you cannot change text or data in the
Preview view.
Print Preview Print Preview displays a reduced view of one row of data as it would appear
when printed.
Setting margins
To specify permanent margin settings for the RichText DataWindow object,
use the Print Specifications page of the Rich Text Object dialog box.
856 PowerBuilder
CHAPTER 29 Working with Rich Text
The General property page on the user’s Rich Text Object dialog box
presents many of the same options as the Document property page in the
development environment.
For more information about the RichTextEdit control, see the chapter on
implementing rich text in Application Techniques.
858 PowerBuilder
CHAPTER 29 Working with Rich Text
Navigating and Table 29-3: Keyboard shortcuts for navigating and selecting text
selecting text
Move or select Navigating key Selection key
A character to the right or left Right Arrow or Shift+Right Arrow or
Left Arrow Shift+Left Arrow
A word to the right or left Ctrl+Right Arrow or Ctrl+Shift+Right Arrow or
Ctrl+Left Arrow Ctrl+Shift+Left Arrow
A line up or down Up Arrow or Shift+Up Arrow or
Down Arrow Shift+Down Arrow
To start of line Home Shift+Home
To end of line End Shift+End
To start of document Ctrl+Home Ctrl+Shift+Home
To end of document Ctrl+End Ctrl+Shift+End
To next input field Ctrl+Tab
To previous input field Shift+Ctrl+Tab
860 PowerBuilder
C H A P T E R 3 0 Using OLE in a DataWindow
Object
About this chapter This chapter describes how to use OLE in DataWindow objects.
Contents
Topic Page
About using OLE in DataWindow objects 861
OLE objects and the OLE presentation style 863
Using OLE columns in a DataWindow object 874
862 PowerBuilder
CHAPTER 30 Using OLE in a DataWindow Object
864 PowerBuilder
CHAPTER 30 Using OLE in a DataWindow Object
2 Select data for the DataWindow object as you do for any DataWindow
object.
For more information about selecting data, see Chapter 17, Defining
DataWindow Objects.
3 Specify how the OLE object will use the DataWindow object’s data on the
Specify OLE Data page:
You can drag the columns you want the OLE object to use to the Target
Data box. You can also control the grouping of data and edit the expression
for a column. If necessary, you can change these specifications later.
For more information, see Specifying data for the OLE object on page
868.
4 Click Next, and then click Finish.
PowerBuilder displays the Insert Object dialog box in which you define
the OLE object.
To use the Insert Object dialog box, see "Defining the OLE object" next.
To embed a new OLE server object using the Create New tab:
1 Select the Create New tab.
2 In the Object Type box, highlight the OLE server you want to use.
You can click Browse to get information about the server from the registry.
3 Optionally display the OLE object as an icon by doing one of the
following:
• Check Display as Icon to display the server application’s default icon
in the control.
• Check Display as Icon and then select Change Icon to supply a
nondefault icon and icon label.
4 Click OK.
The OLE object is inserted in your DataWindow object and the OLE
server is activated. Depending on the OLE server and whether or not you
have already specified how the OLE object will use the DataWindow
object’s data, the object may be empty or may show an initial presentation
of the OLE object. Close the server application and, if you are inserting an
OLE object in a DataWindow object, specify the object’s properties (see
Specifying properties for OLE objects on page 868).
Create From File Use the following procedure if you want to link or embed the contents of an
existing file as an OLE object so that it can be activated using the application
that created it. Most of the steps in this procedure are the same as those for
embedding a new OLE server object.
866 PowerBuilder
CHAPTER 30 Using OLE in a DataWindow Object
To link or embed an existing object using the Create From File tab:
1 Select the Create From File tab.
2 Specify the file name in the File Name box. If you do not know the name
of the file, click the Browse button and select a file in the dialog box.
3 To create a link to the file, rather than embed a copy of the object in the
control, select the Link check box.
4 Click OK.
The OLE object is inserted in your DataWindow object and the OLE
server is activated. Depending on the OLE server and whether or not you
have already specified how the OLE object will use the DataWindow
object’s data, the object might be empty or might show an initial
presentation of the OLE object. Close the server application and, if you are
inserting an OLE object in a DataWindow object, specify the object’s
properties (see Specifying properties for OLE objects on page 868).
Insert Control Use the following procedure if you want to insert an ActiveX control (OLE
custom control) in the DataWindow object.
4 If you did not specify how the OLE object will use the DataWindow
object’s data when you created the DataWindow object, do so on the Data
property page.
If you have inserted an ActiveX control that does not display data, such as
the Clock control, you do not need to transfer data to it.
For more information, see Specifying data for the OLE object on page
868.
Specifying properties For OLE objects, you need to specify how the OLE object will use the
for OLE objects DataWindow object’s data. If you used the OLE presentation style, you did this
when you created the DataWindow object.
If you are inserting an OLE object in an existing DataWindow object, you can
also associate the object with the current row. If you are using the OLE
presentation style, the OLE object is always associated with all rows.
868 PowerBuilder
CHAPTER 30 Using OLE in a DataWindow Object
The way the OLE object uses the data depends on the server. For example, data
transferred to Microsoft Excel is displayed as a spreadsheet. Data transferred
to Microsoft Graph populates its datasheet, which becomes the data being
graphed.
Some ActiveX controls do not display data, so you would not transfer any data
to them. For an ActiveX control such as Visual Speller, you would use
automation to process text when the user requests it.
Group By and Target Two boxes on the Data property page list data columns or expressions:
Data boxes
• Group By Specifies how PowerBuilder groups the data it transfers to the
OLE object. Aggregation functions in the target data expressions use the
groupings specified here.
• Target Data Specifies the data that you want to transfer to the OLE
object.
Populating the Group If you are using the OLE presentation style, you populated the Group By and
By and Target Data Target Data boxes when you created the DataWindow object. If you placed an
boxes
OLE object in an existing DataWindow object, the boxes are empty. You use
the browse buttons next to the Group By and Target Data boxes to open dialog
boxes where you can select the data you want to use or modify your selections.
Specifying a value for The last setting on the Data property page specifies how the OLE object is
Rows associated with rows in the DataWindow object. The selection (all rows,
current row, or page) usually corresponds with the band where you placed the
OLE object, as explained in this table. If you used the OLE presentation style
to create the DataWindow object, this setting does not display on the property
page: the OLE object is always associated with all the rows in the DataWindow
object.
870 PowerBuilder
CHAPTER 30 Using OLE in a DataWindow Object
Additional settings in The Options property page in the OLE object’s Properties view has some
the Properties view additional settings. They are similar to the settings you can make for the OLE
control in a window. These settings display on the General property page for
OLE DataWindow objects. Table 30-2 describes the settings you can make.
To preview the DataWindow object with the OLE object in preview mode:
1 Select File>Run/Preview from the menu bar, or click the Run/Preview
button on the PowerBar.
2 Select Rows>Retrieve from the menu bar.
872 PowerBuilder
CHAPTER 30 Using OLE in a DataWindow Object
The DataWindow object retrieves rows from the database and replaces the
initial presentation of the OLE object with an image of the data that the
OLE server provides.
3 If you associated the OLE object with all rows, activate the OLE object by
double-clicking on it.
Although you can edit the presentation or the data in the server, your
changes do not affect the DataWindow object’s data.
Saving as a PSR
You can save the object with its data by saving the DataWindow object as a
Powersoft report (PSR). Select File>Save As File or File>Save Rows As from
the menu bar.
874 PowerBuilder
CHAPTER 30 Using OLE in a DataWindow Object
You can modify the document in the server, then update the data in the
DataWindow object. When the database is updated, the OLE column, which
contains the modified document, is stored in the database.
Be sure to include the key column in the data source. You cannot include
the blob column in the data source; if you try, a message tells you that its
datatype requires the use of an embedded SQL statement. You add the blob
column later in the DataWindow painter workspace. (If you use Quick
Select, the blob column is not listed in the dialog box.)
3 Select Insert>Control>OLE Database Blob and click where you want the
blob column in the Design view.
The Database Binary/Text Large Object dialog box displays:
Setting properties for The following procedure describes the properties you need to set for the blob
the blob column column.
876 PowerBuilder
CHAPTER 30 Using OLE in a DataWindow Object
4 In the Large Binary/Text Columns box, select the column that contains the
blob datatype from the list.
5 If necessary, change the default key clause in the Key Clause box.
PowerBuilder uses the key clause to build the WHERE clause of the
SELECT statement used to retrieve and update the blob column in the
database. It can be any valid WHERE clause.
Use colon variables to specify DataWindow columns. For example, if you
enter this key clause:
id = :id
the WHERE clause will be:
WHERE id = :id
6 Identify the OLE server application by doing one of the following:
• If you always want to open the same file in the OLE server
application, enter the name of the file in the File Template box.
For example, to specify a particular Microsoft Word document, enter
the name of the DOC file. If the file is not on the current path, enter
the fully qualified name.
• If you do not want to open the same file each time, select an OLE
server application from the OLE Class: Description drop-down list.
When the server does not match the OLE blob data
If you specify a server that does not match the OLE blob object or if
your database contains objects belonging to different servers, the
OLE mechanism can usually handle the situation. It looks for the
server specified in the object and starts it instead of the server you
specified.
8 Click OK.
PowerBuilder closes the dialog box. The blob column is represented by a
box labeled Blob in the Design view.
9 Save the DataWindow object.
The following screenshot shows what a completed Definition page for a Blob
object in a table called ole looks like in the Properties view:
Making the blob If the blob column is invisible in the DataWindow object until you activate the
column visible OLE server, you can make it easy to find the blob column by adding a border
to the object.
Previewing an OLE Before using the DataWindow object in an application, you should preview it
column in the Preview view or in preview mode to see how it works.
878 PowerBuilder
CHAPTER 30 Using OLE in a DataWindow Object
880 PowerBuilder
PA RT 7 Running Your Application
About this chapter This chapter describes how to debug and run an application in
PowerBuilder. The chapter also lists the errors that can occur at runtime.
Contents
Topic Page
Overview of debugging and running applications 883
Debugging an application 884
Running an application 907
Debugging an application
Sometimes an application does not behave the way you think it will. Perhaps a
variable is not being assigned the value you expect, or a script does not perform
as desired. In these situations, you can examine your application by running it
in debug mode.
When you run the application in debug mode, PowerBuilder stops execution
before it executes a line containing a breakpoint (stop). You can then step
through the application and examine its state.
To debug an application:
1 Open the debugger.
2 Set breakpoints at places in the application where you have a problem.
3 Run the application in debug mode.
4 When execution is suspended at a breakpoint, look at the values of
variables, examine the properties of objects in memory and the call stack,
or change the values of variables.
5 Step through the code line by line.
6 As needed, add or modify breakpoints as you run the application.
7 When you uncover a problem, fix your code and run it in the debugger
again.
884 PowerBuilder
CHAPTER 31 Debugging and Running Applications
Views in the debugger The debugger contains several views. Each view shows a different kind of
information about the current state of your application or the debugging
session. Table 31-1 summarizes what each view shows and what you can do
from that view.
886 PowerBuilder
CHAPTER 31 Debugging and Running Applications
Changing Variable The default debugger layout contains a separate view for each variable type in
views a stacked pane. You can combine two or more Variables views in a single pane.
For example, you might want to combine local and global variables in a single
view that you keep at the top of the stacked pane.
Setting breakpoints
A breakpoint is a point in your application code where you want to interrupt
the normal execution of the application while you are debugging. If you
suspect a problem is occurring in a particular script or function call, set a
breakpoint at the beginning of the script or at the line where the function is
called.
When you close the debugger, any breakpoints you set are written to a file
called targetname.usr.opt in the same directory as the target, where targetname
is the name of the target. The breakpoints are available when you reopen the
debugger. When you clear breakpoints, they are permanently removed from the
usr.opt file (if it is not marked readonly).
Sharing targets
If multiple developers use the same target without using source control (a
practice that is not recommended) individual developers can save the
breakpoints they set in a separate file by adding the following entry to the [pb]
section of their pb.ini file:
UserOptionFileExt=abc
where abc might be the developer’s name or initials. Breakpoints set by the
developer would be saved in a file called appname_abc.usr.opt.
Setting a simple This procedure describes setting a breakpoint in the Source view in the
breakpoint debugger. You can also set a breakpoint by selecting Add Breakpoint from the
pop-up menu in the Script view when you are not running the debugger.
888 PowerBuilder
CHAPTER 31 Debugging and Running Applications
Setting occasional If you want to check the progress of a loop without interrupting execution in
and conditional every iteration, you can set an occasional breakpoint that is triggered only after
breakpoints
a specified number of iterations. To specify that execution stops only when
conditions you specify are met, set a conditional breakpoint. You can also set
both occasional and conditional breakpoints at the same location.
• If you specify an occurrence Each time PowerBuilder passes through
the specified location, it increments a counter by one. When the counter
reaches the number specified, it triggers the breakpoint and resets the
counter to zero.
• If you specify a condition Each time PowerBuilder passes through the
specified location, it evaluates the expression. When the expression is true,
it triggers the breakpoint.
• If you specify both an occurrence and a condition Each time
PowerBuilder passes through the specified location, it evaluates the
expression. When the expression is true, it increments the counter. When
the counter reaches the number specified, it triggers the breakpoint and
resets the counter to zero.
For example, if you specify an occurrence of 3 and the condition
notisNull(val), PowerBuilder checks whether val is NULL each time
the statement is reached. The breakpoint is triggered on the third
occurrence of a non-NULL val, then again on the sixth occurrence, and so
forth.
To disable a breakpoint:
• Do one of the following:
• Click the red circle next to the breakpoint in the Breakpoints view or
Edit Breakpoints dialog box
• Select Disable Breakpoint from the pop-up menu in the Source view
• Select Disable from the pop-up menu in the Breakpoints view
The red circle next to the breakpoint is replaced with a white circle.
You can enable a disabled breakpoint from the pop-up menus or by
clicking the white circle.
890 PowerBuilder
CHAPTER 31 Debugging and Running Applications
To clear a breakpoint:
• Do one of the following:
• Double-click the line containing the breakpoint in the Source view
• Select Clear Breakpoint from the pop-up menu in the Source view
• Select Clear from the pop-up menu in the Breakpoints view
• Select the breakpoint in the Edit Breakpoints dialog box and select
Clear
The red circle next to the breakpoint disappears.
Cleaning up
When you terminate a debugging run or close the debugger without
terminating the run, PowerBuilder executes the application’s close event and
destroys any objects, such as autoinstantiated local variables, that it would have
destroyed if the application had continued to run and exited normally.
892 PowerBuilder
CHAPTER 31 Debugging and Running Applications
Remote debugging
When you are debugging a remote component, Tip Watch does not evaluate
expressions or indirect variables.
QuickWatch QuickWatch provides the current value of simple variables and detailed
information about object variables, including the values of all fields in the
variable. QuickWatch can also evaluate function expressions, and you can use
it to change the values of variables, evaluate expressions, and add variables and
expressions to the Watch view.
Remote debugging
When you are debugging a remote component, expressions and indirect
variables are not evaluated, and you cannot modify variable values.
Using Variables views Each Variables view shows one or more types of variables in an expandable
outline. Double-click the variable names or click on the plus and minus signs
next to them to expand and contract the hierarchy. If you open a new Variables
view, it shows all variable types.
894 PowerBuilder
CHAPTER 31 Debugging and Running Applications
About Instance and In the following illustration, an application has stopped at a breakpoint in the
Parent variables script for the Clicked event for the Close menu item on a frame’s File menu.
The Instance Variables view shows the properties of the current instance of the
Close menu item. The Parent Variables view shows the properties of its parent,
an instance of the File menu. Navigating through the hierarchy in the Global
Variables view shows the same objects.
If the variable or expression is in scope, the Watch view shows its value. Empty
quotes indicate that the variable is in scope but has not been initialized. A pair
of glasses in the Watch view indicates that the variable or expression is not in
scope.
Setting variables and You can select variables you want to watch as the application runs by copying
expressions in the them from a Variables view. You can also set a watch on any PowerScript
Watch view
expression. When you close the debugger, any watch variables and expressions
you set are saved.
Using QuickWatch
You can also add variables and expressions to the Watch view from the
QuickWatch dialog box. See QuickWatch on page 893.
896 PowerBuilder
CHAPTER 31 Debugging and Running Applications
2 Double-click the variable, or select Edit Variable from the pop-up menu.
3 Type the new value for the variable in the Modify Variable dialog box and
click OK.
A green arrow indicates the script that you selected. The Source view
shows the script and line number you selected, and the Variables and
Watch views show the variables and expressions in scope in that context.
898 PowerBuilder
CHAPTER 31 Debugging and Running Applications
Changing the Source From the pop-up menu, you can navigate backward and forward through the
view scripts that have been opened so far, open ancestor and dependent scripts, and
go to a specific line in the current script. There are several other ways to change
the script from other views or from the menu bar.
Single-stepping You can use either Step In or Step Over to step through an application one
through an application statement at a time. They have the same result except when the next statement
contains a call to a function. Use Step In if you want to step into a function and
examine the effects of each statement in the function. Use Step Over to execute
the function as a single statement.
900 PowerBuilder
CHAPTER 31 Debugging and Running Applications
Stepping out of a If you step into a function where you do not need to step into each statement,
function use Step Out to continue execution until the function returns.
Limitations
You cannot change the values of enumerated variables, and you cannot change
the value of any variable when you are debugging a remote component.
902 PowerBuilder
CHAPTER 31 Debugging and Running Applications
The solution If you want to debug windows opened this way, you can declare a global
variable of type window and assign it the local variable. If, for example,
GlobalWindow is a global window of type window, you could add the following
line to the end of the preceding script:
GlobalWindow = mywin
You can look at and modify the opened window through the global variable.
When you have finished debugging the window, you can remove the global
variable and the statement assigning the local to the global.
Just-in-time debugging
If you are running your application in regular mode (using the Run button) and
you notice that the application is behaving incorrectly, just-in-time debugging
lets you switch to debug mode without terminating the application.
When you open the debugger while running an application, the application
does not stop executing. The Source, Variables, Call Stack, and Objects in
Memory views are all empty because the debugger does not have any context.
To suspend execution and examine the context in a problem area, open an
appropriate script and set breakpoints, then initiate the action that calls the
script.
If just-in-time debugging is enabled and a system error occurs while an
application is running in regular mode, the debugger opens automatically,
showing the context where the error occurred.
You can also use the DebugBreak function to break into the debugger.
You must enable just-in-time debugging before you run your application to
take advantage of this feature.
904 PowerBuilder
CHAPTER 31 Debugging and Running Applications
#end if
In this example, if you add a breakpoint to the line /* other action*/, the
breakpoint would automatically switch to the line /*debugging code*/.
Pasting a DEBUG You can use the Paste Special>Preprocessor>#If Defined DEBUG Then pop-up
block into a script menu item in the Script view to paste a template into a script.
906 PowerBuilder
CHAPTER 31 Debugging and Running Applications
When one of these exceptions is thrown, a dialog box displays so that you can
choose whether to open the debugger (Break) or pass the exception to the
program (Ignore).
Running an application
When the application seems to be working correctly, you are ready to run it in
regular mode. In regular mode, the application responds to user interaction and
continues to run until the user exits the application or a runtime error occurs.
You can rely on the default runtime error reporting by PowerBuilder or write a
script that specifies your own error processing. You can also generate a
diagnostic trace of your application's execution.
For how to analyze your application’s logic and performance, see Chapter 32,
Tracing and Profiling Applications.
The Run button runs the current target. The current target displays in bold
in the System Tree and its name displays in the Run button tool tip. The
Select and Run button opens a dialog box that lets you select the target to
run.
PowerBuilder becomes minimized and a button displays on the Taskbar.
Your application executes.
908 PowerBuilder
CHAPTER 31 Debugging and Running Applications
Runtime error Table 31-4 lists the runtime error numbers returned in the Number property of
numbers the Error object and the meaning of each number:
910 PowerBuilder
CHAPTER 31 Debugging and Running Applications
Number Meaning
37 Type mismatch accessing external object property name.
38 Incorrect number of subscripts accessing external object property name.
39 Error accessing external object property name.
40 Mismatched ANY datatypes in expression.
41 Illegal ANY data type in expression.
42 Specified argument type differs from required argument type at runtime
in DLL function name.
43 Parent object does not exist.
44 Function has conflicting argument or return type in ancestor.
45 Internal table overflow; maximum number of objects exceeded.
46 Null object reference cannot be assigned or passed to a variable of this
type.
47 Array expected in ANY variable.
48 Size mismatch in array-to-object conversion.
49 Type mismatch in array-to-object conversion.
50 Distributed Service Error: name.
51 Bad argument list for function/event: name.
52 Distributed Communications Error: name.
53 The server name could not be located. It was probably not started.
54 The server name is rejecting new messages. It is in the process of
shutting down.
55 The request caused an abnormal termination. The connection has been
closed.
56 A message was not fully transmitted.
57 This connection object is not connected to a server.
58 Object instance does not exist.
59 Invalid column range.
60 Invalid row range.
61 Invalid conversion of number dimensional array to object.
62 The server name is busy and not accepting new connections.
63 Function/event with no return value used in expression.
64 Object array expected on left side of assignment.
65 Dynamic function not found. Possible causes include: pass by
value/reference mismatch.
66 Invalid subscript for array index operation.
67 Null object reference cannot be assigned or passed to an autoinstantiate.
68 Null object reference cannot be passed to external DLL function name.
Number Meaning
69 Function name cannot be called from a secured runtime session.
70 External DLL function name cannot be called from a secured runtime
session.
71 General protection fault occurred.
72 name failed with an operating system error code of number.
73 Reference parameters cannot be passed to an asynchronous
shared/remote object method.
74 Reference parameters cannot be passed to a shared object method.
75 The server has forced the client to disconnect.
76 Passing null as a parameter to external function name.
77 Object passed to shared/remote object method is not a nonvisual user
object.
78 Listening works only in the Enterprise version of PowerBuilder.
79 The argument to name must be an array.
80 The server has timed out the client connection.
81 Function argument file creator must be a four-character string.
82 Function argument file type must be a four-character string.
83 Attempt to invoke a function or event that is not accessible.
84 Wrong number of arguments passed to function/event call.
85 Error in reference argument passed in function/event call.
86 Ambiguous function/event reference.
87 The connection to the server has been lost.
88 Cannot ask for ClassDefinition Information on open painter: name.
89 5.0 style proxy objects are not supported. Copy the new style proxy that
was generated at migration time.
90 Cannot assign array of type name to variable of type array of name.
91 Cannot convert name in Any variable to name. Possible cause:
uninitialized value.
92 Required property name is missing.
93 CORBA User Exception: exceptionname.
94 CORBA System Exception: exceptionname.
95 CORBA Objects cannot be created locally.
96 Exception Thrown has not been handled.
912 PowerBuilder
CHAPTER 31 Debugging and Running Applications
Number Meaning
97 Cannot save name because of a circular reference problem. Possible
causes:
1 This object references another class, which in turn references this
object.
2 Some other circular reference is pointing back to this object, causing
a deadlock condition.
Suggested actions:
1 Temporarily remove the circular reference from the referenced
object.
2 Make your required changes to this object to refer to that object.
3 Add back the circular reference you removed in step 1.
4 Perform a full rebuild (recommended).
98 Obsolete object reference.
99 Error calling method of a PBNI object.
100 Error loading library containing a PBNI object.
101 Error unloading library containing a PBNI object.
102 Error creating a PBNI object.
103 Error destroying a PBNI object.
104 Error calling PowerBuilder system function functionname.
105 Executing a HALT statement in a server component is strictly forbidden.
106 Function is reserved or not yet implemented.
107 Argument is out of range.
108 Not enough memory to execute the operation.
109 Cannot assign a null value to array variables.
Some errors terminate the application immediately. They do not trigger the
SystemError event.
SystemError event A typical script for the SystemError event includes a CHOOSE CASE control
scripts structure to handle specific errors. To stop the application, include a HALT
statement in the SystemError script.
Caution
You can continue your application after a SystemError event, but doing so can
cause unpredictable and undesirable effects. Where the application will resume
depends on what caused the error. Typically, you are better off reporting the
problem to the user, then stopping the application with HALT.
914 PowerBuilder
C H A P T E R 3 2 Tracing and Profiling
Applications
About this chapter This chapter describes how to generate trace information that you can use
to improve your application’s performance.
Contents
Topic Page
About tracing and profiling an application 915
Collecting trace information 916
Analyzing trace information using profiling tools 928
Analyzing trace information programmatically 934
Generating a trace file without timing information 944
PBDebug tracing
You can also generate a simple text trace file without timer values by
checking Enable PBDebug Tracing in the System Options dialog box.
For more about PBDebug, see Generating a trace file without timing
information on page 944.
When you can trace You can create a trace file when you run an application in the PowerBuilder
an application environment, and when you run an executable outside PowerBuilder. For
machine-code executable files, the trace file is generated only if you check the
Trace Information check box when you build the executable.
When you run an application with tracing turned on, PowerBuilder records a
timer value in a data file every time a specific activity occurs. You control when
logging begins and ends and which activities are recorded.
Creating profiles After you have generated a trace file, you can create several different profiles
or views of the application by extracting different types of information from the
trace file.
PowerBuilder provides three profiling tools that create profiles (views) of the
application for you, but you can also create your own analysis tools.
Using profiling to tune Examining the profiles generated by the profiling tools tells you where the
an application application is spending the most time. You can also find routines that are being
called too often, routines being called that you did not expect to call, or routines
that are not being called at all. Follow these suggestions for tuning an
application:
• The database connection process is often slow. Although you might not be
able to speed this up, you might be able to enhance the user’s perception
of performance by moving the database connection process to a different
place in your application.
• Use profiling to tune algorithms. Algorithmic fixes will yield greater
performance enhancements than changing single lines of code.
• Optimizing an inefficient function is not as effective as removing
unneeded calls to that function.
• Focus on optimizing the routines that are called most often.
• If you cannot speed up a routine, consider adding some user feedback,
such as updating MicroHelp or displaying a progress bar.
916 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
Collection time
The timer values in the trace file exclude the time taken to collect the trace data.
Because an application can be idle (while displaying a MessageBox, for
example), percentage metrics are most meaningful when you control tracing
programmatically, which can help minimize idle time. Percentages are less
meaningful when you create a trace file for a complete application.
If you do not specify a timer kind, the time at which each activity begins and
ends is recorded using the clock timer, which measures an absolute time with
reference to an external activity, such as the computer’s start-up time. The
clock timer measures time in microseconds. Depending on the speed of your
computer's central processing unit, the clock timer can offer a resolution of less
than one microsecond. A timer’s resolution is the smallest unit of time the timer
can measure.
You can also use process or thread timers, which measure time in microseconds
with reference to when the process or thread being executed started. You
should always use the thread timer for distributed applications. Both process
and thread timers exclude the time taken by any other running processes or
threads so that they give you a more accurate measurement of how long the
process or thread is taking to execute, but both have a lower resolution than the
clock timer.
Trace activities You can choose to record in the trace file the time at which any of the following
activities occurs. If you are using the System Options dialog box or a window,
you select the check boxes for the activities you want. If you are using
PowerScript functions to collect trace information, you use the TraceActivity
enumerated type to identify the activity.
918 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
When you begin and end tracing, an activity of type ActBegin! is automatically
recorded in the trace file. User-defined activities, which you use to log
informational messages to the trace file, are the only trace activities enabled by
default.
Using a window
You can create a window that is similar to the Profiling tab on the System
Options dialog box and add it to any application that is under development, so
that you can start and stop tracing when testing specific actions.
The w_starttrace window is available in the PB Code Profiler sample in the
PowerBuilder Code Samples at https://www.appeon.com/developers/library/code-
samples-for-pb. This sample also shows the code used to create the profiling
tools described in Analyzing trace information using profiling tools on page
928.
The w_starttrace window lets you specify a trace file name, label, and timer
kind, as well as which activities you want to trace:
920 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
The following code shows the script for the Clicked event of the Start Trace
button. The text for the button is set to Start Trace in the painter. When the user
clicks Start Trace, the button label changes to Stop Trace. The Clicked event
script checks the text on the button before either starting or stopping tracing.
This script uses the functions described in Collecting trace information using
PowerScript functions on page 925:
// instance variables:
// errorreturn le_errorreturn
integer li_key
if len(trim(sle_filename.text)) = 0 then
messagebox(parent.title, &
'Trace file name is required',information!)
sle_filename.setfocus()
return
end if
end if
return
end if
end if
if cbx_routineentry.checked then
le_errorreturn =TraceEnableActivity(ActRoutine!)
if le_errorreturn <> Success! then
of_errmsg(le_errorreturn, &
'TraceEnableActivity( ActRoutine! )')
Traceclose()
if le_errorreturn <> Success! then
of_errmsg(le_errorreturn,'TraceClose')
end if
return
end if
end if
if cbx_userdefined.checked then
le_errorreturn = TraceEnableActivity( ActUser! )
if le_errorreturn <> Success! then
of_errmsg(le_errorreturn, &
'TraceEnableActivity( ActUser! )')
Traceclose()
if le_errorreturn <> Success! then
of_errmsg(le_errorreturn,'TraceClose')
end if
return
end if
end if
if cbx_systemerrors.checked then
le_errorreturn = TraceEnableActivity(ActError! )
if le_errorreturn <> Success! then
of_errmsg(le_errorreturn, &
'TraceEnableActivity( ActError! )')
Traceclose()
if le_errorreturn <> Success! then
of_errmsg(le_errorreturn,'TraceClose')
end if
return
end if
end if
if cbx_routineline.checked then
le_errorreturn = TraceEnableActivity( ActLine! )
922 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
if cbx_garbagecoll.checked then
le_errorreturn = &
TraceEnableActivity( ActGarbageCollect! )
if le_errorreturn <> Success! then
of_errmsg(le_errorreturn, &
'TraceEnableActivity(ActGarbageCollect! )')
Traceclose()
if le_errorreturn <> Success! then
of_errmsg(le_errorreturn,'TraceClose')
end if
return
end if
end if
// Start tracing
le_errorreturn =TraceBegin( sle_tracelabel.text )
if le_errorreturn <> Success! then
of_errmsg(le_errorreturn,'TraceBegin')
return
end if
le_errorreturn =TraceClose()
if le_errorreturn <> Success! then
of_errmsg(le_errorreturn,'TraceClose')
end if
this.text = is_starttext
parent.title = is_title
end if
of_errmsg function The window uses two functions to handle error messages. The of_errmsg
function displays a message box:
// of_errmsg
Messagebox( this.title,'Error executing '+ as_msg + &
'. Error code : '+ of_converterror(ae_error) )
of_converterror The of_converterror function converts the ErrorReturn parameter to a string:
function
// of_converterror: convert enumerated type
// ErrorReturn parameter to text.
String ls_result
choose case a_error
Case Success!
ls_result = "Success!"
Case FileCloseError!
924 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
ls_result = "FileCloseError!"
Case FileOpenError!
ls_result = "FileOpenError!"
Case FileReadError!
ls_result = "FileReadError!"
Case FileWriteError!
ls_result = "FileWriteError!"
Case FileNotOpenError!
ls_result = "FileNotOpenError!"
Case FileAlreadyOpenError!
ls_result = "FileAlreadyOpenError!"
Case FileInvalidFormatError!
ls_result = "FileInvalidFormatError!"
Case FileNotSetError!
ls_result = "FileNotSetError!"
Case EventNotExistError!
ls_result = "EventNotExistError!"
Case EventWrongPrototypeError!
ls_result = "EventWrongPrototypeError!"
Case ModelNotExistsError!
ls_result = "ModelNotExistsError!"
Case ModelExistsError!
ls_result = "ModelExistsError!"
Case TraceStartedError!
ls_result = "TraceStartedError!"
Case TraceNotStartedError!
ls_result = "TraceNotStartedError!"
Case TraceNoMoreNodes!
ls_result = "TraceNoMoreNodes!"
Case TraceGeneralError!
ls_result = "TraceGeneralError!"
Case FeatureNotSupportedError!
ls_result = "FeatureNotSupportedError!"
Case else
ls_result = "Unknown Error Code"
end choose
return ls_result
In general, you call the functions in the order shown in the table. That is, you
must call TraceOpen before you call any other trace functions. You call
TraceClose when you have finished tracing.
TraceUser and TraceError can be called only when the trace file is open and
tracing is active—that is, after you call TraceBegin and before you call
TraceEnd.
About TraceUser and You can use TraceUser to record specific events in the trace file, such as the
TraceError beginning and end of a body of code. You can also record the execution of a
statement you never expected to reach, such as the DEFAULT statement in a
CHOOSE CASE block. TraceError works just like TraceUser, but you can use it
to signal more severe problems.
Both TraceUser and TraceError take a number and text string as arguments. You
can use a simple text string that states what activity occurred, or you can build
a string that provides more diagnostic information by including some context,
such as the current values of variables. Run the application with only ActUser!
or ActError! tracing turned on and then use the Profiling Trace View to
pinpoint problems quickly.
Example: trace data In this example, the user selects a timer kind from a drop-down list and enters
collection a name for the trace file in a single-line edit box. Typically you would use the
ErrorReturn return value from every trace call to return an error message if the
call fails. For brevity, the example shows this only for the TraceOpen call.
926 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
Several trace activities are disabled for a second trace block. The activities that
are not specifically disabled remain enabled until TraceClose is called.
ErrorReturn le_err
integer li_key
TimerKind ltk_kind
TraceBegin("Trace_block_1")
// first block of code to be traced
// this block has the label Trace_block_1
…
TraceEnd()
TraceDisableActivity(ActObjectDestroy!)
TraceDisableActivity(ActGarbageCollect!)
TraceBegin("Trace_block_2")
// second block of code to be traced
…
TraceEnd()
TraceClose()
928 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
• Source Shows statistics and source code for those routines that
originated in PowerScript source
For each object, the Class view shows all the routines called from each class
with the number of times each routine was called (hit) as well as timing
information for each call. The following illustration shows part of a Class view.
Embedded SQL commands are shown as being called from a pseudo class
called ESQL.
Class view metrics The Class view displays five metrics. The profiling tool accesses these metrics
from instances of the ProfileCall and ProfileRoutine objects. The time scale
you specified in the Preferences dialog box determines how times are
displayed.
Table 32-4: Metrics in the Profiling Class View
Metric What it means
Hits The number of times a routine executed in a particular context.
Self The time spent in the routine or line itself. If the routine or line
was executed more than once, this is the total time spent in the
routine or line itself; it does not include time spent in routines
called by this routine.
%Self Self as a percentage of the total time the calling routine was
active.
Self+Called The time spent in the routine or line and in routines or lines called
from the routine or line. If the routine or line was executed more
than once, this is the total time spent in the routine or line and in
called routines or lines.
%Self+Called Self+Called as a percentage of the total time that tracing was
enabled.
About percentages
The percentages captured in the trace file are based on the total time tracing
was enabled. Because an application can be idle (while displaying a
MessageBox, for example), percentage metrics are most meaningful when you
control tracing programmatically, which can help to minimize idle time.
Percentages are least meaningful when you create a trace file for a complete
application.
930 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
You can specify the current routine by clicking in the various DataWindows.
Table 32-5: Specifying the current routine in the Profiling Routine View
To do this Click here
Establish a new current On the routine. The profiling tool updates the top and
routine in the current bottom DataWindows with information on called and
routine DataWindow calling routines.
Select a calling routine On the routine in the top DataWindow. The profiling tool
as the new routine makes it the current routine in the middle DataWindow.
Select a called routine as On the routine in the bottom DataWindow. The profiling
the new routine tool makes it the current routine in the middle
DataWindow.
Routine view metrics The Routine view displays nine metrics. The profiling tool accesses these
metrics from instances of the ProfileCall and ProfileRoutine objects. The time
scale you specified in the Preferences dialog box determines how times are
displayed.
Table 32-6: Metrics in the Profiling Routine View
Metric What it means
Hits (Called on The number of times a routine executed in a particular context.
Detail tab)
Self The time spent in the routine or line itself. If the routine or line was
executed more than once, this is the total time spent in the routine
or line itself; it does not include time spent in routines called by
this routine.
%Self Self as a percentage of the total time the calling routine was active.
Self Min The shortest time spent in the routine or line itself. If the routine or
line was executed only once, this is the same as AbsoluteSelfTime.
Self Max The longest time spent in the routine or line itself. If the routine or
line was executed only once, this is the same as AbsoluteSelfTime.
Self+Called The time spent in the routine or line and in routines or lines called
from the routine or line. If the routine or line was executed more
than once, this is the total time spent in the routine or line and in
called routines or lines.
%Self+Called Self+Called as a percentage of the total time that tracing was
enabled.
Self+Called The shortest time spent in the routine or line and in called routines
Min or lines. If the routine or line was executed only once, this is the
same as AbsoluteTotalTime.
Self+Called The longest time spent in the routine or line and in called routines
Max or lines. If the routine or line was executed only once, this is the
same as AbsoluteTotalTime.
932 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
You can use the Trace View Options section of the Preferences dialog box to
control the display:
• System routines This option controls whether the Trace view includes
information for lines that execute PowerBuilder system routines.
• Line information This option controls whether the Trace view includes
line numbers.
The following screen shows a Trace view with several nodes expanded. The
number to the right of each item is the execution time for that item.
Trace view metrics The Trace view displays two metrics. The profiling tool accesses these metrics
from instances of the TraceTree and TraceTreeNode objects.
Table 32-7: Metrics in the Profiling Trace View
Entry What it means
Routine or line The routine or line number that was executed.
number
Execution Total execution time for the Tree view entry. This is total time from
time the start of the entry to the end of the entry. For example, if you call
the MessageBox function, this value reflects the elapsed time from
when the message box was opened until the user provided some
kind of response.
About preferences
The specifications you make in the Preferences dialog box control whether the
Trace view displays system functions and line numbers.
934 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
open(w_progress)
// call the of_init window function to initialize
// the w_progress window
w_progress.of_init(lpro_model.numberofactivities, &
'Building Model', this, 'ue_cancel')
936 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
Example: extracting The following function extracts information from a call graph model about the
information from a call routines called from a specific routine. You would use similar functions to
graph model
extract information about the routines that called the given routine and about
the routine itself.
The function takes a ProfileCall object and an index as arguments and returns
a structure containing the number of times the called routine was executed and
execution times for the called routine.
str_func_detail lstr_result
ProfileClass lproclass_class
ProfileRoutine lprort_routine
lstr_result.hits = a_pcall.HitCount
lstr_result.selfTime = a_pcall. &
AbsoluteSelfTime * timeScale
lstr_result.totalTime = a_pcall. &
AbsoluteTotalTime * timeScale
lstr_result.percentSelf = a_pcall.PercentSelfTime
lstr_result.percentTotal= a_pcall.PercentTotalTime
lstr_result.index = al_index
RETURN lstr_result
938 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
TraceTree ltct_treemodel
ltct_treemodel = CREATE TraceTree
ltct_treeModel.SetTraceFileName(is_fileName )
ltct_treeModel.BuildModel(this, 'ue_progress', 1)
For more about using BuildModel, see Using the BuildModel function to build
a call graph model on page 936.
ltct_treemodel.EntryList(ltctn_list)
ll_limit = UpperBound(ltctn_list)
FOR ll_index = 1 to ll_limit
ltctn_node = ltctn_list[ll_index]
of_dumpnode(ltctn_node, lstr_node)
// insert code to handle display of
// the information in the structure here
…
NEXT
The of_dumpnode function takes a TraceTreeNode object and a structure as
arguments and populates the structure with information about each node. The
following code shows part of the function:
string ls_exit, ls_label, ls_routinename
long ll_node_cnt
TraceTreeNode ltctn_list[]
errorreturn l_err
astr_node.Children = FALSE
astr_node.Label = ''
IF NOT isvalid(atctn_node) THEN RETURN
940 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
astr_node.label = ls_label
RETURN
942 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
ls_fileName = sle_filename.Text
ltcf_file = CREATE TraceFile
ltcf_file.Open(ls_fileName)
ls_line = "CollectionTime = " + &
String(Truncate(ltcf_file.CollectionTime, 6)) &
+ "~r~n" + "Number of Activities = " + &
String(ltcf_file.NumberOfActivities) + "~r~n" + &
"Time Stamp " + "Activity" + "~r~n"
mle_output.text = ls_line
ltcan_node = ltcf_file.NextActivity()
DO WHILE IsValid(ltcan_node)
ls_line += of_dumpActivityNode(ltcan_node)
ltcan_node = ltcf_file.NextActivity()
LOOP
mle_output.text = ls_line
ltcf_file.Close()
The following code shows part of of_dumpActivityNode:
string lstr_result
RETURN lstr_result
944 PowerBuilder
CHAPTER 32 Tracing and Profiling Applications
For information on creating the same kind of diagnostic trace file when you run
your compiled application outside PowerBuilder, see Tracing execution on
page 959.
946 PowerBuilder
C H A P T E R 3 3 Creating Executables and
Components
About this chapter This chapter describes how to create an executable version of your target.
It also provides an overview of how you use the PowerBuilder Project
painter to build other kinds of components.
Contents
Topic Page
About building PowerBuilder targets 947
Creating a project 948
Using the Project painter 950
Defining an executable application project 951
Using dynamic libraries 955
Distributing resources 957
Tracing execution 959
Building an executable file and dynamic libraries 960
Building proxies and .NET targets 965
Creating a project
You can create a new project when you create a new target using most Target
wizards. You can also create a project at any time from the Project page in the
New dialog box if you have already created a target of the appropriate type.
The Project page has two kinds of icons: icons that open wizards that help you
set up a project, and icons that open the Project painter. Wizard icons display
next to the icon for the same project type. The following procedure describes
how to create a new project from the Project page.
948 PowerBuilder
CHAPTER 33 Creating Executables and Components
4 Select the wizard or project type you need and click OK.
If you select a wizard, complete the wizard screens to create a new project
with most of its properties specified. Use the context-sensitive Help if you
are not sure what to enter. You can open the Project painter now or later to
modify the properties if necessary and to build the project.
If you do not select a wizard, the Project painter for the type of object you
selected opens so that you can specify properties of the project object.
Once you have created a project, you can open it from the System Tree.
Target-relative paths All paths used in projects are stored as target-relative paths, if possible. If you
and shared projects later move the application to a different location in the file system, or another
user copies or checks out the application, the paths are adjusted relative to the
new target location.
For example, suppose user A has an application target stored in the following
directory structure, where pbl_1.pbl contains the application object:
C:\target1\target1.pbt
C:\target1\pbls\pbl_1.pbl
C:\target1\pbls\pbl_2.pbl
C:\target1\res\target1.pbr
C:\target1\out\target1.exe
When user B copies the application to the following directory structure, no
changes need to be made in the Project painter, because the paths reflect the
new directory structure:
D:\PB\My Targets\Target 1\target1.pbt
D:\PB\My Targets\Target 1\pbls\pbl_1.pbl
D:\PB\My Targets\Target 1\pbls\pbl_2.pbl
D:\PB\My Targets\Target 1\res\target1.pbr
D:\PB\My Targets\Target 1\out\target1.exe
A projects that was created in an earlier version of PowerBuilder using
hard-coded paths must be opened and resaved before the files it references are
modified with target-relative paths.
If a path is not on the drive where the target is stored, then the path is stored as
an absolute path. For example, the path to image files stored on a shared
network directory such as J:\res\images\common is stored as an absolute path
in the project file.
For how to create a new project, see Creating a project on page 948. For more
information about .NET projects, see Deploying Components as .NET
Assemblies or Web Services.
950 PowerBuilder
CHAPTER 33 Creating Executables and Components
952 PowerBuilder
CHAPTER 33 Creating Executables and Components
Location of temporary The machine code generation process puts temporary files in a temporary
files directory, such as the TEMP directory. You can specify a different location in
the [PB] section of your PowerBuilder initialization file with the
CODEGENTEMP variable. You might want to do this if you have limited
space on your local system.
954 PowerBuilder
CHAPTER 33 Creating Executables and Components
For example:
CODEGENTEMP=e:\pbtempdir
2 Make sure the application's library search path includes the new library.
Specifying the When you define your project, you tell PowerBuilder which of the libraries in
dynamic libraries in the application’s library search path will be dynamic by checking the PBD or
your project
DLL check box next to the library name in the Project painter.
Including additional When building a dynamic library, PowerBuilder does not inspect the objects;
resources for a it simply copies the compiled form of the objects into the dynamic library.
dynamic library
Therefore, if any of the objects in the library use resources (pictures, icons, and
pointers)—either specified in a painter or assigned dynamically in a script—
and you do not want to provide these resources separately, you must list the
resources in a PowerBuilder resource (PBR) file. Doing so enables
PowerBuilder to include the resources in the dynamic library when it builds it.
956 PowerBuilder
CHAPTER 33 Creating Executables and Components
You can also select External manifest to generate a standalone manifest file in
XML format that you ship with your application’s executable file, or No
manifest if you do not need to distribute a manifest file.
Execution level Select As Invoker if the application does not need elevated or administrative
privileges. Selecting a different execution level will probably require that you
modify your application to isolate administrative features in a separate process
to receive Vista certification.
Select Require Administrator if the application process must be created by a
member of the Administrators group. If the application user does not start the
process as an administrator, a message box displays so that the user can enter
the appropriate credentials.
Select Highest Available to have the AIS retrieve the highest available access
privileges for the user who starts the process.
UI access If the application needs to drive input to higher privilege windows on the
desktop, such as an on-screen keyboard, select the “Allow access to protected
system UI” check box. For most applications you should not select this check
box. Microsoft provides this setting for user interface Assistive Technology
(Section 508) applications.
Distributing resources
You can choose to distribute your resources (pictures, pointers, and icons)
separately or include them in your executable file or dynamic library.
958 PowerBuilder
CHAPTER 33 Creating Executables and Components
For more information about creating and using PBR files, see the chapter on
packaging your application for deployment in Application Techniques.
Tracing execution
You can trace execution of an executable file built with PowerBuilder. By
tracing execution, you can troubleshoot your application if it does not behave
the same way when run as an executable file as it does when run in the
PowerBuilder development environment. You can also use the trace output to
profile your application: for example, you can see how many times particular
scripts and functions are being executed.
Two kinds of trace You can generate two kinds of trace files:
files
• With timing information You collect trace information by adding code
to the scripts in the application or adding a window that lets users turn
tracing on and off. PowerBuilder generates a binary trace file that you
analyze using a comprehensive set of objects and functions or the Profiling
tools. For more information about tracing and profiling, see About tracing
and profiling an application on page 915.
• Without timing information You collect information by running the
application with the /pbdebug command-line switch. PowerBuilder
generates a text file that logs the creation and destruction of objects and
the execution of scripts and functions.
Tracing execution You generate PBDebug trace information for an executable file by invoking the
using /pbdebug executable with a command-line switch.
Enabling tracing
If you are compiling machine code, you must enable tracing at compile time by
selecting Trace Information in the Project painter Compile Options group. If
you have not enabled tracing when you compile for machine code, no trace
information is generated and the /pbdebug switch has no effect.
If you compile your project in Pcode, the compiler automatically adds the
information needed to enable tracing.
960 PowerBuilder
CHAPTER 33 Creating Executables and Components
962 PowerBuilder
CHAPTER 33 Creating Executables and Components
964 PowerBuilder
CHAPTER 33 Creating Executables and Components
The workspace for all other types of project objects is similar. If you used a
wizard to create the project, it shows the options you selected in the wizard. If
you did not use a wizard, you select the objects the project will use and specify
project properties on tab pages in the workspace.
When you build the project, the Output window shows whether the build was
successful and lists any errors encountered.
Building and You can build and deploy a single project or all the projects in your workspace.
deploying a You can also build and deploy from a command-line. For more information,
workspace
see Building workspaces on page 26.
For more information For more information about building Web service proxies, and EJB client
proxies, see Application Techniques.
For more information about building .NET targets, see Deploying Components
as .NET Assemblies or Web Services.
966 PowerBuilder
PA RT 8 Appendixes
About this appendix This appendix describes each column in the extended attribute system
tables.
Contents
Topic Page
About the extended attribute system tables 969
The extended attribute system tables 970
Edit style types for the PBCatEdt table 973
What to do with the You can open and look at these tables in the Database painter just like other
tables tables. You might want to create a report of the extended attribute information
used in your database by building a DataWindow object whose data source is
the extended attribute system tables.
Caution
You should not change the values in the extended attribute system tables.
PowerBuilder maintains this information automatically whenever you change
information for a table or column in the Database painter.
970 PowerBuilder
APPENDIX A The Extended Attribute System Tables
972 PowerBuilder
APPENDIX A The Extended Attribute System Tables
974 PowerBuilder
APPENDIX A The Extended Attribute System Tables
976 PowerBuilder
APPENDIX A The Extended Attribute System Tables
978 PowerBuilder
APPENDIX A The Extended Attribute System Tables
980 PowerBuilder
APPENDIX A The Extended Attribute System Tables
Value Meaning
Display1 Display value for first entry in code table.
Data1 Data value for first entry in code table.
Display2 Display value for second entry in code table.
Data2 Data value for second entry in code table.
Display and data values are repeated in pairs for each entry in the code
table.
Flag 32-bit flag. Low-order four hex digits are generic edit type; high-order
four are styles within the type. A 1 in any bit indicates the corresponding
style is checked. A 0 in any bit indicates the corresponding style is
unchecked.
Bit 31: Required
Bit 30: Autoskip
Bit 29: Spin control
Bit 28: Read only (code table option)
Bit 27: Use code table
Bit 26: Not used (set to 0)
Bit 25: Not used (set to 0)
Bit 24: Not used (set to 0)
Bit 23 – 16 (2 hex digits): Not used (set to 0)
Bit 15 – 8 (2 hex digits): Always 0 for Edit Mask edit style
Bit 7: Always 0 for Edit Mask edit style
Bit 6: Always 0 for Edit Mask edit style
Bit 5: Always 1 for Edit Mask edit style
Bit 4: Always 0 for Edit Mask edit style
Bits 3 – 0 (1 hex digit): Always 0 for Edit Mask edit style
982 PowerBuilder
A PP E N D I X B The OrcaScript Language
About this appendix This appendix describes the OrcaScript scripting language. OrcaScript
allows you to perform source control operations and build PowerBuilder
workspaces and executables without operator intervention. The full
ORCA tool kit is available to Appeon partners only, but OrcaScript can be
used by any PowerBuilder customer.
Contents
Topic Page
About OrcaScript 983
OrcaScript Commands 985
Usage notes for OrcaScript commands and parameters 991
About OrcaScript
OrcaScript allows you to write batch scripts to process PowerBuilder
applications and files without using the PowerBuilder development
environment. You can use OrcaScript to get the latest version of a target
from source control, build the target PBLs, and compile PowerBuilder
executable files—all without operator intervention.
Using OrcaScript with The targets you obtain from source control using OrcaScript could be
source control placed on a network build computer that is shared by PowerBuilder
developers. This is especially advantageous for large shops with fixed
working hours: the builds could be done nightly by running an OrcaScript
batch file, and an up-to-date version of the targets and libraries would be
available at the start of the next work day.
Developers could then use OrcaScript or operating system commands to
copy the shared files directly to their local computers. Although
developers would still connect directly to source control from their local
workspaces, refreshing the targets in the workspaces would be much faster
since compilation times for complex targets would be greatly minimized.
Batch file order If you include OrcaScript commands in a batch file, the file is read line by line.
Each OrcaScript batch file must begin with a start session command and end
with an end session command. You can save the batch file with any extension.
You run the batch file by calling the OrcaScript executable on a command line
and passing the batch file name as an argument:
OrcaScr170 myOrcaBat.dat
If you use relative directories in the OrcaScript batch file, create the batch file
in the directory that is the required root directory at runtime. This must be in
the same directory or in the path above a directory containing the files
referenced by the batch file.
When you use relative directories, the OrcaScript batch file is portable for all
users. However, users must make the directory where they copy the batch file
the current directory (the one displayed in the DOS prompt) before invoking
OrcaScr170.exe. The command to start the OrcaScript executable can also take
the following parameters:
Parameter Description Example
/D Sets variables that OrcaScr170 /D myVar1=value1
are valid in the /D myVar2=value2 myOrca.dat
batch file
/H or /? Prints syntax help OrcaScr170 /H
to screen
Caution
You should not run an OrcaScript batch file if PowerBuilder is currently
running on the same computer. If the PowerBuilder development environment
is not shut down while OrcaScript is running, your PowerBuilder libraries can
become corrupted. For this reason, casual use of OrcaScript is not
recommended.
Executing DOS The OrcaScript commands can call DOS commands and arguments and the
commands and batch batch file. For example,
file
start session
cmd "delete c:\test.txt"
end session
Or
start session
cmd "c:\test.bat"
end session
984 PowerBuilder
APPENDIX B The OrcaScript Language
About pbc.exe The pbc.exe tool can be used to automate the PowerBuilder application
building process. See below to compare the scripts for building a project using
the OrcaScript batch file and the pbc.exe tool.
OrcaScript batch file
The OrcaScript batch file contains the following scripts:
start session
set liblist
"D:\Test\PB\170cmdvss\test11.pbl;D:\Test\PB\170cmdvss\
appeontry.pbl;"
set application "D:\Test\PB\170cmdvss\test11.pbl"
"test11"
build library "D:\Test\PB\170cmdvss\test11.pbl" "" pbd
build library "D:\Test\PB\170cmdvss\appeontry.pbl" ""
pbd
build executable "D:\Test\PB\170cmdvss\test11.exe" ""
"" "yy" newvstylecontrols
end session
pbc.exe tool
OrcaScript Commands
OrcaScript commands are not case sensitive. The generic command parameters
can include only strings delimited by quotation marks, or predefined variables
and constants without quotation marks. White space is used to separate
multiple parameters for a single command. Any place a string is expected, a
name that has been previously defined (set) in an OrcaScript command can be
used.
986 PowerBuilder
APPENDIX B The OrcaScript Language
Argument Description
true | false Boolean value for enabling or disabling script in conditional
compilation blocks set with the DEBUG condition. The set
debug command applies to standard PowerBuilder targets
only. It affects all objects used by subsequent regenerate and
build application commands. It also affects all objects retrieved
with scc refresh target and scc get latest version commands.
propertyString String for setting the company or product name, copyright
owner, or application description.
versionString String for setting the product or file version numbers. The
FileVersionNum and ProductVersionNum strings must consist
of four integer values representing the major version number,
minor version number, fix version number, and build number,
with each value separated by a decimal point, for example
"11.0.0.3012".
fromFile File that you want to copy during an OrcaScript session.
toFile File name for a file that you copy during an OrcaScript session.
fileName File that you want to delete during an OrcaScript session.
clobberAttribute Determines whether the file copy command overwrites an
existing file. If the destination file does not already exist, the
file copy command creates the file regardless of the
clobberAttribute value you select. Possible values are:
• Clobber (default) File copy command overwrites an
existing file marked read/write, but does not overwrite an
existing file marked read-only
• NoClobber File copy command does not overwrite an
existing file even if it is marked read/write
• Clobber Always File copy command overwrites an
existing file even if it is marked read-only
entryName Pointer to a string whose value is the name of the referenced
object.
entryType Value specifying the type of the referenced object. Values can
be: application, datawindow, function, menu, query, struct,
userobject, window, pipe, project, or proxy. Certain
abbreviations (app, dw, fn, struct, uo, and win) are allowed as
substitute values.
toPblName Name of the PBL to which you copy an entry.
pbrName Name of a resource file you want to include in a build.
pbd | 32 Select PBD to generate PowerBuilder dynamic libraries.
Select 32 to generate platform-specific machine code. You
must enter a full path for a PBL or PBR if you select 32 as the
value of this argument in an OrcaScript build library command.
988 PowerBuilder
APPENDIX B The OrcaScript Language
Argument Description
exeName Name of the executable you want to build.
iconName Name of an icon to use for an executable you build with
OrcaScript.
pbdFlags String composed of a series of Y and N values for each library
in the library list. A value of "nnyy" indicates that there are
four libraries in the library list, the last two being PBDs.
Objects from PBLs are copied into the executable; objects
from PBDs are not copied.
machinecode Use to compile the project as machine code.
newvstylecontrols Use Microsoft XP visual style for controls.
x64 Compile the project as a 64-bit executable.
full | migrate | Build strategy for the session application.
incremental | 3pass 3pass performs a full rebuild of the application. It should be
used instead of full when there are complex inherited
relationships.
projectName Name of the project object you want to build and deploy.
serverName Name of the server where you want to deploy a project.
serverPort Port for the server where you want to deploy a project.
logID Login ID for the server where you want to deploy a project.
logPass Login password for the server where you want to deploy a
project.
pbdName Name of a PBD you append to an EXE.
pblComments Comments for a PBL you create in an OrcaScript session.
Arguments for source In addition to some of the arguments listed in the preceding table, OrcaScript
control commands source control commands use the following arguments:
Argument Description
workspaceName Name of the workspace to connect to source control. You must
include the path to the workspace, although you can use a relative
path.
sccProvider Name of the source control provider.
userID Name of the user registered to source control.
password Password for the user ID.
logFileName Name of a log file used to record SCC transactions.
projectPath Path to the source control project.
localProjectPath Local root directory for the project.
auxProjectPath Contains any string that the SCC provider wants to associate with
the project. It has a different meaning for every SCC vendor.
targetName Name of the target for source control operations.
Argument Description
true | false Boolean value for appending to the source control log file. If this
command is not used but a log file is specified, the session value
defaults to “true”.
offline Keyword indicating that an actual SCC connection will not be
required for this session. It is appropriate only when the
ImportOnly refresh option is used on a subsequent scc set
target command. When refreshing a target using ImportOnly,
no communication with the SCC provider is required at runtime,
so the job may be run offline.
refreshType Value can be:
• refresh_all Gets latest version of all objects from the SCC
provider and refreshes all target libraries. Does not perform
comparisons.
• outofdate Performs comparisons and updates objects that
are out of date. If no refreshType value is specified, the
refreshType defaults to outofdate.
Combining values
You can combine compatible refreshType and refreshOption
values (for example, outofdate and exclude_checkout) in the
same string if the values are separated by a blank space.
990 PowerBuilder
APPENDIX B The OrcaScript Language
Source control You can use OrcaScript source control commands instead of the commands to
example set the library list and application. The following is an example of an
OrcaScript session that builds the same libraries as the previous example, but
uses the target properties to set a library list and application:
start session
scc get connect properties "testbld\testbld.pbw"
scc connect
scc set target "c:\testbld\qadbtest\qadbtest.pbt" "outofdate
exclude_checkout"
scc refresh target "incremental"
build library ".\shared_obj\shared_obj.pbl" "" pbd
build library ".\datatypes\datatype.pbl" "" pbd
build library ".\chgreqs\chgreqs.pbl" "" pbd
build executable ".\qadbtest\qadbtest.exe" ".\emp.ico" ".\qadbtest.pbr"
"nyyy"
scc close
end session
You can call the scc connect command only after getting connection properties,
and you must call it before you set or refresh the source-controlled targets. You
must call the scc close command before you end your OrcaScript session.
Set DEBUG example The build application full command in the following example recompiles all of
the objects in the application PBL with the DEBUG condition disabled, and the
buildapp_p.exe application created by the build executable command behaves
exactly like the production application.
start session
set debug false
set liblist "testdebug\buildapp.pbl"
set application "testdebug\buildapp.pbl" "testdebug"
build application full
build executable
"destination_1\buildapp_p.exe" "icon\icon9.ico" "" "N"
end session
Setting the debug value only affects objects that are compiled or regenerated
after the set debug command is issued. The following example copies the PBL
generated from the previous example after it was compiled with the debug
condition disabled. In this example, even though set debug true is called before
it builds the debug_copy.exe executable, the code in DEBUG conditional
compilation blocks is not enabled because none of the commands that follow
the set debug call invoke the PowerScript compiler.
start session
set debug TRUE
992 PowerBuilder
APPENDIX B The OrcaScript Language
SCC connection The SCC get connect properties command is an easy way to populate the Orca
properties SCC connection structure with the source control properties of a local
workspace. However, to create OrcaScript batch files that are portable from
one workstation to another, the recommended technique is to set each property
explicitly. Many of these properties are vendor specific. The best way to obtain
correct values is to copy them directly from the SCC log file for your
PowerBuilder workspace.
After you have obtained the values you need from the SCC log file, you can
create portable batch files by setting the required connection properties and
using relative directories and URLs for path information. The following
example shows portable OrcaScript batch file commands for a workspace that
connects to PBNative:
start session
scc set connect property provider "PB Native"
scc set connect property userid "Jane"
scc set connect property localprojpath ".\"
scc set connect property project "\\network_computer\PBNative_Archive\qadb"
scc set connect property logfile ".\MyPortableExample.log"
scc set connect property logappend "FALSE"
scc set connect property deletetempfiles "FALSE"
scc connect
; Perform refresh and build operations
scc close
end session
Using OrcaScript with You can call scc connect offline to build source control targets offline. When
source control targets you use this command, you must specify ImportOnly as a refresh option. If you
offline
also specify the Refresh_all option or the OutOfDate or Exclude_checkout
refresh types, no connection is made to source control.
For the OutOfDate refresh type, the object source residing in the PBL is
compared with the object source on the local project path. If these object
sources are different, the object source on the local project path is imported and
compiled.
For the Exclude_checkout refresh type, the workspace PBC file is used to
determine current status. In order for the offline exclude_checkout processing
to locate the PBC file, you must use the scc get connect properties
workspaceName command at the beginning of the script. Objects marked as
checked out to the current user in the PBC file will not be imported into the
PBLs during target processing.
994 PowerBuilder
APPENDIX B The OrcaScript Language
Setting refreshType When you set up a target with a source control connection, you can use
and refreshOption refreshType and refreshOption options in various combinations. You can even
values
combine these values in the same string if the values are separated by a blank
space. For example:
scc set target ".\dbauto\dbauto.pbt" "refresh_all
importonly”
Refresh_all option Refresh_all performs no comparisons and imports all
applicable objects. Refresh_all behavior varies depending on whether
ImportOnly is set. If ImportOnly is off, Refresh All issues an
SccGetLatestVersion call to obtain the tip revision of the PBT file specified in
the scc set target command. From the PBT file, it obtains the library list for the
target. It then calls SccGetLatestVersion to obtain the tip revision of the PBG
file associated with each PBL.
Each PBG file contains a list of objects registered under source control that
reside in the associated PBL. Refresh All then issues SccGetLatestVersion to
obtain the tip revision of each object and imports these objects into the PBL.
In offline processing, ImportOnly must be set to on. If you also set the
Refresh_all option, the PBT file that already exists on the local project path is
used to obtain the library list for the target. The PBG file that also exists on the
local project path is then read to obtain a list of objects associated with each
PBL. Refresh_all then processes the PBG lists, importing source entries
residing on the local project path into the appropriate PBL.
ImportOnly option When ImportOnly is on, the expectation is that the user
has already populated the local project path with the desired revision of each
object. ImportOnly is used to build a target from a previous milestone, such as
a version label or a promotion model that does not represent the tip revision of
each object. Therefore, no SccGetLatestVersion calls are issued. The desired
revisions of the PBT, PBG, and object source files must already exist on the
local project path and they are used to import objects into the PBLs. You must
use this option if you are building a source controlled target while you are
offline.
996 PowerBuilder
APPENDIX B The OrcaScript Language
If you use Exclude_checkout processing while offline, the workspace PBC file
is used to determine current status, so you must specify the set get connect
properties workspaceName command. Objects marked as checked out to the
current user in the PBC file will not be imported into the PBLs during target
processing.
Build command OrcaScript build commands for an executable or a library fail if the executable
failures or library already exists in the build directory. To prevent an OrcaScript batch
file containing these commands from failing, move or delete existing
executables and libraries from the build directory before running the batch
script.
Escape characters for OrcaScript, like PowerScript, uses the tilde ( ~ ) as an escape character. If you
string variables need to include a special character, such as a quotation mark, inside a string,
you must place a tilde in front of it. A character in an OrcaScript batch file with
a tilde in front of it is processed as a literal character.
Ending an OrcaScript You must close an OrcaScript session after you finish calling other OrcaScript
session commands. You close an OrcaScript session by calling:
end session
Property values are deleted during end-session processing. If an OrcaScript
program starts numerous sessions, each individual session must contain
statements to specify property values, such as those assigned in set exeinfo or
scc set connect commands. However, variables that you set on a batch script
command line using the /D parameter, or inside a batch file using the set
variable_name=”value” syntax, remain valid for the entire multisession
program.
998 PowerBuilder
Index
1000 PowerBuilder
Index
1002 PowerBuilder
Index
1004 PowerBuilder
Index
1006 PowerBuilder
Index
dot notation E
referring to menu items 347
edges, displaying in DataWindow painter 585
referring to properties of windows and controls 241
Edit edit style
referring to structures 218
defining 626
DoubleClicked event in ListBox control 282
defining code tables with 638
drag and drop events 365
Edit Mask edit style
dragging and dropping, in Database painter 391
defining 630
drawing controls, adding to DataWindow objects 571
defining code tables with 639
drawing objects in windows
spin controls 632
list of 250
edit masks
using 275
keyboard behavior in 278
drop lines, graph 751
using 276
DROP VIEW statement 421
edit style properties 625
drop-down calendar, in EditMask control 278
edit styles
drop-down menus
about 622
about 315
and selection criteria 482
changing order of menu items 327
applying to columns 625
deleting menu items 328
deleting 649
triggering clicked events 345
in databases 400
drop-down toolbars 48
in DataWindow objects 610
DropDownDataWindow edit style
in Specify Retrieval Criteria dialog box 565
defining 633
maintaining 649
defining code tables with 639
working with in Database painter 624
DropDownDataWindow edit style properties 635
working with in DataWindow painter 626
DropDownListBox controls
EditMask controls
defining accelerator keys for 262, 263
defining as spin controls 278
edit property 281
prefix 253
prefix 253
using 276
using 280
EditMask property sheet 277
DropDownListBox edit style
elevation, in 3D graphs 743
defining 627
ellipses, in command buttons 269
defining code tables with 638
Enabled property
DropDownPictureListBox controls
for controls 264
adding images 281, 282
for menu items 330
prefix 253
encapsulated functions 195
using 281
encoding declaration 812
DTD, about 800
Enter key 269
duplicate menu item names 323
Equality Required property 566
duplicate values, index 415
error messages, customizing in validation rules 646
duplicating menu items 326
Error objects
dynamic libraries
default 119
about 955
defining descendent user object 363, 366
execution search path 962
using 908
objects copied to 964
error rows, correcting in pipelines 456
specifying in Project painter 956
errors
dynamic user objects 372
compile 188
1008 PowerBuilder
Index
1010 PowerBuilder
Index
GIF images 270, 274, 275, 284 sorting series and categories 744
global functions specifying categories 734
access level 194 specifying overlap and spacing of bars and columns
opening Function painter 194 747
user-defined 191 specifying pointers 751
global objects specifying properties of axes 748
specifying defaults 119, 374 specifying rows 733
specifying user objects for 374 specifying series 735
global search 152 specifying type 743
global standard class user objects 374 specifying values 734
global structures text properties in 744
about 213 titles in 743
opening Structure painter 214 types of 724
referring to 218 using display formats 746
saving 216 using Graph presentation style 741
global variables using in applications 728
and menu item scripts 346 using in windows 752
and windows 241 GraphType property 743
pasting into scripts 176 grid lines, graph 751
gradients Grid style
for DataWindow objects 548 basic properties 550
graph controls in windows, prefix 253 detail band in 523
graphics, adding to DataWindow objects 572 displaying grid lines 550
graphs of DataWindow objects 469
about 721 reordering columns 537
adding to DataWindow objects 583 resizing columns 536
adding to reports 583 using split horizontal scrolling 537
autosizing text 745 working in 536
changing position of 731 grid, aligning controls in DataWindow objects 586
data types of axes 749 grid, aligning controls in windows 256
default positioning in DataWindow objects 592 group box, adding to DataWindow objects 572
default positioning in reports 592 GROUP BY criteria 501
defining properties 742 group headers, in XML 822
examples 736 Group presentation style
expressions in 746 properties of 660, 782
in DataWindow objects 729 using 658
legends in 743 GroupBox controls in windows
major and minor divisions 750 and radio buttons 272
multiple series 735 default tab order 260
names of 743 prefix 253
parts of 722 GroupBox controls, using 275
placing in windows 752 grouping
rotating text 746 in SQL Select 501
scaling axes 749 restricting 502
selecting data 732 groups in DataWindow objects
single series 735 graphing 733
1012 PowerBuilder
Index
1014 PowerBuilder
Index
local variables, and menu item scripts 346 changing order of 327
locked menu names 323 Clicked event 345
log files deleting 328
about 394 duplicate names 323
saving 394 duplicating 326
logging events 345
exporting table syntax 407 Help event 345
exporting view syntax 421 inserting in descendent menus 350
starting 394 moving 327
stopping 394 navigating in 327
logical operators 483 properties 329, 330
LookUpDisplay function 734 referring to, in scripts 347
renaming 323
Selected event 345
selecting 327
M ShiftToRight 350
mailing labels 469 using variables 346
main windows writing scripts for 344
about 225 Menu painter
specifying window type 231 associating toolbar pictures with menu items 341
major divisions, in graphs 750 inherited menu 348
manifest file opening 320, 321, 338
for standard PowerBuilder applications 956 saving menus 328
security tab 954 workspace 316
masks Menu painter overview 316
for display formats 615 menu properties 332
using 276 menu scripts, calling ancestor scripts 312
Match button with validation rules 645 menus
match patterns, validation rules 645 about 315
Matching Library Entries dialog box 153 associating with windows 232
MDI applications building 316
about 228 calling ancestor functions 312
creating shell 22 creating by inheriting 348
frames 225 creating new 320, 321, 338
MDI frames creating separation lines 326
adding toolbars to 336 deleting menu items 328
menu and toolbar enhancements 340 in descendent objects 307
menu bars moving items in 327
about 315 navigating in 327
adding to windows 354 saving 328
changing order of items 327 using inheritance with 348
deleting items 328 window 315
menu item events 344, 345 message boxes 227
menu items Message objects
about 315 default 119
associating toolbar pictures with 341 defining descendent user object 363, 366
1016 PowerBuilder
Index
1018 PowerBuilder
Index
points, saving text size in 255 of user object names 368, 372
points, specifying size for tables 399 presentation styles
polymorphism 192 of DataWindow objects 466
PopMenu function 355 using Crosstab 753
pop-up menus using Graph 741
controlling toolbars with 48 using Group 658
creating an instance of the menu 355 preview
displaying 355 for crosstabs 763
for toolbars 343 for windows 238
in Library painter 143 retrieving rows 528
use of in applications 315 Preview button 242
pop-up windows Preview view
about 226 in DataWindow painter 528
modal 227 modifying data 530
naming parents of 226 previewing
specifying window type 231 OLE DataWindow objects 872
position windows 238
changing control's 256 primary keys
changing graph? 731 about 410
equalizing 258 defining 412
of windows 234 displaying in Database painter 411
PowerBar identifying updatable rows 597
about 47 joining tables 419, 493
adding custom buttons to 51 modifying 414
controlling display of 48 opening related tables 412
using 14 Print Options dialog box 166
PowerBuilder initialization file, format 58 Print Preview
PowerBuilder units 234 about 533
PowerBuilder, opening from command line 41 command 533
PowerScript print specifications, reports 552
about 7 printing
expressions in computed fields 576 data, using Print Preview 533
statements 199 DataWindow objects 535
PowerTips 336, 343 in Data Manipulation painter 427
assigning text in custom buttons 52 scripts 175
using 15 window definitions 239
predefined objects in applications 119 private libraries, organizing 138
preference variables procedures, defining 196
Default3D 266 processing instructions in XML template 820
for colors 265 profiles, creating from trace file 915
preferences profiles, in pipelines 445
changing print settings 239 profiling an application 915
setting default grid size 257 progress bars, freestanding 280
prefixes Project painter
in window names 237 building an executable 960
of controls, default 253 defining an executable application project 951
1020 PowerBuilder
Index
1022 PowerBuilder
Index
S in windows 239
inherited 308
Save As command, changing function name 200
overriding ancestor 311
Save As dialog box 538
pasting with Browser 176
Save Rows As dialog box 427
printing 175
saving
referring to menu items 322
blob data in databases 879
referring to structures 218
data in DataWindow objects 563
reverting to unedited version 180
data in external files 538
searching for strings in 152
data in HTML Table format 544
writing 171
DataWindow objects 514
scroll bars
layouts in views 46
for text boxes 276
menus 328
freestanding 279
pipelines 442, 457
in list boxes 283
queries 516
on windows 235
reports 514
SDI application 23
structures 216
Search Library Entries dialog box
user-defined functions 199
in Library painter 201
windows 237
using 153
scatter graphs 725
search path
SCC API version control interface 62
for resource files 958
SccMaxArraySize, PB.INI file setting 76
specifying libraries 122
SccMultiCheckout, PB.INI file setting 81
search strings, library entry 152
scope, variable 241
seeing nonvisual objects 374
Script icon
Select All command 251
in Select Event list box 172
Select Application dialog box
of inherited scripts 309
about 24
Script view 113
New button 20
about 171
Select painter
context-sensitive Help 187
adding tables 490
scripts
colors in 490
about 7
defining retrieval arguments 496
changing labels in 272
joining tables 493
changing text size 255
opening 488
compiling 187
saving work as query 488
copying files into 179
selecting tables 489
defined 7
specifying selection, sorting, and grouping criteria
displaying referenced objects 126, 127
498
extending 310
specifying what is displayed 490
for custom visual user objects 372
Select painter overview 488
for descendent user objects 371
Select Pointer property tab page 234
for menu items 344, 346
SELECT statements
for user events 209
building in Database painter 429
for user objects 372
displaying 492
in Application painter 115
editing syntactically 492
in User Object painter 360
for view, displaying 419
in Window painter 228
1024 PowerBuilder
Index
1026 PowerBuilder
Index
1028 PowerBuilder
Index
1030 PowerBuilder
Index
Z
X zero display format 617
Zoom command, in print preview 534
X and Y values
and window position 234
in grid 257
x property 698
x1, x2 property 698
XML
about 799
associating a namespace with a schema 828
Detail Start element 809
exporting 820
exporting metadata 826
header and detail sections 808
importing 830
importing group headers 832
importing with a template 831
importing without a template 835
in the DataWindow painter 803
Iterate Header for Groups 822
Iterate Header for Groups and Detail Start element
809
parsing 802, 804
syntax 801
templates, about 804
templates, creating 806
templates, editing 812
templates, saving 808
tracing import 839
valid and well-formed 800
XML declaration in XML export template 812
XML Schema 801
XSL-FO, saving data as 543
1032 PowerBuilder
Users Guide 1033
1034 PowerBuilder
Users Guide 1035
1036 PowerBuilder
Users Guide 1037
1038 PowerBuilder