Power Builder 9 Data Window Programmers Guide (Manual)
Power Builder 9 Data Window Programmers Guide (Manual)
Power Builder 9 Data Window Programmers Guide (Manual)
PowerBuilder®
9
DOCUMENT ID: 37775-01-0900-01
To order additional documents, U.S. and Canadian customers should call Customer Fulfillment at (800) 685-8225, fax (617) 229-9845.
Customers in other countries with a U.S. license agreement may contact Customer Fulfillment via the above fax number. All other
international customers should contact their Sybase subsidiary or local distributor. 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 Sybase, Inc.
Sybase, the Sybase logo, AccelaTrade, ADA Workbench, Adaptable Windowing Environment, Adaptive Component Architecture,
Adaptive Server, Adaptive Server Anywhere, Adaptive Server Enterprise, Adaptive Server Enterprise Monitor, Adaptive Server
Enterprise Replication, Adaptive Server Everywhere, Adaptive Server IQ, Adaptive Warehouse, Anywhere Studio, Application
Manager, AppModeler, APT Workbench, APT-Build, APT-Edit, APT-Execute, APT-FORMS, APT-Translator, APT-Library, Backup
Server, BizTracker, ClearConnect, Client-Library, Client Services, Convoy/DM, Copernicus, Data Pipeline, Data Workbench,
DataArchitect, Database Analyzer, DataExpress, DataServer, DataWindow, DB-Library, dbQueue, Developers Workbench, Direct
Connect Anywhere, DirectConnect, Distribution Director, e-ADK, E-Anywhere, e-Biz Integrator, E-Whatever, EC Gateway, ECMAP,
ECRTP, eFulfillment Accelerator, Embedded SQL, EMS, Enterprise Application Studio, Enterprise Client/Server, Enterprise Connect,
Enterprise Data Studio, Enterprise Manager, Enterprise SQL Server Manager, Enterprise Work Architecture, Enterprise Work Designer,
Enterprise Work Modeler, eProcurement Accelerator, EWA, Financial Fusion, Financial Fusion Server, Gateway Manager, GlobalFIX,
ImpactNow, Industry Warehouse Studio, InfoMaker, Information Anywhere, Information Everywhere, InformationConnect,
InternetBuilder, iScript, Jaguar CTS, jConnect for JDBC, MainframeConnect, Maintenance Express, MDI Access Server, MDI Database
Gateway, media.splash, MetaWorks, MySupport, Net-Gateway, Net-Library, New Era of Networks, ObjectConnect, ObjectCycle,
OmniConnect, OmniSQL Access Module, OmniSQL Toolkit, Open Biz, Open Client, Open ClientConnect, Open Client/Server, Open
Client/Server Interfaces, Open Gateway, Open Server, Open ServerConnect, Open Solutions, Optima++, PB-Gen, PC APT Execute, PC
Net Library, Power++, power.stop, PowerAMC, PowerBuilder, PowerBuilder Foundation Class Library, PowerDesigner,
PowerDimensions, PowerDynamo, PowerJ, PowerScript, PowerSite, PowerSocket, Powersoft, PowerStage, PowerStudio, PowerTips,
Powersoft Portfolio, Powersoft Professional, PowerWare Desktop, PowerWare Enterprise, ProcessAnalyst, Rapport, Report Workbench,
Report-Execute, Replication Agent, Replication Driver, Replication Server, Replication Server Manager, Replication Toolkit, Resource
Manager, RW-DisplayLib, S-Designor, SDF, Secure SQL Server, Secure SQL Toolset, Security Guardian, SKILS, smart.partners,
smart.parts, smart.script, SQL Advantage, SQL Anywhere, SQL Anywhere Studio, SQL Code Checker, SQL Debug, SQL Edit, SQL
Edit/TPU, SQL Everywhere, SQL Modeler, SQL Remote, SQL Server, SQL Server Manager, SQL SMART, SQL Toolset, SQL Server/
CFT, SQL Server/DBM, SQL Server SNMP SubAgent, SQL Station, SQLJ, STEP, SupportNow, S.W.I.F.T. Message Format Libraries,
Sybase Central, Sybase Client/Server Interfaces, Sybase Financial Server, Sybase Gateways, Sybase MPP, Sybase SQL Desktop, Sybase
SQL Lifecycle, Sybase SQL Workgroup, Sybase User Workbench, SybaseWare, Syber Financial, SyberAssist, SyBooks, System 10,
System 11, System XI (logo), SystemTools, Tabular Data Stream, TradeForce, Transact-SQL, Translation Toolkit, UltraLite.NET,
UNIBOM, Unilib, Uninull, Unisep, Unistring, URK Runtime Kit for UniCode, Viewer, Visual Components, VisualSpeller, VisualWriter,
VQL, WarehouseArchitect, Warehouse Control Center, Warehouse Studio, Warehouse WORKS, Watcom, Watcom SQL, Watcom SQL
Server, Web Deployment Kit, Web.PB, Web.SQL, WebSights, WebViewer, WorkGroup SQL Server, XA-Library, XA-Server and XP
Server are trademarks of Sybase, Inc. 11/02
Unicode and the Unicode Logo are registered trademarks of Unicode, Inc.
All other company and product names used herein may be trademarks or registered trademarks of their respective companies.
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.
iv PowerBuilder
Contents
CHAPTER 8 Using the DataWindow Web Control for ActiveX ..................... 165
About the Web ActiveX ................................................................ 165
HTML for inserting the controls on a Web page........................... 168
Object element ...................................................................... 168
Properties and Param elements............................................ 169
How to use the Web ActiveX in a Web target .............................. 170
DataWindow objects for the Web ActiveX.................................... 173
What the DataWindow object can include............................. 173
Managing DataWindow objects in PowerBuilder libraries ..... 173
Specifying a DataWindow object for the control.................... 174
Using the DataWindow Transaction Object control...................... 175
Making database connections...................................................... 177
Connecting and retrieving data ............................................. 178
Coding for the Web ActiveX ......................................................... 179
Data types for method arguments and return values ............ 179
Setting event return codes .................................................... 180
Deploying the Web ActiveX.......................................................... 180
vi PowerBuilder
About This Book
viii PowerBuilder
CH A PTE R 1 About DataWindow Technology
About this chapter This chapter describes what DataWindow objects are and the ways you
can use them in various application architectures and programming
environments.
Contents
Topic Page
About DataWindow objects, controls, and components 1
Choosing a DataWindow technology 5
PowerBuilder DataWindow control 8
2 PowerBuilder
CHAPTER 1 About DataWindow Technology
For examples of the presentation styles, see the PowerBuilder User’s Guide.
Data sources The data source specifies where the data in the DataWindow comes from and
what data items are displayed. Data can come from tables in a database, or you
can import data from a file or specify the data in code. For databases, the data
specification is saved in a SQL statement. In all cases, the DataWindow object
saves the names of the data items to display, as well as their data types.
Basic process
Using a DataWindow involves two main steps:
1 Use the DataWindow painter to create or edit a DataWindow object.
In the painter, you define the data source, presentation style, and all other
properties of the object, such as display formats, validation rules, sorting
and filtering criteria, and graphs.
2 In your development environment, put a DataWindow control or
component in a window, form, or Web page and associate a DataWindow
object with it.
It is through this control that your application communicates with the
DataWindow object you created in the DataWindow painter. You write
code to manipulate the DataWindow control and the DataWindow object
it contains. Typically, your code retrieves and updates data, changes the
appearance of the data, handles errors, and shares data between
DataWindow controls.
4 PowerBuilder
CHAPTER 1 About DataWindow Technology
Web DataWindow
The Web DataWindow is a thin-client DataWindow implementation for Web
applications. It provides most of the data manipulation, presentation, and
scripting capabilities of the PowerBuilder DataWindow without requiring any
PowerBuilder DLLs on the client.
Functionality The Web DataWindow supports a subset of the PowerBuilder DataWindow
events and methods, including dynamic modification of the DataWindow
object. The user can modify and update data. Graph, OLE, and RichText
presentation styles and controls are not supported.
Client requirements The technology works in any browser, but the appearance of the generated
HTML is usually best in Internet Explorer. Generated HTML can be
dynamically optimized for Netscape or Internet Explorer, or scaled back to
handle older browsers.
Server requirements A component server and a dynamic page server work together to generate a
client control with data and include it in a Web page. Each time the user
requests a new page of data, updates data, or inserts or deletes rows, the server
gets a request to generate a new page. Depending on how state is managed, the
component may retrieve data each time it is called, causing added load on the
server.
Development tools The Web Target interface in PowerBuilder provides the Web DataWindow
DTC that you can use to develop Web DataWindows without hand coding. You
can also write your own server-side scripts to create Web DataWindows using
the component server’s API. You can write the scripts for interpretation by a
specific page server type (PowerDynamo, Active Server Pages, or JavaServer
Pages). For Web site targets, you can use the Web Target object model to write
server scripts that are type-neutral—the scripts can be deployed to either
PowerDynamo or Active Server Pages.
When you use the Web DataWindow DTC on a 4GL Web page, server-side
events are available and page variables can enhance the dynamic capabilities
of your Web application. You cannot hand code a Web DataWindow on a 4GL
Web page.
6 PowerBuilder
CHAPTER 1 About DataWindow Technology
For information about the Web DataWindow, see Chapter 6, “Using the Web
DataWindow.” For information about the Web DataWindow DTC, see
Working with Web and JSP Targets.
DataWindow plug-in
The DataWindow plug-in is a browser plug-in that displays Powersoft reports
(PSRs).
Functionality A PSR is a frozen DataWindow; it cannot be modified and the data does not
stay current. However, a PSR is a compact representation of the DataWindow
definition and data and can be downloaded efficiently. It is an efficient means
of viewing batch-produced reports.
The user cannot modify or update the data.
Client requirements The plug-in executable must be installed in the browser plug-in directory. It
cannot be downloaded and installed automatically. The plug-in works in
Netscape browsers. Internet Explorer browsers prior to version 5.5 also support
the plug-in.
DataWindow behavior that would compromise security of the client, such as
SaveAs, is not disabled.
Development tools You can use PowerBuilder or InfoMaker to create PSRs.
For more information about the plug-in architecture, see Application
Techniques.
8 PowerBuilder
CHAPTER 1 About DataWindow Technology
In the PowerBuilder Browser you can examine the properties, events, and
methods of DataWindow controls and DataStore objects on the system tab
page. If you have a library open that contains DataWindow objects, you can
examine the internal properties of the DataWindow object on the Browser’s
DataWindow tab page.
DataWindow objects The DataWindow control or DataStore object uses a DataWindow object,
which determines what data is retrieved and how it is displayed. The control
can also display Powersoft reports (PSRs), which do not need to retrieve data.
A DataWindow object for a PowerBuilder application can have any
presentation style.
Database connections The PowerBuilder DataWindow can use ODBC, JDBC, and native database
drivers for database connectivity. Users can connect to a data source on any
server to which they have access, including databases and middle-tier servers
on the Internet.
To make a connection, you can use the internal Transaction object of the
DataWindow, or you can make the connection with a separate PowerBuilder
transaction object.
A PowerBuilder application provides a default Transaction object, SQLCA;
you can define additional Transaction objects if you need to make additional
connections. When you connect with a separate Transaction object, you can
control when SQL COMMIT and ROLLBACK statements occur, and you can
use the same connection for multiple controls.
For more information about using a Transaction object with a DataWindow, see
Chapter 2, “Using DataWindow Objects”.
For more information about PowerBuilder Transaction objects, see Application
Techniques in the PowerBuilder documentation set.
Coding You write scripts in the Window or User Object painter to connect to the
database, retrieve data, process user input, and update data.
In PowerBuilder, you can take advantage of object inheritance by defining a
user object inherited from a DataWindow control and adding your own custom
functionality. You can reuse the customized DataWindow control throughout
your applications.
You create DataStore objects, the nonvisual version of a DataWindow control,
by creating them in a script and calling methods for the object. You can also
define a user object that is inherited from a DataStore and customize it. For
more information, see Chapter 4, “Using DataStore Objects”.
Libraries and You store DataWindow objects in PowerBuilder libraries (PBLs) during
applications development. When you build your application, you can include the
DataWindow objects in the application executable or in PowerBuilder dynamic
libraries (PBDs).
For more information about designing DataWindow objects and building a
PowerBuilder application, see the PowerBuilder User’s Guide and Application
Techniques.
10 PowerBuilder
CH A PTE R 2 Using DataWindow Objects
About this chapter This chapter describes how to use DataWindow objects in an application.
Contents
Topic Page
About using DataWindow objects 11
Putting a DataWindow object into a control 12
Accessing the database 18
Importing data from an external source 26
Manipulating data in a DataWindow control 27
Accessing the properties of a DataWindow object 35
Handling DataWindow errors 36
Updating the database 41
Creating reports 45
Using nested reports 47
Using crosstabs 49
Generating HTML 52
Before you begin This chapter assumes that you know how to build DataWindow objects in
the DataWindow painter, as described in the PowerBuilder User’s Guide.
Managing Several painters let you manage and package your DataWindow objects for use
DataWindow objects in applications.
In particular, you can maintain DataWindow objects in one or more libraries
(PBL files). When you are ready to use your DataWindow objects in
applications, you can package them in more compact runtime libraries (PBD
files).
For further details on how to build and organize DataWindow objects, see the
PowerBuilder User’s Guide.
Using DataWindow After you build a DataWindow object (or PSR file) in the DataWindow painter,
objects you can use it to display and process information from the appropriate data
source. The sections that follow explore the details of how to do this.
12 PowerBuilder
CHAPTER 2 Using DataWindow Objects
The DataWindow object name To avoid confusion, you should use different
prefixes for DataWindow objects and DataWindow controls. The prefix d_ is
commonly used for DataWindow objects. For example, if the name of the
DataWindow control is dw_customer, you might want to name the
corresponding DataWindow object d_customer.
14 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Setting the transaction object when you change the DataWindow object
When you change the DataWindow object during execution, you may need to
call setTrans or setTransObject again.
For more information, see “Setting the transaction object for the DataWindow
control” on page 19.
Dynamically creating You can also create a new DataWindow object during execution and associate
a DataWindow object it with a control.
For more information, see Chapter 3, “Dynamically Changing DataWindow
Objects”.
16 PowerBuilder
CHAPTER 2 Using DataWindow Objects
dw_emp.DataObject = "d_emp_hist"
The DataWindow object d_emp_hist was created in the DataWindow painter
and stored in a library on the application search path. The control dw_emp is
contained in the window and is saved as part of the window definition.
Preventing redrawing
You can use the SetRedraw method to turn off redrawing in order to avoid
flicker and reduce redrawing time when you are making several changes to the
properties of an object or control. Dynamically changing the DataWindow
object at execution time implicitly turns redrawing on. To turn redrawing off
again, call the SetRedraw method every time you change the DataWindow
object:
dw_emp.DataObject = "d_emp_hist"
dw_emp.SetRedraw(FALSE)
Using PSR files To put a PSR file into a DataWindow control at execution time, change the
control's DataObject property to specify that PSR file name.
18 PowerBuilder
CHAPTER 2 Using DataWindow Objects
To learn more about setting values for the transaction object, connecting to the
database, and disconnecting from the database, see:
• PowerBuilder Application Techniques, "Using Transaction Objects"
• Web DataWindow “Specifying the database connection and retrieving
data” on page 143
• Web ActiveX “Using the DataWindow Transaction Object control” on
page 175
20 PowerBuilder
CHAPTER 2 Using DataWindow Objects
The transaction object also stores error messages returned from the database in
its properties. You can use the error information to determine whether to
commit or roll back database changes.
When to use it When the DataWindow control uses a separate transaction object, you have
more control of the database processing and are responsible for managing the
database transaction.
There are several reasons to use a separate transaction object:
• You have several DataWindow controls that connect to the same database
and you want to make one database connection for all of them, saving the
overhead of multiple connections
• You want to control transaction processing
• You require the improved performance provided by keeping database
connections open
How it works PowerBuilder The SetTransObject method associates a transaction object
with the DataWindow control. PowerBuilder has a default transaction object
called SQLCA that is automatically instantiated. You can set its connection
properties, connect, and assign it to the DataWindow control.
The following statement uses SetTransObject to associate the DataWindow
control dw_emp with the default transaction object (SQLCA):
// Set connection parameters in the transaction object
SQLCA.DBMS = ...
SQLCA.database = ...
CONNECT USING SQLCA;
dw_emp.SetTransObject(SQLCA)
dw_emp.Retrieve( )
Instead of or in addition to using the predefined SQLCA transaction object, you
can define your own transaction object in a script. This is necessary if your
application needs to connect to more than one database at the same time.
The following statement uses SetTransObject to associate dw_customer with a
programmer-created transaction object (trans_customer):
transaction trans_customer
trans_customer = CREATE transaction
// Set connection parameters in the transaction object
trans_customer.DBMS = ...
trans_customer.database = ...
CONNECT USING trans_customer;
dw_customer.SetTransObject(trans_customer)
dw_customer.Retrieve( )
22 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Web ActiveX To use a separate transaction object for the Web ActiveX, you
add an OBJECT element for the Sybase DataWindow Transaction Object
control to the Web page. You can set its connection properties using Param
elements or a script.
A script that connects and retrieves data would have statements like these:
trans_1.Connect( );
dw_employee.SetTransObject( trans_1 );
dw_employee.Retrieve( );
trans_1.Disconnect( );
For more information For more information about database transaction processing:
• PowerBuilder See the chapter on using transaction objects in
Application Techniques
• Web ActiveX SeeChapter 8, “Using the DataWindow Web Control for
ActiveX”
For more information about SetTrans and SetTransObject methods, see the
DataWindow Reference.
Updating data
After users have made changes to data in a DataWindow control, you can use
the Update method to save those changes in the database.
In PowerBuilder, the code looks like this:
dw_emp.Update()
24 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Update sends to the database all inserts, changes, and deletions made in the
DataWindow control since the last Update method. When you are using an
external transaction object, you can then commit (or roll back) those database
updates. In PowerBuilder, you use SQL statements. In the Web ActiveX, you
use methods and properties of the transaction object. In the Web DataWindow
client control, update requests call the update method in the server component,
which handles the commit or rollback.
For more specifics on how a DataWindow control updates the database (that is,
which SQL statements are sent in which situations), see “Updating the
database” on page 41.
Examples The following example shows code that connects, retrieves, updates, commits
or rolls back, and disconnects from the database.
Although the example shows all database operations in a single script or
function, most applications separate these operations. In a PowerBuilder
application, for example, an application could connect to the database in the
application Open event, retrieve and update data in one or more window
scripts, and disconnect from the database in the application Close event.
PowerBuilder The following statements retrieve and update data using the
transaction object EmpSQL and the DataWindow control dw_emp:
// Connect to the database specified in the
// transaction object EmpSQL
CONNECT USING EmpSQL;
Web ActiveX The following JavaScript statements retrieve and update data
using the transaction object EmpSQL and the DataWindow control dw_emp.
// Connect to the database specified in the
// transaction object EmpSQL
EmpSQL.Connect( );
26 PowerBuilder
CHAPTER 2 Using DataWindow Objects
All environments You can also get data into the DataWindow by using the SetItem method or by
using a DataWindow expression.
For more information on the SetItem method and DataWindow expressions,
see "Manipulating data in a DataWindow control" next.
About the edit control As the user moves around the DataWindow control, the DataWindow places an
edit control over the current cell (row and column):
About text The contents of the edit control are called text. Text is data that has not yet been
accepted by the DataWindow control. Data entered in the edit control is not in
a DataWindow buffer yet; it is simply text in the edit control.
About items When the user changes the contents of the edit control and presses ENTER or
leaves the cell (by tabbing, using the mouse, or pressing UP ARROW or DOWN
ARROW), the DataWindow processes the data and either accepts or rejects it,
depending on whether it meets the requirements specified for the column. If the
data is accepted, the text is moved to the current row and column in the
DataWindow Primary buffer. The data in the Primary buffer for a particular
column is referred to as an item.
Events for changing When data is changed in the edit control, several events occur. The names of
text and items the events are different in each environment, as shown in the table. This chapter
refers to events using PowerBuilder names.
Table 2-2: Event names in different environments
Event Description
PowerBuilder,
Web DataWindow
client control Web ActiveX
EditChanged (not onEditChange Occurs for each keystroke the user
available on client types in the edit control.
control)
28 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Event Description
PowerBuilder,
Web DataWindow
client control Web ActiveX
ItemChanged beforeItemChange Occurs when a cell has been
modified and loses focus.
ItemError onItemError Occurs when new data fails the
validation rules for the column.
ItemFocusChanged onItemFocusChange Occurs when the current item in the
control changes.
How text is processed When the data in a column in a DataWindow has been changed and the column
in the edit control loses focus (for example, because the user tabs to the next column), the
following sequence of events occurs:
1 The DataWindow control converts the text into the correct data type for the
column. For example, if the user is in a numeric column, the DataWindow
control converts the string that was entered into a number. If the data
cannot be converted, the ItemError event is triggered.
2 If the data converts successfully to the correct type, the DataWindow
control applies any validation rule used by the column. If the data fails
validation, the ItemError event is triggered.
3 If the data passes validation, then the ItemChanged event is triggered. If
you set an action/return code of 1 in the ItemChanged event, the
DataWindow control rejects the data and does not allow the focus to
change. In this case, the ItemError event is triggered.
4 If the ItemChanged event accepts the data, the ItemFocusChanged event
is triggered next and the data is stored as an item in a buffer.
Action/return codes You can affect the outcome of events by specifying numeric values in the
for events event’s program code. For example, step 3 above describes how you can force
data to be rejected with a code of 1 in the ItemChanged event.
To specify action/return codes:
• PowerBuilder and Web DataWindow Use a RETURN statement
• Web ActiveX Call the SetActionCode or setActionCode method
For information about codes for individual events, see the DataWindow
Reference.
30 PowerBuilder
CHAPTER 2 Using DataWindow Objects
For more information about these methods, see the DataWindow Reference.
32 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Some, but not all, of these methods are available for the Web DataWindow
client control, server component, or both. Each development environment
provides a reference list of methods. For a complete list of DataWindow
methods, see the PowerBuilder Browser for PowerScript targets or the
Components tab of the System Tree for Web targets.
For complete information on DataWindow methods, see the DataWindow
Reference.
34 PowerBuilder
CHAPTER 2 Using DataWindow Objects
The following statement changes the value of the Border property for the
empname column to 1:
dw_emp.Modify("empname.Border=1");
Using expressions DataWindow property expressions provide access to properties with fewer
nested strings. In PowerBuilder, you can handle problems with incorrect object
and property names in the Error event:
PowerBuilder Use the Object property and dot notation. For example:
integer li_border
li_border = Integer(dw_1.Object.empname.Border)
dw_1.Object.empname.Border = 1
For reference material on the available variations for property expressions, see
the DataWindow Reference.
36 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Table 2-4: Return codes for the Retrieve and Update methods
Return
Method code Meaning
Retrieve >=1 Retrieval succeeded; returns the number of rows retrieved.
-1 Retrieval failed; DBError event triggered.
0 No data retrieved.
Update 1 Update succeeded.
-1 Update failed; DBError event triggered.
trans_a.Rollback( );
}
Using the DBError The DataWindow control triggers its DBError event whenever there is an error
event following a retrieval or update; that is, if the Retrieve or Update methods return
–1. For example, if you try to insert a row that does not have values for all
columns that have been defined as not allowing NULL, the DBMS rejects the
row and the DBError event is triggered.
By default, the DataWindow control displays a message box describing the
error message from the DBMS:
In many cases you may want to code your own processing in the DBError event
and suppress the default message box. Here are some tips for doing this:
Table 2-5: Tips for processing messages from DBError event
To Do this
Get the DBMS's error code Use the SQLDBCode argument of the DBError
event.
Get the DBMS's message text Use the SQLErrText argument of the DBError
event.
Suppress the default message box Specify an action/return code of 1.
38 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Web ActiveX In JavaScript, the code for the DBError event might look like
this:
// Database error -195 means that some of the
// required values are missing
if (sqldbcode == -195) {
alert("Missing information:\n" +
"You have not supplied values for all " +
"the required fields.");
}
// Action code suppresses default message box
dw_1.SetActionCode(1);
If the emp_name column did not exist in the DataWindow, or if you had
misspelled the property name, the compiler would not detect the error.
However, at execution time, PowerBuilder would trigger the DataWindow
control’s Error event.
Using a Try-Catch The Error event is triggered even if you have surrounded an error producing
block data or property expression in a Try-Catch block. The catch statement is
executed after the Error event is triggered, but only if you do not code the Error
event or do not change the default Error event action from ExceptionFail!. The
following example shows a property expression in a Try-Catch block:
TRY
dw_1.Object.emp_name.Visible = "0"
CATCH (dwruntimeerror dw_e)
MessageBox (“DWRuntimeError”, dw_e.text)
END TRY
Determining the cause The Error event has several arguments that provide information about the error
of the error condition. You can check the values of the arguments to determine the cause of
the error. For example, you can obtain the internal error number and error text,
the name of the object whose script caused the error, and the full text of the
script where the error occurred. The information provided by the Error event’s
arguments can be helpful in debugging expressions that are not checked by the
compiler.
If you catch a DWRuntimeError error, you can use the properties of that class
instead of the Error event arguments to provide information about the error
condition. The following table displays the correspondences between the Error
event arguments and the DWRuntimeError properties.
Table 2-6: Correspondence between Error event arguments and
DWRuntimeError properties
Error event argument DWRuntimeError property
errornumber number
errorline line
errortext text
errorwindowmenu objectname
errorobject class
errorscript routinename
Controlling the When the Error event is triggered, you can have the application ignore the error
outcome of the event and continue processing, substitute a different return value, or escalate the error
by triggering the SystemError event. In the Error event, you can set two
arguments passed by reference to control the outcome of the event.
40 PowerBuilder
CHAPTER 2 Using DataWindow Objects
For a complete description of the arguments of the Error event, see the
DataWindow Reference.
How statuses are set When data is retrieved When data is retrieved into a DataWindow, all rows
and columns initially have a status of NotModified!.
After data has changed in a column in a particular row, either because the user
changed the data or the data was changed programmatically, such as through
the SetItem method, the column status for that column changes to
DataModified!. Once the status for any column in a retrieved row changes to
DataModified!, the row status also changes to DataModified!.
When rows are inserted When a row is inserted into a DataWindow, it
initially has a row status of New!, and all columns in that row initially have a
column status of NotModified!. After data has changed in a column in the row,
either because the user changed the data or the data was changed
programmatically, such as through the SetItem method, the column status
changes to DataModified!. Once the status for any column in the inserted row
changes to DataModified!, the row status changes to NewModified!.
When a DataWindow column has a default value, the column’s status does not
change to DataModified! until the user makes at least one actual change to a
column in that row.
42 PowerBuilder
CHAPTER 2 Using DataWindow Objects
When Update is called For rows in the Primary and Filter buffers When the Update method is
called, the DataWindow control generates SQL INSERT and UPDATE
statements for rows in the Primary and/or Filter buffers based upon the
following row statuses:
Table 2-9: Row status after INSERT and UPDATE statements
Row status SQL statement generated
NewModified! INSERT
DataModified! UPDATE
Changing column You use SetItemStatus to change the column status from DataModified! to
status NotModified!, or vice versa.
Changing row status Changing row status is a little more complicated. The following table
illustrates the effect of changing from one row status to another:
Table 2-10: Effects of changing from one row status to another
Specified status
Original status New! NewModified! DataModified! NotModified!
New! - Yes Yes No
NewModified! No - Yes New!
DataModified! NewModified! Yes - Yes
NotModified! Yes Yes Yes -
In the preceding table, Yes means the change is valid. For example, issuing
SetItemStatus on a row that has the status NotModified! to change the status to
New! does change the status to New!. No means that the change is not valid
and the status is not changed.
Issuing SetItemStatus to change a row status from NewModified! to
NotModified! actually changes the status to New!. Issuing SetItemStatus to
change a row status from DataModified! to New! actually changes the status to
NewModified!.
Changing a row's status to NotModified! or New! causes all columns in that
row to be assigned a column status of NotModified!. Change the column’s
status to DataModified! to ensure that an update results in a SQL Update.
44 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Creating reports
You can use DataWindow objects to create standard business reports such as
financial statements, sales order reports, employee lists, or inventory reports.
To create a production report, you:
• Determine the type of report you want to produce
• Build a DataWindow object to display data for the report
• Place the DataWindow object in a DataWindow control on a window or
form
• Write code to perform the processing required to populate the
DataWindow control and print the contents as a report
Using fonts
Printer fonts are usually shorter and fatter than screen fonts, so text may not
print in the report exactly as it displays in the DataWindow painter. You can pad
the text fields to compensate for this discrepancy.
You should test the report format with a small amount of data before you print
a large report.
46 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Availability
Composite and nested reports are not available in the Web DataWindow.
To learn about designing nested reports, see the PowerBuilder User's Guide.
Printing multiple An advantage of composite reports is that you can print multiple reports on a
updatable page. A limitation of composite reports is that they are not updatable, so you
DataWindows on a
page cannot directly print several updatable DataWindows on one page. However,
there is an indirect way to do that, as follows.
You can use the GetChild method on named nested reports in a composite
report to get a reference to a nested report. After getting the reference to the
nested report, you can address the nested report during execution like other
DataWindows.
Using this technique, you can call the ShareData method to share data between
multiple updatable DataWindow controls and the nested reports in your
composite report. This allows you to print multiple updatable DataWindows on
a page through the composite report.
3 Add the composite report to the window or form (it can be hidden).
Re-retrieving data
Each time you retrieve data into the composite report, all references (handles)
to nested reports become invalid, and data sharing with the nested reports is
terminated. Therefore, be sure to call GetChild and ShareData each time after
retrieving data.
Creating and You can create and destroy nested reports in a DataWindow object dynamically
destroying nested during execution using the same technique you use to create and destroy other
reports during
execution controls in a DataWindow object.
Creating nested reports To create a nested report, use the CREATE
keyword with the Modify method. Supply the appropriate values for the nested
report's properties.
When creating a nested report, you need to re-retrieve data to see the report. In
a composite report, you can either retrieve data for the whole report or use
GetChild to get a reference to the new nested report and retrieve its data
directly. For nested reports in other reports, you need to retrieve data for the
base report.
Destroying nested reports To destroy a nested report, use the DESTROY
keyword with the Modify method. The nested report disappears immediately.
48 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Using crosstabs
To perform certain kinds of data analysis, you may want to design
DataWindow objects in the Crosstab presentation style. The basic steps for
using crosstabs in an application are the same ones you follow for the other
DataWindow types, but there are some additional topics concerning crosstabs
that you should know about.
To learn about designing crosstabs, see the PowerBuilder User's Guide.
For more about composite DataWindows, see the PowerBuilder User's Guide.
Availability
This technique is available in PowerBuilder and the Web ActiveX.
With the CrosstabDialog method, you can allow users to redefine which
columns in the retrieved data are associated with the crosstab's columns, rows,
and values during execution.
The CrossTabDialog method displays the Crosstab Definition dialog box for
the user to define the data for the crosstab's columns, rows, and values (using
the same techniques you use in the DataWindow painter). When the user clicks
OK in the dialog box, the DataWindow control rebuilds the crosstab with the
new specifications.
Displaying You can display informational messages when a crosstab is rebuilt during
informational execution as a result of the call to CrosstabDialog. (The messages are the same
messages
ones you see when building a crosstab in the DataWindow painter, such as
Retrieving data and Building crosstab.) You may want to do this if
you are working with a very large number of rows and rebuilding the crosstab
could take a long time.
PowerBuilder In PowerBuilder, you use a user event to display the crosstab’s
informational messages.
50 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Availability
You can use this technique in all DataWindow environments.
Changes that do not You can change the following properties without forcing the DataWindow
force a rebuild control to rebuild the crosstab:
Changes that force a If you change any other properties, the DataWindow control rebuilds the
rebuild structure of the crosstab when Modify is called. You should combine all needed
expressions into one Modify call so that the DataWindow control has to rebuild
the crosstab only once.
Default values for For computations derived from existing columns, the DataWindow control by
properties default uses the properties from the existing columns. For completely new
columns, properties (such as font, color, and so on) default to the first column
of the preexisting crosstab. Properties for text in headers default to the
properties of the first text control in the preexisting crosstab's first header line.
For more about the Modify method, see Chapter 3, “Dynamically Changing
DataWindow Objects”. For details on the DataWindow object properties, see
the DataWindow Reference.
Generating HTML
You can use the data in a DataWindow object to create HyperText Markup
Language (HTML) syntax. Once the HTML has been created, you can display
it in a Web browser.
52 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Web DataWindow
This section does not describe the Web DataWindow. The Web DataWindow
uses DataWindow object properties that are described in Chapter 6, “Using the
Web DataWindow” and the DataWindow Reference. In particular, see the
Data.HTML and HTMLGen properties.
Techniques you can You can use any of several techniques to generate HTML from a DataWindow
use object.
In a painter In both the DataWindow painter and the Output view in the
Database painter, you can save retrieved data in HTML format. To do this in
the DataWindow painter, select File>Save Rows As from the menu. In the
Database painter, open the Output view, then select Rows>Save Rows As from
the menu. In both painters, specify HTML Table as the format for the file.
In your application code You can obtain an HTML string of the
DataWindow presentation and data from the Data.HTMLTable property. You
can save the string in a variable and modify the HTML with string
manipulation operations. In PowerBuilder, you can also use the FileOpen and
FileWrite functions to save the HTML to a file.
The HTMLTable property has its own properties which you can set to control
the HTML attributes and style sheet associated with the Table HTML element.
PowerBuilder only In PowerBuilder, there are two more techniques
available to you. You can:
• Call the SaveAs method to save the contents of a DataWindow directly to
a file on disk. To save the data in HTML format, you need to specify
HTMLTable as the file type when you call SaveAs.
• Call the GenerateHTMLForm method to create an HTML form from data
contained in a DataWindow control or DataStore whose DataWindow
object uses the Freeform or Tabular presentation style.
Choosing presentation Some DataWindow presentation styles translate better into HTML than others.
styles The following presentation styles produce good results:
Tabular
Group
Freeform
Crosstab
Grid
The Composite, Graph, RichText, and OLE 2.0 presentation styles produce
HTML output that is based on the result only, and not on the presentation style.
DataWindows that have overlapping controls may not produce the expected
results. Nested reports are ignored; they are not included in the generated
HTML.
Example This example illustrates how you might use DataWindow-generated HTML in
an application.
The key line of code gets the HTML from the DataWindow by referring to its
HTMLTable property. Variations for each environment are shown below. In
PowerBuilder, you can use the Describe method or a property expression. The
Web ActiveX has to use Describe.
PowerBuilder
ls_htmlstring = dw_1.Object.DataWindow.Data.HTMLTable
Web ActiveX
str_html = dw_1.Describe("DataWindow.Data.HTMLTable");
The complete example that follows is implemented in PowerBuilder.
The window below displays customer data in a tabular DataWindow object. By
pressing the Browse button, the user can translate the contents of the
DataWindow object into HTML format and invoke a Web browser to view the
HTML output. By pressing the Select Browser button, the user can tell the
application which Web browser to use:
54 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Script for the Select Browser button The script for the Select Browser
button displays a dialog box where the user can select an executable file for a
Web browser. The path to the executable is stored in is_Browser, which is an
instance variable defined on the window:
String ls_BrowserName
Integer li_Result
IF li_Result = -1 THEN
MessageBox("No Browser", "No Browser selected")
END IF
Script for the Browse button The script for the Browse button creates an
HTML string from the data in the DataWindow by assigning the
Data.HTMLTable property to a string variable. After constructing the HTML
string, the script adds a header to the HTML string. Then the script saves the
HTML to a file and runs the Web browser to display the output:
String ls_HTML, ls_FileName, ls_BrowserPath
Integer li_FileNumber, li_Bytes,
Integer li_RunResult, li_Result
Controlling display
You control table display and style sheet usage through the
HTMLTable.GenerateCSS property. The HTMLTable.GenerateCSS property
controls the downward compatibility of the HTML found in the HTMLTable
property. If HTMLTable.GenerateCSS is FALSE, formatting (style sheet
references) is not referenced in the HTMLTable property; if it is TRUE, the
HTMLTable property includes elements that reference the cascading style
sheet saved in HTML.StyleSheet.
56 PowerBuilder
CHAPTER 2 Using DataWindow Objects
This screen shows an HTML table in a browser using custom display features:
58 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Availability
The SaveAs method is not available for the Web control for ActiveX.
.3{COLOR:#000000;BACKGROUND:#ffffff;FONT-
STYLE:normal;FONT-WEIGHT:normal;FONT:8pt "MS Sans
Serif", sans-serif;TEXT-DECORATION:none}
.3{COLOR:#000000;BACKGROUND:#ffffff;FONT-
STYLE:normal;FONT-WEIGHT:normal;FONT:8pt "MS Sans
Serif", sans-serif;TEXT-DECORATION:none}
-->
</STYLE>
Edit style conversion The GenerateHTMLForm method converts column edit styles into the
appropriate HTML elements:
Table 2-12: HTML elements generated for column edit styles
Column edit style HTML element
CheckBox Input element specifying TYPE=CHECKBOX.
DropDownDataWindow Select element with a single Option element.
DropDownListBox Select element with one Option element for each item
in the DropDownListBox.
60 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Generating syntax To generate HTML form syntax, you call the GenerateHTMLForm method:
instancename.GenerateHTMLForm ( syntax, style, action { , startrow,
endrow, startcolumn, endcolumn { , buffer } } )
The method places the Form element syntax into the syntax argument and the
HTML style sheet into the style argument, both of which are passed by
reference.
IF li_return = -1 THEN
MessageBox("HTML", "GenerateHTMLForm failed")
ELSE
// of_MakeHTMLPage is an object method,
// described in the next section.
ls_html = this.of_MakeHTMLPage &
(ls_syntax, ls_style)
END IF
After calling the GenerateHTMLForm method, the ls_syntax variable contains
a Form element. Here is an example:
<FORM ACTION=
"/cgi-
bin/pbcgi60.exe/myapp/uo_webtest/f_emplist"
METHOD=POST>
<P>
<P><FONT CLASS=2>Employee ID:</FONT>
<INPUT TYPE=TEXT NAME="emp_id_1" VALUE="501">
<P><FONT CLASS=2>Status:</FONT>
<INPUT TYPE="RADIO" NAME="status_1" CHECKED CLASS=5
><FONT CLASS=5 >Active
<P>
<INPUT TYPE="RADIO" NAME="status_1" CLASS=5 >
<FONT CLASS=5 >Terminated
<P>
<INPUT TYPE="RADIO" NAME="status_1" CLASS=5 >
<FONT CLASS=5 >On Leave
<P>
<P>
<BR>
<INPUT TYPE=SUBMIT NAME=SAMPLE VALUE="OK">
</FORM>
The ls_stylesheet variable from the previous example contains a Style element,
an example of which is shown below:
<STYLE TYPE="text/css">
<!--
.2{COLOR:#000000;BACKGROUND:#ffffff;FONT-
STYLE:normal;FONT-WEIGHT:normal;FONT:9pt "Arial",
sans-serif;TEXT-DECORATION:none}
.3{COLOR:#000000;BACKGROUND:#ffffff;FONT-
STYLE:normal;FONT-WEIGHT:normal;FONT:8pt "MS Sans
Serif", sans-serif;TEXT-DECORATION:none}
.5{COLOR:#000000;BACKGROUND:#ffffff;FONT-
STYLE:normal;FONT-WEIGHT:normal;FONT:8pt "MS Sans
Serif", sans-serif;TEXT-DECORATION:none}
-->
</STYLE>
62 PowerBuilder
CHAPTER 2 Using DataWindow Objects
Creating an HTML To use the syntax and style sheet returned by the GenerateHTMLForm method,
page you must write code to merge them into an HTML page. A complete HTML
page requires <HTML> and <BODY> elements to contain the style sheet and
syntax.
One way to do this is to create a global or object function that returns a
complete HTML page, taking as arguments the Form and Style elements
generated by the GenerateHTMLForm method. Such a function might contain
the following code:
// Function Name: of_MakeHTMLPage
// Arguments: String as_syntax, String as_style
// Returns: String
//***********************************
String ls_html
IF as_syntax = "" THEN
RETURN ""
END IF
ls_html = "<HTML>"
ls_html += as_style
ls_html += "<BODY>"
ls_html += "<H1>Employee Information</H1>"
ls_html += as_syntax
ls_html += "</BODY></HTML>"
RETURN ls_html
64 PowerBuilder
CH A PTE R 3 Dynamically Changing
DataWindow Objects
About this chapter This chapter describes how to modify and create DataWindow objects
during execution.
Contents
Topic Page
About dynamic DataWindow processing 65
Modifying a DataWindow object 66
Creating a DataWindow object 67
Providing query ability to users 70
Providing Help buttons 74
Reusing a DataWindow object 75
What you can do Using this dynamic capability, you can allow users to change the appearance
of the DataWindow object (for example, change the color and font of the text)
or create ad hoc queries by redefining the data source. After you create a
dynamic DataWindow object and the user is satisfied with the way it looks and
the data that is displayed, the user can print the contents as a report.
66 PowerBuilder
CHAPTER 3 Dynamically Changing DataWindow Objects
This lets you add DataWindow controls (such as text, bitmaps, and graphic
controls) dynamically to the DataWindow object.
For how to get a good idea of the correct Create syntax, see “Specifying
the DataWindow object syntax” on page 68.
• Destroy controls in a DataWindow object
This lets you dynamically remove controls you no longer need.
PowerBuilder tool for PowerBuilder only Included with PowerBuilder is DW Syntax, a tool that
easier coding of makes it easy to build the correct syntax for property expressions, Describe,
DataWindow syntax
Modify, and SyntaxFromSQL statements. You click buttons to specify which
properties of a DataWindow you want to use, and DW Syntax automatically
builds the appropriate syntax, which you can copy and paste into your
application code.
To access DW Syntax, select File>New and select the Tool tab.
Viewing DataWindow PowerBuilder only You can use the PowerBuilder Browser to get a list of
object properties in DataWindow properties: on the DataWindow tab, select a DataWindow object
PowerBuilder
in the left pane and Properties in the right pane. To see the properties for a
control in a DataWindow object, double-click the DataWindow object name,
then select the control.
DataWindow painter
You should use the techniques described here for creating a DataWindow from
syntax only if you cannot accomplish what you need to in the DataWindow
painter. The usual way of creating DataWindow objects is to use the
DataWindow painter.
To learn about creating DataWindow objects in the DataWindow painter, see
the PowerBuilder User's Guide.
You use the Create method to create a DataWindow object dynamically during
execution. Create generates a DataWindow object using source code that you
specify. It replaces the DataWindow object currently in the specified
DataWindow control with the new DataWindow object.
Specifying the There are several ways to specify or generate the syntax required for the Create
DataWindow object method. Not all the techniques are available in all environments.
syntax
In PowerBuilder, you can:
• Use the SyntaxFromSQL method of the transaction object
• Use the LibraryExport PowerScript function
In all environments, you can:
• Use the DataWindow.Syntax property of the DataWindow object
• Create the syntax yourself
Using SyntaxFromSQL You are likely to use SyntaxFromSQL to create the
syntax for most dynamic DataWindow objects. If you use SyntaxFromSQL, all
you have to do is provide the SELECT statement and the presentation style.
In PowerBuilder, SyntaxFromSQL is a method of the transaction object. The
transaction object must be connected when you call the method.
68 PowerBuilder
CHAPTER 3 Dynamically Changing DataWindow Objects
• The name of a string you want to fill with any error messages that may
result
SyntaxFromSQL returns the complete syntax for a DataWindow object that is
built using the specified SELECT statement.
Limitations
You cannot use query mode in a DataWindow object that contains the UNION
keyword or nested SELECT statements.
70 PowerBuilder
CHAPTER 3 Dynamically Changing DataWindow Objects
Next, query mode is turned on. The retrieved data disappears and users are
presented with empty rows where they can specify selection criteria. Here the
user wants to retrieve rows where Quarter = Q1 and Units > 15:
Next, Retrieve is called and query mode is turned off. The DataWindow control
adds the criteria to the SELECT statement, retrieves the three rows that meet
the criteria, and displays them to the user:
You can turn query mode back on, allow the user to revise the selection criteria,
and retrieve again.
How the criteria affect Criteria specified by the user are added to the SELECT statement that
the SELECT originally defined the DataWindow object.
statement
For example, if the original SELECT statement was:
SELECT printer.rep, printer.quarter, printer.product,
printer.units
FROM printer
WHERE printer.units < 70
72 PowerBuilder
CHAPTER 3 Dynamically Changing DataWindow Objects
In PowerBuilder:
dw_1.Modify("mycolumn.criteria.override_edit=yes")
In JavaScript:
dw_1.Modify("mycolumn.criteria.override_edit=yes");
You can also specify this in the DataWindow painter by checking Override Edit
on the General property page for the column. With properties overridden for
criteria, users can specify any number of characters in a cell (they are not
constrained by the number of characters allowed in the column in the
database).
Forcing users to You can force users to specify criteria for a column during query mode by
specify criteria for a coding the following:
column
In PowerBuilder:
dw_1.Modify("mycolumn.criteria.required=yes")
In JavaScript:
dw_1.Modify("mycolumn.criteria.required=yes");
You can also specify this in the DataWindow painter by checking Equality
Required on the General property page for the column. Doing this ensures that
the user specifies criteria for the column and that the criteria for the column use
= rather than other operators, such as < or >=.
74 PowerBuilder
CHAPTER 3 Dynamically Changing DataWindow Objects
You can reuse a DataWindow object by retrieving its syntax from the library it
is stored in, then using the syntax to create a DataWindow object dynamically
in a DataWindow control.
Here is a typical way to accomplish this in an application. Use:
• The LibraryDirectory function to obtain a list of DataWindow objects and
other library entries in the current library
• A DropDownListBox to list the DataWindow objects in the library and
then allow the user to select a DataWindow from the list
• The LibraryExport function to export the selected DataWindow object
syntax into a string variable
• The Create method to use the DataWindow syntax to create the
DataWindow object in the specified DataWindow control
• The Describe method to get the current DataWindow object syntax—for
example:
string dwSyntax
dwSyntax = dw_1.Describe("datawindow.syntax")
• The Modify method to allow the user to modify the DataWindow object
• The LibraryImport function to save the user-modified DataWindow object
in a library
For information about the PowerScript functions, see the PowerScript
Reference. For information about the DataWindow methods Create, Describe,
and Modify, see the DataWindow Reference.
76 PowerBuilder
CH A PTE R 4 Using DataStore Objects
About this chapter This chapter describes how to use DataStore objects in an application.
Contents
Topic Page
About DataStores 77
Working with a DataStore 80
Using a custom DataStore object 80
Accessing and manipulating data in a DataStore 82
Sharing information 84
Before you begin This chapter assumes you know how to build DataWindow objects in the
DataWindow painter, as described in the PowerBuilder User’s Guide.
About DataStores
A DataStore is a nonvisual DataWindow control. DataStores act just like
DataWindow controls except that they do not have many of the visual
characteristics associated with DataWindow controls. Like a DataWindow
control, a DataStore has a DataWindow object associated with it.
Availability
In PowerBuilder, a DataStore is a nonvisual object. The Web control for
ActiveX does not support DataStores.
The Web DataWindow server component uses an instance of a custom
DataStore object to hold the DataWindow definition and data. See “Using
a custom DataStore object” on page 80.
When to use a DataStore DataStores are useful when you need to access data but do not need the
visual presentation of a DataWindow control. DataStores allow you to:
When a window shows multiple views of the same information, you can
use a DataStore to hold the result set. By sharing data between a DataStore
and one or more DataWindow controls, you can provide different views of
the same information without retrieving the data more than once.
• Manipulate table rows without using embedded SQL statements
In places where an application calls for row manipulation without the need
for display, you can use DataStores to handle the database processing
instead of embedded SQL statements. DataStores typically perform faster
at execution time than embedded SQL statements. Also, because the SQL
is stored with the DataWindow object when you use a DataStore, you can
easily reuse the SQL.
• Perform database access on an application server
78 PowerBuilder
CHAPTER 4 Using DataStore Objects
SetSort and SetFilter You can use the SetSort and SetFilter methods to
specify sort and filter criteria for a DataStore object, just as you would with a
DataWindow control. However, when you are working with a DataWindow
control, if you pass a NULL value to either SetSort or SetFilter, the
DataWindow prompts the user to enter information. When you’re working
with a DataStore, you must supply a valid format when you call the method.
Moreover, you must supply a valid format when you share data between a
DataStore and a DataWindow control; you cannot pass the NULL value to the
DataWindow control rather than the DataStore.
Prompt for Criteria You can define your DataWindow objects so that the
user is prompted for retrieval criteria before the DataWindow retrieves data.
This feature works with DataWindow controls only. It is not supported with
DataStores.
SaveAs When you use the SaveAs method with a DataWindow object, you
can pass an empty string for the filename argument so that the user is prompted
for a file name to save to. If you are working with a DataStore, you must supply
the filename argument.
Prompt for Printing For DataWindow controls, you can specify that a print
setup dialog box display at execution time, either by checking the Prompt
Before Printing checkbox on the DataWindow object’s Print Specifications
property page, or by setting the DataWindow object’s Print.Prompt property in
a script. This is not supported with DataStores.
Retrieval arguments If you call the Retrieve method for a DataWindow
control that has a DataWindow object that expects an argument, but do not
specify the argument in the method call, the DataWindow prompts the user for
a retrieval argument. This behavior is not supported with DataStores.
DataStores have Many of the methods and events that pertain to the visual presentation of the
some visual methods data in a DataWindow do not apply to DataStores. However, because you can
print the contents of a DataStore and also import data into a DataStore,
DataStores have some visually oriented events and methods. For example,
DataStores support the SetBorderStyle and SetSeriesStyle methods so that you
can control the presentation of the data at print time. Similarly, DataStores
support the ItemError event, because data imported from a string or file that
does not pass the validation rules for a column triggers this event.
For a complete list of the methods and events for the DataStore object and
information about each method, see the DataWindow Reference.
DataStores require no Unlike DataWindow controls, DataStores do not require any visual overhead
visual overhead in a window. Using a DataStore is therefore more efficient than hiding a
DataWindow control in a window.
80 PowerBuilder
CHAPTER 4 Using DataStore Objects
82 PowerBuilder
CHAPTER 4 Using DataStore Objects
About the Edit control The DataStore object has an Edit control. However, the Edit control for a
DataStore behaves in a slightly different manner from the Edit control for a
DataWindow. The Edit control for a DataWindow keeps track of text entered
by the user in the current cell (row and column); the Edit control for a
DataStore is used to manage data imported from an external source, such as the
clipboard or a file. The text in the Edit control for a DataStore cannot be
changed directly by the user. It must be manipulated programmatically.
Programming with There are many methods for manipulating DataStore objects. These are some
DataStores of the more commonly used:
Table 4-2: Common methods in DataStore objects
Method Purpose
DeleteRow Deletes the specified row from the DataStore.
Filter Filters rows in the DataStore based on the current filter criteria.
InsertRow Inserts a new row.
Print Sends the contents of the DataStore to the current printer.
Reset Clears all rows in the DataStore.
Retrieve Retrieves rows from the database.
RowsCopy Copies rows from one DataStore to another DataStore or
DataWindow control.
RowsMove Moves rows from one DataStore to another DataStore or
DataWindow control.
ShareData Shares data among different DataStores or DataWindow controls.
See “Sharing information” on page 84.
Sort Sorts the rows of the DataStore based on the current sort criteria.
Update Sends to the database all inserts, changes, and deletions that have
been made since the last Update.
Property and data expressions You can use the same property and data
expressions as for the DataWindow control. For information, see the
DataWindow Reference.
Using DataStore properties and events This chapter mentions only a few
of the properties and events that you can use to manipulate DataStores. For
more information about DataStore properties and events, see the DataWindow
Reference.
Sharing information
The ShareData method allows you to share a result set among two different
DataStores or DataWindow controls. When you share information, you remove
the need to retrieve the same data multiple times.
The ShareData method shares data retrieved by one DataWindow control or
DataStore (called the primary DataWindow) with another DataWindow control
or DataStore (the secondary DataWindow).
Result set When you share data, the result set descriptions for the DataWindow objects
descriptions must must be the same. However, the SELECT statements can be different. For
match
example, you could use the ShareData method to share data between
DataWindow objects that have the following SELECT statements (because the
result set descriptions are the same):
SELECT dept_id from dept
84 PowerBuilder
CHAPTER 4 Using DataStore Objects
86 PowerBuilder
CHAPTER 4 Using DataStore Objects
When the window or When the window closes, the DataStore gets destroyed.
form closes
This code is for the window’s Close event:
destroy ids_datastore
When the Employee Salary Information radio button is selected, the window
displays a graph that shows employee salary information by department:
This window has one DataWindow control called dw_display. It uses two
DataStores to process data retrieved from the database. The first DataStore
(ids_emp_list) shares its result set with the second DataStore (ids_emp_graph).
The DataWindow objects associated with the two DataStores have the same
result set description.
When the window or When the window or form opens, the application sets the mouse pointer to the
form opens hourglass shape. Then the code creates the two DataStores and sets the
DataWindow objects for the DataStores. Next the code sets the transaction
object for ids_emp_list and issues a Retrieve method to retrieve some data.
After retrieving data, the code shares the result set for ids_emp_list with
ids_emp_graph. The final statement triggers the Clicked event for the
Employee List radio button.
This code is for the window’s Open event:
SetPointer(HourGlass!)
ids_emp_list = Create DataStore
ids_emp_graph = Create DataStore
ids_emp_list.DataObject = "d_emp_list"
ids_emp_graph.DataObject = "d_emp_graph"
ids_emp_list.SetTransObject(sqlca)
ids_emp_list.Retrieve()
ids_emp_list.ShareData(ids_emp_graph)
rb_emp_list.EVENT Clicked()
Code for the The code for the Employee List radio button (called rb_emp_list) sets the
Employee List radio DataWindow object for the DataWindow control to be the same as the
button
DataWindow object for ids_emp_list. Then the script displays the data by
sharing the result set for the ids_emp_list DataStore with the DataWindow
control.
This code is for the Employee List radio button’s Clicked event:
dw_display.DataObject = ids_emp_list.DataObject
ids_emp_list.ShareData(dw_display)
Code for the The code for the Employee Salary Information radio button (called rb_graph)
Employee Salary is similar to the code for the List radio button. It sets the DataWindow object
Information radio
button for the DataWindow control to be the same as the DataWindow object for
ids_emp_graph. Then it displays the data by sharing the result set for the
ids_emp_graph DataStore with the DataWindow control.
This code is for the Employee Salary Information radio button’s Clicked event:
dw_display.DataObject = ids_emp_graph.DataObject
ids_emp_graph.ShareData(dw_display)
88 PowerBuilder
CHAPTER 4 Using DataStore Objects
When the window or When the window closes, the DataStores get destroyed.
form closes
This code is for the window’s Close event:
Destroy ids_emp_list
Destroy ids_emp_graph
90 PowerBuilder
CH A PTE R 5 Manipulating Graphs
About this chapter This chapter describes how to write code that allows you to access and
change a graph in your application at execution time.
Contents
Topic Page
Using graphs 91
Modifying graph properties 92
Accessing data properties 94
Using point and click 101
Using graphs
Supported environments
PowerBuilder and Web ActiveX Graphs are supported. Because you
can print DataStores, PowerBuilder provides some events and functions
for DataStores that pertain to the visual presentation of the data. However,
graph functions such as CategoryCount, CategoryName, GetData,
SeriesCount, and so forth depend on the visual graph control, which is not
created for a DataStore. These functions return an error value or an empty
string when used with DataStore objects.
Web DataWindow Graphs are not supported. If you use a DataWindow
object that includes graphs, the graphs are ignored. If you use a
DataWindow object with the Graph presentation style, nothing displays.
Working with graphs The following sections describe how you can access (and optionally modify) a
in your code graph by addressing its properties in code at execution time. There are two
kinds of graph properties:
• Properties of the graph definition itself These properties are initially
set in the DataWindow painter when you create a graph. They include a
graph’s type, title, axis labels, whether axes have major divisions, and so
on.
• Properties of the data These properties are relevant only at execution
time, when data has been loaded into the graph. They include the number
of series in a graph (series are created at execution time), colors of bars or
columns for a series, whether the series is an overlay, text that identifies
the categories (categories are created at execution time), and so on.
You can change these graph properties at execution time by assigning values to
the graph’s properties in code.
Property expressions PowerBuilder You can modify properties using property expressions. For
example, to change the type of the graph gr_emp to Column, you could code:
dw_empinfo.Object.gr_emp.GraphType = ColGraph!
92 PowerBuilder
CHAPTER 5 Manipulating Graphs
To change the title of the graph at execution time, you could code:
dw_empinfo.Object.gr_emp.Title = "New title"
Modify method In any environment , you can use the Modify method to reference parts of a
graph.
Example for PowerBuilder For example, to change the title of graph gr_emp
in DataWindow control dw_empinfo, you could code:
dw_empinfo.Modify("gr_emp.Title = 'New title'")
Example for Web ActiveX This example changes the label text for the Value
axis of graph gr_emp in the DataWindow control dw_empinfo:
dw_empinfo.Modify("gr_emp.Values.Label = 'New label'");
For a complete list of graph properties, see the DataWindow Reference.
boolean Italic
…
grAxis Values, Category, Series
boolean AutoScale
int MajorDivisions
int MinorDivisions
string Label
…
94 PowerBuilder
CHAPTER 5 Manipulating Graphs
Web ActiveX These methods get information about the data and its display.
There are additional helper methods available whenever the equivalent
PowerBuilder method uses an argument passed by reference. These helper
methods are identified in the second column of the following table (and are
described in the DataWindow Reference):
Table 5-2: Common methods for graph DataWindows in Web ActiveX
Method Information provided
CategoryCount The number of categories in a graph.
CategoryName The name of a category, given its number.
DataCount The number of data points in a series.
FindCategory The number of a category, given its name.
FindSeries The number of a series, given its name.
ObjectAtPointer The graph element the mouse was positioned over when it
was clicked. Call ObjectAtPointerSeries and
ObjectAtPointerDataPoint to get additional information.
SeriesCount The number of series in a graph.
SeriesName The name of a series, given its number.
Getting information about a data point’s appearance
GetDataPieExplode The percentage at which a pie slice is exploded. Call
GetDataPieExplodePercentage to retrieve the requested
value.
GetDataStyleColor The color of a specified data point. Call
GetDataStyleColorValue to retrieve the requested value.
GetDataStyleFill The fill pattern of a specified data point. Call
GetDataStyleFillPattern to retrieve the requested value.
GetDataStyleLine The line style and width of a specified data point. Call
GetDataStyleLineWidth and GetDataStyleLineStyle to
retrieve the requested values.
GetDataStyleSymbol The symbol of a specified data point. Call
GetDataStyleSymbolValue to retrieve the requested value.
Getting a data point’s value
GetDataDate The value of a data point that contains a date, given its
series and position. Call GetDataDateVariable to retrieve
the requested value.
GetDataNumber The value of a numeric data point, given its series and
position. Call GetDataNumberVariable to retrieve the
requested value.
GetDataString The value of a string data point, given its series and
position. Call GetDataStringVariable to retrieve the
requested value.
96 PowerBuilder
CHAPTER 5 Manipulating Graphs
Web ActiveX You can save an image of the graph on the clipboard, but you
cannot save data in a file. Writing to the file system is a security violation for
an ActiveX control:
Table 5-4: Web Active X method for saving data from a graph
Method Action
Clipboard Copies a bitmap image of the specified graph to the clipboard.
98 PowerBuilder
CHAPTER 5 Manipulating Graphs
100 PowerBuilder
CHAPTER 5 Manipulating Graphs
102 PowerBuilder
CHAPTER 5 Manipulating Graphs
GraphName = "gr_sales";
ObjectType =
dw_sales.GrObjectAtPointer(GraphName);
if (ObjectType == 1) {
SeriesName =
dw_sales.GetSeriesName(GraphName,
SeriesNum);
alert(dw_sales.GetSeriesName(GraphName,
SeriesNum) +" value is " + Value);
}
}
}
104 PowerBuilder
CH A PTE R 6 Using the Web DataWindow
About this chapter This chapter describes how to use the Web DataWindow in a data-based
Web application.
Contents
Topic Page
What the Web DataWindow is 105
Designing DataWindow objects 110
Setting up database connections 121
Deploying DataWindow objects to the component server 123
Creating Web page templates 126
Writing client-side scripts 128
HTML DataWindow
The Web DataWindow was formerly called the HTML DataWindow; both
terms refer to the same technology.
When you have developed and deployed the pieces the Web DataWindow
needs, here is what happens:
1 In a Web browser, a user requests the URL for a page.
2 The Web server passes the request to the page server, which locates the
template for the requested page and executes server-side scripts in the
template.
3 The server-side scripts connect to the (transaction) server component,
passing it information about the DataWindow and the database
connection.
4 Methods on the server component retrieve data required for the
DataWindow from the database and translate the DataWindow definition,
data, and state into HTML and JavaScript.
5 The server component returns the HTML and JavaScript to the page
server.
106 PowerBuilder
CHAPTER 6 Using the Web DataWindow
6 The page server replaces the server-side script in the requested Web page
with the generated HTML and JavaScript and returns the page to the Web
browser via the Web server.
7 The user interacts with the DataWindow—for example, requesting the
next page or updating the data.
8 The Web server passes the URL with added action parameters to the page
server, and the cycle begins again.
Figure 6-1: How the Web DataWindow works
The generic component has methods that you call in your Web page template
to instantiate and configure the component. It also provides most of the
methods available on the PowerBuilder DataWindow control. You should
probably use the generic component when you are getting started with the Web
DataWindow. Later you may want to build and deploy a custom component
that uses the methods of the generic EAServer component interface or that uses
only the methods you design for the component. See “Using a custom server
component” on page 150.
The following table displays all types of DataWindow server components:
Table 6-1: DataWindow server components and supported platforms
DataWindow
server Platform (server component
component name) Description
Generic EAServer Prebuilt (Generic COM
(DataWindow::HTMLGenerator90) component is prebuilt
or ActiveX). No generation
COM or compiling of stubs
(PowerBuilder.HTMLDataWindow) required.
Container (can EAServer Deploy with Web DW
include (PackageName::ComponentName Container project wizard.
multiple using generic Increases performance by
DataWindow DataWindow::HTMLGenerator90 reducing calls to server.
definitions) interface) No generation or
compiling of stubs
required.
108 PowerBuilder
CHAPTER 6 Using the Web DataWindow
DataWindow
server Platform (server component
component name) Description
Custom EAServer Use to increase flexibility
(hybrid) (PackageName::ComponentName of generic component.
using generic Can build and deploy with
DataWindow::HTMLGenerator90 PB object or project
interface) wizard. Generic methods
remain available.
Custom (user- EAServer Potentially best for
designed) (PackageName::ComponentName) performance and
or scalability. Can use to
COM avoid downloads of
(PackageName.ComponentName) unneeded generic
methods to client.
Client control Embedding client-side scripts The Web DataWindow client control is the
JavaScript and HTML that is generated by the server component and
embedded in the page returned to the Web client. Client-side scripts that you
add to your Web page template and wrap in SCRIPT tags are embedded as
JavaScript in the client control.
JavaScript caching Some features available on the client control are
optional: events, methods, data update and validation, and display formatting
for newly-entered data. The size of the generated JavaScript increases as you
add more client-side functionality. You can cache client-side methods in
JavaScript files on your Web server, reducing the size of the HTML generated
for Web DataWindow pages and improving performance on the client machine
if the browser is configured to use cached files.
For information on enabling JavaScript caching, see “Using JavaScript
caching for Web DataWindow methods” on page 118 and the discussion of
HTMLGen properties in the DataWindow Reference.
Using client-side events Events that are triggered on the client control and
several of the client control methods do not require the server component to
reload the page, so processing on the client is typically much faster than
processing performed on the server.
For more information about enabling features on the client, see “Setting
HTML properties in the DataWindow painter” on page 111 and “Controlling
what HTML is generated” on page 142. For more about writing scripts, see
“Writing client-side scripts” on page 128.
For complete documentation of the events and methods available on the server
component and the client control, see the DataWindow Reference or the
PowerBuilder online Help.
110 PowerBuilder
CHAPTER 6 Using the Web DataWindow
Table 6-3: HTML properties you can set in the DataWindow painter
Property User interface fields Allows you to
HTMLDW HTML DataWindow View the HTML in a browser
check box on the General using Design>HTML Preview
page of the DataWindow (or if you plan to use the
object Property view. DataWindow object with a
Selecting this check box custom Web DataWindow
sets this property to Yes. server component). The
generic server component
automatically sets this property
to Yes.
HTMLTable.property All fields on the HTML Change the display
Table page of the characteristics of HTML
DataWindow object tables, including border style
Property view. and cell width and padding.
HTMLGen.property All fields on the HTML Control the number of rows
Generation page and the displayed on the page, generate
JavaScript Generation HTML for a specific browser
page of the DataWindow or HTML version, choose
object Property view (You client-side features to
can also start the incorporate into the page, and
JavaScript Generation set up JavaScript caching to
wizard from a button on enhance performance.
the JavaScript Generation
page).
HTML.property All fields on the HTML Set up hyperlinks and retrieval
page of the Property view arguments typically used to
for a Column, Computed create master/detail Web
Field, Text, or Picture pages, specify whether the
control in a DataWindow content of a control should be
object. rendered as HTML, and
specify any HTML to be
appended to a control.
112 PowerBuilder
CHAPTER 6 Using the Web DataWindow
You can also cache client-side methods in JavaScript (JS) files to reduce the
size of the generated code and increase performance on both the server and the
client. Without JavaScript caching, each time a Web DataWindow is rendered
in a client browser, JavaScript code for DataWindow methods is generated on
the server and downloaded to the client. When you set DataWindow properties
to reference cached JS files, the methods defined in the files are not generated
with the HTML in any Web DataWindow pages that are sent to the page server
(and client browser).
For more information, see “Using JavaScript caching for Web DataWindow
methods” on page 118.
Using expressions
In general, expressions for validation rules and computed fields are translated
into JavaScript and evaluated in the client browser. For validation of data entry,
the user gets immediate feedback on the new data.
Some expressions have to be evaluated on the server. This may be because the
evaluation involves all the rows, rather than data on the current page only, or
because the expression does not translate into JavaScript.
If an expression includes these functions, it will be evaluated on the server:
• Aggregation functions, like Sum, Max, Average, First
• Case function
• External functions
If you use an aggregation function in a computed field, the value is computed
on the server and displayed on the client. If the user edits data, the value is not
updated. If an action occurs that reloads the page, the value is computed again
based on the changed data.
114 PowerBuilder
CHAPTER 6 Using the Web DataWindow
No validation
The HTML generator does not validate the HTML you include in controls in
DataWindow objects. If the HTML is not valid, the DataWindow may not
display correctly.
Appending HTML to a The AppendedHTML property enables you to append your own HTML to the
control HTML generated by the HTML generator component. You can use this feature
to specify attributes and event actions. The HTML you specify for the
AppendedHTML property value is appended to generated syntax for the
rendering of a DataWindow control before the closing bracket of the HTML
element for that control.
No validation
The HTML generator does not validate the HTML you append to controls in
DataWindow objects. If the HTML is not valid, the DataWindow may not
display correctly.
You must also make sure not to use an event handler name that is already
generated for a DataWindow control as a client-side event handler. These
include:
Table 6-5: Generated event handler names
DataWindow control Generated event handler names
Edit, EditMask, DropDownListBox, or onFocus, onClick, onChange, and onBlur
DropDownDataWindow
CheckBox or RadioButton onFocus, onClick, and onBlur
TextBox, Picture with link, or Button onClick
Setting SelfLink Button actions send information back to the server, whose scripts apply the
properties to enable action to the DataWindow data. Then the HTML page is reloaded. To complete
navigation buttons
this loop, you must set the SelfLink property for the DataWindow object so that
the server knows what page to reload.
You can set this property in the DataWindow painter on the HTML Generation
tab in the DataWindow properties view, or you can set it in a server-side script.
The value is the name of the application server template or file to be reloaded—
generally, the name of the current document. If the DataWindow uses retrieval
arguments, they must be provided in the SelfLinkArgs property.
For more information, see “Passing page-specific data to the reloaded page”
on page 145 and the SetSelfLink method in the DataWindow Reference. For
information on setting links on a DataWindow object (such as a button or
column) in the PowerBuilder HTML editor, see the chapter on the Web
DataWindow DTC in Working with Web and JSP Targets.
GIF and JPEG images The picture on a button in a DataWindow object can be rendered in the Web
for buttons browser as a JPEG, GIF, or BMP image. Use a JPEG or GIF image to ensure
that the image will display on all browsers. PowerBuilder provides GIF images
for commonly used buttons such as Retrieve, Update, PageNext, and so on.
These pictures are included in the DWACTION.JAR file in the
Sybase\Shared\PowerBuilder directory.
To make the images available to the HTML page in the Web browser, you must
uncompress the JAR file, deploy the image files to the page server, and set the
HTMLGen.ResourceBase property to the directory where the files are located.
116 PowerBuilder
CHAPTER 6 Using the Web DataWindow
Alternative to buttons: If you want to use an existing DataWindow object that does not have Button
use methods of the controls, you can edit the DataWindow object and save a new version with
client control
Button controls. However, if you are sharing DataWindow objects with an
existing application and it is not practical to edit them, your Web page can
include HTML buttons that call methods of the Web DataWindow client
control.
There are methods of the client control that correspond to each of the supported
button actions. For information, see “Writing client-side scripts” on page 128.
Using Picture controls You can use any image types the browser supports, most commonly JPEG or
GIF. Use relative paths for ease of deployment.
To make sure the images are available to the HTML page in the Web browser,
place the image files in a directory on the Web server and then set the
HTMLGen.ResourceBase property to that directory. You can do this in the
DataWindow painter on the JavaScript Generation page of the DataWindow
property view, or in a script:
dwMine.Modify("DataWindow.HTMLGen.ResourceBase=
'C:\Sybase\MyApp\Images'")
The ResourceBase property also specifies the location of JavaScript include
files. See “Using JavaScript caching for Web DataWindow methods” on page
118.
At runtime, a server-side script should find out what browser the current client
is using and pass that information to the server component. For information,
see “SetBrowser” on page 143 and the SetBrowser method in the DataWindow
Reference or online Help.
Using absolute Netscape implements absolute positioning differently than Internet Explorer.
positioning in To format the DataWindow with absolute positioning for Netscape browsers,
Netscape
you must set the DataWindow HTMLGen.NetscapeLayers property to TRUE.
You can do this in the DataWindow painter by selecting the Use Layers for
Netscape check box on the HTML Generation page of the DataWindow
property view. Alternatively, you can use a DataWindow Modify call in the
script for the Generate method of the HTML Generator
(nv_remote_datawindow in PBDWRMT.PBL that ships with PowerBuilder).
The default DataWindow HTML generator generates code for determining the
browser type and version of the client browser. For Netscape browsers earlier
than the 4.0 version, the DataWindow is formatted as an HTML table, whether
or not the NetscapeLayers property is set.
Limitations in Netscape
Certain functionality in a Netscape browser using absolute positioning may not
be identical to the functionality available with Internet Explorer. For example,
you cannot tab between DataWindow columns using a Netscape browser on an
NT machine, although you can do this using a Netscape browser on a Solaris
machine.
118 PowerBuilder
CHAPTER 6 Using the Web DataWindow
All of these properties are optional. You can set each of the properties from the
JavaScript Generation page of the DataWindow property view, selecting the
files you generate with the wizard as values. The wizard registers each file it
generates, making it available for selection from the drop-down lists in the
DataWindow property view.
Using the You must deploy all cached files for your Web application to your Web server.
ResourceBase You can use relative URLs or path names for cached JS files if you specify their
property
location in the HTMLGen.ResourceBase property. (You set these on the
JavaScript Generation page of the DataWindow property view in the
DataWindow painter.) The ResourceBase property is also used to specify the
location of image files.
If you do not set the HTMLGen.ResourceBase property, you must include the
complete URL in the values of any of the HTMLGen properties that you set.
In either case, the URLs are rendered as SRC attributes inside SCRIPT tags in
the pages generated by the Web DataWindow component and sent to the client
browser.
Setting the properties You can customize the DataWindow HTML Generator component
in script (nv_remote_datawindow in PBDWRMT.PBL that ships with PowerBuilder),
setting the HTMLGen properties in the script for the Generate method. This
example sets the URL location for included files and names the files for
common and date-formatted Web DataWindow methods that you deploy to the
Web server (and that will be downloaded to browser clients the first time they
connect to the Web site):
ids_datastore.Modify &
("DataWindow.HTMLGen.ResourceBase=" +&
"'http://www.myserver.com/JavaScripts'")
ids_datastore.Modify &
("DataWindow.HTMLGen.CommonJSFile=" +&
"'dwcomn.js'")
ids_datastore.Modify &
("DataWindow.HTMLGen.DateJSFile=" +&
"'dwdate.js'")
User-defined You can also reference a file where you store your own client-side JavaScript
JavaScript methods methods. To use this feature, you must assign the name of the file to the
DataWindow HTMLGen.UserJSFile property and make sure the file is
available to your Web server. As for the wizard-generated JavaScript files, you
can use the HTMLGen.ResourceBase property to set the location for the file,
or you can include the complete path to the file in the property value
assignment.
You can make this assignment in the DataWindow painter or in script. The
following script sets the user-defined JS file to MyMethods.JS:
ids_datastore.Modify &
("DataWindow.HTMLGen.UserJSFile=" +&
"'http://my_server.com/JavaScripts/MyMethods.JS'")
This example will be rendered in the generated HTML page as:
<SCRIPT LANGUAGE="JavaScript" SRC=
"http://my_server.com/JavaScripts/MyMethods.JS">
</SCRIPT>
120 PowerBuilder
CHAPTER 6 Using the Web DataWindow
You can then call client-side methods stored in the MyMethods.JS file from the
HTML syntax rendered for (or appended to) controls in a DataWindow object.
For information on generating or appending HTML syntax to controls, see
“Rendering HTML for controls in a Web DataWindow” on page 114.
If you are using MTS as the component server, you must use ODBC to take
advantage of connection pooling and transaction management features. The
data source for your DataWindow objects must be configured as a system DSN
on MTS or IIS because both run as services.
When you are defining DataWindow objects, you can use the types of
connectivity software documented in Connecting to Your Database. To
simplify setting up database connections on the server, use the same type of
connection in the DataWindow painter that will be used when the DataWindow
is deployed. For example, if you plan to use the DataWindow object in
EAServer with an Open Client connection, use Open Client in the
DataWindow painter too.
Creating a connection To use the HTMLGenerator90 component (or your own custom component) in
cache on EAServer EAServer, you need to define a connection cache for the database it will use.
122 PowerBuilder
CHAPTER 6 Using the Web DataWindow
5 Enter a name for the cache and click OK. (You cannot change the name
later.)
6 In the Connection Cache Properties dialog box, specify database
connection information on the General tab and the driver you want to use
on the Driver tab.
For ODBC on Windows: for Database Connection:Server Name on the
General tab, specify the DSN you defined in step 1. You do not need to
specify a user name or password if they are specified as part of the DSN.
On the Driver tab, click the ODBC radio button and specify ODBC32.dll
for the Driver Class or File.
For other connection types: see the EAServer Getting Started book for
your platform.
7 Select the Enable Cache-by-Name Access check box on the Cache tab.
8 Click Refresh on the General tab (the Refresh button is available only on
the Connection Cache Properties dialog box accessed from the server
node).
9 To test the connection, click Ping.
For more detailed information about setting up connection caches, see the
EAServer documentation.
Connection cache
Specifying a profile sets database transaction properties for the component, but
you still need to create a connection cache in Jaguar Manager for the database
the component will access.
Service classes You can add a custom class user object to your project to perform any special
processing you require. This object acts as a service class. The custom class
user object must be in the same library as the DataWindow objects or on the
target’s library list. When you build the Web DataWindow Container project,
select the class in the Select Objects dialog box in the Project painter.
For more information, see “Using service classes” on page 159.
124 PowerBuilder
CHAPTER 6 Using the Web DataWindow
Instantiating the When you create an instance of the container component, you must either
container component provide a Java proxy for the component or pass
DataWindow/HTMLGenerator90 as the last argument to the
CreateComponent method. This specifies that the component uses the proxy
provided for the generic component. For example:
dwObj = java.CreateComponent
("ContainerPkg/ContComponent",
"iiop://testMachine:9000", "Jagadmin", "",
"DataWindow/HTMLGenerator90" );
This is the same way you instantiate custom components. For more
information on custom components, see “Instantiating the custom component”
on page 156.
Selecting a To select a DataWindow from the container component, you must use the
DataWindow from the SetDWObjectEx method rather than the SetDWObject method:
container component
//Only the DW is needed, as package already specified
//above when connecting
retVal = dwObj.SetDWObjectEx("d_mydw");
document.write("SetDwObject = " + retVal);
For more information on the SetDWObject method, see “Loading the
DataWindow object” on page 141 and the DataWindow Reference.
Using the component You can select the container component when you use the Web/JSP
with the Web DataWindow Page wizard to create a new Web page. On the Choose EAServer
DataWindow DTC
Profile page in the wizard, check the Use Custom Web DW Component check
box. Then, when you click Next, the wizard prompts you for the component
name and the DataWindow in the component that you want to include on your
Web page.
On the DataWindow page of the Web DataWindow DTC property sheet, you
can also specify a container component and the DataWindow in the container
component that you want to use on a Web page. Selecting a container
component on the DataWindow page automatically selects it on the HTML
Generator page of the DTC property sheet. (If you want, it is possible just to
use the container component to generate HTML for a DataWindow that you
select from a PBL, PSR, or SRD file).
126 PowerBuilder
CHAPTER 6 Using the Web DataWindow
For how to use the DTC, see Working with Web and JSP Targets.
Using the Web Target The Web DataWindow DTC uses a set of objects in the Web Target object
object model model. If you want more flexibility than the Web DataWindow DTC provides,
you can write your own server-side scripts that instantiate and manipulate the
server component using the Web Target object model.
For example, the following script defines the DataWindow object name and the
PBL that contains it, sets up database and EAServer connection parameters,
instantiates the server component, specifies client control properties, and
generates HTML:
<!--SCRIPT
var dwMine_pbl = "htgenex.pbl";
// Get DataWindow name from page parameter if defined
var dwMine_name = psDocument.GetParam("dwName");
if (dwMine_name + "" == "undefined"){
dwMine_name = "d_tabular_emp";
}
// Set up DataWindow object variables
dwSrcLoc = new PSDataWindowSourceClass(
dwMine_pbl, dwMine_name);
// Set database connection parameters
// Set ConnectOption to return an error if
// connection fails
dwDbParm = new PSConnectionParmsClass(
"ConnectString='DSN=EAS Demo DB V3;UID=dba;
PWD=sql', ConnectOption='SQL_DRIVER_CONNECT,
SQL_DRIVER_NOPROMPT'");
// Set EAServer connection parameters
dwJagParm = new PSJaguarConnection("localhost:9000",
"jagadmin", "", "DataWindow/HTMLGenerator90",
false);
The example above uses the PSDataWindowClass object to create the server
component. If you are using EAServer, you can use the
PSWebDataWindowClass object, which provides server-side events and
additional methods.
For more information about the Web DataWindow DTC and the Web Target
object model, see Working with Web and JSP Targets. For information about
methods and events of Web Target object model classes, see the Web and JSP
Target Reference.
Extending the DTC The code generated by the Web DataWindow DTC can be modified by
code changing DataWindow object properties in the DataWindow painter or
changing DTC properties and then regenerating the code. If you want to
include additional customizations, you can modify the generated code in the
editor’s Source view. To prevent your customizations from being overwritten
when the Web page is regenerated, remove the METADATA tags that surround
the code.
Calling the Web Instead of using the DTC or Web Target object model, you can use any HTML
DataWindow server editor (including the Web Target HTML editor) to write code that instantiates
component methods
the server component and calls its methods directly. See “Instantiating and
configuring the server component” on page 138.
Most of these events have similar arguments and the same return codes as the
events of the PowerBuilder DataWindow control. For information, see the
DataWindow Reference or online Help.
128 PowerBuilder
CHAPTER 6 Using the Web DataWindow
Implementing an To write a script for an event of the client control, you define a function whose
event name is the control name plus the event name, separated by an underscore:
HTMLGenObjectName_eventname ( arguments )
The control name is the one you specified using the SetHTMLObjectName
method or the Object Name property on the HTML Generation page in the
DataWindow painter. The script must be enclosed in SCRIPT tags. You can
include client methods in the script if client scripting is enabled (described
next).
This example prevents focus from changing if the user tries to go back to an
earlier row. In this case the name of the DataWindow control is dwMine:
<SCRIPT Language=JavaScript>
function dwMine_RowFocusChanging(curRow, newRow)
{
if (newRow < curRow) { return 1; }
}
</SCRIPT>
You can put the script anywhere in your Web page template. If you are using a
Web target, you do not need to define a function to wrap your event code. You
can code client-side events directly in the editor by selecting the DataWindow
control name in the leftmost drop-down list in the toolbar and the event name
in the center drop-down list.
Calling client methods To write scripts that call methods of the client control, you must enable client
scripting. To do so, you can set the Client Scriptable property in the
DataWindow painter or call the SetWeight method in a server-side script.
Several client methods accomplish the same tasks as actions of Button
controls. If your DataWindow object uses Button controls to implement
scrolling and updating, you may not need to do any client scripting.
You can use the following methods on the client (methods marked with an
asterisk force the Web page to be reloaded):
AcceptText GetItem ScrollPriorPage *
DeletedCount GetItemStatus SetItem
DeleteRow * InsertRow * SetColumn
GetClickedColumn ModifiedCount SetRow
GetClickedRow Retrieve * SetSort
GetColumn RowCount Sort *
GetFullContext ScrollFirstPage * Update *
GetNextModified ScrollLastPage *
GetRow ScrollNextPage *
GetNextModified
The GetNextModified method finds modified rows in the current page only.
For information about these methods, see the DataWindow Reference or online
Help.
This example includes a form with a button that causes data to be updated on
the server:
<FORM NAME="update">
<INPUT type="button" value="Update"
onClick="{dwMine.Update();}">
Note that you can get the same functionality with the Update action for a
Button control in the DataWindow object.
Multiple DataWindows If you have multiple updatable Web DataWindows on the same Web page, you
on a page can script the OnSubmit client-side event to synchronize them before the
changes on the page are submitted. You call the GetFullContext method to get
a string that represents the context of the client side control that would be
passed on a submit, and transfer the context to the other DataWindow control.
To enable the second DataWindow to create the required fields on the submit
form, each of the DataWindows must have two arguments defined as self-link
arguments:
dw_1.SetSelfLink(document.name,
"dw_2_context=''|dw_2_action=''")
dw_2.SetSelfLink(document.name,
"dw_1_context=''|dw_1_action=''")
This client-side script transfers the context and action from dw_2 to dw_1
when dw_1 is submitted, and from dw_1 to dw_2 when dw_2 is submitted:
<SCRIPT>
function dw_1_OnSubmit()
{
dw_1.submitForm.dw_2_context.value =
dw_2.GetFullContext();
dw_1.submitForm.dw_2_action.value = "";
}
function dw_2_OnSubmit()
{
130 PowerBuilder
CHAPTER 6 Using the Web DataWindow
dw_2.submitForm.dw_1_context.value =
dw_1.GetFullContext();
dw_2.submitForm.dw_1_action.value = "";
}
</SCRIPT>
132 PowerBuilder
CH A PTE R 7 Server-Side Processing for the
Web DataWindow
About this chapter This chapter presents design and programming techniques as well as an
overview of configuration requirements for the server-side Web
DataWindow component.
Contents
Topic Page
Server configuration details 133
Instantiating and configuring the server component 138
Using a custom server component 150
Using service classes 159
Using the Web If you install EAServer and PowerDynamo on the same computer, most of the
DataWindow with configuration is done for you. You can use PowerBuilder Web Target wizards
PowerDynamo
to perform any additional setup tasks.
However, if you design your own custom class user objects, you must generate
and compile the stubs, making sure that the compiled stubs are included in the
PowerDynamo class path.
134 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
Using the Web To use Web DataWindows and access EAServer components in JSP pages that
DataWindow with you deploy to a Tomcat server, you must add the following JAR files and
Tomcat
classes to the class path used by Tomcat at startup:
• pbjdbc1290.jar
• jconn2.jar
• easclient.jar
• easj2ee.jar
• EAServer_home\html\classes
• EAServer_home\java\classes
where EAServer_home is the full path to the EAServer where the Web
DataWindow component is installed. To add the required files to the Tomcat
class path, you need to edit the catalina.bat file in the Tomcat bin directory.
Using the Web You can also use the Web DataWindow with Microsoft servers, but more
DataWindow with a configuration tasks are required. On MTS or IIS, you access the COM version
COM component
of the generic server component (PowerBuilder.HTMLDataWindow) using
automation methods called from any page server, such as PowerDynamo or
ASP. For example, to instantiate the generic COM component from ASP:
dwMine = Server.CreateObject(
"PowerBuilder.HTMLDataWindow")
The COM server component is provided in PBDWR90.DLL. You can also
write your own custom class user object based on the sample source code in
PBDWRMT.PBL.
For more information about building Web pages that use the Web DataWindow
server component, see “Instantiating and configuring the server component”
on page 138.
You need to register the COM server component and install PowerBuilder
runtime files and the PBL or PBD containing your DataWindow objects on the
MTS or IIS server computer.
Transaction server The following table summarizes the configuration tasks you need to perform
configuration tasks on the transaction server:
Table 7-1: Configuration tasks for transaction server
Server Tasks
EAServer, IIS, or Copy the PBLs, PBDs, SRDs, or PSRs containing the
MTS definitions of your DataWindow objects to a directory on the
EAServer server’s path or the system path if the server
component is running as a service (always true for MTS or IIS).
EAServer Set up a DSN and a connection cache for your data source.
IIS or MTS • Copy the following PowerBuilder runtime files to the system
path: PBVM90.DLL, LIBJCC.DLL, PBDWE90.DLL,
PBODB90.DLL, PBODB90.INI
• Copy the file containing the generic COM server component
to the system path and register it:
regsvr32.exe pbdwr90.dll
• If you designed your own custom class user object and built
a COM server component, you need to copy your component
DLL to the server and register it
• If necessary, install the ODBC driver for your DBMS and use
the ODBC Administrator to define an ODBC data source for
your DataWindow objects as a system DSN
MTS If MTS is hosting the server component and running on a
different computer from IIS, create a client install package using
MTS Explorer and install it on the IIS machine. For more
information, see the MTS documentation.
136 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
Page server The following table summarizes the configuration tasks you need to perform
configuration tasks on the page server:
Table 7-2: Configuration tasks for page server
Server Tasks
PowerDynamo or Copy the HTML pages, scripts, images, and other application
ASP files to the page server. You can use the Web target deployment
controller for PowerDynamo or ASP to copy them to the server.
JSP Copy the JSPs, custom tag libraries, scripts, images, and other
files to the page server. You can use the Web target deployment
controller for JSP to copy them to the server.
Although a custom tag library you add to a page is placed in the
Web-Inf\tld directory and deployed with the target, you must
manually copy any classes or archives required by the tag
library. Tag library class files should be copied to the
Web-Inf\classes directory, and tag library archive files should be
copied to the Web-Inf\lib directory.
For information about the Web DataWindow custom tag library,
see the "Custom Tag Reference" chapter in the Web and JSP
Target Reference.
PowerDynamo Create a Web site and define a mapping in Sybase Central that
(with any associates the connection profile for your database with the Web
component site pathname you will use in the URL. (The PowerDynamo
server) Web Site target wizard can do this for you.)
PowerDynamo If PowerDynamo and EAServer are not installed on the same
(with EAServer as computer:
the component • Copy JAGCLIENT.EXE from the EAServer client
server) subdirectory to the PowerDynamo server, run it, and select
Java Runtime.
• Add Sybase\Shared\Sun\jdknnn\bin to the system PATH
environment variable.
• Add Sybase\Shared\Sun\jdknnn\lib\classes.zip to the
CLASSPATH environment variable.
In Sybase Central, open the General Settings folder in the
PowerDynamo Configuration utility and check that the Sun
Java VM is selected (the default).
Server Tasks
ASP (with If ASP and EAServer are not installed on the same computer:
EAServer as the • Copy JAGCLIENT.EXE from the EAServer client
component subdirectory to the ASP server, run it, and select ActiveX
server) Runtime.
• Copy PBDWR90.TLB and PBDWR90.REG to the ASP
server from the Sybase\Shared\PowerBuilder directory on
the computer where PowerBuilder is installed.
• Edit the HKEY_CLASSES_ROOT\TypeLib lines in
PBDWR90.REG that show the location of the
PBDWR90.TLB file to show the correct location on the ASP
server.
• Double-click PBDWR90.REG to install its information into
the Windows registry.
If you designed your own custom class user object, generate
TLB and REG files for the component in Jaguar Manager and
register them on the ASP server. For more information, see the
chapter on creating ActiveX clients in the EAServer
Programmer’s Guide.
138 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
Methods with more than one syntax have a different form for each syntax to
overcome restrictions on the use of overloading. For example, the ClearValues
method takes a string as an argument and the ClearValuesByColNum method
takes a number.
For a complete list of supported DataWindow control methods, see the
DataWindow Reference or the online Help.
Configuration and Other methods are available to set up the component, retrieve data, establish
generation methods persistent values needed by your Web page, and generate HTML.
If you use a custom server component, there are additional configuration tasks.
For more information, see “Using a custom server component” on page 150.
Coding steps In your server-side script, you will code these tasks:
1 Instantiate the component.
2 Load the DataWindow object.
3 Control what HTML is generated (for example, by specifying what
functionality to include and what browser to target).
4 Specify the database connection and retrieve data.
5 Pass page-specific data to the reloaded page.
6 Pass user action information to the server component.
7 Insert the generated HTML in the page template.
Sample code for each of these tasks follows. Most of the code examples show
the DynaScript code you would use to instantiate and configure the EAServer
component. Some ASP examples are provided, but the code in other ASP
server-side scripts would be similar to the DynaScript examples shown here.
For detailed information about the methods used in the examples, see the
DataWindow Reference or the online Help.
140 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
142 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
Optimizing HTML for a SetBrowser The Web DataWindow can generate HTML optimized for
browser particular browsers and versions. In particular, it can generate code for
Microsoft and Netscape browsers. The browser may be different each time the
server component is instantiated by a different client, so this information
cannot be preset in the DataWindow painter. You can tell it what browser and
version to target in the server-side script. In the painter, you can set the HTML
Version property to specify what level of HTML to generate if the browser is
not recognized.
For information on what HTML features the DataWindow uses for different
browsers, see the DataWindow Reference or the HTMLGen.property topic in
online Help.
At runtime, the HTTP header sent from the client browser to the Web server
contains the HTTP_USER_AGENT value, which the server component can
use to identify the client browser.
In PowerDynamo, you can use the GetServerVariable method of the document
object to get the HTTP_USER_AGENT value:
dwMine.SetBrowser(
document.GetServerVariable("HTTP_USER_AGENT"));
In ASP, you can use the ServerVariables method of the Request object to get
the HTTP_USER_AGENT value:
var clientbrowser =
Request.ServerVariables("HTTP_USER_AGENT");
dwMine.SetBrowser(clientbrowser);
The data source must be defined on the server machine. It must be a system
DSN on EAServer if the component is running as a service, and it must always
be a system DSN on MTS or IIS. This statement connects to the EAS Demo
DB sample database:
dwMine.SetTrans("ODBC",
"ConnectString='DSN=EAS Demo DB
V3;UID=dba;PWD=sql'",
"", "", "", "", "")
Retrieving data Retrieve To tell the server component to retrieve data, you call the Retrieve
method or, if the DataWindow object expects retrieval arguments, the
RetrieveEx method.
This DynaScript code calls Retrieve and, if the return value reports an error,
calls GetLastErrorString for the error message text. In ASP, use
Response.Write instead of document.Writeln:
retVal = dwMine.Retrieve();
if (retVal < 0 )
{
document.Writeln("Error on Retrieve: " + retVal +
"<BR>");
document.Writeln(dwMine.GetLastErrorString() +
"<BR>")
}
Specifying retrieval RetrieveEx If the DataWindow object expects retrieval arguments, call
arguments RetrieveEx:
dwMine.RetrieveEx("60000");
Typically, the retrieval arguments are not constants. They are page parameters
passed to the page from another page where the user filled in a form or clicked
a hyperlink. If the DataWindow expects more than one retrieval argument, the
arguments must be passed in a single string. The arguments in the string must
be separated by newline characters (\n), and individual values cannot contain
newline characters as part of the value. Array values must be separated by tab
characters (\t).
144 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
Values passed into the page are properties of the value property of the
document object. For example, this form prompts the user for a salary:
<FORM ACTION="salaryrpt.stm" NAME="log" METHOD="POST">
<p>Please enter a salary ceiling:</p>
<P><INPUT TYPE="text" NAME="salary" SIZE="15"></p>
<p><Center>
<INPUT TYPE="Submit" VALUE="Register">
</Center></p>
</FORM>
Getting the URL for To reload the page correctly in response to user actions, the server component
the page needs to know the URL of the page template. You can get this information from
the name property of the document object or the SCRIPT_NAME server
variable.
In PowerDynamo, use the GetServerVariable method of the document object:
var url = document.GetServerVariable( "SCRIPT_NAME" );
In ASP, use the ServerVariables method of the Request object:
var url = Request.ServerVariables( "SCRIPT_NAME" );
Building a self-link Self-link arguments become page parameters in the reloaded page. Your script
argument string typically looks at an existing page parameter and re-creates it using a self-link
argument. The syntax for specifying a self-link argument string is:
pageparam1=’expr1’|pageparam2=’expr2’...|pageparamn=’exprn’
The string can contain one or more page parameter and expression pairs
separated by pipes ( | ). Each expression is a DataWindow expression that
evaluates to a string. Usually you specify constant string values that are already
values of page parameters rather than expressions.
The expression is enclosed in quotes, and if the value is a constant, it must also
be enclosed in quotes. For example, if a page parameter called logname is
passed to the page and it has the value Fred, the string you need to pass in the
SetSelfLink method is:
logname='"Fred"'
To get the value from the current logname parameter, which is already defined
for the page, you build the expression using the logname page parameter. The
single quotes and inner double quotes are embedded in the expression. The
current value of logname is inserted between the quotes:
var linkargs =
"logname='\"" + document.value.logname + "\"'";
An expression does not need the inner quotes:
var linkargs = "date='String(Today())'";
Passing the URL and SetSelfLink Use the URL obtained from the SCRIPT_NAME server variable
argument string to and the link arguments string you built as arguments to the SetSelfLink
SetSelfLink
method:
dwMine.SetSelfLink(url, linkargs);
146 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
Retrieval arguments The first time the page is loaded, the retrieval argument might be:
as self-link values
• A page parameter passed from another page. The user might have clicked
a URL that included the value or filled in a form that posted the value.
• A new value calculated in the current script.
If the value is a page parameter, then you can re-create the page parameter
using SetSelfLink. If the value is from some other source, you need to write
code that gets the value from the source (which might be a page parameter) the
first time the page is loaded and from a page parameter when it is reloaded.
Examples These PowerDynamo examples show code that works with the types of values
listed above. They illustrate how to get each type of value and use it in both
RetrieveEx and SetSelfLink method calls.
Value from another page If the user entered a product ID in a form to get
detailed information on the product, the product ID is passed to the product
report template as a page parameter. The page parameter should always exist
because it comes from the calling page, but the code provides a default value
anyway:
if (exists(document.value.prodid)) {
prod_id = document.value.prodid;
} else {
prod_id = "1";
}
dwMine.RetrieveEx(prod_id);
dwMine.SetSelfLink(document.name,
"prodid=" + "'\"" + prod_id + "\"'");
Calculated value If the value is to be calculated in the script, then the page
parameter will not exist the first time the script runs. If the random page
parameter exists, the script gets the value from the parameter; otherwise the
script calculates a value using a Math function:
if (exists(document.value.random)) {
rnd = parseInt(document.value.random);
} else {
rnd = Math.random();
}
dwMine.RetrieveEx(rnd);
dwMine.SetSelfLink(document.name,
"random=" + "'\"" + String(rnd) + "\"'";
Multiple values In this example, a Web page with a form prompts the user for
a user name and a product category and the level of detail the user wants to see.
The code uses the product category as a retrieval argument for the Web
DataWindow. The script selects a DataWindow object based on the level of
detail. All three values are carried over each time the page is reloaded:
// Get product category as a retrieval arg
if (exists(document.value.category)){
retrievearg = document.value.category;
} else {
retrievearg = "all";
}
rtn = dwMine.RetrieveEx(retrievearg);
if (rtn < 0) {
... // Check for error
}
// Get the user name
if (exists(document.value.username)){
username = document.value.username;
document.Write("<P>Dear " + username + "</P>");
}
document.Write("<P>Here is the report you
requested.</P>");
148 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
This DynaScript code uses a function called GetParam to see if the parameters
have been defined (meaning that the page is a reloaded page) and if so, calls
SetAction to send the action information to the server component:
// Function to test whether page parameters are defined
function GetParam( envparam ) {
if( exists(document.value[envparam] ) ) {
return document.value[envparam];
}
return "";
};
// Check if we need to perform the action
var dwMine_action = GetParam("dwMine_action");
var dwMine_context = GetParam("dwMine_context");
150 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
For information on creating a custom component that uses the generic Web
DataWindow interface, see “Creating a custom server component in
EAServer” on page 152 or “Deploying DataWindow objects to the component
server” on page 123.
Writing your own For full control of HTML generation and the state of the DataStore object that
custom component holds the DataWindow definition and data, you can write your own custom
class user object in PowerBuilder and deploy it as an EAServer or COM
component. Using a custom component that includes only the processing you
need can reduce the size of the client control returned to the Web client.
The source code for the generic component is available in PBDWRMT.PBL in
the PowerBuilder code examples directory so that you can examine or reuse it.
You can modify or add to the code in this PBL or start from scratch, using the
sample PBL as a model for your own component.
Your server component will use methods on a DataStore object to retrieve data
and return the data and state to the client as HTML. To get the HTML and
JavaScript that represents the state, data, and presentation of the DataWindow
object, use the Describe method:
ls_html = ds_1.Describe("DataWindow.Data.HTML")
To update the HTML according to user actions, use the SetHTMLAction
method:
li_rtn = ds_1.SetHTMLAction(arg_action, arg_context)
SetHTMLAction restores the state of the DataStore based on the context
passed in as an argument and then changes the state based on the passed action.
For more information about SetHTMLAction, see the DataWindow Reference
or online Help. For information about working with DataStore objects, see
Chapter 4, “Using DataStore Objects”.
If you create your own server component and deploy it to EAServer, you must
also generate and compile the stubs. For information on generating and
compiling stubs, see the EAServer documentation.
If you deploy the user object as a COM component, you need to register it. For
information about registering COM components, see “Server configuration
details” on page 133.
152 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
8 On the All Properties tab, add the properties for which you want preset
values.
General properties These properties specify settings that take effect when
the component is instantiated.
Table 7-3: General properties to add for custom component
General property Description
com.sybase.datawindow. Specifies the PBL, the PBD that contains the
sourceFileName DataWindow object for the component, or the SRD or
PSR file that is the DataWindow object.
See also the SetDWObject method in the online Help
or DataWindow Reference.
com.sybase.datawindow. The name of the DataWindow object in the PBL or
dwObjectName PBD specified for sourceFileName.
See also the SetDWObject method.
com.sybase.datawindow. Whether component properties can be modified from
fixed server-side script (SetDWObject, Create, Modify, and
SetTrans methods) that instantiates the component.
Values are:
• Yes — Properties are fixed and cannot be changed.
• No — Properties can be changed.
com.sybase.datawindow. A list of PowerBuilder user objects that are in the PBL
serverServiceClasses or PBD specified in sourceFileName. The class names
should be separated by semicolons (;). The user objects
implement custom events for data validation.
For information on custom events, see the
SetServerServiceClasses method in the online Help or
DataWindow Reference.
com.sybase.datawindow. Specifies whether the server attempts to maintain its
serverSideState state between method calls. Values are:
• Yes — The server component keeps the result set
and keeps the transaction open if possible.
• No — (Default) The result set is not saved and the
server component uses information passed back
from the client to retrieve the result set again and
restore any uncommitted changes.
com.sybase.datawindow. Whether calls to component methods are included in
trace the EAServer server log. Values are:
• Yes — Calls to component methods are listed in the
log.
• No — (Default) Calls to component methods are not
logged.
154 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
// Get browser
var browser = document.GetServerVariable
("HTTP_USER_AGENT");
156 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
document.Write(dwMine.OneTripEx("dwMine", retrievearg,
browser, selfLink, selflinkarg, action,
context));
Using a stateful You can increase performance by maintaining state on the server. To maintain
component state, the page server’s session object keeps a reference to the server
component. If the server component is running in EAServer, you must mark
the component as a stateful object and set a timeout value for the component.
Failing to set a timeout value if you are using the component as a stateful object
will result in orphaned instances of the component on the server.
Maintaining state on the server provides faster response time if the same
component is accessed again. However, it also increases the server resources
used for each client connection.
To minimize impact on server resources, a short timeout on a session lets the
server get rid of a component that might not be requested again. If the
component is called again, its state can be restored from the client state
information. When the number of hits on a page is expected to be large, setting
a shorter timeout reduces the number of instances that need to be maintained
simultaneously.
Marking the object as To mark the component as a stateful object, set the component’s
stateful com.sybase.datawindow.serverSideState property in Jaguar Manager or call
the SetServerSideState method in a server-side script:
dwMine.SetServerSideState( true );
You should not set the com.sybase.jaguar.component.stateless property for the
HTMLGenerator90 component in Jaguar Manager.
If you are using the Web Target object model, you specify whether the database
state is managed on the server by passing the boolean value TRUE as the
second parameter to the PSDataWindowClass constructor:
dw_1 = new PSDataWindowClass("dw_list", true,
jagConn, dwSource, dbConn, 5);
Passing this parameter calls the SetServerSideState method, but it does not set
a timeout value—you need to set a timeout value whether or not you are using
the Web Target object model.
Setting timeout values To set the timeout value for the HTMLGenerator90 component, open its
Component Properties dialog box in Jaguar Manager and set the
com.sybase.jaguar.component.timeout property. Timeout values are specified
in seconds; a value of 0 means the component never times out. Since the state
of the component is saved in the PowerDynamo session object, the timeout
values for the PowerDynamo session and the HTMLGenerator90 component
should be the same.
158 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
160 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
The arguments are the same as those documented for the similarly named
DataWindow events in the DataWindow Reference, with the exception of
the additional DataStore argument, which gives the user object access to
the Web DataWindow data.
3 In the event script, use return codes to specify whether the server
component should cancel the event.
The return codes are also the same as those documented in the
DataWindow Reference. Any of the service classes that implements the
event can specify that the event be canceled.
4 Register the service classes for the component.
There are two ways to make the user object available as a service class:
• For any component in EAServer or another supported server such as
MTS, call the SetServerServiceClasses method in the Web page
template’s server-side script:
dwMine.SetServerServiceClasses
("uo_update_validate;uo_retrieve_process");
• For a custom component in EAServer, add this property in Jaguar
Manager:
com.sybase.datawindow.serverServiceClasses
Set its value to the list of user object names, with names separated by
semicolons. For example:
uo_update_validate;uo_retrieve_process
Example Suppose that you want to check that data did not exceed a budgeted total before
it was updated in the database. You might set up a service class that implements
the UpdateStart event.
FOR i = 1 to ll_upper
total = total + darray[i]
NEXT
IF ds_budget.Object.cf_expense_total < total THEN
RETURN 1
END IF
162 PowerBuilder
CHAPTER 7 Server-Side Processing for the Web DataWindow
Example Suppose that you want to check that data did not exceed a budgeted total before
it was updated in the database. You might set up a service class that implements
the UpdateStart event.
The method declaration would be:
public void UpdateStart (UpdateEvent event,
DataStore ds)
The body of this method has a DataStore that retrieves data from a budget table
and compares it to the component’s data:
import powersoft.datawindow.event.*;
import powersoft.datawindow.*;
164 PowerBuilder
CH A PTE R 8 Using the DataWindow Web
Control for ActiveX
About this chapter This chapter describes how to use the Sybase DataWindow Web control
for ActiveX (Web ActiveX).
Contents
Topic Page
About the Web ActiveX 165
HTML for inserting the controls on a Web page 168
How to use the Web ActiveX in a Web target 170
DataWindow objects for the Web ActiveX 173
Using the DataWindow Transaction Object control 175
Making database connections 177
Coding for the Web ActiveX 179
Deploying the Web ActiveX 180
Browser support
The Web ActiveX and Transaction Object control are designed to work in
browsers that support ActiveX controls, such as Microsoft Internet Explorer
version 3 and higher.
The DataWindow controls are not designed to work in Netscape browsers,
which do not support ActiveX controls. Even if you use third-party plugins to
enable ActiveX support, scripting for the controls works differently and is not
tested.
Development When you install PowerBuilder, the Setup program registers the Web ActiveX
environment and the Transaction Object control in the Windows registry. The class
information entered in the registry is visible in the PowerBuilder Browser
under OLE Custom Controls on the OLE tab. You can also examine the
properties, events, and methods of the controls on the OLE tab of the Browser.
In a Web target, you can develop Web pages that use the Web ActiveX and
Transaction Object control. You can drag and drop these controls from the
Components tab of the System Tree to a Web page. You can also examine the
properties, events, and methods of these controls from the System Tree. In the
HTML editor, you can insert the control, set property values using the control
property sheets, and write event scripts in the script editor.
For more information, see “How to use the Web ActiveX in a Web target” on
page 170.
In addition to the Web target HTML editor, you can use any text editor to write
HTML for the controls. However, other development environments are not
supported and do not provide advanced authoring support.
For information about the required HTML, see “HTML for inserting the
controls on a Web page” on page 168.
DataWindow objects The Web ActiveX uses a DataWindow object, which determines what data is
retrieved and how it is displayed. The Web ActiveX can also display Powersoft
reports (PSRs), which do not need to retrieve data.
A DataWindow object for the Web ActiveX can have any presentation style
except RichText.
DataWindow objects are stored in PowerBuilder libraries (PBLs) or
PowerBuilder dynamic libraries (PBDs). The DataWindow libraries are stored
on the Web server and downloaded as needed by the Internet Explorer browser.
You use a URL to point to the library. It can be relative or absolute, using any
supported protocol—for example, http, ftp, or file.
166 PowerBuilder
CHAPTER 8 Using the DataWindow Web Control for ActiveX
For more information, see “DataWindow objects for the Web ActiveX” on
page 173.
Database connections The Web ActiveX uses JDBC for database connectivity. Users can connect to
a data source on any server to which they have access, including databases and
middle-tier servers on the Internet.
You can use internal transaction properties for specifying a connection; or you
can make the connection with a separate Transaction object, the Sybase
DataWindow Transaction Object control. When you connect using a separate
Transaction object, you can control when SQL COMMIT and ROLLBACK
statements occur and you can use the same connection for multiple Web
ActiveX controls.
For more information, see “Using the DataWindow Transaction Object
control” on page 175.
Scripting Since the Web ActiveX is designed for Internet Explorer, you can use Jscript
or another ECMAScript-compatible scripting language for scripting purposes.
In general, you can use the same methods as in a PowerBuilder application.
However, there are a few differences:
• Data types are mapped to the basic JavaScript types of string, number,
boolean, and various object types
• ECMAScript languages do not support arguments passed by reference; so
instead of checking the value of a reference argument, you call a separate
method to retrieve the value
• Enumerated data types are not supported; instead, specify the integer that
corresponds to the enumerated data value
For more information, see “Coding for the Web ActiveX” on page 179.
Events The Web ActiveX supports the same events as a standard DataWindow control,
with these differences:
• Event names are different to conform to Web conventions
• Events in ECMAScript languages do not have return values; instead you
can call SetActionCode to affect the outcome of an event
Deployment The Web ActiveX is provided as a CAB file, which allows the client browser
to install and register the control. When the user downloads a Web page that
refers to the CAB file, the browser also downloads the CAB file if necessary,
unpacks it, and registers the control.
For more information, see “Deploying the Web ActiveX” on page 180.
Object element
How it works ActiveX controls use the Object element to specify the GUID (a unique
identifier) of the control as well as the space the control takes on the page. The
Object tag looks like this:
<OBJECT id=PSDWC1 height=357 classid="CLSID:99991503-
9999-1000-8000-080009AC61A9" width=343>
</OBJECT>
In a Web target, when you insert the Web ActiveX control by dragging from
the System Tree or by using the Insert>Component menu item, the Object tag
is written for you.
CODEBASE attribute If your users need to download the controls, you can include the CODEBASE
attribute in the Object element to identify the file to be downloaded. After the
browser downloads the CAB file, it unpacks it and registers the ActiveX
controls in the user’s system registry.
The value for CODEBASE has the format:
url#version
A typical value for CODEBASE uses a relative URL:
CODEBASE="cabs/psdwc90.cab#9,0,0,3514"
URL The URL is the location of the DataWindow control’s CAB file on your
Web server. It can be an absolute or relative URL.
Version The version is a set of four numbers, separated by commas. The
numbers must match the version of the CAB file. The version number of the
CAB file is the same as the version number for PowerBuilder.
168 PowerBuilder
CHAPTER 8 Using the DataWindow Web Control for ActiveX
"http://www.domain.com/psdwc90.cab#Version=9,0,1,3514"
id=PSDWC1 height=357 classid="CLSID:99991503-9999-
1000-8000-080009AC61A9" width=343>
</OBJECT>
New versions When you get new versions of the CAB file, you can change the version
numbers on the Web page and cause the browser to install a new version of the
control.
For more information about how to deploy new versions, see “Deploying the
Web ActiveX” on page 180.
The Web ActiveX also inserts Param elements for custom properties. You set
these custom properties from the Sybase DataWindow Web Control Properties
dialog box. To open this dialog box you can click the Control Properties button
on the ActiveX page of the ActiveX OBJECTn Properties dialog box for the
Web ActiveX control.
The Sybase DataWindow Web Control Properties dialog box has four tab pages
where you can set custom properties: General, Scrolling, Transaction, and
Trans User. The Transaction Object control has only two custom property
pages: Transaction and Trans User.
Standard ActiveX <PARAM VALUE=65536 NAME="_Version"></PARAM>
properties <PARAM VALUE=9280 NAME="_ExtentX"></PARAM>
<PARAM VALUE=5155 NAME="_ExtentY"></PARAM>
<PARAM VALUE=2 NAME="_StockProps"></PARAM>
<PARAM VALUE="" NAME=Caption></PARAM>
Properties on General <PARAM VALUE="javadwtest.pbl" NAME=SourceFileName>
page </PARAM>
<PARAM VALUE="d_emp" NAME=DataWindowObject></PARAM>
<PARAM VALUE=0 NAME=SuppressEvents></PARAM>
Properties on <PARAM VALUE=0 NAME=VScrollBar></PARAM>
Scrolling page <PARAM VALUE=0 NAME=HScrollBar></PARAM>
<PARAM VALUE=0 NAME=HSplitScroll></PARAM>
<PARAM VALUE=0 NAME=LiveScroll></PARAM>
Properties on <PARAM
Transaction page VALUE="Driver='com.sybase.jdbc2.jdbc.SybDriver',
URL='jdbc:sybase:Tds:localhost:2638'" NAME=dbParm>
</PARAM>
Properties on Trans <PARAM VALUE=dba NAME=LogId></PARAM>
User page <PARAM VALUE=sql NAME=LogPass></PARAM>
170 PowerBuilder
CHAPTER 8 Using the DataWindow Web Control for ActiveX
❖ To use the System Tree when writing code for the controls:
1 On the Page tab of the System Tree, expand window in the Client Side
branch.
2 Under window, expand Properties and find the name of your control as one
of the properties.
3 For the control, expand Properties, Events, or Methods.
4 Find the item you want to insert in the script editor and drag it to its
position in the code.
A fully qualified expression is inserted, such as:
window.dw1.Describe(propertylist)
window.dw1.dbParm
Substitute your own variables and expressions for method parameters.
172 PowerBuilder
CHAPTER 8 Using the DataWindow Web Control for ActiveX
PowerBuilder version
PBLs must be migrated to Version 9 or later.
Grouping A PBL or PBD is downloaded in its entirety from the Web server; therefore,
DataWindow objects you should make sure your library includes only those objects needed on your
into libraries
Web pages. You can group DataWindow objects that are used on different Web
pages in a single library; however, you should avoid forcing users to download
objects used on pages they will not view.
When choosing how to group DataWindow objects into libraries, make the set
of objects in the library correspond to the typical set of pages the user will view.
Although a single download saves a lot of communications overhead, it is
worthwhile for users only if they view the pages that use the objects.
Using other resources A DataWindow object can use external resources such as bitmaps or cursors.
in the DataWindow You can use a resource file when you build a PBD to include these resources
object
in the library. You can also store these resources on the Web server. A relative
path in the DataWindow object can point to the file’s location on the Web
server. The browser retrieves the resource as needed.
A DataWindow object can use other DataWindow objects, such as drop-down
DataWindows. Make sure these objects are included in the downloaded library.
174 PowerBuilder
CHAPTER 8 Using the DataWindow Web Control for ActiveX
• Relative URLs:
financedws.pbd
dwlibraries/financedws.pbd
• Absolute file path (can be useful while developing pages):
d:/web project/dwlibraries/financedws.pbd
In the Web ActiveX property sheet, when you use the Browse button to look
for the library, you browse the file system, not URLs. After the full path is
inserted in the field, you probably should edit it so that it is valid when your
Web pages are deployed.
Web targets If you are working in a PowerBuilder Web target, it is a good
idea to include both the library and the Web page in the workspace. If you do,
SourceFileName can be a relative path that is valid in both your design and
deployment environments.
Changing SourceFileName during execution You can change the value of
SourceFileName in a script. If you do, you also have to specify a value for
DataWindowObject that is valid in the new library. You must also call
SetTransObject again if you are using a separate transaction object.
About The value for DataWindowObject is the name of a DataWindow object that is
DataWindowObject in the library specified in SourceFileName.
If the library is accessible in the development environment (for example, it is
part of the PowerBuilder workspace and you specify a relative URL), then the
property sheet displays a drop-down list of the DataWindow objects contained
in the library.
Internal transaction Both the Web ActiveX control and the Transaction Object control can establish
management or a database connection. The one you use depends on your needs.
separate Transaction
object There are two main reasons to use the Transaction Object control:
• You can make one database connection for several Web ActiveX controls,
saving the overhead of multiple connections.
• You can control transaction processing with Connect and Disconnect
methods, equivalent to the SQL statements CONNECT and
DISCONNECT. If the AutoCommit property is set to False, you can
control when an update is committed or rolled back (by calling the
Commit and Rollback methods).
If you have only one control and are simply retrieving data, you do not need
either of these features. Instead of instantiating a separate control, you can set
the connection properties of the Web ActiveX itself and allow it to connect and
disconnect for each database access.
Status and error The Transaction Object control receives status information from the database.
information You can test the success or failure of a database operation and get status
information with these methods, which are equivalent to PowerBuilder
transaction object properties:
• GetSQLCode
• GetDBCode
• GetSQLErrText
• GetSQLNRows
• GetSQLReturnData
Hiding the Transaction The Transaction Object control has no visual aspect, but if it is in the BODY
Object control section of the Web page, it still takes up space. You can set its HEIGHT and
WIDTH attributes to very small values or use style sheet settings to make it
invisible.
If you put it in the HEAD section, you will not have access to its property sheet
in a PowerBuilder Web target.
For information on setting properties for making a database connection, see
"Making database connections" next.
176 PowerBuilder
CHAPTER 8 Using the DataWindow Web Control for ActiveX
About dbParm For JDBC drivers, the dbParm property specifies essential connection
information. Its value is a string that contains at least two values. Those values
identify the driver you want to use and the URL of the database, in a format
understood by the driver.
The format is:
Driver='JDBCclassname',URL='database_url'
To find the class name for Driver and the format of the database URL, check
the documentation from the DBMS vendor.
For examples of setting these properties in Param elements, see “Properties
and Param elements” on page 169.
JConnect in the If you want to use JConnect when you define DataWindow objects, put the
development Java classes for JConnect on the class path. An instruction like this should
environment
appear in AUTOEXEC.BAT:
SET CLASSPATH=d:\Program Files\Sybase\Shared\JConnect-5_5
178 PowerBuilder
CHAPTER 8 Using the DataWindow Web Control for ActiveX
180 PowerBuilder
CHAPTER 8 Using the DataWindow Web Control for ActiveX
❖ To deploy the new CAB file when you get a new version of PowerBuilder:
1 Find the new version number by checking the version number of any
PowerBuilder DLL (as described in “HTML for inserting the controls on
a Web page” on page 168).
2 Edit the Web pages that refer to the CAB file. Change the version number
in the CODEBASE attribute to match the new number.
3 Replace the CAB file on the Web server with the new version.
182 PowerBuilder
Index
A crosstabs
modifying during execution 51
absolute positioning, Netscape browser 118
users redefining during execution 50
accent marks, Web DataWindow 114
using in applications 49
action codes 38
viewing underlying data 49
aggregation functions, Web DataWindow 113
custom DataStore objects 80
applications
architectures 5
using DataWindow objects in 11
D
data
B retrieving and updating 23
saving in graphs 97
bitmaps, dynamically adding and removing 66
sharing 83
buffers
updating 24
DataStore 82
Web control for ActiveX 178
DataWindow 27, 41
Web DataWindow 111, 143
Button controls, Web DataWindow 115
data sources
external 26, 82
types 3
C database connections
about 18
CAB file, Web control for ActiveX 180 Web control for ActiveX 177
Case function, Web DataWindow 113 Web DataWindow 143
character set, foreign language 114 database errors 37
Clicked events in graphs 101 databases
client control, Web DataWindow 109 communicating with 18
client/server applications 5 connecting automatically 20
CODEBASE HTML attribute, Web ActiveX 168 data source 3
column status in DataWindow controls 41 disconnecting automatically 20
COMMIT statement and SetTransObject 21 retrieving, presenting, and manipulating data 2, 23
communication with databases 18 snapshot connections 20
CONNECT statement and SetTransObject 21 transaction management 21
connection caches, defining in EAServer 122 updating 24
controls, supported in Web DataWindow 110 DataModified status 41
create capability for Modify 66 DataObject property of DataWindow controls 16
Create method 67 DataStore objects
CreateComponent method, example 140 about 2
CrosstabDialog function 50 accessing data 82
184 PowerBuilder
Index
186 PowerBuilder
Index
188 PowerBuilder