Back to Basics: Database Development Berndt Hamboeck
From information storage to SQL commands 6
Feature: The Debut of DataWindow.NET Part 1 Jim O’Neil
DataWindow technology meets the .NET Framework 10
Flowcharts: Does the Stupid Thing Work? Mike Deasy
In the beginning there was humor 16
Feature: Adaptive Server Enterprise Bruce Armstrong
Produce more powerful results with your ASE database 18
Data Interfaces: OLE DB (Microsoft SQL Sanjiv Das
Server) Part 2 DataWindows and OLE DB 24
Pocket PB: Not Tomorrow…Today Bill Allison
Pocket PowerBuilder and Custom Today items 30
www.PowerBuilderJournal.com
U.S. $15.00 (CANADA $16.00)
APRIL 2004 - Volume: 11 Issue: 4
RETAILERS PLEASE DISPLAY UNTIL JUNE 30, 2004
$15.00US $16.00CAN
Whither PowerScriptIn these days of tight IT budgets,
managers make purchasing decisionsbased on perceived needs
by Bruce Armstrong pg. 4
From the Co-editors Wireless’s Next Step
One thing we love to do in high tech is invent new terms
by Bob Hendry pg. 3
Industry Announcementsby Bruce Armstrong pg. 34
Pocket PowerBuilder 1.5 adds support for additional native objects
and controls for the Pocket PC
• • •EAServer 5.0 offers significant
enhancements to EAServer Manager,providing support for HTTP directory
browsing and more
0 09281 01314 3
0 3
POWERBUILDER AND .NET pg.10
Don't Mess with it
You StupidIdiot!
DidYou Messwith It?Does
AnyoneKnow?
Will YouGet in
Yes
Yes
Yes
No
No
NO PROBLEM!!!
CanYou BlameSomeone
Else?
Yes
No
pkidy15u.dll DisplayApp 1
Run App
User taps Item
DisplayA 2
August 15–19 Orlando, FL
04
3www.SYS-CON.COM/pbdj/ PBDJ volume11 issue4
E D I T O R I A L A D V I S O R Y B O A R DBRUCE ARMSTRONG, MICHAEL BARLOTTA, ANDY BLUM,
RICHARD BROOKS, KOUROS GORGANI, BAHADIR KARUV, PhD,BERNIE METZGER, JOHN OLSON, SEAN RHODY
COEDITOR-IN-CHIEF: BRUCE ARMSTRONGCOEDITOR-IN-CHIEF: BOB HENDRYEXECUTIVE EDITOR: NANCY VALENTINEASSOCIATE EDITOR: JAMIE MATUSOW ASSOCIATE EDITOR: GAIL SCHULTZ ASSOCIATE EDITOR: JEAN CASSIDYASSOCIATE EDITOR: JENNIFER VAN WINCKEL
ONLINE EDITOR: LIN GOETZCONTRIBUTING EDITOR: JOHN OLSON
TECHNICAL EDITOR: BERNIE METZGERNEWS EDITOR: BRUCE ARMSTRONG
DATAWINDOWS EDITOR: RICHARD BROOKSRESEARCH EDITOR: BAHADIR KARUV, PhD
W R I T E R S I N T H I S I S S U EBILL ALLISON, BRUCE ARMSTRONG, SANJIV DAS,
MIKE DEASY, BERNDT HAMBOECK, BOB HENDRY, JIM O’NEIL
S U B S C R I P T I O N SFOR SUBSCRIPTIONS AND REQUESTS FOR BULK ORDERS,
PLEASE SEND YOUR LETTERS TO SUBSCRIPTION DEPARTMENT
SUBSCRIPTION HOTLINE: 888 303-5282COVER PRICE: $15/ISSUE
DOMESTIC: $149/YR. (12 ISSUES) CANADA/MEXICO: $169/YR.OVERSEAS: BASIC SUBSCRIPTION PRICE PLUS AIRMAIL POSTAGE
(U.S. BANKS OR MONEY ORDERS). BACK ISSUES: $12 U.S., $15 ALL OTHERS
PRESIDENT AND CEO: FUAT KIRCAALIVICE PRESIDENT, BUSINESS DEVELOPMENT: GRISHA DAVIDA
SENIOR VP, SALES & MARKETING: CARMEN GONZALEZPRODUCTION CONSULTANT: JIM MORGAN
GROUP PUBLISHER: JEREMY GEELANVICE PRESIDENT, SALES & MARKETING: MILES SILVERMAN
ACCOUNTS RECEIVABLE CHARLOTTE LOPEZFINANCIAL ANALYST: JOAN LAROSEACCOUNTS PAYABLE: BETTY WHITE
ADVERTISING DIRECTOR: ROBYN FORMADIRECTOR, SALES & MARKETING: MEGAN MUSSA
ADVERTISING SALES MANAGER: ALISA CATALANOADVERTISING SALES MANAGER: CARRIE GEBERT
ASSOCIATE SALES MANAGER: KRISTIN KUHNLEASSOCIATE SALES MANAGER: BETH JONES
PRESIDENT, EVENTS: GRISHA DAVIDACONFERENCE MANAGER: LIN GOETZ
ART DIRECTOR: ALEX BOTEROASSOCIATE ART DIRECTOR: LOUIS F. CUFFARIASSOCIATE ART DIRECTOR: RICHARD SILVERBERGASSISTANT ART DIRECTOR: TAMI BEATTY
VICE PRESIDENT, INFORMATION SYSTEMS: ROBERT DIAMONDWEB DESIGNER: STEPHEN KILMURRAYWEB DESIGNER: CHRISTOPHER CROCE
CIRCULATION SERVICE COORDINATOR: SHELIA DICKERSONCIRCULATION SERVICE COORDINATOR: EDNA EARLE RUSSELLCIRCULATION SERVICE COORDINATOR: LINDA LIPTON
JDJ STORE: BRUNILDA STAROPOLI
E D I T O R I A L O F F I C E SSYS-CON MEDIA
135 CHESTNUT RIDGE ROAD, MONTVALE, NJ 07645TELEPHONE: 201 802-3000 FAX: 201 782-9600
POWERBUILDER DEVELOPER’S JOURNAL (ISSN#1078-1889) is published monthly (12 times a year) for $149 by
SYS-CON Publications, Inc.,135 Chestnut Ridge Rd., Montvale, NJ 07645 Periodicals Postage rates are paid at
Montvale, NJ 07645 and additional mailing offices.POSTMASTER: Send address changes to:
POWERBUILDER DEVELOPER’S JOURNAL, SYS-CON Publications, Inc.,135 Chestnut Ridge Rd., Montvale, NJ 07645
© C O P Y R I G H TCopyright © 2004 by SYS-CON Publications, Inc. All rights reserved.
No part of this publication may be reproduced or transmitted in any form or by anymeans, electronic or mechanical, including photocopy or any information storage andretrieval system, without written permission. For promotional reprints, contact reprint coordinator Carrie Gebert. SYS-CON Publications, Inc., reserves the right to revise,republish and authorize its readers to use the articles submitted for publication.
WORLDWIDE NEWSSTAND DISTRIBUTIONCurtis Circulation Company. New Milford, NJNEWSSTAND DISTRIBUTION CONSULTANT
Gregory Associates/W.R.D.S. 732-607-9941 [email protected]
FOR LIST RENTAL INFORMATION:Kevin Collopy: 845 731-2684, [email protected] Cipolla: 845 731-3832, [email protected]
All brand and product names used on these pages are trade names,service marks or trademarks of their respective companies.
SYS-CON Publications, Inc., is not affiliated with the companies or products covered in PowerBuilder Developer’s Journal.
Bob Hendry is a PowerBuilder instructor for Envision Software Systems and a frequent speaker at national and international PowerBuilder conferences. He specializes in PFC development
and has written two books on the subject, including Programming with the PFC 6.0.
Wireless’s Next Step
One thing we love to do in high tech is invent new terms, especially acronyms, but newterms of any form really appeal to us. I must confess I find the terminology of technologyto be one of its paramount appeals. Of course, new terms sometimes fall into pervasive use
without adequate definition, leading to confusion, but making the originator or purveyor of suchterms feel great nonetheless. Sometimes terms fall into disfavor almost as rapidly as they appear.
Two terms floating around right now are access and distribution. Access is most often usedfor “Internet access,” implying the connection between a user or point of presence and the restof the Internet, usually represented by and often called a “cloud.” Distribution, on the otherhand, is the mechanism that provides the connection between a given user and said point ofpresence. All of this is very interesting in the context of wireless because it defines what is cer-tain to be one of the key battles in the evolution of wireless communications.
To illustrate this, consider two different models for wirelessly connecting to the Internet. Thefirst, based purely on access, is to use a relatively long-range connection between the client andthe entry point to the Internet cloud, akin to the way cellular works today. This is how most peo-ple envision 3G or WiMAX, for example, being used to access the Internet. The problem withthis model is that it uses fairly large cells, and thus doesn’t have good frequency-reuse charac-teristics for a large number of users and/or high bandwidth connections – limiting the numberof users and/or the speed of their connections, thus driving up prices. But it does allow a userequipped with a mobile access connection to carry this connection everywhere the appropriateinfrastructure exists.
The alternative would be to bring the Internet via a wired or wireless point-to-point connec-tion to a point of presence, and then use a distribution mechanism to provide the final link to theuser. An example here might be to use WiMAX or some functionally equivalent terrestrialmicrowave link to connect to a point of presence, and then use a Wi-Fi access point (again, forexample) to provide the infrastructure end of a distribution network. The other end would be, ofcourse, notebooks, PDAs, or handsets equipped with Wi-Fi capability. This allows a fair number ofusers to share the otherwise expensive wide-area broadband connection, and also largely solvesthe problem of getting wide-area signals to penetrate a building by avoiding it altogether.
Which model is better? That depends. It would be great to carry only one radio and have itwork everywhere. But this is something of a pipe dream, since it’s unlikely we’ll see a singlewide-area technology deployed everywhere. We also have a problem with building radio pene-tration as noted above, but we might be able to address this issue via repeaters or in-buildingmicrocells, as is done with cellular today.
On the other hand, using Wi-Fi as a distribution mechanism also makes a lot of sense, but youmight need a lot of access points to make this work. We can also deploy Wi-Fi meshes or lots ofaccess points in a metropolitan area, in effect using Wi-Fi as an access technology. Wi-Fi is certainto be pervasive, and has the potential for very high throughput, so why not just settle on that?
The bottom line is that both models will continue to flourish. Keep in mind that multimodeclients (and, eventually, multimode clients implemented with software-defined radio, or SDR)will mitigate this issue to some degree. One of the really exciting possibilities for future wirelesscommunications systems is that we may see wireless services disappear quite literally into theether, and not have to worry about having the right radio. It could eventually all be quite auto-matic and transparent. While our primary goal in wireless communications remains to narrowor even eliminate the behavioral and performance differences that exist between it and wire, anequally important goal is to improve ease of use so end users can do more communicating andless network-oriented thinking and planning. Oh, and there’s another term – SDR. We’ll coverthat in a later issue. And maybe a few others as well. ▼
BOB HENDRY, EDITOR-IN-CHIEF
FROM THE CO-EDITOR
4 PBDJ volume11 issue4 www.SYS-CON.COM/pbdj/
FROM THE CO-EDITOR
WRITTEN BYBRUCE
ARMSTRONG
Whither PowerScript
AUTHOR BIOBruce Armstrong is an
independent contractorin the Los Angeles area. A
member of TeamSybase,he has been using
PowerBuilder since ver-sion 1.0.B. He was a con-tributing author to SYS-CON’s PowerBuilder 4.0Secrets of the Masters
and the editor of SAMs’PowerBuilder 9:
Advanced Client/ServerDevelopment.
Since you’re reading this magazine,I have to assume that you have avested interest in PowerBuilder
and its continued success, and long tosee it regain some of its popularity.Many believe more marketing bySybase is the answer, but it’s only onepiece of the solution. Focusing on thatsolution ignores some importantdynamics taking place in the industry.
In these days of tight IT budgets,managers make purchasing decisionsbased on perceived needs. Those per-ceived needs are rarely the same as theneeds of the development staff. Youmay prefer PowerBuilder (as I do)because you are significantly more pro-ductive with it than any other tool.However, the perceived needs I’m hear-ing from development managers aremore along these lines:• Large talent pools: Are there enough
developers in the market who knowhow to use the software tools so theycan add resources as needed withouta huge recruiting effort? This alsohelps ensure that training is readilyavailable and affordably priced.
• Nonproprietary languages: Will thefuture of the language their develop-ment tools are based on be subject tothe whims (and perhaps bankruptcies)of one single vendor? This has beenone of the major, compelling points ofJava and the impetus for Microsoft tointroduce C# as an alternative.
• Reduce number of languages:Development managers have facedsignificant staff reductions, and arenow finding it hard to continue tosupport the wide variety of languagestheir applications are currently writ-ten in. They want to maximize theirstaff and reduce the impact of anyadditional staff losses by consolidat-ing development efforts to a smallerset of languages that can be moreeasily managed.
To address such management con-cerns, people have frequently suggestedthat the scripting language in
PowerBuilder should be changed fromPowerScript to a more nonproprietarylanguage. For the past few years, Javawas the favorite nominee for the newlanguage; C# is now another option.
However, such a move would becounterproductive for a number of rea-sons. First, Sybase would still have tomaintain PowerScript as a scripting lan-guage for backward compatibility,resulting in a dilution of the efforts oftheir development staff. Second, it’s alittle late in the game to try to positionPowerBuilder as a Java or C# develop-ment tool. The third and perhaps mostimportant reason is that implementingJava or C# as a scripting language wouldbe counterproductive to the main rea-sons that people would consider usingPowerBuilder to begin with: ease ofdevelopment and productivity.
You may have seen the controversysurrounding the statements of PhilipGreenspun (computer science instructorat MIT) in his Weblog that Java was an“SUV” (http://blogs.law.harvard.edu/philg/2003/09/20#a1762). Greenspunmust have been referring to the non-.NET version of Visual Basic, becausemany folks are finding that the transitionto .NET rivals Java for complexity. TomButton, the first Visual Basic productmanager and then later the vice presi-dent of developer tools for Microsoft,acknowledged .NET may be a difficulttransition for “meat and potatoes” devel-opers, but said the Internet’s require-ments are so different that Microsoftdidn’t want to settle for incrementalchanges. Kathleen Dollard, MicrosoftMVP, noted that “Microsoft is attemptingto address the complexity of Visual Basicin the Whidbey release, but that alonewon’t be enough to save the hobbyistprogrammer.”
The point is that folks are beginningto realize the complexity of the Java and.NET environments and the negativeimpact that it’s having on developerproductivity. Now is not the time to addthat additional burden on PowerBuilderas well. Instead, it’s time to focus again
on what made PowerBuilder a populardevelopment tool: giving developers atool that was both easy to use and high-ly productive. That doesn’t meanchanges aren’t needed. I see a need forimprovement in three areas:• IDE features: While the integration of
PD into PB is a good thing, we needto go further. In particular, true refac-toring support would be a great helpto those who are maintaining legacyapplications.
• Controls: We need some additionalWindows controls (better toolbarsupport, dockable windows, etc.). Inaddition, we need a new RTF controlthat wraps the one Microsoft suppliesin the OS while maintaining the olderone for another major release toallow people to transition. We alsoneed support for more current fea-tures of existing controls. In particu-lar, the DataWindow needs to addsupport for hierarchical display, auto-sizing columns, etc. We’ve been ableto implement most of that throughthe PFC, but it should be native tothe control now.
• PowerScript: If we want to attractpeople who are frustrated with thecomplexities of Java and .NET, thelanguage is going to have to addsome of the more modern featuresthat those developers will expect,such as parameterized constructors,user-defined enumerations, andinterfaces, and that will make all of usmore productive.
I’m sure you can think of others. Ifyou do, be sure to use the ISUGenhancement request system at theISUG Web site to let Sybase know(www.isug.com). In addition, if you arean ISUG member you can comment onthem and indicate your “vote” forwhether they should be incorporated.That gives Sybase some feel for whattheir customers believe is important.
Till next month....▼
www.SYS-CON.COM/pbdj/6 PBDJ volume11 issue4
SECURITY
Database DevelopmentFrom information storage to SQL commands
Iremember quite well the first timeI started developing databaseapplications. Back then I hadheard a lot of different terms and
names that I didn’t understand, and Iwasn’t courageous enough to askwhat those terms meant (yes, I wasvery young and shy). Now, severalyears later, everything is clear, so ifyou’re in this same position and havejust starting programming databases,this article may help you. If you are adatabase veteran, this article may helpyou understand the problems new-comers have when they’re just start-ing as junior developers within yourproject. Okay, let’s start.
What Is a Database?Think of a database as an organized
mechanism that is capable of storinginformation and through which one ormore users are able to look at storedinformation in an effective and efficientmanner. An example from everyday lifeis a phone book, which can be seen as atype of database. Its data consists ofrows that contain attributes like indi-vidual names, addresses, and, of course,telephone numbers. The listings arealphabetized or indexed, allowing theuser to reference a particular personwith ease.
This data is stored in a databasesomewhere on a computer and is con-tinually maintained as people move todifferent cities or states. Entries areadded or deleted from the phone bookand also modified as people changenames, addresses, and/or telephonenumbers. This is exactly what’s donewith data in a database. In very simpleterms, a database is a collection of data.
What Is SQL?If you ever come to Europe and visit
the author of this article, you’ll be sur-prised at how many different languages(at least dialects) are spoken just within
a two-mile radius of where I live. Even Imight have trouble ordering from amenu via my native tongue if the waiterspeaks only his country’s language.Imagine that the database is a foreignland in which you seek information. Thelanguage spoken there is called theStructured Query Language (SQL),which is what you’ll have to speak toexpress your needs. Just as you’d order ameal from a menu in a different countryor town, using this language you canrequest specific information from with-in a database in the form of a query. SQLis the standard language used to com-municate with a relational database.The prototype was originally developedby IBM. SQL is pronounced either oftwo ways: as the letters S-Q-L, or as“sequel”; both pronunciations areacceptable. However, most experiencedSQL users tend to use the latter pronun-ciation.
What Is ANSI SQL?You may have heard the term ANSI
or IS standard. The American NationalStandards Institute (ANSI) is an organi-zation that approves certain standardsin many different industries. SQL isconsidered the standard language inrelational database communication,originally approved in 1986 based onIBM’s implementation. In 1987, theANSI SQL standard was accepted as theinternational standard by theInternational Standards Organization(ISO). The standard was revised again in1992 and called SQL-92. The neweststandard is now called SQL-99; it’s alsoreferred to as SQL3. SQL-99 has fiveinterrelated documents and other doc-uments may be added in the nearfuture. The five interrelated parts are:• SQL/Framework: Specifies the gener-
al requirements for conformance anddefines the fundamental concepts ofSQL
• SQL/Foundation: Defines the syntax
and operations of SQL• SQL/Call-Level Interface: Defines the
interface for application program-ming to SQL
• SQL/Persistent Stored Modules:Defines the control structures thatthen define SQL routines and alsodefines the modules that contain SQLroutines
• SQL/Host Language Bindings:Defines how to embed SQL state-ments in application programs thatare written in a standard program-ming language
The latest ANSI standard (SQL-99),which has replaced the SQL-92 stan-dard, is about 2,000 pages, so if you’rebored and don’t know what to do checkthem out at www.sql-99.org.
With any new standard, there areboth advantages and disadvantages.First and foremost, a standard steers allinterested vendors of products in theappropriate direction for development.In the case of SQL, a standard provides abasic skeleton of necessary fundamen-tals, which as an end result allows con-sistency between various implementa-tions and better serves increased porta-bility (not only for database programs,but databases in general and individualswho manage databases).
Some may argue that a standard isnot that good, limiting the flexibility andpossible capabilities of a particularimplementation. However, most vendorswho comply with the standard haveadded product-specific enhancementsto standard SQL to fill in these gaps.
A standard is good, considering boththe advantages and disadvantages. Theexpected standard demands featuresthat should be available in any com-plete SQL implementation and outlinesbasic concepts that not only force con-sistency between all competitive SQLimplementations, but also increase thevalue of a SQL programmer.
WRITTEN BYBERNDT
HAMBOECK
AUTHOR BIOBerndt Hamboeck is asenior consultant forBHITCON (www.bhitcon.net). He’s a CSI,
SCAPC8, EASAC, andSCJP2 and started hisSybase development
using PB5.
©2002 Sybase, Inc. All rights reserved. All trademarks are the property of their respective owners.
T H E S T R A I G H T G O O D S O N E A S e r v e r .
It’s easy. It’s proven. Sybase EAServer is the
complete solution with the highest ROI
for moving PowerBuilder applications to the
Web. But don’t just take our word for it. Sierra
Club, The Greenbrier Companies and Hennepin County, MN, I n f o r m a t i o n A n y w h e r e™
have all rapidly web-enabled their PowerBuilder apps
with a faster and easier time to market. To discover how
you can leverage your existing investments, check out
our ROI Case Study Guide at
www.sybase.com/pbextension.
S Y B A S E e - B U S I N E S S S O F T W A R E .
E V E R Y T H I N G W O R K S B E T T E R W H E N E V E R Y T H I N G W O R K S T O G E T H E R .TM
BRING APPS TO THE WEB
WITHOUT LEAVINGYOUR POWERBUILDER
INVESTMENTBEHIND.
8 PBDJ volume11 issue4 www.SYS-CON.COM/pbdj/
Relational DatabasesA relational database is a database
divided into logical units called tables,where tables are related to one anotherwithin the database. A relational data-base allows data to be broken down intological, smaller, and manageable units,allowing for easier maintenance andproviding more optimal database per-formance according to the level of orga-nization. Tables are related to oneanother through a common key (datavalue) in a relational database. Again,tables are related in a relational data-base, allowing adequate data to beretrieved in a single query (although thedesired data may exist in more than onetable). By having keys, or fields, amongrelational database tables, data frommultiple tables can be joined to formone large result set.
Client/Server TechnologyIn the past, the computer industry
was predominately ruled by mainframecomputers – large, powerful systemswith both high storage capacity and highdata-processing capabilities. Users com-municated with the mainframe throughdumb terminals that did not think ontheir own, but relied solely on the main-frame’s CPU, storage, and memory. Eachterminal had a data line attached to themainframe. The mainframe environ-ment definitely served its purpose andstill does today in many businesses, buta greater technology was soon intro-duced: the client/server model.
Modern database systems reside onvarious types of computer systems withvarious operating systems. The mostcommon types of operating systems areWindows-based systems and common-line systems such as Unix. Databasesreside mainly in client/server and Webenvironments. A lack of training andexperience is the main reason for failedimplementations of database systems.Nevertheless, an understanding of theclient/server model and Web-based sys-tems is imperative with the rising (andsometimes unreasonable) demandsplaced on today’s businesses as well asthe development of Internet technolo-gies and network computing.
An Introduction to Web-BasedDatabase Systems
Business information systems aremoving toward Web integration.Databases are now accessible throughthe Internet, meaning that customersaccess an organization’s informationthrough an Internet browser such asInternet Explorer, Netscape, or Opra
(just to mention the most used ones).Customers (users of data) are able to
order merchandise, check inventories,check the status of orders, make admin-istrative changes to accounts, transfermoney from one account to another, andso forth. A customer simply invokes anInternet browser, goes to the organiza-tion’s Web site, logs in (if required by theorganization), and uses an applicationbuilt into the organization’s Web page toaccess data. Most organizations requireusers to register with them and will issuea login and password to the customer.
Of course, many things occur behindthe scenes when a database is beingaccessed via a Web browser. SQL, forinstance, can be executed by the Webapplication. This executed SQL is usedto access the organization’s database,return data to the Web server, and thenreturn that data to the customer’sInternet browser.
The basic structure of a Web-baseddatabase system is similar to that of aclient/server system from a user’s stand-
point. Each user has a client machinethat has a connection to the Internetand contains a Web browser. The net-work just happens to be the Internet (inthe case of a Web-based database), asopposed to a local network. For themost part, a client is still accessing aserver for information. It doesn’t matterthat the server may exist in anotherstate, or even another country. The mainpoint of Web-based database systems isto expand the potential customer baseof a database system that knows nophysical location bounds, thus increas-ing data availability and an organiza-tion’s customer base.
Different SQL ImplementationsEach implementation of SQL is more
or less vendor specific. A database serv-er is a product like any other piece ofsoftware on the market; one vendoroffers this feature, another one that fea-ture, but it is to the benefit of the vendorto ensure that its implementation is
compliant with the current ANSI stan-dard so that users are able to port appli-cations easily and know how to use it; itwould be very discouraging otherwisefor the developers or database users tohave to learn another language to main-tain functionality with the newlyinstalled system.
With each vendor’s implementation,however, you’ll find that there areenhancements that serve a purpose foreach database server. These enhance-ments – special commands, options, ortools – are a bonus to the standard SQLpackage and available with a specificimplementation. Keep in mind that ifyou use these enhancements, you won’tbe able to easily port a database orapplication to another system.
Popular Relational DatabaseVendors
Some of the best-known databasevendors are Sybase, Oracle, Microsoft,and IBM (including Informix); they offervarious versions of relational databasesat a significant cost. There are also othervendors or groups who supply opensource versions of a relational database,like MySQL, PostgresSQL, and SAP, allwith some advantages and disadvan-tages for their users. There are manymore vendors than the ones mentioned;however, this list included names that Ithought you may recognize.
A SQL SessionYou have probably heard the term
SQL session already; this means that auser interacts with a relational databasethrough the use of SQL commands. Thesession is established when a user ini-tially connects to the database. Withinthe scope of such a SQL session, all validSQL commands can be entered by theuser to query the database, manipulatedata in the database, and define data-base structures such as tables or viewswith its columns. A session may beinvoked by either a direct connection tothe database, through an applicationlike ISQL, or any in-house developedapplication written in PowerBuilder, forexample. In both cases, sessions arenormally established by a user at a ter-minal or workstation that communi-cates through a network with the com-puter that hosts the database.
To establish a database connectionthe CONNECT USING <transac-tionobject>; command is used inPowerBuilder. When you attempt toconnect to a database usingPowerBuilder, you need to provide apassword that is associated with your
“Data administration is much more specific toeach SQL implementa-tion than those core
commands of the SQLlanguage are”
current username. The username isused to authenticate yourself to thedatabase, and the password is the keythat allows entrance.
When a user disconnects from adatabase, the SQL session is terminated.The “DISCONNECT USING <transac-tionobject>;” command is used to dis-connect a user from the database.
Types of SQL CommandsNow we’ll discuss the basic cate-
gories of the different commands usedin SQL to perform various functions.These functions include the building ofdifferent database objects, manipulatingthese objects, filling the database tableswith your data, updating and deletingexisting rows in tables, getting the dataout, controlling user rights, and data-base administration.
The categories these commands fitinto are:• Data Definition Language (DDL)• Data Manipulation Language (DML)• Data Query Language (DQL)• Data Control Language (DCL)• Data administration commands• Transactional control commands
DEFINING DB STRUCTURESData Definition Language is the part
of SQL that allows a database user tocreate and restructure database objects,such as the creation or the deletion of atable. Some of the most fundamentalDDL commands include the following:• CREATE TABLE: Creates a new table
with one or more columns• ALTER TABLE: Removes or adds one
or more columns, or changes the datatype or nullability of one or morecolumns
• DROP TABLE: Drops the specifiedtable
• CREATE INDEX: Creates an index onthe specified columns of the specifiedtable
• DROP INDEX: Drops the specifiedindex
MANIPULATE YOUR DATAData Manipulation Language is used
to manipulate the data within the objectsof a relational database. There are threebasic commands:• INSERT: Adds data to a table• UPDATE: Changes existing data with-
in a table• DELETE: Removes data from a table
SELECTING DATATo get data (information) out of a
database, use a query. A query is issuedto the database through an application
interface or via a command-lineprompt. Though comprised of only onecommand, Data Query Language is themost concentrated form of SQL formodern relational database users. Thebase command is:• SELECT: Composes queries against a
relational database. Queries, fromsimple to complex, from vague tospecific, can be easily created.
DATA CONTROL LANGUAGEData control commands allow you to
control access to data within your data-base. These DCL commands are used tocreate objects related to user access andcontrol the distribution of privilegesamong users. Some data control com-mands are:• GRANT: Grants the specified object
permission for a specific object (atable view or stored procedure)
• REVOKE: Removes permissions previ-ously granted
DATA ADMINISTRATIONThese commands allow the user to
perform audits and perform analysis onoperations within the database, forexample. They can also be used to helpanalyze system performance (for exam-ple, the set statistics commands in ASE).
Don’t get data administration con-fused with database administration.Database administration is the overalladministration of a database, whichenvelops the use of all levels of com-mands. Data administration is muchmore specific to each SQL implementa-tion than those core commands of theSQL language are.
TRANSACTIONAL CONTROLIn addition to the previously intro-
duced categories, there are commandsthat allow the user to manage databasetransactions.• COMMIT: Saves and ends database
transactions• ROLLBACK: Takes back database
transactions• SAVEPOINT: Creates points within
groups of transactions in which toROLLBACK
• SET TRANSACTION: Places a nameon a transaction
ConclusionThis article provided you with an
overview of some terms you’ll hearwhen you start database development. Iwish you many years of happy databasecoding with PowerBuilder! ▼
9PBDJ volume11 issue3www.SYS-CON.COM/pbdj/
previewing may 11, 2004,at networld+interop, las vegas
InformationStoragE+Security
Journal!
for more information visit www.ISSJournal.com
From the World’s Leading i-Technology Publisher
©COPYRIGHT 2004 SYS-CON MEDIA. ALL BRAND AND PRODUCT NAMES ARE TRADE NAMES, SERVICE MARKS OR TRADEMARKS OF THEIR RESPECTIVE COMPANIES.
10 www.SYS-CON.COM/pbdj/PBDJ volume11 issue4
Introduced in 1991 and patented in October 1996,PowerBuilder’s DataWindow technology remains one of the mostflexible, dynamic, and versatile means for data retrieval, modifi-cation, and presentation available in any development tool. By
launching DataWindow.NET along with PowerBuilder 10 later thisyear, Sybase is continuing its commitment to the four-phased .NETstrategy announced in 2002.
DataWindow.NET is a separate product offering that bringsPowerBuilder’s hallmark technology to the growing number of pro-grammers in Microsoft’s.NET environment, including those usingdevelopment tools such as Microsoft’s Visual Studio .NET, Borland’sC#Builder, and the open source #develop (SharpDevelop). In this two-part article we’ll look at the overall design of this exciting new productas well as work through a simple example in C#.
Author’s note: This article was written late in the Beta 1 cycle ofPowerBuilder 10 and so some details may not completely or accuratelyreflect what is delivered in subsequent beta cycles or whenDataWindow.NET becomes generally available.
High-Level ArchitectureThe primary functionality of the DataWindow is concentrated into
two .NET assemblies (see Figure 1), DataWindow.DLL (built in C#) andDataWindowInterop.DLL (built in managed C++), as well as the coreDataWindow server engine, PBDWN100.DLL, which is built usingunmanaged C++. Since PowerBuilder shares the core DataWindowengine, the behavior of the DataWindow in the .NET environment willbe nearly identical to that of PowerBuilder. This design approach is insharp contrast to that of the Java DataWindow implementation that
was formerly delivered with Sybase PowerJ, an implementation thatmany feel included an inadequate subset of the PowerBuilderDataWindow functionality.
In addition to the two DataWindow assemblies and the core engine,the OLE-DB, ODBC, and native database (Oracle, Sybase ASE andDirectConnect, and Informix) drivers familiar to PowerBuilder develop-ers are included. These drivers are identical to those delivered withPowerBuilder and so offer the same feature set and performance thatyou are accustomed to within PowerBuilder applications.
To those well-established connectivity options, Sybase is introduc-ing a new ADO.NET driver allowing .NET programmers to use a singledatabase connection seamlessly across various programming con-structs including Command objects, DataSets, DataTables, DataViews,and, of course, the Sybase DataWindow. The ADO.NET driver imple-mentation consists of a .NET assembly (PBDATA100.DLL) as well as anunmanaged driver library (PBADO100.DLL) that parallels the imple-mentation and feature set of the other PowerBuilder native databaseinterfaces.
Also being delivered is DataWindow Designer, a graphical userinterface for developing DataWindow objects. This product is a modifi-cation of the now discontinued DataWindow Builder, which was essen-tially a standalone PowerBuilder DataWindow painter that JavaDataWindow developers could use to create DataWindow objects with-out the need for the complete PowerBuilder product. PowerBuilderdevelopers who also plan to use DataWindows in .NET applicationscan bypass this tool and use the PowerBuilder 10 environment instead.
DataWindow Object ModelFigure 2 shows a portion of the DataWindow object model generat-
FEATURE
WRITTEN BY JIM O’NEIL
An overview of the architecture Part 1
11PBDJ volume11 issue4www.SYS-CON.COM/pbdj/
ed via the reverse-engineering features of Sybase PowerDesigner 10. Ithighlights the four interfaces and the three main classes that constitutethe DataWindow. In addition to these classes and interfaces, there aretwo transaction classes for accessing back-end databases as well as del-egates (or event handlers) and exception classes to round out theimplementation. We’ll look at all these aspects next.
DataWindow Interfaces and ClassesAs you can see from the object model diagram in Figure 2, three of
the four interfaces correspond directly with the three main classes:DataWindowChild, DataStore, and DataWindowControl. We’ll brieflyexplore the interrelationships of these interfaces and classes.
IDATAWINDOWBASE/DATAWINDOWCHILDThe root interface is IDataWindowBase, which includes the subset
of methods shared by all three classes including Retrieve, UpdateData(yes, there are some naming changes!), and the familiar family ofGetItem and SetItem methods. The DataWindowChild class directlyimplements this interface, whereas the DataStore and DataWindowControl classes do so indirectly by implementing separate interfacesthat extend IDataWindowBase.
You’ll also notice that DataWindowChild is a class and extends thebasic .NET System.Object class. Compared to PowerBuilder, whereDataWindowChild extends a PowerBuilder structure, this is not a trueclass.
IDATASTORE/DATASTOREThe IDataStore interface extends IDataWindowBase by adding
properties and methods appropriate for a DataStore (and DataWindowcontrol) but not available for a DataWindow child. These include theLibraryList and DataWindowObject properties, which are used to spec-ify the DataWindow object definition assigned to a specific instance ofa DataStore or DataWindow control. Also defined on IDataStore are anumber of events that will appear familiar, albeit with some namingchanges to reflect standard .NET naming conventions (e.g., BeginRetrieve in lieu of PowerBuilder’s RetrieveStart, BeginPrint forPrintStart, and BeginUpdate for UpdateStart).
The DataStore class extends the .NET System.ComponentModel.Component class, which in turn extends System.MarshalByRefObject,thus fulfilling one of the requirements for allowing DataStore instancesto be used across domain boundaries in applications that supportremoting, which is the .NET approach to building distributed applica-tions.
IDATAWINDOW/DATAWINDOWCONTROLFurther refining IDataStore is the IDataWindow interface that incor-
porates the methods and events that have visual context in aDataWindow control such as scrolling, selecting a row, and changingthe column that has input focus. The DataWindowControl class alsoimplements a second interface, IDataWindowGraph, which includes allof the graph-related methods such as SetSeriesStyle, FindCategory, andDataCount.
The DataWindowControl class extends System.Windows.Forms.Control, which includes classes such as buttons, labels, the list view,and numerous other widgets familiar to developers of rich-client appli-cations.
The progressive refinement of functionality gained through theinheritance hierarchy of the three main interfaces offers some powerfulcapabilities that even PowerBuilder developers do not currently have.Have you ever had to duplicate your PowerBuilder code because youneed to apply the same operation, say a sort, to both a DataStore and aDataWindow control? When programming in a .NET language, you canbuild methods that accept an argument of IDataStore, so at runtimeeither a DataWindow control or a DataStore can be passed in.
TRANSACTION CLASSESComplementing the interfaces and classes that contain the imple-
mentation of the DataWindow and DataStore are two additional classesthat facilitate the connectivity from the DataWindow objects to a data-base. These classes are illustrated in the object model diagram shownin Figure 3.
TRANSACTIONThe Transaction class is analogous to the Transaction object in
PowerBuilder. Most of the properties should appear familiar, as will theDbmsType enumeration options that in PowerBuilder are provided asstrings to the DBMS property of the Transaction object. TheTransaction class in the .NET product provides direct object methodsfor database connectivity and transaction management as opposed tothe PowerScript statements of CONNECT, DISCONNECT, ROLLBACK,and COMMIT, each of which accepts an optional USING transaction-object clause. You’ll also notice that the syntax-from-SQL functionalityis retained in the .NET environment, thus offering the same capabilitiesto create DataWindows “on-the-fly” as in PowerBuilder.
ADOTRANSACTIONOne of the disadvantages of using the Transaction class is that it
cannot be shared by other .NET database constructs such as DataSetsor Command objects, and that’s where the Sybase.DataWindow.AdoTransaction class comes in. AdoTransaction is modeled on theSystem.Data.IDbCommand interface that every ADO.NET providerimplements. Specifically, AdoTransaction encompasses:• A reference to an object that implements the System.Data.
IDbConnection interface; for instance, this might be a System.Data.OleDb.OleDbConnection class reference representing a con-nection to an Oracle database via an OLE-DB.NET data provider.
• An optional, transitory reference to a System.Data.IDbTransactioninterface representing an open transaction to the database on theconnection referenced by the System.Data.IDbConnection interfacedescribed above.
• The infrastructure necessary to associate the ADO.NET connectionwith the internal transaction semantics of a DataWindow control orDataStore instance.
Listing 1 provides code segments from a representative approachfor managing a transaction in ADO.NET to update a DataStore. In anactual application these various code fragments would likely appear indifferent events or scripts. Also, for clarity each fragment assumes thatthe System.Data and Sybase.DataWindow namespaces have beenexplicitly declared within the respective modules via the directive.
DelegatesThe design pattern for implementing events in .NET is based on the
FIGURE 1 | Sybase DataWindow.NET architecture
12 www.SYS-CON.COM/pbdj/PBDJ volume11 issue4
use of delegates (or event handlers), which arespecialized classes that provide a callbackmechanism to methods or, more specifically,events that share the same signature as thedelegate. One or more methods can be associ-ated with a given event handler so that when-ever the associated event is triggered, thosemethods on the receiving object will execute.The event itself is initiated when code else-
where in an application invokes a method onthe target object with the specific name “On”followed by the name of the desired event.
The DataWindow uses this same .NET par-adigm to implement the events of theDataStore and DataWindow control, with theadded twist that the destination and some-times the source of the events are within theunmanaged code of the DataWindow server
engine. For applications that use the corefunctionality of the DataStore andDataWindowControl classes – theDataWindowChild class has no events – thedetails of how the event processing is imple-mented are not a primary concern; however, ifyou plan to extend DataWindow functionalityto include new custom events, you’ll need toensure that the design conforms to the .NETFramework delegate model.
When writing code for events, you’ll imme-diately find that many of their names havebeen modified from their analogs inPowerBuilder to conform to .NET namingstandards. A second difference you’ll notice isthat regardless of the event, you’ll always havetwo specific arguments available:• sender: A System.Object reference indicating
the class that originated the event• e: An object or descendant of
System.EventArgs that contains additionalinformation relevant to the event
Optionally, a specialized descendant classSystem.CancelEventArgs can be used (orextended) whenever an event is cancelable. Asan example, in RowFocusChanging, if it isdetermined that the current row should not beallowed to change, you can set the Cancelproperty of the argument class to true to pre-vent the RowFocusChanged event from firing.In PowerBuilder, you would have done this byreturning the value of 1 from the RowFocusChanging event or would have used the dep-recated SetActionCode method.
For the DataStore class, most events havean argument structure that’s specialized forthe specific event type. For instance, theretrieve events (BeginRetrieve, RowRetrieved,and EndRetrieve) are passed row count androw number data via a RetrieveEventArgs classinstance (or descendant thereof). Likewise, forthe print events the page and copy numbersare provided in descendants of PrintEventArgs, and for the EndUpdate event the num-ber of rows deleted is available inEndUpdateEventArgs.
Of note to the DataStore class and toDataWindowControl by virtue of inheritance,a new DataWindowCreated event not current-ly available to PowerBuilder users is provided.The DataWindowCreated event fires whenevera new DataWindow object is assigned to theDataStore or DataWindow control, a type of“postopen” event for those familiar with thatconcept used in the PowerBuilder FoundationClasses (PFC). This construct is particularlyimportant in form instantiation code wherethe nature of the .NET event processing cou-pled with internal DataWindow engine eventhandling is such that it is not programmatical-ly correct to reference the properties of aDataWindow control or DataStore instance incode until this event has fired.
The DataWindowControl class extendsSystem.Windows.Forms.Control and thereforeinherits quite a few events shared by the com-
FIGURE 3 | Transaction classes
FIGURE 2 | DataWindow interfaces and classes
©2003 Sybase, Inc. All rights reserved. All trademarks are the property of their respective owners.
INFORMATION LIQUIDITY.
POWERBUILDER 9.0THE CLASSIC,
TRIED-AND-PROVENCLIENT/SERVER
DEVELOPMENT TOOL.
S Y B A S E I N T E G R A T I O N T E C H N O L O G I E S . E V E R Y T H I N G W O R K S B E T T E R W H E N E V E R Y T H I N G W O R K S T O G E T H E R .TM
POWERBUILDER 9.0THE HANG-ONTO-
YOUR-SEAT CLIENT/SERVER
DEVELOPMENT TOOL.
4GL RAD Tools
For years, PowerBuilder® has reigned
as the premier development tool
for client/server applications. Our
newest iteration extends both our
leadership and your investment
in skills and applications for
client/server development. There’s
a host of exciting new features.
Download all the technical details
at sybase.com/powerbuilder.
Take your client/server applications
to the next level with the
PowerBuilder Native Interface.
Integrate your existing and new
PowerBuilder applications with
C and C++ applications. And
easily work with J2EE and .NET
components and applications
exposed as Web Services. Details
at sybase.com/powerbuilder.
14 www.SYS-CON.COM/pbdj/PBDJ volume11 issue4
mon user interface controls. Instead of havinga Clicked event as in PowerBuilder, you willsee a Click event that fires in the expectedmanner, and similarly for DoubleClick and thevarious mouse-related methods includingdrag-drop activities. For these inheritedevents, you’ll notice that the argument struc-ture is rather void of information from aDataWindow perspective, where you are usedto receiving row, column, and sometimes evenadditional information.
Overloading these built-in events with
new DataWindow-specific event structuresor creating additional but similarly namedevents would have been confusing for a .NETprogrammer; therefore, the information isobtained via a property on the DataWindowObject, ObjectUnderMouse. This propertycaptures information that you’re accustomedto obtaining in PowerBuilder using theGetObjectAtPointer and GetBandAtPointermethods; however, instead of a tab-delimit-ed string, the object information is con-tained in a structure and a class instancethat contains the properties of the specificobject selected.
Figure 4 shows the class hierarchy thatimplements the ObjectUnderMouse function-ality. The DataWindow band information androw number are properties of the ObjectAtPointer structure, but more detailed informa-tion is contained in the Gob (short for GraphicObject) property. Note that the GraphicObjectclass is abstract, reflecting the fact that theactual runtime class of the Gob property willdepend on which specific DataWindow objectwas encountered. If you click on a label in theDataWindow control, the actual class of the
Gob property will be GraphicObjectText; how-ever, if it were a column you selected, youwould obtain an instance of theGraphicObjectColumn class instead and beable to access the column number from with-in it as demonstrated in Listing 2.
With this code in place, whenever one ofthe column objects in the dwDepartmentDataWindow is clicked on, a message box willbe displayed (see Figure 5). (We’ll create a ver-sion of a DataWindow object that you can trythis code out on in Part 2.)
As you can see from the class hierarchy inFigure 4, only the GraphicObjectColumndescendant class currently contains any addi-tional information; however, this class struc-ture paves the way for a future release to addadditional properties to each of theGraphicObject descendant classes, ultimatelyresulting in “dot-notation” functionality simi-lar to that which became available in version 5of PowerBuilder.
ExceptionsOne of the more noticeable differences that
an experienced PowerBuilder developer will dis-cover when programming in the .NET world isthe pervasive use of exceptions. None of thePowerScript functions that operate on aDataWindow control (or on a DataStore orDataWindow children) are exception enabledand instead typically return a value of –1 when afailure is detected. In .NET most DataWindowand DataStore methods will throw one or moreexception types depending on the nature of thefailure in the method processing. Table 1includes a partial list of the exceptions as of thiswriting. Refinements continue to be made soyou can expect the exceptions raised by thereleased version of the product to differ at leastslightly.
Many of the exceptions shown in Table 1extend built-in classes derived from System.Exception. For instance, InvalidColumnException and InvalidRowNumberExceptionboth extend System.ArgumentOutOfRangeException, thus allowing .NET developers tohandle the DataWindow exceptions at varyinglevels of granularity.
SummaryIn this article, we looked at the overall
architecture of DataWindow.NET. In Part 2we’ll develop a sample application that con-tains two DataWindows with a master-detailrelationship.▼
AUTHOR BIOJim O’Neil is a principal technical support engineer at Sybase, Inc. Hehas been with Sybase for nearly eight years, concentrating on resolv-ing customer issues with Sybase products including PowerBuilder,EAServer, and PowerJ. Prior to Sybase, Jim spent about 10 yearsworking as a software engineer for two defense contracting firms.
FIGURE 5 | Output from Listing 2
TABLE 1 | Sample DataWindow exceptions
FIGURE 4 | GraphicObject class hierarchy
Exception When RaisedChildNotFoundException When the GetChild method fails to find a nested report or
DropDownDataWindow with the provided name
DbErrorException When an error occurs in a database-related operation; this exception replacesthe DBError event in PowerBuilder
DataWindowLoadFailedException When the requested DataWindow object cannot be found in the suppliedlibrary list
InvalidColumnException When an invalid column number or name is supplied as an argument to amethod
InvalidExpressionException When an expression supplied to methods such as Filter, Sort, and Modify isfound to be invalid
InvalidRowNumberException When an invalid row number is supplied as an argument to a method
MethodFailureException When a method fails for some unexpected reason
~for listings continue to page 33~
16 PBDJ volume11 issue4 www.SYS-CON.COM/pbdj/
FLOWCHARTS
Does the Stupid ThingWork?
In the beginning there was humor
We have all seen them, allremember them – the IToffice funnies. There wasthe Story of Creation as
told to URK – a lovely reenactment ofGenesis put together by hard-coremainframers. There was a document(prepared by individuals working in thedefense industry) that had a hilariouslist of acronyms, mostly defining themany ways that the worker bee wasdumped upon. It was before Dilbert,before the blond jokes, even before wecould IM each other with the latestclassic comedy. It was simplicity itself.
The “Does The Stupid Thing Work”flowchart (see Figure 1) showed you inno uncertain terms how to cover yourbackside in case you were actuallydoing some work, showing some initia-tive, or attempting to be helpful. It washysterical; I never worked in an officewhere someone did not either have itpinned to their cube, tucked into a fileof humor, or passed around en masse.The problem is that over time it seemsthat we have adopted some of the idealsin this flowchart into real life.
A Title Is Worth a Thousand Pictures
At the top of the flowchart is thebeginning question, the start symbol –with a neat and orderly A and B optionflowing down from that initial query.Right off the bat, the attitude is thatwhatever it is your users have asked youto maintain, develop, or deploy is stu-pid. This is inherently true because theusers who have paid you handsomelyfor your labor are themselves idiots.This is the first stumbling block to oursuccess and longevity as IT profession-als. They are not all stupid, and most oftheir ideas aren’t. We tend to lean onour intelligence as logical programmersand analysts, and forget that withouttheir business knowledge, we would
simply be writing our openingPowerBuilder program that whenclicked upon says “hello”.
We have to remember to embraceour business team. They are the onescoming up with the projects that arekeeping us in beans and rice, and theydon’t appreciate condescension. Thestarting point for this particular flow-chart always seemed offensive in myview.
Yes It Does, or No It Doesn’tThe branches before you now pre-
sent the first challenge. If you follow theyes branch and it does work, then youare led to a process box that says “Don’tMess With It.” This is certainly the safeplay, and from a support standpoint(oddly enough) it could be the right one,if the application is perfect. Has theapplication been optimized for speed?Does it meet every single user require-ment exactly as they want? Is everyscreen quick, effective, and aestheticallypleasing? I’m guessing not. It is possible,but I have seldom encountered the per-fect app. Yes, I am showing my perfec-tionist programmer side, but there arealways things to check. If nothing else,your version of PowerBuilder willbecome nonsupported in a few years, ifit hasn’t already. The safe play is to justkeep supporting your users, but the wiseplay is to look for ways to make it better.If you don’t mess with it, you are sent tothe end statement, which is “NoProblem!!!!” This may or may not be true.
Did You Mess With It?If it doesn’t work, the next question
(truly the key to the whole ugly flow-chart) is “Did You Mess With It?” Ofcourse, the crux of the word mess isthat you yourself may be incompetentand have done some damage. Guesswhat, gang, it happens. One of themany things we analysts do for a livingis fix broken things. To fix that which is
broken, sometimes we have to teardown the flow, break the system into itsvarious parts, and find out what iswrong. You must mess with it, if it isbroken. If you answer Yes to the MessWith It question, you’re sent to anotherprocess box that says, “You StupidIdiot!” Not only are you not a stupididiot, you are truly doing what you aregetting paid for.
The next question in the Yes branchis “Does Anyone Know?” If you followthe No branch, it leads you to the “HideIt!” process. Hiding our work is one ofthe truly dangerous moves that you canmake. Don’t do it; stand up and give ashout. Make yourself proactive and findhelp, find a way to bring your troublesinto the team and make it better.Hiding it is one of the quickest waysonto the street. Of course, in the worldof our horrendous chart, if you Hide Ityou go to the end and have, “NoProblems!!!!” Nothing could be furtherfrom the truth.
If someone does know, and you fol-low the Yes box from the Decision tree,you are led to the “You Poor Fool!”process. While you may feel like a poorfool for a day or two, bringing brokenthings into the light of reality and theglare of the workbench is essential. Youaren’t going to hurt yourself with hon-esty.
The Blame GameThe next decision box after Poor
Fool is a question, “Can You BlameSomeone Else?” Here we have yetanother macabre trap. If you are unableto blame someone else, you go into anendless loop in this flowchart, headingback up to the Poor Fool process, whichagain sends you trying to blame some-one else. There is a certain prescientlogic about making this an endless loop.We have all worked with blamedumpers – sadly they will always be
WRITTEN BYMIKE DEASY
AUTHOR BIOMichael Deasy is a staffanalyst with the PugetSound Blood Center in
Seattle. He has beenworking with
PowerBuilder since version 3. Mike holds
an MBA from SouthernNazerne University. ~continued on page 33~
BE YOUR OWN
MOBILE SUPER HEROWITH THE POWER OF
POCKET POWERBUILDER
YOU HAVE THE SKILL SETLET SYBASE GIVE YOU THE POWER!
Got PowerBuilder? Go Mobile!
PowerBuilder® developers can easily leverage their expertise to create newor extend existing applications using the Pocket.
Pocket PowerBuilder—a new rapid application development tool that speeds thecreation of mobile and wireless enterprise Pocket PC applications.
Go Mobile now with this limited time offer!Purchase Pocket PowerBuilder today at $495. That’s more than 50%
savings. Checkout it out today at: http://eshop.sybase.com/eshop
© 2003 Sybase, Inc. All rights reserved. All trademarks are the property of their respective owners.
www.SYS-CON.COM/pbdj/18 PBDJ volume11 issue4
FEATURE
WRITTEN BY BRUCE ARMSTRONG
Sybase was one of the early pioneers of the client/server rela-tional database. Adaptive Server Enterprise (formerly SybaseSQL Server) was one of the first to adopt significant newfeatures such as stored procedures, triggers, a cost-based
optimizer, BLOB columns, and Java in the database. Sybase’s focusfor ASE, however, has been on providing a highly dependable data-base, which can handle large online transaction processing (OLTP)applications. That’s one of the reasons that ASE is used extensivelythroughout the financial industry. Sybase’s interest in providing astate-of-the-art, front-end development tool for ASE was the pri-mary reason they merged with PowerSoft in 1995 and obtainedPowerBuilder in the process.
Connecting to ASEPowerBuilder 9 provides two drivers for connecting to ASE: the SYC
interface and the SYJ interface. The SYJ interface is based on a differentversion of the CT-Lib client layer, which is used when deployingPowerBuilder components into EAServer. This article will focus on theSYC driver, since it’s the one used for client/server applications.
There are a number of database connection parameters that affecthow PowerBuilder interacts with the ASE database. They are describedin Tables 2–8, which can be downloaded from the PBDJ Web site,www.sys-con.com/pbdj/sourcec.cfm. Note that many of these parame-ters are ignored if the SYJ driver is used. In addition, the parameters inTable 8 having to do with third-party security mechanisms would onlybe adequately covered in a chapter or perhaps even a book of theirown. Therefore they are only presented here in brief form for com-pleteness.
Note also that as of PowerBuilder 9 the stored procedures thatPowerBuilder used to require before it would connect to an ASE data-base are no longer required. PowerBuilder will actually operate some-what faster in making catalog calls if those stored procedures do exist,so they’re still recommended, but they are no longer necessary.
Data TypesTable 1 lists some of the various ASE data types and their
PowerBuilder equivalents.Note that the PowerBuilder database painter lists IDENTITY as a
column data type. Technically, IDENTITY is a property applied toNUMERIC data type columns. When you specify an IDENTITY columnin the PowerBuilder database painter, it automatically creates aNUMERIC column with a scale of 18 and a precision of 0 (the latterbeing required for the IDENTITY property to apply) and with theIDENTITY property set. A NUMERIC column that has the IDENTITYproperty set will automatically increment in value as rows are insertedinto the table they are in. They are particularly useful for assigningnonintelligent key values to rows of data.
A TIMESTAMP column is generally used to prevent update colli-sions in the database. That is, when two or more users have read thesame record and one of the users updates it, some evaluation shouldbe made to determine whether the other users can update that samerecord without reselecting it first. Since a TIMESTAMP column is incre-mented with each update, it’s a simple matter to compare the originalvalue in the column with the current value to determine if another userhas modified the record since it was originally read.
Knowing this, PowerBuilder treats the TIMESTAMP data type a bitdifferently. If you include a TIMESTAMP column in a DataWindowselect statement and then look at the Update Specifications for theDataWindow, you’ll notice that the TIMESTAMP column does notappear. That’s because PowerBuilder will automatically include theTIMESTAMP column in the WHERE clause to check for the update col-lision.
DataWindowsThe primary means of interaction with the ASE database is through
DataWindows and should be used whenever possible. TheDataWindow provides significant features, such as handling optimisticconcurrency and automatic generation of update statements.
Easier use, better production
19PBDJ volume11 issue4www.SYS-CON.COM/pbdj/
Using a SQL Statement for the SourceUsing a SQL statement is the most straightforward method of get-
ting data from the database into the DataWindow. ASE is one of thedatabases that allow you to include nested subselects in the SELECTportion of a SQL statement (see Listing 1).
However, as powerful as this is, there are times when a standardSQL statement won’t provide the information needed. What happens ifsome complex processing needs to be performed on the data before it’sshown to the user? That’s one of the reasons using a stored procedureas the source for a DataWindow is so prevalent when ASE is the targetdatabase.
Using a Stored Procedure for the SourceIn addition to allowing more complex processing, a stored proce-
dure offers some other advantages over a standard SELECT statement.First, stored procedures in the database are precompiled, which meansthey’ll significantly outperform uncompiled SQL statements. In addi-tion, stored procedures provide for data hiding in that the end userdoesn’t need to know or have the ability to access the underlying tablesin order to retrieve the data.
We could simply take the SQL statement we were using above,embed it in a stored procedure (see Listing 2), and then indicate thatwe want to base the DataWindow on this stored procedure (see Figure1).
An ASE stored procedure can return more than one result set (seeListing 3). A DataWindow, however, is capable of displaying only one ofthese result sets. By default, it will display only the first one, but it ispossible to direct the DataWindow to display the second. Note that thedescriptions of the result sets must be the same for this technique towork. The data could be coming from entirely different locations, onlythe number and data type of the columns has to be the same.
To tell the DataWindow to retrieve the result set in the DataWindowpainter, first create the DataWindow. Then right-click on the ColumnSpecifications section and select the Stored Procedure… option on themenu that appears.
In the resulting dialog, change the value of the result set to 2 (seeFigure 2). If you retrieve the DataWindow after this, the data shown willbe from the second result set. Note that PowerBuilder still has toretrieve the first result set before it can retrieve the second; it just dis-cards the data. This may cause significant delays in displaying the dataif the first result takes considerable time to complete.
The same thing can be accomplished dynamically in PowerScriptby modifying the Table.SQLAction.Method property of theDataWindow object. If the DataWindow was still pointed to the firstresult set and we queried the value of that property at runtime, itwould be:
1 execute dbo.multipleresultsetdemo;1
We then modify that property as follows:
dw_x.Object.DataWindow.Table.SQLAction.Method =
"2 execute dbo.multipleresultsetdemo;1"
The number that appears in front of the execute statement is theresult set we want. ASE allows you to create more than one stored pro-cedure with the same name and then designate which one you want toexecute by number. The number that appears after the name of thestored procedure above is the number that PowerBuilder passes toASE; it indicates the procedure number in case there is more than onewith the same name.
The examples shown so far simply retrieve data pretty much direct-ly from existing tables. What if significant processing needs to be donebefore the data is returned to the user? With ASE, the solution is to usea temporary table to hold the data while it’s being processed (seeListing 4).
The # in the table name tells ASE that this is a temporary table sothat it automatically deletes the table when the procedure is done. Thedata we want to manipulate is copied into the temporary table, modi-fied (in this case a simple update), and then the data is selected out ofthe temporary table as output. Note that you will need to set theAutoCommit property of the transaction object to TRUE before callingthis procedure. The CREATE TABLE statement is a DDL statement andgenerally ASE will not allow DDL to be executed within the scope of atransaction. (There is an “allow DDL in transaction” option for thedatabase, but it’s generally not recommended because it can seriouslyimpact performance.)
Using Stored Procedures for UpdatesIf you’re going to be using stored procedures to query the database,
either you’re not going to allow updates from the DataWindow (it’s areport) or you’re going to allow updates and there’s a good chanceyou’re going to use stored procedures for the updates as well. If you’reusing the stored procedure to provide for information hiding (prevent-ing the user from directly selecting off the base tables), it makes little
TABLE 1 | ASE and PowerBuilder data types
ASE Data Type Description PowerBuilder Data Type
CHAR Fixed length character values ( limited string to 255 characters prior to ASE 12.5, limited to a page size in ASE 12.5)
VARCHAR Variable length character values string(limited to 255 characters prior to ASE 12.5, limited to a page size in ASE 12.5)
TEXT Variable length character values of up blobto 2GB
BINARY Fixed length binary data ( limited to blob255 characters prior to ASE 12.5, limited to a page size in ASE 12.5)
VARBINARY Variable length binary data ( limited to blob255 characters prior to ASE 12.5, limited to a page size in ASE 12.5)
IMAGE Variable length binary data of up to blob2GB
NCHAR Fixed length double width character blob or char array(ASE 12.5 only) values of up to a page sizeNVARCHAR Variable-length double-width blob or char array(ASE 12.5 only) character values of up to a page sizeBIT Whole number, either 0 or 1 integer
FIGURE 1 | Basing a DataWindow source on a stored procedure
www.SYS-CON.COM/pbdj/PBDJ volume11 issue420
sense to allow them to have direct update capabilities on those sametables.
To do that, you’ll need three separate procedures: one for inserts(see Listing 5), one for deletes (see Listing 6), and one for updates (seeListing 7). (Listings 6–12 can be downloaded from www.sys-con.com/pbdj/sourcec.cfm.)
We then assign each of these stored procedures to the DataWindowthrough the stored procedure update dialog. The update procedure notonly passes the new column values but the original column values aswell so that the stored procedure can check for an update collision.
Note that before we can actually perform updates through thestored procedure, we’ll still need to specify some options in the UpdateSpecifications portion (see Figure 3).
Stored ProceduresWhen a DataWindow cannot handle the desired interaction with the
database, the next method of choice is stored procedures. Stored pro-cedures allow the client front end to be isolated from the specific busi-ness logic, so that the front end does not need to be recompiled andredeployed if business logic changes.
AS REMOTE PROCEDURE CALLSBy far the preferred method of invoking stored procedures in the
database is through RPCFUNC. To do this, you’ll first need to create a
custom user object inherited from the transaction standard nonvisualclass (File->New->PB Object->Standard Class and select transaction).The stored procedures are declared as if they were external functions ina DLL. Select Declare from the first dropdown list box in the scriptpainter and Local External Functions from the second dropdown list,then right-click in the script painter and on the popup menu selectPaste Special -> SQL -> Remote Stored Procedures. A dialog will appearlisting all the stored functions and procedures in the database you areconnected to that the user you’re logged in as can execute. For exam-ple, suppose we are working with the following stored procedure :
CREATE PROCEDURE dbo.getemployeename
(@emp_id int, @emp_name varchar(40) out )
AS
BEGIN
select @emp_name =
emp_fname + ' ' + emp_lname
from dbo.employee
where emp_id = @emp_id
if @@rowcount = 0 raiserror 20000 "No such employee"
END
The RPCFUNC declaration in our custom transaction object wouldthen look like this:
protected function long getemployeename ( &
long emp_id, ref string emp_name ) &
RPCFUNC ALIAS FOR "dbo.getemployeename"
The recommended method for declaring the stored functions andprocedures is with protected scope in the user object, and then writingpublic object functions as wrappers for them. That way if any workneeds to be done to the data before or after making the call, it can belocated in the object with the call. This will make more sense when weget to some of the issues associated with making these calls, particular-ly returning strings by reference.
For this example, we’ll create the following object-level function onour custom transaction object:
public function string of_getemployeename (
integer a_emp_id);
string ls_emp_name
ls_emp_name = Space (40)
getemployeename ( a_emp_id, ls_emp_name )
Return ls_emp_name
end function
You simply need to make a connection available at runtimebased on this custom user object in order to execute the storedfunctions/procedures. If SQLCA is the only connection used in yourapplication, you can make your custom user object the class thatSQLCA is automatically created from. Do this by opening up theapplication object in its painter, selecting “Additional Properties”from the Properties tab, selecting the “Variable Types” tab page, andthen entering the name of your custom user object in place of“transaction” for the SQLCA variable type.
Listing 8 provides an example of calling that stored procedure nowas a method of the transaction object, which, if successful, providessomething similar to Figure 4.
Note that the stored procedure checks the number of rows returnedfrom the select statement by examining the @@rowcount databasevariable. No rows returned would not be a SQL error, but may be abusiness logic error condition nonetheless that we want to make theuser aware of. We do this through the RAISERROR statement, whichallows us to return a custom error code (20,000 or higher, lower valuesare reserved by the database) and a custom error message (256 charac-
FIGURE 2 | Setting the result set number for the DataWindow
FIGURE 3 | Update specifications dialog
21www.SYS-CON.COM/pbdj/ PBDJ volume11 issue4
ters or less). Those values are assigned to the SQLDBCode andSQLErrText properties of the transaction object after the call. With thesample code provided in Listing 8, we get the result shown in Figure 5 ifwe attempt to query the database for an employee name using aninvalid employee ID.
AS EMBEDDED SQLAlthough the RPCFUNC method is preferred, there are some situa-
tions in which invoking stored procedures through embedded SQL isrequired. In particular, retrieving multiple result sets when the descrip-tion of the result sets differs has to be done in embedded SQL. In addi-tion, embedded SQL has to be used when some of the arguments to thestored procedure (those that have default values) are not going to bepassed.
Multiple Result SetsThe following code demonstrates returning multiple results sets.
The first result set in this example is from a list of employees, and thesecond is from a list of departments. Note in particular that the resultsets don’t even have the same number of columns:
CREATE PROCEDURE dbo.embeddedsqlspdemo
AS
BEGIN
select emp_id,
emp_fname,
emp_lname
from employee
select dept_id,
dept_name
from department
END
The PowerScript that we use to retrieve both looks like Listing 9.Note that as soon as we’ve finished fetching the first result set, we
simply continue fetching through the second (and subsequent) resultsets.
Optional ArgumentsIf you use the RPCFUNC method to call stored procedures, you
have to provide a value for every argument, even those that havedefaults declared in the stored procedure. Listing 10 demonstratesthat this is not a limitation when they are called from embeddedSQL.
Note that of the 20 arguments to this stored procedure, only four(emp_id, emp_fname, emp_last, and start_date) are actually required.The following PowerScript shows we can pass just those four:
datetime ldt_today
ldt_today = DateTime ( Today() )
DECLARE proc PROCEDURE FOR dbo.namednotation
@emp_id = 10,
@emp_fname = 'John',
@emp_lname = 'Doe',
@start_date = :ldt_today ;
EXECUTE proc ;
CLOSE proc ;
Embedded SQLIt’s my opinion that embedded SQL should only be used when
other options (i.e., DataWindows and stored procedures calls) cannotprovide the required functionality. Nevertheless, there are limited sit-
uations where using embedded SQL is appropriate. In those cases,though, I would still recommend using object-level functions on acustom transaction object in order to consolidate the database-spe-cific calls. For example, an embedded SQL replacement for ourof_getemployeename sample from above might look something likethis:
public function string of_getemployeename (
integer a_emp_id);
string ls_emp_name
select emp_fname + ' ' + emp_lname
into :ls_emp_name
from dbo.employee
where emp_id = :a_emp_id
Return ls_emp_name
end function
Special IssuesIDENTITY COLUMNS
As mentioned previously, ASE has an identity property that can beassigned to numeric columns in order to generate nonintelligent keysfor tables. PowerBuilder supports such identity columns in the
FIGURE 4 | Successful call to stored procedure
FIGURE 5 | Unsuccessful call to stored procedure
22 www.SYS-CON.COM/pbdj/PBDJ volume11 issue4
DataWindow Update Specifications.If the identity column is designated in the update specifications,
PowerBuilder will query the database for the value (based on the valueof the @@identity database variable) after each insert to the database.
HIDING OBJECT OWNERSHIPAs with many other databases, ASE prefixes database objects with
the name of the owner of the object. If a SQL statement contains anobject reference that’s not prefixed with the object owner’s name, ASEwill search for an object with that name belonging to the logged-in user(as do most other databases). ASE does have a somewhat uniquebehavior after that though. What it will do if it doesn’t find the objectbelonging to the logged-in user is search for an object of that name thatbelongs to the database owner.
Therefore, the method used with ASE to hide object ownership is tocreate the database objects so that they are owned by the databaseowner. However, you generally don’t want all of the developers usingthe database owner account to work in the database. Fortunately, ASEallows you to alias the developer’s logins to the database owner so thatthey can create objects under the database owner’s ID without loggingin as the database owner. Note that for this to work the developer’slogin cannot be a user in the database. ASE checks the sysusers tablefirst to determine if the user is authorized for the database and, if theyare, allows them in without applying the alias. It’s only when the personlogging in is not a user in the database that it checks the sysalternatestable and applies the alias.
USING DBHANDLE AND CT-LIBThe transaction object has a number of properties and methods,
including the DBHandle method. Generally that’s used to determinewhether or not the transaction object is currently connected to thedatabase (a positive value indicates it is). However, the DBHandle isactually much more useful than that. The value that is returned isactually a pointer to the database connection that can be used byDLLs called from PowerBuilder. This could be used to implement fea-tures that might not be directly supported within PowerBuilder. Forexample, Open Client has a connection property called CS_USERDA-TA that can be used to pass additional information about a connec-tion to the server. In addition to ASE, using the DBHandle for externalDLL calls is supported for the MS SQL Server, Oracle, and ODBC dri-vers.
We don’t have to create a custom DLL to demonstrate this, however.We can simply call the exported functions on the CT-LIB DLLs directlyfrom PowerBuilder. For example, the ct_conn_prop method can beused to set and get a number of properties of the connection. We coulddeclare it as a local external function on our transaction object as fol-lows:
function long connectionprop ( &
ulong connection, &
long action, &
long property, &
ref long buffer, &
long buflen, &
long outlen) LIBRARY 'libct.dll' &
ALIAS FOR 'ct_con_props'
We’ll pass the DBHandle in the connection argument. Theaction argument accepts an enumerated value indicating the oper-ation we want to perform (get, set, etc.), and the property argumentaccepts an enumerated value indicating the property we are tryingto access. The values of these enumerated constants are providedin the cspublic.h file provided with Open Client. The calls them-selves are documented in the Open Client Client-Library/CReference Manual.
The buffer argument is the actual value of the property that’s being
set or retrieved, which is why it’s being passed by reference. Since thedata type being returned depends on the property being accessed, youwould have to declare the local external function somewhat differentlyfor some properties. You could actually declare the function severaltimes using different data types for the forth argument. This is calledoverloading the function, and PowerBuilder will select the appropriateone to use at runtime based on the data type you pass to the functionwhen you call it.
The buflen argument indicates the size of the variable being passedby reference in the buffer argument. It’s unused when retrieving thevalue of a C integer value, so we’re passing an enumerated value indi-cating that. Finally the outlen argument indicates the size of the datathe function returned in the forth argument. In this case of a C integervalue return, it’s also unused and we need to pass a C NULL instead.Normally the outlen argument is also passed by reference, but the waywe indicate to a DLL that we are passing a null for a value is to declareit as a nonreference long and pass a 0. The ALIAS FOR clause in thedeclaration allows us to provide our declared function with a name dif-ferent than the one used in the DLL.
As you’ve probably guessed, I’m going to create an object-levelfunction to wrap the DLL call (see Listing 11). Here is a sample of aPowerScript call using the function.
long ll_limit
long cs_no_limit = -9999
ll_limit = SQLCA.of_gettextlimit ()
IF ll_limit = cs_no_limit THEN
MessageBox ( "Text Limit", "No Limit!" )
ELSE
MessageBox ( "Text Limit", String ( ll_limit ) )
END IF
USING PRINT STATEMENTS FOR DEBUGGINGOne popular technique for debugging stored procedures, at least for
folks using interactive tools like ISQL, is to include print statements inthe code in order to return information during the processing of thestored procedure (see Listing 12).
Previous versions of PowerBuilder had problems with stored proce-dures that contained such statements. PowerBuilder 9 does not havethis problem though; the text of the print statements is returned toPowerBuilder and recorded in the database trace log file (provided thatthe TRA or TRACE prefix has been added to the DBMS parameter forthe transaction object).
Therefore, print statements can be used for debugging stored proce-dures, and you can run the database connection in trace mode andexamine the trace log file to see the results.
ConclusionThe ASE database provides a number of very powerful features
whose use is not always well documented. This article reviewed the useof those features so that your development efforts with that databaseare easier to accomplish and produce more powerful results.▼
AUTHOR BIOBruce Armstrong is an independent contractor in the Los Angeles area. A member of TeamSybase, he hasbeen using PowerBuilder since version 1.0.B. He was a contributing author to SYS-CON’s PowerBuilder 4.0Secrets of the Masters and the editor of SAM’s PowerBuilder 9: Advanced Client/Server Development. Heis also a member of the editorial board for PowerBuilder Developer’s Journal and the author of severalPBDJ articles, including a monthly news article.
• • •
This article is based on PowerBuilder 9 Client/Server Development by various authors (ISBN 0672325004),
published by Sams Publishing. Also look for PowerBuilder 9 Internet and Distributed Application
Development.
23PBDJ volume11 issue4www.SYS-CON.COM/pbdj/
Listing 1: Select with subselectSELECT employee.emp_id ,
employee.emp_fname ,employee.emp_lname ,employee.salary ,
( select dept_name from department dept where dept.dept_id =
employee.dept_id )as deptname,
salary / ( select max ( salary )
from employee ) as percentile
FROM employee ;
Listing 2: Simple Stored ProcedureCREATE PROCEDURE dbo.sp_getemployees AS
BEGIN SELECT dbo.employee.emp_id ,
dbo.employee.emp_fname ,dbo.employee.emp_lname ,dbo.employee.salary ,( select dept_name
from dbo.department dept where dept.dept_id =
dbo.employee.dept_id )as deptname,
salary / ( select max ( salary ) from dbo.employee ) as percentile
FROM dbo.employee END
Listing 3: Multiple result set stored procedure for DataWindowsourceCREATE PROCEDURE dbo.multipleresultsetdemo AS
BEGIN select *
from employee where salary >=
( select max ( salary ) / 2from employee )
select *from employeewhere salary <
( select max ( salary ) / 2from employee )
END
Listing 4: Stored procedure using a temporary table CREATE PROCEDURE dbo.temptabledemo AS
BEGIN create table #employee_working (
emp_id int not null,manager_id int null,emp_fname varchar(20) not null,emp_lname varchar(20) not null,dept_id int not null,street varchar(40) not null,city varchar(20) not null,state varchar(4) not null,zip_code varchar(9) not null,phone varchar(10) null,status char(1) null,ss_number varchar(11) not null,salary numeric(20, 3) not null,start_date datetime not null,termination_date datetime null,birth_date datetime null,bene_health_ins char(1) null,bene_life_ins char(1) null,bene_day_care char(1) null,sex char(1) null )
insert into #employee_workingselect * from employee
update #employee_workingset salary = salary + 10000where salary < (
select max ( salary )from employee )
select * from #employee_working
END
Listing 5: Insert stored procedureCREATE PROCEDURE dbo.insertemployee
@emp_id int,@manager_id int,@emp_fname varchar(20),@emp_lname varchar(20),@dept_id int,@street varchar(40),@city varchar(20),@state varchar(4),@zip_code varchar(9),@phone varchar(10),@status char(1),@ss_number varchar(11),@salary numeric(20, 3),@start_date datetime,@termination_date datetime,@birth_date datetime,@bene_health_ins char(1),@bene_life_ins char(1),@bene_day_care char(1),@sex char(1)
AS BEGIN
insert into employee (emp_id,manager_id,emp_fname,emp_lname,dept_id,street,city,state,zip_code,phone,status,ss_number,salary,start_date,termination_date,birth_date,bene_health_ins,bene_life_ins,bene_day_care,sex )
VALUES (@emp_id,@manager_id,@emp_fname,@emp_lname,@dept_id,@street,@city,@state,@zip_code,@phone,@status,@ss_number,@salary,@start_date,@termination_date,@birth_date,@bene_health_ins,@bene_life_ins,@bene_day_care,@sex )
END
www.sys-con.com/pbdj/DOWNLOAD THE CODE!
24 www.SYS-CON.COM/pbdj/PBDJ volume11 issue4
DATA INTERFACES
OLE DB (Microsoft SQL Server) Part 2
DataWindows and OLE DB
Part 1 of this article (PBDJ, Vol.11, issue 3) defined an OLE DB,discussed the OLE DB interfacesprovided with PowerBuilder,
and connecting to and accessing MSSQL Server. In Part 2 I’ll discussDataWindows and BLOBs, and answersome frequently asked questions aboutPowerBuilder and OLE DB.
DataWindows and OLE DBThe primary means of interaction
with a database is through DataWindows,which should be used whenever possible.The DataWindow provides significantfeatures, such as easy result set handling,lots of formatting options, and automaticgeneration of update statements.
USING A SQL STATEMENT FOR THE SOURCE
You can create DataWindows basedon any standard SELECT statement thatworks with your DBMS. As long as PBcan determine the type of data beingreturned by the SELECT statement, itcan create a DataWindow mapped tothose columns. A simple example is:
select
[id]
, [fname]
, [lname]
, [address]
, [city]
, [state]
, [zip]
, [phone]
, [company_name]
from customer
USING A STORED PROCEDURE FOR THE SOURCE
Let’s now take the above SQL state-ment and create an equivalent storedprocedure in the database to give us thesame result set. The syntax to do so isshown in Listing 1.
To constrain the resulting rows to a
more meaningful data set and a moremanageable number, we can set upparameters in the stored procedure thatare used to filter the rows from thedatabase. An example of a stored proce-dure for this is in Listing 2.
Let’s use this latter stored procedureas a source for a new DataWindow thatwe build. When creating theDataWindow, specify that the datasource is a stored procedure and PB willlet you select from a list of stored proce-dures in the database.
USING STORED PROCEDURES FOR UPDATES
First we need to create a stored pro-cedure to update a row in the Customertable. Listing 3 shows a simple storedprocedure to do this. It assumes thatthe Customer ID is the primary key andwill be used to identify the row thatneeds to be updated.
OLE Database Binary LargeObject (BLOB) Columns
In this section we’ll look at a simpleexample of storing binary objects(specifically a Word document) in theMicrosoft SQL Server database. We’lluse embedded SQL to interact with thedatabase and OLE Automation tolaunch Word to edit the stored docu-ment. (The sample application for thisarticle can be downloaded fromwww.sys-con.com/pbdj/sourcec.cfm.)
Apart from documents, BLOBs arecommonly used for storing pictures inthe database. For parts managementsystems, you could store images of theparts in the database and serve them upon Web pages.
The sample database supplied withthis example application has one Worddocument stored in it. Let’s look at thecode that retrieves this document fromthe database and edit it.
The code (see Listing 4) behind the“edit BLOB from database” button in
the sample application does the follow-ing:• Gets the BLOB from the database
based on the ID typed in by the user• Saves this BLOB to a file on the local
file system• Opens Word using OLE Automation• Sends a command to Word to open
the document just saved• Makes Word visible
The code behind the “save BLOB todatabase” button is shown in Listing 5,with all the error-checking codestripped out to reduce the amount ofspace it takes up here. This pretty muchreverses the logic of the edit functionabove. It does the following:• Makes sure an ID has been assigned
to the BLOB• Lets the user select a Word document
for uploading to the database• Reads this into a local variable• Inserts a row in the database for this
ID if necessary• Updates the record with the BLOB
based on the specified ID
Stored ProceduresStored procedures are valuable tools
for several reasons. The two main rea-sons I prefer using stored proceduresinstead of direct SQL are the increasedsecurity and the ability to incorporatebusiness logic in them.
From a security point of view, themajor advantage is that you don’t needto expose the underlying table struc-tures to the application. Users can begiven rights to execute the stored proce-dure but denied rights to the underlyingtables. This helps reduce the chancesthat they might be able to directlyaccess the tables and change or evenread data.
In terms of business logic, there areseveral things you can do, from datavalidation to writing out change logsand audit trails.
WRITTEN BYSANJIV DAS
AUTHOR BIOSanjiv Das is a member
of TeamSybase.
PowerBuilder® 9.0 gives you the power
and flexibility to create applications for
the platform of your choice in today’s
heterogeneous environments. You’ll find
new RAD JavaServerTM Pages, tools for
Web Services, third-party application
server support and more. Get the power
you need to develop and integrate
new Web, n-tier and rich-client apps.
Technical details are waiting for you
now at sybase.com/powerbuilder.
INFORMATION LIQUIDITY.
HE SAYS J2EE.SHE SAYS .NET.
YOU SAY POWERBUILDER 9.0
4GL RAD Tools
©2003 Sybase, Inc. All rights reserved. All trademarks are the property of their respective owners.
S Y B A S E I N T E G R A T I O N T E C H N O L O G I E S . E V E R Y T H I N G W O R K S B E T T E R W H E N E V E R Y T H I N G W O R K S T O G E T H E R .TM
www.SYS-CON.COM/pbdj/PBDJ volume11 issue426
The sample application includes anexample of using simple stored proce-dures with DataWindows to retrieve andupdate data.
EMBEDDED SQLOne reason embedded SQL was com-
monly used was because it was so easy.It’s not a recommended approach,though, and should be used sparingly, if
at all. Preferred methods of data accessare DataWindows and stored procedures.
PowerBuilder and OLE DBFrequently Asked Questions
In the following section I’veaddressed some of the questions askedby PowerBuilder developers about con-necting to Microsoft SQL Server 2000from PB applications.
IDENTITY COLUMNSMicrosoft SQL Server allows you to
create columns in the database thatautogenerate sequence numbers andare typically used as key columns tohelp join tables. These values are gener-ated by Microsoft SQL Server when therow is inserted into the database, so ifyou would like to display the value inyour DataWindow, PowerBuilder makesit easy by enabling this in just one easyadditional step.
In the Update properties for theDataWindow, just specify which columnis an identity column (see Figure 1).Look at the Identity Column example inthe sample application to see how thisworks.
VARIABLES IN DOUBLE QUOTESHow do you tell Microsoft SQL
Server not to assume that anythingenclosed in double quotes is an objectname?
You can send a directive to MicrosoftSQL Server before you run the SQLstatement. The directive in this case is:
SET QUOTED_IDENTIFIER < ON or OFF >
Take a look at the “Quoted Identifier”example in the sample application.
DATABASE CHARACTER COLUMNSLONGER THAN 255 CHARACTERS
The DB-lib database interface fromMicrosoft was written for Microsoft SQLServer 6.5, which only allowed string
FIGURE 1 | Specify identity column name
Listing 1CREATE PROCEDURE [dbo].[sp_list_customers] ASBEGIN
select[id]
, [fname], [lname], [address], [city], [state], [zip], [phone], [company_name]
from customerEND
Listing 2CREATE PROCEDURE [dbo].[sp_list_customers_in_state]
@s_state char(2)ASBEGIN
select[id]
, [fname], [lname], [address]
, [city], [state], [zip], [phone], [company_name]
from customerWhere state = @s_state
END
Listing 3CREATE PROCEDURE [dbo].[sp_update_customer]
@i_id int, @s_fname char(15), @s_lname char(20), @s_address char(35), @s_city char(20), @s_state char(2), @s_zip char(10), @s_phone char(12), @s_company_name char(35)
ASBEGIN
Update dbo.CustomerSet
[fname] = @s_fname, [lname] = @s_lname, [address] = @s_address, [city] = @s_city
GET MOREOUT OF
POWERBUILDER®
WITH POWERDESIGNER® 9.5.2!
• Integrate PowerBuilder logic in a heterogeneousenvironment that includes Java,™ J2EE™ and.NET™ to ensure PowerBuilder skills stayrelevant in the modern IT infrastructure.
• Manage simple and complex designs easilyusing unique features like Object/Relationalmapping, customizable pattern based codegeneration, VBScript customization, and more…
1-877-230-6771 | www.sybase-iad-services.com/30081a
• Easily re-factor code from ANY PowerBuilderobject into an n-tier architecture with completereverse engineering capabilities.
• Apply the advantages of UML to PowerBuilderdevelopment with comprehensive code generationand round-trip engineering.
Source: 08830081A
Download a FREE evaluation copyof PowerDesigner 9.5.2 Today!www.sybase-iad-services.com/30081a
Download a FREE evaluation copyof PowerDesigner 9.5.2 Today!www.sybase-iad-services.com/30081a
www.SYS-CON.COM/pbdj/PBDJ volume11 issue428
, [state] = @s_state, [zip] = @s_zip, [phone] = @s_phone, [company_name] = @s_company_name
Where [id] = @i_idENDGO
Listing 4String ls_DocID, ls_DocPath, ls_MessageTitleInteger li_FileNum, li_Countblob lblb_Doc
ls_MessageTitle = "PB9 OLE DB Example"
MessageBox ( ls_MessageTitle, "This function allows youto select a Word document from the database and edit itin Word. ~r~n~r~nPlease note that after editing, thedocument is not automatically saved to the database." )
ls_DocID = sle_DocID.Text
If len ( trim ( ls_docID ) ) = 0 ThenMessageBox ( ls_MessageTitle, "Please enter a Document
ID" )sle_DocID.SetFocus ( )Return
End If
ls_DocPath = 'C:\PB9 OLE DB Example.doc'
If FileExists ( ls_DocPath ) ThenFileDelete ( ls_DocPath )
End If
Select count(*) into :li_count from ole where id =:ls_docID;
If li_count = 0 thenMessageBox ( ls_MessageTitle, "A document with this ID
does not exist in the database. Please enter anotherdocument ID" )
sle_DocID.SetFocus ( )Return
End If
li_filenum = FileOpen ( ls_docpath, StreamMode!, Write!)
If li_filenum = -1 or IsNull ( li_filenum ) ThenMessageBox ( ls_MessageTitle, "Error creating file" )Return
End If
SelectBLOB docInto :lblb_DocFrom oleWhere id = :ls_DocID ;
If SQLCA.SQLCode <> 0 ThenMessageBox ("SQLErrorText", SQLCA.SQLErrText )Return
End If
If FileWrite ( li_FileNum, lblb_Doc ) <= 0 ThenMessageBox ( ls_MessageTitle, "Error. Please try
again" )Return
End If
FileClose ( li_FileNum )
If iole_Doc.ConnectToNewObject("word.application") = 0
Theniole_Doc.Documents.open( ls_DocPath )
ElseMessageBox(ls_MessageTitle, 'Unable to start an OLE
server process!', Exclamation!)End If
// Display the document in Wordiole_Doc.Visible=TRUE
Listing 5string ls_docID, ls_docpath, ls_docname,ls_MessageTitleinteger i, li_count, li_rtn, li_filenumBlob lblb_Doc
ls_MessageTitle = "PB9 OLE DB Example"
MessageBox ( ls_MessageTitle, "This function allows youto select a Word document from your disk and stores itin the database" )
ls_DocID = sle_DocID.text
//…
li_rtn = GetFileOpenName("PB9 OLE DB Example - SelectFile (less than 32765 characters long)", &
ls_docpath, ls_docname, "DOC", &"Doc Files (*.DOC),*.DOC,", &"C:\", 16410)
li_filenum = FileOpen ( ls_docpath, StreamMode!, Read! )
//…
FileRead ( li_FileNum, lblb_Doc )//…
FileClose ( li_FileNum )
Select count(*) into :li_count from ole where id =:ls_docID;
If li_count > 0 thenIf MessageBox ( ls_MessageTitle, "A document with this
ID exists. Do you want to replace it ?", Question!,YesNo! ) = 1 Then
UpdateBlob oleset doc = :lblb_Docwhere id = :ls_docid ;
//…Else
ReturnEnd If
ElseInsert into ole (id, description) values (:ls_docID,
:ls_MessageTitle);
//…
UpdateBlob oleset doc = :lblb_Docwhere id = :ls_docid ;
//…End If
MessageBox ( ls_MessageTitle, "File saved to database" )
www.sys-con.com/pbdj/DOWNLOAD THE CODE!
columns up to 255 characters long.Though this interface does work withMicrosoft SQL Server 2000, it won’t letyou access some of the newer features –such as getting values from characterfields longer than 255 characters. Thatinterface had a limit of 255 charactersfor regular string columns to reflect thesame restriction that existed in the data-base. Now that this is no longer a data-base-imposed restriction, you need touse a new set of drivers to access thisupdated database feature. The newinterface for Microsoft SQL Server 2000is OLE DB.
WHAT DOES ANSI_PADDING DO?This is a setting in Microsoft SQL
Server that tells it whether to save trail-ing blanks in varchar columns or trailingzeroes in varbinary columns. This set-ting is only used when creating tables.Once the table is created, changing thissetting does not affect the way the datais stored in or retrieved from that table.
CONNECTING TO THE DATABASE USINGWINDOWS AUTHENTICATION
An additional value in the DBParmattribute of the transaction object isused to indicate whether you want to
use Integrated Windows Authenticationinstead of Microsoft SQL ServerAuthentication.
To the DBParm attribute of thetransaction object, add the stringIntegratedSecurity='SSPI'.
A sample DBParm setting is:
PROVIDER='SQLOLEDB',DATASOURCE='(local
)',PROVIDERSTRING='DataBase=EASDemoDB'
,IntegratedSecurity='SSPI'
If you don’t use Windows integratedauthentication, you need to specify val-ues for the transaction attributes LogIDand LogPass. If the IntegratedSecurityparameter is set, the login ID and pass-word values are ignored.
The initial window in the sample
application shows how to connect witheither mode of authentication.
ConclusionOLE DB is a powerful data interface
specification that allows data con-sumers to access many different typesof data sources from various dataproviders and service providers using aconsistent interface. It allows you towrite SQL queries and other statementsto work with data in data sources thatmay or may not support SQL natively.OLE DB connections typically offer bet-ter performance than ODBC connec-tions. Fortunately for those of us devel-oping applications with PowerBuilder,we don’t need to worry about the actualOLE DB specification becausePowerBuilder provides a seamless inte-gration with the required OLE DB inter-faces.▼
~~~This article was originally intended to be pub-
lished as part of PowerBuilder 9 Client/Server
Development by various authors (ISBN
0672325004) from Sams Publishing. Also look
for PowerBuilder 9 Internet and Distributed
Application Development.
“PowerBuilder provides a seamlessintegration with the
required OLE DBinterfaces “
PBDJ ADVERTISER INDEXADVERTISER URL PHONE PAGE
Advertiser is fully responsible for all financial liability and terms of the contract executed by theiragents or agencies who are acting on behalf of the advertiser. This index is provided as an addi-tional service to our readers. The publisher does not assume any liability for errors or omissions.
Active Endpoints www.active-endpoints.com 2
Amyuni Technologies, Inc. www.amyuni.com 866-926-9864 5
ClearNova www.clearnova.com/thinkcap 15
E.Crane Computing www.ecrane.com 603-226-4041 36
iAnywhere www.ianywhere.com 800-801-2069 35
ISSJ www.issjournal.com 9
Powerbuilder Developer's Journal www.powerbuilderjournal.com 201-802-3026 31
Sybase, Inc www.sybase.com/pbextension 925-236-5000 17
Sybase, Inc www.sybase.com/powerbuilder 925-236-5000 13
Sybase, Inc www.sybase-iad-services.com/30081a 877-230-6771 7
Sybase, Inc. www.sybase.com/powerbuilder 925-236-5000 25
Sybase, Inc. http://eshop.sybaase.com/eshop 925-236-5000 27
© 2004 SYS-CON MEDIA. ALL RIGHT RESERVED. OFFER SUBJECT TO CHANGE WITHOUT NOTICE
Subscribe Now!$6999
www.SYS-CON.com/JDJor call
1-888-303-52821 YEAR/
12 ISSUES
The World’sLeading i-TechnologyMagazineJust GotBetter!
Now with expanded business
coverage, JDJ is the world’s premier independent, vendor-
neutral print resource for the ever-expanding international
community of IT professionals. The World’s Leading i-Technology Publisher
The Most Popular i-TechnologyMagazine in the World !
30 www.SYS-CON.COM/pbdj/PBDJ volume11 issue4
POCKET POWERBUILDER
Pocket PowerBuilder and Custom Today Items
One of the primary featuresof the Pocket PC is the TodayScreen. It is an idea centralto the concept of working
with a PDA. Its purpose is to providefeedback information at a glance fromrunning applications, although initial-ly it appears to be merely an easilyaccessible shortcut screen.
The Pocket PowerBuilderConcept
Pocket PowerBuilder provides theability to display text information andan icon in a custom Today item on theToday Screen. This basic functionality isprovided to allow the PPB developer toformat data and send it to the TodayItem screen – thereby giving the useraccess to important data at a glance.This information can range from a stat-ic text reminder to changing data pow-ered from a DataWindow in a runningPPB application.
The PPB custom Today item mirrorsthe major functionality of the Pocket PCcustom Today item.
The MechanicsThe Pocket PC operating system
looks in the registry for Today Screenitems each time the system loads. Theregistry key that it searches on thedevice is [HKEY_LOCAL_MACHINE]\Software\Microsoft\Today\Items. This
is where PPB will place any entries thatneed to be displayed as custom Todayitems. This key contains system Todayitems as well as non-PPB custom items.
The standard registry keys for anyToday item are shown in Table 1.
In addition, Pocket PB creates thekeys shown in Table 2.
PKTDY15U.DLLAll PPB custom Today items utilize a dll
installed along with PPB, namelypktdy15u.dll. It’s loaded by the Pocket PCoperating system upon initialization of theToday Screen when a custom PocketPowerBuilder Today item is encountered.This is the module that will control theinteraction between the system and theinformation associated with the PPB cus-tom Today item. It will handle system noti-fications, such as painting the window, aswell as reading and writing necessary reg-istry entries. Since the dll takes care ofthese housekeeping duties, it allows thePPB developer to concentrate on the func-tionality of the custom Today Item.
If the PPB developer indicates a“Display Application”, pktdy15u.dll willlaunch the PPB VM and correspondingapplication into a separate address spacewhen the item is initialized. If the devel-oper indicates a “Running Application”,pktdy15u.dll will launch the PPB VM andapplication into a separate address spacewhen the user taps the custom TodayItem (see Figure 1). Please keep in mindthat the more PPB custom Today itemsyou have running with DisplayApplications, the more memory will betaken up with the separate data seg-ments of the PPB VM for each one.
It’s important that the developerdoesn’t change the name of the customToday item once deployed. The Todaymodule (pktdy15u.dll) holds name-based information about each PPB cus-tom Today item when the system isrunning. Should the name of the itemchange while it’s running, unexpectedbehavior could result. This is the reason
that the name property cannot bechanged dynamically like some of theother properties of the Today item.
SampleTo better understand the process of
creating and deploying a custom TodayItem, let’s work through the customToday item sample provided with PPB –a_clock_display, which is included as“tdy_sample1” in the code examples.
Creating a Today ItemThe custom Today Item is part of the
application object. Therefore, we set theproperties for the item in the applica-tion painter. The “Today Item” tab inthe properties page has fields that arealmost directly related to the entriesthat end up in the registry of the device.
Viewing the corresponding device reg-istry values using a remote registry editorfor this sample would show Figure 2.
Notice that the color properties havebeen changed to values (as described inthe help file), and that our remainingproperties have been created as entries,along with the necessary system values,which have been automatically generated.The values are shown directly from theregistry for demonstration purposes only– it’s not recommended that these valuesbe changed by means other than throughthe PPB IDE and the Pocket PC settingstab. The keys shown were defined earlier.
The clock is a very simple applica-tion. Upon initialization, the item dis-plays the text “Custom Sample Timer”.We created an invisible window in theapplication that has a timer event trig-ger every second. When the eventoccurs, the Today item text is changedusing the following line of PowerScript:
a_clock_display.TodayDisplayText =
String(Now(), "hh:mm:ss")
This causes the Today item text todisplay the current time as a string.
We could also dynamically change
WRITTEN BYBILL ALLISON
Not Tomorrow … Today!!!
Key Name PurposeName The string by which the item is identified by the
system. For PPB, this must not be changed afterdeployment.
DLL Tells the system which dll to load to run thisapp. In our case it will be pktdy15u.dll.
Flags Set to 0, not currently used in PPBOptions Set to 0, not currently used in PPBEnabled Set to 1 initially during deployment. Toggled to
indicate whether the item should show up onthe Today Screen.
Type Set to 4 to indicate a custom Today item.
TABLE 1 |
AUTHOR BIOBill Allison is a softwareengineer at Sybase Inc.
He has been working on the PocketPowerBuilder
development teamsince its beginning,
and had been on the PowerBuilder
development teamsince version 6.
• Each issue is devoted exclusively to the newest aspects of PB development using version 9.0, Pocket PB 1.0, PowerDesigner 9.5.2, iAnywhere Solutions, etc.
• Written by acknowledged PB and EAServer experts
• Published monthly, circulated worldwide - the world's first and leading PowerBuilder print and online resource
• Now in its 10th year !
For more details contactCarrie Gebert 201 802.3026 [email protected] www.sys-con.com/pbdj/
YOUR FASTEST ROUTE TO POWERBUILDER DEVELOPERS
www.SYS-CON.COM/pbdj/32 PBDJ volume11 issue4
the background color to red as follows:
a_clock_display.BackColor = 255
Saving Changes to a Today Item
It is possible for us to save changes tothe Today item dynamically, which will bereflected the next time the Today item isdisplayed. Basically, this means that thevalue gets written back to the registry bypktdy15u.dll. As mentioned earlier, thismodule associates the proper registryentry with the name, so changing thename key while a PPB custom Today itemis loaded can result in undefined behavior.
The following keys can be writtenback to the registry:
a_clock_display.Display Text
a_clock_display.DisplayApp
a_clock_display.RunningApp
a_clock_display.Order
a_clock_display.BackColor
a_clock_display.TextColor
After making the changes inPowerScript, the developer simplyissues the following:
a_clock_display.TodaySave()
to cause the values to be written back tothe registry. The registry values will beused the next time the Today item isloaded/reloaded.
Deploying a Today ItemDeploying the Today Item is as sim-
ple as clicking the “Deploy Today Item”checkbox in the Project Painter. Thisitem is available as a separate checkboxbecause the developer may not wish todeploy the item each time a project isdeployed. If the Today item is alreadyrunning on the device, PPB will issue awarning that it is not able to copy theexecutable file to the device.
It’s important to note that since wedefined the “Display Application” as“\Program Files\a_clock_display.exe”,we deploy the executable to this loca-tion in the project painter. Otherwisethe VM will not be able to locate theexecutable, and we will not see ourclock displayed as a Today item. Thesame applies to “Running Application.”
Deleting Today ItemsA dialog has been recently added to
PPB that allows the developer to deleteany PPB custom Today items deployedto their device. It is located in the ProjectPainter, and clicking “Design->DeleteCustom Today Items…” will bring up a
dialog box that displays the current listof customer PPB Today items. Select anyitem(s) that you wish to delete and pressthe “Delete Item(s)” button to removethem from your device. This removaldeletes the entries from the registry, butleaves any executable in place.
EXAMPLES OF TODAY ITEMSTo emphasize the versatility of the
Today Screen items, I have put togethera few possible custom Today ideas.• Stock Ticker: This has been included
recently as a Today item sample.Using PocketSoap, a query is periodi-cally made with a PPB application toquery the price of a given stock. Thisvalue is then updated on the TodayScreen. This sample (see Figure 3) isincluded with PPB 1.5.1.
• “ToDo” Item: A user could have numer-ous tasks and corresponding due dateswith priorities stored in a simple data-base. A PPB application could displaythose tasks, one at a time, in a customToday Item window. Once a task wascompleted, the user could tap the itemto mark it as completed (which wouldupdate the database), and the next taskwould be displayed.
Looking AheadThe Pocket PowerBuilder custom
Today item was created to allow theapplication developer to display infor-mation on the Today Screen of thedevice. Currently, we can only displaytext and an icon in a fixed-size window.Future revisions of the custom Todayitem could allow for further enhance-ments, such as a custom-sized window,where the developer could increase ordecrease the size of the window on theToday Screen according to how muchdata needs to be displayed.
Another possibility would be thefacility to provide a “snapshot” of aDataWindow for display in the Todayitem. Since an interactive DataWindowin the Today Screen is currently boundby technical limitations, we may providethe ability to show a graphic that wouldrepresent the current state of aDataWindow and its information.
Finally, a Pocket PC Today item hasthe option of showing an “OptionsDialog” to provide additional configura-tion information for a given Today item.PPB may provide a generic options dialogfor all PPB custom items on a given PDA,or it may provide the ability to tailor eachPPB custom item individually. This por-tion is still in the research phase.▼
TodayScreen
PPB Item 1
pkidy15u.dll DisplayApp 1
Run App 1
User taps Item
DisplayApp 2
PPB Item 2
FIGURE 1 |
TABLE 2 |
FIGURE 2 |
FIGURE 3 |
Key Name PurposeBackColor The color of the background in the Today
item window (expressed as a long asdescribed in the help file)
TextColor The color of the text in the Today item window (expressed as a long as described inthe help file)
RunningApp The application that will be launched whenthe Today item is tapped.
DisplayApp The PPB application that is powering the display properties (text, color) of the PPBcustom Today item. As an example, a PPBapp could be setting the text of the Todayitem to reflect the current time.
DisplayText When a Today item is initialized, this is thetext that will be in the window until it ischanged, either manually or via a PPB application (see “Display App” above).
33www.SYS-CON.COM/pbdj/ PBDJ volume11 issue4
~continued from page 16~
with us and they do loop around endlessly. In our broken world,finding someone to blame leads you to the Nirvana of “NoProblem!!!” and you again end sadly. Standing up for our mistakestakes courage, it takes resolve, and it always makes your path easier.The Japanese have a saying, “Fix the problem, not the blame.” Toooften we do neither.
What If You Didn’t Mess with the Broken Item?If you didn’t Mess With It, then you are sent to one of the final
decision boxes, which asks “Will You Get in Trouble?” This is yetanother crux of the CYA thinking. If you will get in trouble, you aresent directly to the Poor Fool box so you can start looking for some-one to blame. Inevitably, this is a course too often taken. If you won’tget in trouble, the flowchart again prompts a cover up with theprocess “File-13 It.” If you do toss it out, broken and blameless, youwill be doing yourself and your customer a disservice. Certainly thecover up can lead to the glorious No Problem box in the end, and, ofcourse, that is where the flowchart ends. But it isn’t reality.
And In The EndThe Shangri-La of every level of our witless flow is “No Problem”
– and every means of getting there seems fraught with peril.Certainly the easy ways of doing nothing, blaming others, coveringup problems, or discarding them completely seem to make sense attimes. Most of us learned not to do these things as children, some ofus later in life. The mentality that this flow chart exploits is one ofweakened character. Don’t let yourself get caught in it. We havecome a long way since the ’80s; hopefully we have learned to takeresponsibility for every line of code that we create, fix, or MessWith.▼
Does the Stupid Thing Work?
Does the Stupid Thing Work?
NO PROBLEM!!!
Don't Mess with it
You StupidIdiot!
Hide It!
File-13It
You PoorFool!!!
DidYou Messwith It?Does
AnyoneKnow?
CanYou BlameSomeone
Else?
Will YouGet in
Trouble?
Yes
Yes
Yes
Yes
Yes
No
No No
No
No
Listing 1: Using ADO.NET transaction processing// connect via ADO.NET
OleDb.OleDbConnection oleDbConn = new
OleDb.OleDbConnection();
oleDbConn.ConnectionString = "User ID=dba;Password=sql;Data
Source=EAS Demo DB V10;Provider=ASAProv.90";
oleDbConn.Open();
//
//associate the ADO.NET connection within internal
'PowerBuilder' DB structure
AdoTransaction adoTrans = new AdoTransaction(oleDbConn);
adoTrans.BindConnection();
//
//retrieve a DataStore using the ADO.NET connection
DataStore ds = new DataStore("pbdj.pbl", "d_department");
ds.SetAdoTransaction(adoTrans);
ds.Retrieve();
//
// perform the update within a transaction
try
{
// begin transaction, update and commit
adoTrans.Transaction =
adoTrans.Connection.BeginTransaction();
ds.UpdateData(true, false);
adoTrans.Transaction.Commit();
// we're successful if we get here, so reset status flags
ds.ResetUpdateStatus();
}
catch (DbErrorException ex)
{
// catch "DBError" and rollback
adoTrans.Transaction.Rollback();
}
Listing 2: Using the ObjectUnderMouse propertyprivate void dwDepartment_Click(object sender,
System.EventArgs e)
{
ObjectAtPointer oap = dwDepartment.ObjectUnderMouse;
GraphicObject gob = oap.Gob;
GraphicObjectColumn gobColumn;
String s;
if (gob is GraphicObjectColumn)
{
gobColumn = (GraphicObjectColumn) gob;
s = "Band: " + oap.BandName + "\n" +
"Group: " + ((oap.BandLevel > 0) ?
oap.BandLevel.ToString() : "none") + "\n" +
"Row: " + oap.RowNumber.ToString() + "\n" +
"Column: " + gob.Name + " (Sequence #: " +
gobColumn.ColumnNumber.ToString() + ")\n"+
"Value: " + dwDepartment.GetItemString(oap.RowNumber,
gob.Name);
MessageBox.Show(s, "Selected
www.sys-con.com/pbdj/DOWNLOAD THE CODE!
~continued from page 14~
34 www.SYS-CON.COM/pbdj/PBDJ volume11 issue4
THIRD-PARTY UTILITIESPBDelta2/21 – PBDR released version 4.0.5of PBDelta, a utility for determin-ing the difference between versionsof PowerBuilder code. The new ver-sion fixes a bug in the mergeoption and adds XP support forPowerBuilder 9.www.pbdr.com/software/pbdelta.htm
Cool Menu2/05 – Aart Onkenhout released thelatest build of CoolMenu, a utilityfor adding bitmaps to the menus inPowerBuilder applications. Thenew build added functions forUnicode (to work with PB10) andfixed a problem when menutextwas changed on selecting a menu-item when the menu was alreadyopen.www.xs4all.nl/~onkie/coolmenu.html
PB Code Analyzer2/10 – Ascension Labs released ver-sion 3.9 of PB Code Analyzer. Thenew version of PB Code Analyzerimplements new graphical con-trols, upgrades the installation pro-gram, and contains a few minorenhancements.www.ascensionlabs.com/pbcodeanalyz-
er.htm
POWERBUILDERPocket PowerBuilder 1.52/9 – Sybase announced the gen-eral availability of PocketPowerBuilder 1.5. The new versionadds support for additional nativeobjects and controls for thePocket PC, adding a custom itemto the Today screen, the Pocket PC2003 emulator, source code con-trol, setting the SIP display foredit controls, suppressing the tap-and-hold visual cue, providing anicon for an application, new pro-ject object check boxes, theDWSyntax tool, and a default win-dow size for Smartphone applica-tions.www.sybase.com/products/internetap-
pdevttools/pocketpowerbuilder
EASERVEREAServer 5.02/9 – Sybase announced the avail-ability of Sybase EAServer 5.0. Thenew version offers significantenhancements to EAServerManager, provides support forHTTP directory browsing, adds anew Transaction Manager,enhances Java connection manage-ment, and adds greater support forremote systems management. Italso includes enhancements inserver logging, runtime monitor-ing, and admin role management.A new Web Services Toolkit is pro-vided, including a private UDDIserver and a Web-based adminis-tration tool.www.sybase.com/products/application-
servers/easerver
POWERDESIGNERPowerDesigner 102/9 – Sybase announced the avail-ability of PowerDesigner 10. Thenew version includes a move dia-gram wizard, enhancements incode naming conventions, addssupport for extended links andobjects to all model types, providesa composite view option, adds sup-ports for MDA and extended col-lections, allows a stereotype to beused as a metaclass, and addsevent handlers and metaclassexclusions. The new version addsother enhancements for conceptu-al and physical data modeling,object-oriented modeling, andbusiness process modeling, as wellas adding a new XML model type.www.sybase.com/products/enterprise-
modeling/powerdesigner
CORPORATENew Member of Board ofDirectors2/23 – Sybase announced the elec-tion of Jack E. Sum, CPA, to theboard of directors of the company.Sum was appointed as a Class 2Director with a term expiring inMay 2006. He will serve on theAudit Committee and Board Affairs
Committee. Sum was recentlyretired as a partner from theaccounting firm ofPricewaterhouseCoopers, where hewas employed from 1968 through2003.
Diogenes, Inc.2/17 – Sybase announced it hadentered into a global sales agree-ment with Diogenes, Inc., a soft-ware infrastructure provider forbuilding mission-critical transac-tion delivery network (TDN) appli-cations to process transactionsover the Internet and private net-works. Under the terms of theagreement, Sybase is able to resellthe Diogenes Suite directly to itscustomers in conjunction with itsown products. www.diogenesinc.com
Lifeboat Distribution2/9 – Sybase announced an extend-ed partnership with LifeboatDistribution to provide developerswith access to the full suite ofSybase application developmentproducts. Lifeboat Distribution, aninternational wholesale provider ofsoftware development tools, utili-ties, and other technology benefit-ing computer software resellers,will now be able to offer Sybasedeveloper–focused products tomore than 6,000 resellers world-wide. www.lifeboatdistribution.com
SQL ANYWHEREM-Business AnywhereDeveloper Edition2/17 – iAnywhere Solutions, a sub-sidiary of Sybase, announced theavailability of the free M-BusinessAnywhere Developer Edition,which enables developers to deliv-er Web-based content and applica-tions to PDAs with minimal recod-ing. In addition, the companyunveiled new integration with SQLAnywhere Studio, enabling devel-opers to leverage the market-lead-ing mobile database to create data-
driven, Web-based mobile applica-tions.http://crm.sybase.com/sybase/www/iAS/
mbusiness_developer_download.jsp
Health Care Applications2/24 – iAnywhere Solutions, a sub-sidiary of Sybase, announced thatSQL Anywhere Studio powershealth care applications developedby BeyondNow Technologies, ACerner Company, Cogon Systems,HealthWyse, and MicrosysComputing. The data managementand synchronization capabilities ofSQL Anywhere enable health careorganizations of any size to delivertimely access to critical patientinformation, streamline businessprocesses, and reduce administra-tive costs.
ADAPTIVE SERVER ENTERPRISESalesforce.com2/25 – Salesforce.com and Sybaseannounced plans to further inte-grate salesforce.com and Sybasetechnologies, including Sybase IQand Sybase Replication Server. Theplanned integration will be com-pleted through sforce, the on-demand platform that powers thesalesforce.com service for over9,000 customers worldwide.http://salesforce.com/us/developers/
EVENTSSixth Annual Sybase ToolsSeminarApril 19, 2004 – Minneapolis, MNThis year’s seminar will highlightthe skills developers need to workwith PowerBuilder 10, PocketPowerBuilder, and EAServer.Technologies covered will includeJava, JSP, XML, Web DataWindow,and .NET. www.powerobjects.com/seminar/default.
htm
TechWave 2004August 15–19, 2004, Orlando, FLwww.sybase.com/techwave2004
PowerBuilder NewsAll things of interest to the PB community BY BRUCE ARMSTRONG
We knowtheropes.
Forget the wires.
www.ianywhere.com
Wondering how to get your Wi-Fi pro-
jects off the ground? We can show
you how. We’re iAnywhere Solutions,
the leading provider of solutions for
the unwired enterprise.
Emerging wireless technologies such
as Wi-Fi now enable businesses to
deliver a desktop computing experi-
ence to mobile workers. We have
more than a decade of experience
delivering "always available" access to
corporate data and applications –
keeping your mobile workers produc-
tive when they don’t have a wireless
connection and providing information
security and synchronization services
when they enter a wireless LAN or hot
spot.
More than ten thousand companies
and one thousand partners worldwide
rely on mobile technology from
iAnywhere Solutions.
Let us show you the ropes to get your
Wi-Fi solutions off the ground quick-
ly. Call 1-800-801-2069 or visit
www.ianywhere.com.
Copyright 2003. iAnywhere Solutions, Inc. All rights reserved. iAnywhere is a trademark of Sybase, Inc. or its subsidiaries.All other trademarks are the property of their respective owners.