Psref 2
Psref 2
PowerBuilder
DOCUMENT ID: 37782-01-0900-01 LAST REVISED: March 2003 Copyright 1989-2003 by Sybase, Inc. All rights reserved. This publication pertains to Sybase software and to any subsequent release until otherwise indicated in new editions or technical notes. Information in this document is subject to change without notice. The software described herein is furnished under a license agreement, and it may be used or copied only in accordance with the terms of that agreement. To order additional documents, U.S. and Canadian customers should call Customer Fulfillment at (800) 685-8225, fax (617) 229-9845. Customers in other countries with a U.S. license agreement may contact Customer Fulfillment via the above fax number. All other international customers should contact their Sybase subsidiary or local distributor. Upgrades are provided only at regularly scheduled software release dates. No part of this publication may be reproduced, transmitted, or translated in any form or by any means, electronic, mechanical, manual, optical, or otherwise, without the prior written permission of Sybase, Inc. Sybase, the Sybase logo, AccelaTrade, ADA Workbench, Adaptable Windowing Environment, Adaptive Component Architecture, Adaptive Server, Adaptive Server Anywhere, Adaptive Server Enterprise, Adaptive Server Enterprise Monitor, Adaptive Server Enterprise Replication, Adaptive Server Everywhere, Adaptive Server IQ, Adaptive Warehouse, Anywhere Studio, Application Manager, AppModeler, APT Workbench, APT-Build, APT-Edit, APT-Execute, APT-FORMS, APT-Translator, APT-Library, Backup Server, BizTracker, ClearConnect, Client-Library, Client Services, Convoy/DM, Copernicus, Data Pipeline, Data Workbench, DataArchitect, Database Analyzer, DataExpress, DataServer, DataWindow, DB-Library, dbQueue, Developers Workbench, Direct Connect Anywhere, DirectConnect, Distribution Director, e-ADK, E-Anywhere, e-Biz Integrator, E-Whatever, EC Gateway, ECMAP, ECRTP, eFulfillment Accelerator, Embedded SQL, EMS, Enterprise Application Studio, Enterprise Client/Server, Enterprise Connect, Enterprise Data Studio, Enterprise Manager, Enterprise SQL Server Manager, Enterprise Work Architecture, Enterprise Work Designer, Enterprise Work Modeler, eProcurement Accelerator, EWA, Financial Fusion, Financial Fusion Server, Gateway Manager, GlobalFIX, ImpactNow, Industry Warehouse Studio, InfoMaker, Information Anywhere, Information Everywhere, InformationConnect, InternetBuilder, iScript, Jaguar CTS, jConnect for JDBC, MainframeConnect, Maintenance Express, MDI Access Server, MDI Database Gateway, media.splash, MetaWorks, MySupport, Net-Gateway, Net-Library, New Era of Networks, ObjectConnect, ObjectCycle, OmniConnect, OmniSQL Access Module, OmniSQL Toolkit, Open Biz, Open Client, Open ClientConnect, Open Client/Server, Open Client/Server Interfaces, Open Gateway, Open Server, Open ServerConnect, Open Solutions, Optima++, PB-Gen, PC APT Execute, PC Net Library, Power++, power.stop, PowerAMC, PowerBuilder, PowerBuilder Foundation Class Library, PowerDesigner, PowerDimensions, PowerDynamo, PowerJ, PowerScript, PowerSite, PowerSocket, Powersoft, PowerStage, PowerStudio, PowerTips, Powersoft Portfolio, Powersoft Professional, PowerWare Desktop, PowerWare Enterprise, ProcessAnalyst, Rapport, Report Workbench, Report-Execute, Replication Agent, Replication Driver, Replication Server, Replication Server Manager, Replication Toolkit, Resource Manager, RW-DisplayLib, S-Designor, SDF, Secure SQL Server, Secure SQL Toolset, Security Guardian, SKILS, smart.partners, smart.parts, smart.script, SQL Advantage, SQL Anywhere, SQL Anywhere Studio, SQL Code Checker, SQL Debug, SQL Edit, SQL Edit/TPU, SQL Everywhere, SQL Modeler, SQL Remote, SQL Server, SQL Server Manager, SQL SMART, SQL Toolset, SQL Server/ CFT, SQL Server/DBM, SQL Server SNMP SubAgent, SQL Station, SQLJ, STEP, SupportNow, S.W.I.F.T. Message Format Libraries, Sybase Central, Sybase Client/Server Interfaces, Sybase Financial Server, Sybase Gateways, Sybase MPP, Sybase SQL Desktop, Sybase SQL Lifecycle, Sybase SQL Workgroup, Sybase User Workbench, SybaseWare, Syber Financial, SyberAssist, SyBooks, System 10, System 11, System XI (logo), SystemTools, Tabular Data Stream, TradeForce, Transact-SQL, Translation Toolkit, UltraLite.NET, UNIBOM, Unilib, Uninull, Unisep, Unistring, URK Runtime Kit for UniCode, Viewer, Visual Components, VisualSpeller, VisualWriter, VQL, WarehouseArchitect, Warehouse Control Center, Warehouse Studio, Warehouse WORKS, Watcom, Watcom SQL, Watcom SQL Server, Web Deployment Kit, Web.PB, Web.SQL, WebSights, WebViewer, WorkGroup SQL Server, XA-Library, XA-Server and XP Server are trademarks of Sybase, Inc. 11/02 Unicode and the Unicode Logo are registered trademarks of Unicode, Inc. All other company and product names used herein may be trademarks or registered trademarks of their respective companies. Use, duplication, or disclosure by the government is subject to the restrictions set forth in subparagraph (c)(1)(ii) of DFARS 52.2277013 for the DOD and as set forth in FAR 52.227-19(a)-(d) for civilian agencies. Sybase, Inc., One Sybase Drive, Dublin, CA 94568.
Contents
CHAPTER 10
PowerScript Functions ............................................................... Abs ............................................................................................... ACos ............................................................................................ Activate ........................................................................................ AddCategory ................................................................................ AddColumn .................................................................................. AddData ....................................................................................... AddItem ........................................................................................ AddLargePicture .......................................................................... AddPicture.................................................................................... AddSeries..................................................................................... AddSmallPicture........................................................................... AddStatePicture ........................................................................... AddToLibraryList .......................................................................... Arrange ........................................................................................ ArrangeSheets ............................................................................. Asc ............................................................................................... ASin.............................................................................................. ATan............................................................................................. Beep ............................................................................................. BeginTransaction ......................................................................... Blob .............................................................................................. BlobEdit ........................................................................................ BlobMid ........................................................................................ BuildModel ................................................................................... Cancel .......................................................................................... CanUndo ...................................................................................... CategoryCount ............................................................................. CategoryName ............................................................................. Ceiling .......................................................................................... ChangeDirectory ..........................................................................
311 312 313 314 316 317 318 321 326 327 328 330 331 332 334 335 336 337 338 338 339 341 342 343 345 348 349 350 351 352 353
iii
Contents
ChangeMenu................................................................................ Char ............................................................................................. Check ........................................................................................... ChooseColor ................................................................................ ClassList....................................................................................... ClassName................................................................................... Clear............................................................................................. Clipboard...................................................................................... Close ............................................................................................ CloseChannel............................................................................... CloseTab...................................................................................... CloseUserObject .......................................................................... CloseWithReturn .......................................................................... CollapseItem ................................................................................ CommandParm ............................................................................ CommitTransaction ...................................................................... ConnectToNewObject .................................................................. ConnectToNewRemoteObject ..................................................... ConnectToObject ......................................................................... ConnectToRemoteObject............................................................. ConnectToServer ......................................................................... Copy............................................................................................. CopyRTF...................................................................................... Cos............................................................................................... Cpu............................................................................................... CreateDirectory ............................................................................ CreateInstance............................................................................. CreatePage .................................................................................. Cut................................................................................................ DataCount .................................................................................... DataSource .................................................................................. Date.............................................................................................. DateTime...................................................................................... Day............................................................................................... DayName ..................................................................................... DayNumber .................................................................................. DaysAfter ..................................................................................... DBHandle..................................................................................... DebugBreak ................................................................................. Dec............................................................................................... DeleteCategory ............................................................................ DeleteColumn .............................................................................. DeleteColumns.............................................................................
354 355 356 357 358 359 361 363 366 370 371 373 375 378 379 381 383 385 387 390 393 396 398 400 401 401 402 406 407 409 410 412 416 418 419 420 421 422 422 423 424 425 425
iv
PowerBuilder
Contents
DeleteData ................................................................................... DeleteItem.................................................................................... DeleteItems .................................................................................. DeleteLargePicture ...................................................................... DeleteLargePictures..................................................................... DeletePicture................................................................................ DeletePictures.............................................................................. DeleteSeries................................................................................. DeleteSmallPicture....................................................................... DeleteSmallPictures..................................................................... DeleteStatePicture ....................................................................... DeleteStatePictures ..................................................................... DestroyModel ............................................................................... DirectoryExists ............................................................................. DirList ........................................................................................... DirSelect....................................................................................... Disable ......................................................................................... DisableCommit ............................................................................. DisconnectObject ......................................................................... DisconnectServer......................................................................... Double.......................................................................................... DoVerb ......................................................................................... Drag ............................................................................................. DraggedObject ............................................................................. Draw............................................................................................. EditLabel ...................................................................................... Enable .......................................................................................... EnableCommit.............................................................................. EntryList ....................................................................................... ExecRemote................................................................................. Exp ............................................................................................... ExpandAll ..................................................................................... ExpandItem .................................................................................. Fact .............................................................................................. FileClose ...................................................................................... FileCopy ....................................................................................... FileDelete ..................................................................................... FileExists...................................................................................... FileLength .................................................................................... FileMove....................................................................................... FileOpen....................................................................................... FileRead....................................................................................... FileSeek .......................................................................................
426 427 430 431 431 432 432 433 434 434 435 435 436 437 438 440 441 442 443 444 445 446 447 449 450 451 453 454 455 456 459 460 461 461 462 463 464 465 466 467 468 470 473
Contents
FileWrite ....................................................................................... Fill................................................................................................. FillW ............................................................................................. Find .............................................................................................. FindCategory................................................................................ FindClassDefinition ...................................................................... FindFunctionDefinition ................................................................. FindItem ....................................................................................... FindMatchingFunction .................................................................. FindNext....................................................................................... FindSeries .................................................................................... FindTypeDefinition ....................................................................... FromAnsi...................................................................................... FromUnicode................................................................................ GarbageCollect ............................................................................ GarbageCollectGetTimeLimit ....................................................... GarbageCollectSetTimeLimit ....................................................... GetActiveSheet ............................................................................ GetAlignment ............................................................................... GetApplication.............................................................................. GetArgElement............................................................................. GetAutomationNativePointer........................................................ GetCertificateLabel ...................................................................... GetChildrenList ............................................................................ GetColumn ................................................................................... GetCommandDDE ....................................................................... GetCommandDDEOrigin.............................................................. GetCompanyName ...................................................................... GetContextKeywords ................................................................... GetContextService ....................................................................... GetCredentialAttribute.................................................................. GetCurrentDirectory ..................................................................... GetData........................................................................................ GetDataDDE ................................................................................ GetDataDDEOrigin....................................................................... GetDataPieExplode...................................................................... GetDataStyle................................................................................ GetDataValue............................................................................... GetDynamicDate .......................................................................... GetDynamicDateTime .................................................................. GetDynamicNumber..................................................................... GetDynamicString ........................................................................ GetDynamicTime .........................................................................
474 476 477 477 479 480 481 482 488 490 491 492 494 495 497 497 498 499 500 501 502 503 504 507 509 511 512 513 514 515 517 519 520 525 526 527 529 535 537 539 541 542 543
vi
PowerBuilder
Contents
GetEnvironment ........................................................................... GetFileOpenName ....................................................................... GetFileSaveName........................................................................ GetFirstSheet ............................................................................... GetFixesVersion........................................................................... GetFocus...................................................................................... GetFolder ..................................................................................... GetGlobalProperty ....................................................................... GetHostObject.............................................................................. GetItem ........................................................................................ GetItemAtPointer.......................................................................... GetLastReturn.............................................................................. GetLibraryList............................................................................... GetMajorVersion .......................................................................... GetMessage................................................................................. GetMinorVersion .......................................................................... GetName...................................................................................... GetNativePointer.......................................................................... GetNextSheet............................................................................... GetOrigin...................................................................................... GetParagraphSetting ................................................................... GetParent..................................................................................... GetPin .......................................................................................... GetRecordSet .............................................................................. GetRemote................................................................................... GetSeriesStyle ............................................................................. GetShortName ............................................................................. GetSpacing .................................................................................. GetStatus ..................................................................................... GetTextColor................................................................................ GetTextStyle ................................................................................ GetToolbar ................................................................................... GetToolbarPos ............................................................................. GetTransactionName ................................................................... GetURL ........................................................................................ GetVersionName.......................................................................... Handle.......................................................................................... Hide.............................................................................................. Hour ............................................................................................. HyperLinkToURL.......................................................................... Idle ............................................................................................... ImpersonateClient ........................................................................ ImportClipboard............................................................................
544 546 550 552 553 554 555 556 557 558 561 562 563 564 565 566 567 568 569 570 571 572 574 576 577 580 586 587 588 590 591 592 594 597 598 599 600 602 603 604 605 607 608
vii
Contents
ImportFile ..................................................................................... ImportString.................................................................................. IncomingCallList ........................................................................... Init ................................................................................................ InputFieldChangeData ................................................................. InputFieldCurrentName ................................................................ InputFieldDeleteCurrent ............................................................... InputFieldGetData ........................................................................ InputFieldInsert ............................................................................ InputFieldLocate........................................................................... InsertCategory.............................................................................. InsertClass ................................................................................... InsertColumn ................................................................................ InsertData..................................................................................... InsertDocument ............................................................................ InsertFile ...................................................................................... InsertItem ..................................................................................... InsertItemFirst .............................................................................. InsertItemLast .............................................................................. InsertItemSort............................................................................... InsertObject.................................................................................. InsertPicture ................................................................................. InsertSeries .................................................................................. Int ................................................................................................. Integer .......................................................................................... InternetData ................................................................................. IntHigh.......................................................................................... IntLow........................................................................................... InvokePBFunction ........................................................................ _Is_A ............................................................................................ IsAlive........................................................................................... IsAllArabic .................................................................................... IsAllHebrew .................................................................................. IsAnyArabic .................................................................................. IsAnyHebrew ................................................................................ IsArabic ........................................................................................ IsArabicAndNumbers ................................................................... IsCallerInRole............................................................................... IsDate........................................................................................... IsHebrew ...................................................................................... IsHebrewAndNumbers ................................................................. IsImpersonating............................................................................
611 615 618 620 624 626 627 628 629 630 632 634 635 636 639 641 642 648 650 653 656 657 658 659 660 662 663 663 664 666 667 668 669 670 671 672 673 674 676 677 678 679
viii
PowerBuilder
Contents
IsInTransaction............................................................................. IsNull ............................................................................................ IsNumber...................................................................................... IsPreview...................................................................................... IsSecurityEnabled ........................................................................ IsTime .......................................................................................... IsTransactionAborted ................................................................... IsValid .......................................................................................... KeyDown...................................................................................... LastPos ........................................................................................ Left ............................................................................................... LeftW............................................................................................ LeftTrim ........................................................................................ LeftTrimW..................................................................................... Len ............................................................................................... LenW............................................................................................ Length .......................................................................................... LibraryCreate ............................................................................... LibraryDelete................................................................................ LibraryDirectory............................................................................ LibraryDirectoryEx........................................................................ LibraryExport................................................................................ LibraryImport ................................................................................ LineCount..................................................................................... LineLength ................................................................................... LineList......................................................................................... LinkTo .......................................................................................... Log ............................................................................................... LogTen ......................................................................................... Long ............................................................................................. LongLong ..................................................................................... Lookup ......................................................................................... Lower ........................................................................................... LowerBound ................................................................................. mailAddress ................................................................................. mailDeleteMessage...................................................................... mailGetMessages ........................................................................ mailHandle ................................................................................... mailLogoff..................................................................................... mailLogon..................................................................................... mailReadMessage ....................................................................... mailRecipientDetails..................................................................... mailResolveRecipient...................................................................
680 681 682 683 684 685 686 687 688 691 693 694 695 695 696 697 698 699 700 701 703 705 706 708 709 710 711 712 714 715 717 719 724 725 726 728 729 731 732 733 735 737 739
ix
Contents
mailSaveMessage ........................................................................ mailSend ...................................................................................... Match ........................................................................................... MatchW ........................................................................................ Max .............................................................................................. MemberDelete.............................................................................. MemberExists .............................................................................. MemberRename .......................................................................... MessageBox ................................................................................ Mid ............................................................................................... MidW ............................................................................................ Min ............................................................................................... Minute .......................................................................................... Mod .............................................................................................. ModifyData ................................................................................... Month ........................................................................................... Move ............................................................................................ MoveTab ...................................................................................... _Narrow........................................................................................ NextActivity .................................................................................. Now .............................................................................................. ObjectAtPointer ............................................................................ Object_To_String ......................................................................... OffsetPos ..................................................................................... Open ............................................................................................ OpenChannel ............................................................................... OpenSheet ................................................................................... OpenSheetWithParm ................................................................... OpenTab ...................................................................................... OpenTabWithParm ...................................................................... OpenUserObject .......................................................................... OpenUserObjectWithParm........................................................... OpenWithParm............................................................................. OutgoingCallList ........................................................................... PageCount ................................................................................... PageCreated ................................................................................ ParentWindow .............................................................................. Paste ............................................................................................ PasteLink ..................................................................................... PasteRTF ..................................................................................... PasteSpecial ................................................................................ Pi .................................................................................................. PixelsToUnits ...............................................................................
742 744 746 749 749 750 751 752 753 755 757 758 758 759 760 762 763 765 766 767 769 770 773 774 775 790 792 794 797 801 806 810 815 820 822 823 824 825 827 828 829 830 831
PowerBuilder
Contents
PointerX ....................................................................................... PointerY ....................................................................................... PopMenu...................................................................................... PopulateError ............................................................................... Pos ............................................................................................... PosW............................................................................................ Position ........................................................................................ Post .............................................................................................. PostEvent..................................................................................... PostURL....................................................................................... Preview ........................................................................................ Print.............................................................................................. PrintBitmap................................................................................... PrintCancel................................................................................... PrintClose..................................................................................... PrintDataWindow ......................................................................... PrintDefineFont ............................................................................ PrintGetPrinter ............................................................................. PrintGetPrinters............................................................................ PrintLine ....................................................................................... PrintOpen ..................................................................................... PrintOval ...................................................................................... PrintPage ..................................................................................... PrintRect ...................................................................................... PrintRoundRect............................................................................ PrintScreen .................................................................................. PrintSend ..................................................................................... PrintSetFont ................................................................................. PrintSetPrinter.............................................................................. PrintSetSpacing ........................................................................... PrintSetup .................................................................................... PrintSetupPrinter.......................................................................... PrintText....................................................................................... PrintWidth..................................................................................... PrintX ........................................................................................... PrintY ........................................................................................... ProfileInt ....................................................................................... ProfileString.................................................................................. Rand............................................................................................. Randomize ................................................................................... Read............................................................................................. Real.............................................................................................. RegistryDelete..............................................................................
832 833 834 836 837 838 839 844 845 848 850 851 857 858 860 861 862 864 865 866 867 869 871 872 874 876 877 879 880 881 882 883 884 886 887 888 889 891 893 894 895 898 899
xi
Contents
RegistryGet .................................................................................. RegistryKeys ................................................................................ RegistrySet................................................................................... RegistryValues ............................................................................. RelativeDate................................................................................. RelativeTime ................................................................................ ReleaseAutomationNativePointer ................................................ ReleaseNativePointer .................................................................. RemoveDirectory ......................................................................... Repair........................................................................................... Replace ........................................................................................ ReplaceW..................................................................................... ReplaceText ................................................................................. Reset............................................................................................ ResetArgElements ....................................................................... ResetDataColors.......................................................................... Resize .......................................................................................... Resolve_Initial_References ......................................................... RespondRemote .......................................................................... Restart.......................................................................................... ResumeTransaction ..................................................................... Reverse........................................................................................ RevertToSelf ................................................................................ RGB ............................................................................................. Right............................................................................................. RightW ......................................................................................... RightTrim...................................................................................... RightTrimW .................................................................................. RollbackOnly ................................................................................ RollbackTransaction..................................................................... Round........................................................................................... RoutineList ................................................................................... Run............................................................................................... Save ............................................................................................. SaveAs......................................................................................... SaveDocument............................................................................. Scroll ............................................................................................ ScrollNextPage ............................................................................ ScrollNextRow.............................................................................. ScrollPriorPage ............................................................................ ScrollPriorRow ............................................................................. ScrollToRow ................................................................................. Second .........................................................................................
900 902 903 905 906 907 908 909 910 911 912 913 914 915 918 919 920 921 923 924 925 927 928 929 931 931 932 932 933 935 937 938 939 941 943 950 951 952 953 954 955 956 957
xii
PowerBuilder
Contents
SecondsAfter................................................................................ 958 Seek ............................................................................................. 959 SelectedColumn........................................................................... 961 SelectedIndex .............................................................................. 962 SelectedItem ................................................................................ 963 SelectedLength ............................................................................ 964 SelectedLine ................................................................................ 965 SelectedPage............................................................................... 966 SelectedStart................................................................................ 967 SelectedText ................................................................................ 968 SelectionRange............................................................................ 970 SelectItem .................................................................................... 971 SelectObject................................................................................. 975 SelectTab ..................................................................................... 976 SelectText .................................................................................... 977 SelectTextAll ................................................................................ 981 SelectTextLine ............................................................................. 982 SelectTextWord............................................................................ 983 Send............................................................................................. 985 SeriesCount ................................................................................. 987 SeriesName ................................................................................. 988 SetAbort ....................................................................................... 989 SetAlignment................................................................................ 992 SetArgElement ............................................................................. 993 SetAutomationLocale ................................................................... 994 SetAutomationPointer .................................................................. 996 SetAutomationTimeout................................................................. 997 SetColumn ................................................................................... 999 SetComplete .............................................................................. 1000 SetData ...................................................................................... 1003 SetDataDDE............................................................................... 1005 SetDataPieExplode .................................................................... 1007 SetDataStyle .............................................................................. 1009 SetDropHighlight ........................................................................ 1015 SetDynamicParm ....................................................................... 1016 SetFirstVisible ............................................................................ 1018 SetFocus .................................................................................... 1019 SetGlobalProperty...................................................................... 1020 SetItem....................................................................................... 1021 SetLevelPictures ........................................................................ 1025 SetLibraryList ............................................................................. 1026 SetMask ..................................................................................... 1028 SetMessage ............................................................................... 1030
xiii
Contents
SetMicroHelp.............................................................................. SetNull........................................................................................ SetOverlayPicture ...................................................................... SetParagraphSetting .................................................................. SetPicture................................................................................... SetPointer .................................................................................. SetPosition ................................................................................. SetProfileString .......................................................................... SetRange ................................................................................... SetRecordSet............................................................................. SetRedraw ................................................................................. SetRemote ................................................................................. SetResultSet .............................................................................. SetSeriesStyle............................................................................ SetSpacing................................................................................. SetState ..................................................................................... SetTextColor .............................................................................. SetTextStyle............................................................................... SetTimeout................................................................................. SetToolbar.................................................................................. SetToolbarPos ........................................................................... SetTop........................................................................................ SetTraceFileName ..................................................................... SetTransPool ............................................................................. SharedObjectDirectory............................................................... SharedObjectGet ....................................................................... SharedObjectRegister................................................................ SharedObjectUnregister............................................................. Show .......................................................................................... ShowHeadFoot .......................................................................... ShowHelp................................................................................... ShowPopupHelp ........................................................................ Sign ............................................................................................ SignalError ................................................................................. Sin .............................................................................................. Sleep .......................................................................................... Sort............................................................................................. SortAll......................................................................................... Space ......................................................................................... Sqrt............................................................................................. Start............................................................................................ StartHotLink ............................................................................... StartServerDDE .........................................................................
1031 1032 1033 1036 1037 1038 1039 1042 1044 1045 1047 1048 1051 1052 1059 1060 1061 1062 1063 1065 1067 1071 1072 1073 1075 1076 1079 1080 1081 1082 1083 1085 1086 1087 1088 1088 1089 1091 1092 1093 1094 1101 1103
xiv
PowerBuilder
Contents
State........................................................................................... StepIt.......................................................................................... Stop............................................................................................ StopHotLink................................................................................ StopServerDDE.......................................................................... String.......................................................................................... String_To_Object ....................................................................... SuspendTransaction .................................................................. SyntaxFromSQL......................................................................... SystemRoutine........................................................................... TabPostEvent............................................................................. TabTriggerEvent ........................................................................ Tan ............................................................................................. Text ............................................................................................ TextLine ..................................................................................... Time ........................................................................................... Timer .......................................................................................... ToAnsi ........................................................................................ Today ......................................................................................... Top ............................................................................................. TotalColumns ............................................................................. TotalItems .................................................................................. TotalSelected ............................................................................. ToUnicode.................................................................................. TraceBegin................................................................................. TraceClose................................................................................. TraceDisableActivity................................................................... TraceEnableActivity ................................................................... TraceEnd.................................................................................... TraceError .................................................................................. TraceOpen ................................................................................. TraceUser .................................................................................. TriggerEvent............................................................................... TriggerPBEvent.......................................................................... Trim ............................................................................................ TrimW......................................................................................... Truncate ..................................................................................... TrustVerify.................................................................................. TypeOf ....................................................................................... Uncheck ..................................................................................... Undo........................................................................................... UnitsToPixels ............................................................................. UpdateLinksDialog .....................................................................
1105 1107 1107 1108 1109 1110 1115 1118 1120 1123 1124 1125 1126 1127 1128 1129 1132 1134 1135 1136 1137 1138 1139 1140 1141 1143 1144 1146 1148 1149 1150 1152 1153 1155 1157 1157 1158 1159 1162 1164 1166 1167 1168
xv
Contents
Upper ......................................................................................... UpperBound ............................................................................... Which ......................................................................................... WordCap .................................................................................... WorkSpaceHeight ...................................................................... WorkSpaceWidth ....................................................................... WorkSpaceX .............................................................................. WorkSpaceY .............................................................................. Write........................................................................................... XMLParseFile............................................................................. XMLParseString ......................................................................... Year............................................................................................ Yield ...........................................................................................
1170 1171 1173 1175 1176 1178 1179 1180 1181 1182 1185 1188 1189
xvi
PowerBuilder
This book is for programmers who will use PowerBuilder to build client/server, multitier, or Web applications. This book describes syntax and usage information for the PowerScript language including variables, expressions, statements, events, and functions. The printed version of this book is divided into two volumes:
Volume Volume 1 Volume 2 Contents Chapters 1-9 Chapter 10 (PowerScript Functions)
Two volumes
For a complete list of PowerBuilder documentation, see the preface of PowerBuilder Getting Started. Use the Sybase Technical Library CD and the Technical Library Product Manuals Web site to learn more about your product: The Technical Library CD contains product manuals and is included with your software. The DynaText reader (included on the Technical Library CD) allows you to access technical information about your product in an easy-to-use format. Refer to the Technical Library Installation Guide in your documentation package for instructions on installing and starting the Technical Library. The Technical Library Product Manuals Web site is an HTML version of the Technical Library CD that you can access using a standard Web browser. In addition to product manuals, you will find links to EBFs/Updates, Technical Documents, Case Management, Solved Cases, newsgroups, and the Sybase Developer Network. To access the Technical Library Product Manuals Web site, go to
Product Manuals at http://www.sybase.com/support/manuals/.
xvii
Conventions
To indicate When used in descriptive text, this font indicates: Command, function, and method names Keywords such as true, false, and null Datatypes such as integer and char Database column names such as emp_id and f_name User-defined objects such as dw_emp or w_main When used in descriptive text and syntax descriptions, oblique font indicates: Variables, such as myCounter Parts of input text that must be substituted, such as pblname.pbd
File>Save
dw_1.Update()
File and path names Menu names and menu items are displayed in plain text. The greater than symbol (>) shows you how to navigate menu selections. For example, File>Save indicates select Save from the File menu. Monospace font indicates: Information that you enter in a dialog box or on a command line Sample script fragments Sample output fragments
Each Sybase installation that has purchased a support contract has one or more designated people who are authorized to contact Sybase Technical Support. If you cannot resolve a problem using the manuals or online help, please have the designated person contact Sybase Technical Support or the Sybase subsidiary in your area.
xviii
PowerBuilder
CH A PTE R
1 0
PowerScript Functions
This chapter provides syntax, descriptions, and examples for PowerScript functions. The functions are listed alphabetically. For information about functions that apply to DataWindows or DataStores, see also the DataWindow Reference. Methods that apply to DataWindows, but not to other PowerBuilder controls, are listed only in the DataWindow Reference.
311
Abs
Abs
Description Syntax
The datatype of n. Returns the absolute value of n. If n is NULL, Abs returns NULL. All these statements set num to 4:
integer i, num i = num num num num 4 = = = =
312
PowerBuilder
CHAPTER 10
PowerScript Functions
ACos
Description Syntax
This code in the Clicked event of a button catches a runtime error that occurs when an arccosine is taken for a user-entered valuepassed in a variablethat is outside of the permitted range:
Double ld_num ld_num = Double (sle_1.text) TRY sle_2.text = string (acos (ld_num)) CATCH (runtimeerror er) MessageBox("Runtime Error", er.getmessage()) END TRY See also
313
Activate
Activate
Description Applies to Syntax
Activates the object in an OLE container, allowing the user to work with the object using the servers commands. OLE controls and OLE DWObjects (objects within a DataWindow object that is within a DataWindow control)
objectref.Activate ( activationtype ) Argument objectref Description The name of the OLE control or the fully qualified name of a OLE DWObject within a DataWindow control that contains the object you want to activate. The fully qualified name for a DWObject has this syntax:
dwcontrol.Object.dwobjectname
activationtype (optional)
A value of the enumerated datatype omActivateType specifying where the user will work with the OLE object. Values are: InPlace! (Default) The object is activated within the control. The subset of menus provided by the server application are merged with the PowerBuilder applications menus. OffSite! The object is activated in the server application, which gives the user access to more of the server applications functionality. For the OLE control, activationtype is required.
Return value
error occurs: -1 -2 -3 -4 -5 -9 Container is empty Invalid verb for object Verb not implemented by object No verbs supported by object Object cannot execute verb now Other error
This example activates the OLE DWObject ole_graph in the DataWindow control dw_1 in the Microsoft Graph server application:
integer result result = dw_1.Object.ole_graph.Activate(OffSite!)
314
PowerBuilder
CHAPTER 10
PowerScript Functions
See also
DoVerb
OLEActivate in the DataWindow Reference or the online Help
SelectObject
315
AddCategory
AddCategory
Description Applies to Syntax
Adds a new category to the category axis of a graph. AddCategory is for a category axis whose datatype is string. Graph controls in windows and user objects. Does not apply to graphs within DataWindow objects because their data comes directly from the DataWindow.
controlname.AddCategory ( categoryname ) Argument controlname categoryname Description The name of the graph to which you want to add a category. A string whose value is the name of the category you want to add to controlname. The category will appear as a label on the category axis.
Return value
Integer. Returns the number assigned to the category if it succeeds. If categoryname already exists as a label on the category axis, AddCategory returns the number of the existing category. Returns -1 if an error occurs. If any arguments value is NULL, AddCategory returns NULL. AddCategory adds a category to the end of the category axis. The category becomes an empty slot in each series to which you can assign a data point. A tick mark exists on the category axis for all the categories associated with the graph.
Usage
When the datatype of the category axis is string, you can specify the empty string ("") as the category name. However, because category names must be unique, there can be only one category with that name. Category names are unique if they have different capitalization. To add categories when the axis datatype is date, DateTime, number, or time, use InsertCategory. To insert a category in the middle of a series, use InsertCategory. You can also use InsertCategory to add a category to the end of a series, as AddCategory does, but it requires an additional argument to do so. To add data to a series in the graph, use the AddData or InsertData function. You can add a data value and put it in a new category, or you can add or change data in an existing category. To add a series to the graph, use the AddSeries function.
Examples
See also
316
PowerBuilder
CHAPTER 10
PowerScript Functions
AddColumn
Description Applies to Syntax
Adds a column with a specified label, alignment, and width. ListView controls
listviewname.AddColumn ( label, alignment, width ) Argument listviewname label alignment Description The name of the ListView control to which you want to add a column. A string whose value is the name of the column you are adding. A value of the enumerated datatype Alignment specifying the alignment of the column you are adding. Values are: Center! Justify! Left! width Right! An integer whose value is the width of the column you are adding, in PowerBuilder units.
The AddColumn function adds a column at the end of the existing columns unlike the InsertColumn function which inserts a column at a specified location. Use SetItem and SetColumn to change the values for existing items. To add new items, use AddItem. To create columns for the report view of a ListView control, use AddColumn.
Examples
This script for a ListView event creates three columns in a ListView control:
integer index FOR index = 3 to 25 This.AddItem ("Category " + String (index), 1 ) NEXT This.AddColumn("Name" , Left! , 1000) This.AddColumn("Size" , Left! , 400) This.AddColumn("Date" , Left! , 300)
See also
317
AddData
AddData
Adds a value to the end of a series of a graph. The syntax you use depends on the type of graph.
To add data to Any graph type except scatter Scatter graphs Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
Long. Returns the position of the data value in the series if it succeeds and -1 if an error occurs. If any arguments value is NULL, AddData returns NULL.
When you use Syntax 1, AddData adds a value to the end of the specified series or to the specified category, if it already exists. If categoryvalue is a new category, the category is added to the end of the series with a label for the data points tick mark. If the axis is sorted, the new category is incorporated into the existing order. If the category already exists, the new data replaces the old data at the data point for the category. For example, if the third category label specified in series 1 is March and you add data in series 4 and specify the category label March, the data is added at data point 3 in series 4.
318
PowerBuilder
CHAPTER 10
PowerScript Functions
When the axis datatype is string, you can specify the empty string ("") as the category name. Because category names must be unique, there can be only one category with a blank name. If you use AddData to add data without specifying a category, you will have data points without categories, which is not the same as a category whose name is "". To insert data in the middle of a series, use InsertData. You can also use InsertData to add data to the end of a series, as AddData does, although it requires an additional argument to do it. For a comparison of AddData, InsertData, and ModifyData, see Equivalent Syntax in InsertData.
Examples
These statements add a data value of 1250 to the series named Costs and assign the data point the category label Jan in the graph gr_product_data:
integer SeriesNbr // Get the number of the series. SeriesNbr = gr_product_data.FindSeries("Costs") gr_product_data.AddData(SeriesNbr, 1250, "Jan")
These statements add a data value of 1250 to the end of the series named Costs in the graph gr_product_data but do not assign the data point to a category:
integer SeriesNbr // Get the number of the series. SeriesNbr = gr_product_data.FindSeries("Costs") gr_product_data.AddData(SeriesNbr, 1250) See also
319
AddData
Syntax 2
Description Syntax
Long. Returns the position of the data value in the series if it succeeds and -1 if an error occurs. If any arguments value is NULL, AddData returns NULL.
These statements add the x and y values of a data point to the series named Costs in the scatter graph gr_sales_yr:
integer SeriesNbr // Get the number of the series. SeriesNbr = gr_sales_yr.FindSeries("Costs") gr_sales_yr.AddData(SeriesNbr, 12, 3)
See also
320
PowerBuilder
CHAPTER 10
PowerScript Functions
AddItem
Adds an item to a list control.
To add an item to A ListBox or DropDownListBox control A PictureListBox or DropDownPictureListBox control A ListView control when you only need to specify the item name and picture index A ListView control when you need to specify all the properties for the item Use Syntax 1 Syntax 2 Syntax 3 Syntax 4
Syntax 1
Description Applies to Syntax
Return value
Integer. Returns the position of the new item. If the list is sorted, the position returned is the position of the item after the list is sorted. Returns -1 if it fails. If any arguments value is NULL, AddItem returns NULL.
Usage
If the ListBox already contains items, AddItem adds the new item to the end of the list. If the list is sorted (its Sorted property is TRUE), PowerBuilder re-sorts the list after the item is added. A list can have duplicate items. Items in the list are tracked by their position in the list, not their text.
AddItem and InsertItem do not update the Items property array. You can use FindItem to find items added during execution.
321
AddItem
ListBox portion of a DropDownListBox will have a large number of items and you want to display an HScrollBar, call the SetRedraw function to turn Redraw off, add the items, call SetRedraw again to set Redraw on, and then set the HScrollBar property to TRUE. Otherwise, it may take longer than expected to add the items.
Examples
This example adds the item Edit File to the ListBox lb_Actions:
integer rownbr string s s = "Edit File" rownbr = lb_Actions.AddItem(s)
If lb_Actions contains Add and Run and the Sorted property is FALSE, the statement above returns 3 (because Edit File becomes the third and last item). If the Sorted property is TRUE, the statement above returns 2 (because Edit File becomes the second item after the list is sorted alphabetically).
See also
Syntax 2
Description Applies to Syntax
322
PowerBuilder
CHAPTER 10
PowerScript Functions
Return value
Integer. Returns the position of the new item. If the list is sorted, the position returned is the position of the item after the list is sorted. Returns -1 if it fails. If any arguments value is NULL, AddItem returns NULL.
Usage
If you do not specify a picture index, the newly added item will not have a picture. If you specify a picture index that does not exist, that number is still stored with the picture. If you add pictures to the picture array so that the index becomes valid, the item will then show the corresponding picture. For additional notes about items in list boxes, see Syntax 1.
Examples
If plb_birds contains Robin and Swallow and the Sorted property is FALSE, the AddItem function above returns 3 because Cardinal becomes the third and last item. If the Sorted property is TRUE, AddItem returns 1 because Cardinal is first when the list is sorted alphabetically.
See also
Syntax 3
Description Applies to Syntax
323
AddItem
Integer. Returns the index of the item if it succeeds and -1 if an error occurs.
Use this syntax if you only need to specify the label and picture index of the item you are adding to the ListView. If you need to specify more than the label and picture index, use Syntax 4. This example uses AddItem in the Constructor event to add three items to a ListView control:
lv_1.AddItem("Sanyo" , 1) lv_1.AddItem("Onkyo" , 1) lv_1.AddItem("Aiwa" , 1)
Examples
See also
Syntax 4
Description Applies to Syntax
Integer. Returns the index of the item if it succeeds and -1 if an error occurs.
Use this syntax if you need to specify all the properties for the item you want to add. If you only need to specify the label and picture index, use Syntax 3. This example uses AddItem in a CommandButton Clicked event to add a ListView item for each click:
count = count + 1 listviewitem l_lvi l_lvi.PictureIndex = 2 l_lvi.Label = "Item "+ string(count) lv_1.AddItem(l_lvi)
324
PowerBuilder
CHAPTER 10
PowerScript Functions
See also
325
AddLargePicture
AddLargePicture
Description Applies to Syntax
Adds a bitmap, icon, or cursor to the large image list. ListView controls
listviewname.AddLargePicture ( picturename ) Argument listviewname picturename Description The name of the ListView control to which you are adding a bitmap, icon, or cursor The name of the bitmap, icon, or cursor you are adding to the large image list
When you add a large picture to a ListView, it is given the next available picture index in the ListView. For example, if your ListView has two pictures, the next picture you add will be assigned picture index number 3. Before you add large pictures, you can specify scaling for the pictures by setting the LargePictureWidth and LargePictureHeight properties. The dimensions in effect when you add the first picture determine the scaling for all pictures. Changing the property values after you add pictures has no effect. If you do not specify values for LargePictureWidth and LargePictureHeight before you add pictures, the dimensions of the first image determine the scaling for all pictures you add. When you add a bitmap, specify the color in the bitmap that will be transparent by setting the LargePictureMaskColor property before calling AddLargePicture. You can change the LargePictureMaskColor property between calls.
Examples
This example adds the file folder.ico"to the large picture index of the ListView lv_files:
// Add large picture integer index index = lv_files.AddLargePicture("folder.ico")
See also
DeleteLargePicture
326
PowerBuilder
CHAPTER 10
PowerScript Functions
AddPicture
Description Applies to Syntax
Adds a bitmap, icon, or cursor to the main image list. PictureListBox, DropDownPictureListBox, and TreeView controls
controlname.AddPicture ( picturename ) Argument controlname picturename Description The name of the control to which you want to add an icon, cursor, or bitmap to the main image list The name of the icon, cursor, or bitmap you want to add to the main image list
Integer. Returns the picture index number if it succeeds and -1 if an error occurs.
The picture is assigned an index in the order in which it is added to the control. Adding pictures during execution does not update the PictureName property array. Because the picture is added at the end of the list, the return value from AddPicture is the number of pictures associated with the control. Before you add pictures, you can specify scaling for the pictures by setting the PictureWidth and PictureHeight properties. The dimensions in effect when you add the first picture determine the scaling for all pictures. Changing the property values after you add pictures has no effect. If you do not specify values for PictureWidth and PictureHeight before you add pictures, the dimensions of the first image determine the scaling for all pictures you add. When a you add a bitmap, specify the color in the bitmap that will be transparent by setting the PictureMaskColor property before calling AddPicture. You can change the PictureMaskColor property between calls.
Examples
This example adds a picture to a TreeView control and associates it with a new TreeView item:
long ll_tvi integer li_picture li_picture = & tv_list.AddPicture("c:\apps_pb\staff.ico") ll_tvi = tv_list.FindItem(RootTreeItem!, 0) tv_list.InsertItemFirst(ll_tvi, "Dept.", li_picture)
See also
DeletePicture
327
AddSeries
AddSeries
Description
Adds a series to a graph, naming it with the specified name. The new series is also assigned a number. A graphs series are numbered consecutively, according to the order in which they are added. Graph controls in windows and user objects. Does not apply to graphs within DataWindow objects because their data comes directly from the DataWindow.
controlname.AddSeries ( seriesname ) Argument controlname seriesname Description The name of the graph in which you want to add a series A string whose value is the name of the series you want to add to controlname
Applies to Syntax
Return value
Integer. Returns the number assigned to the series if it succeeds. If seriesname is a duplicate, AddSeries returns the number of the existing series. If an error occurs, it returns -1. If any arguments value is NULL, AddSeries returns NULL.
Usage
Adds seriesname to the graph controlname and assigns the series a number. The number identifies the series within the graph. The numbers are assigned in sequence. The first series you add to the graph is assigned number 1 and is the first series displayed in the graph; the next is assigned 2; and so on. The series name must be unique within the graph. If you specify a name that already exists in the graph, AddSeries returns the number of the existing series. Series names are unique if they have different capitalization. The series name can be an empty string (""). However, because series names must be unique, only one series can have a blank name. If you want to insert a series in the middle of the list, use InsertSeries. You can also use InsertSeries to add a series to the end of the list, as AddSeries does, although it requires an additional argument to do it. To add data to a series in the graph, use the AddData or InsertData function. To add a category to a series, use the InsertCategory or AddCategory function.
Examples
These statements add the series named Costs to the graph gr_product_data:
integer series_nbr series_nbr = gr_product_data.AddSeries("Costs")
328
PowerBuilder
CHAPTER 10
PowerScript Functions
See also
329
AddSmallPicture
AddSmallPicture
Description Applies to Syntax
Adds a bitmap, icon, or cursor to the small image list. ListView controls
listviewname.AddSmallPicture ( picturename ) Argument listviewname picturename Description The name of the ListView control to which you are adding a small image The name of the bitmap, icon, or cursor you are adding to the ListView control small image list
When you add a small picture to a ListView control, it is given the next available picture index in the ListView. For example, if your ListView has two pictures, the next picture you add will have index number 3. Before you add small pictures, you can specify scaling for the pictures by setting the SmallPictureWidth and SmallPictureHeight properties. The dimensions in effect when you add the first picture determine the scaling for all pictures. Changing the property values after you add pictures has no effect. If you do not specify values for SmallPictureWidth and SmallPictureHeight before you add pictures, the dimensions of the first image determine the scaling for all pictures you add. Before you call AddSmallPicture, specify the color in the bitmap that will be transparent by setting the SmallPictureMaskColor property. You can change the SmallPictureMaskColor property between calls.
Examples
This example adds the file "shortcut.ico" to the small picture index of the ListView lv_files:
//Add small picture integer index index = lv_files.AddSmallPicture("shortcut.ico")
See also
DeleteSmallPicture
330
PowerBuilder
CHAPTER 10
PowerScript Functions
AddStatePicture
Description Applies to Syntax
Adds a bitmap, icon, or cursor to the state image list. ListView and TreeView controls
controlname.AddStatePicture ( picturename ) Argument controlname picturename Description The name of the ListView or TreeView control to which you are adding a bitmap, cursor, or icon The name of the bitmap, icon, or cursor you are adding
For ListViews in large icon view, the state picture is a picture displayed to the left of the large picture, by default in a smaller size. For TreeViews, the state picture is displayed to the left of the regular picture and the item is moved to the right to make room for it. If you specify either StatePictureWidth or StatePictureHeight, the picture is scaled to the size specified by that property. When a you add a bitmap, specify the color in the bitmap that will be transparent by setting the StatePictureMaskColor property before calling AddPicture. You can change the StatePictureMaskColor property between calls.
Examples
This example adds the file star.ico to the state picture index of the ListView lv_files:
//Add state picture integer index index = lv_files.AddStatePicture("star.ico")
See also
DeleteStatePicture
331
AddToLibraryList
AddToLibraryList
Description Syntax
Adds new files to the library search path of an application or component at runtime.
AddToLibraryList ( filelist ) Argument filelist Description A comma-separated list of file names. Specify the full file name with its extension. If you do not specify a path, PowerBuilder uses the systems search path to find the file.
Return value
-1
The application or component is being run in the PowerBuilder development environment, rather than from a standalone executable or server. The new library list or existing library list is empty, or another internal error has occurred.
-2 Usage
When an application needs to load an object, PowerBuilder searches for the object first in the executable file and then in the dynamic libraries specified for the application. For a deployed component, PowerBuilder searches the PBD files in the components library list. You can specify additional library files with AddToLibraryList. Calling AddToLibraryList appends a new list of files, in the order in which they are specified in filelist, to the list of library files specified in the target. If filelist contains a file name that is already in the library list, that file name is not added to the library list. If filelist contains more than one occurrence of a given file name, the first occurrence is added to the library list. To avoid problems that can occur when components share resources, you should use AddToLibraryList instead of SetLibraryList to add additional PBD files to the search list of a component deployed to EAServer. PowerBuilder cannot check whether the libraries you specify are appropriate for the application. It is up to you to make sure the libraries contain the objects that the application or component needs. This function has no effect in the PowerBuilder development environment.
332
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This example adds different PBDs to the library search path depending on whether product or customer processing is to be performed:
CHOOSE CASE processkind CASE "product" AddToLibraryList(prod.pbd) CASE "customer" AddToLibraryList(cust.pbd) END CHOOSE
See also
GetLibraryList SetLibraryList
333
Arrange
Arrange
Description Applies to Syntax
Can only be used with large icon and small icon views. This example arranges the icons in a ListView control:
lv_list.Arrange()
334
PowerBuilder
CHAPTER 10
PowerScript Functions
ArrangeSheets
Description
Arranges the windows contained in an MDI frame. (Windows that are contained in an MDI frame are called sheets.) You can arrange the open sheets and the icons of minimized sheets or just the icons. MDI frame windows
mdiframe.ArrangeSheets ( arrangetype ) Argument mdiframe arrangetype Description The name of an MDI frame window. A value of the ArrangeTypes enumerated datatype specifying how you want the open sheets arranged in the MDI frame window. Values are: Cascade! Cascade the sheets that are not minimized so that each sheets title bar is visible and arrange icons of minimized sheets in a row at the bottom of the frame. Layer! Layer the sheets that are not minimized so that each sheet completely covers the one below it and arrange icons of minimized sheets in a row at the bottom of the frame. Tile! Tile the sheets that are not minimized so that they do not overlap and arrange icons of minimized sheets in a row at the bottom of the frame. TileHorizontal! Tile the sheets that are not minimized so that each is beside the other without overlapping and arrange icons of minimized sheets in a row at the bottom of the frame. Icons! Arrange the minimized sheets in a row at the bottom of the frame.
Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, ArrangeSheets returns NULL.
This statement in the script for the Clicked event for an item on a menu tiles the open sheets that are not minimized in the MDI frame window called MDI_User:
MDI_User.ArrangeSheets(Tile!)
This statement in the script for the Clicked event for an item on a menu arranges the icons of the minimized sheets at the bottom of the MDI frame window called MDI_User:
MDI_User.ArrangeSheets(Icons!) See also
GetActiveSheet OpenSheet
335
Asc
Asc
Description Syntax
Integer. Returns the ASCII value of the first character in string. If string is NULL, Asc returns NULL.
You can use Asc to find out the case of a character by testing whether its ASCII value is within the appropriate range. This statement returns 65, the ASCII value for uppercase A:
Asc("A")
This example is a function that converts an array of integers into a string. Each integer specifies two characters. Its low byte is the first character in the pair and the high byte (ASCII * 256) is the second character. The function has an argument (iarr) which is the integer array:
string str_from_int, hold_str integer arraylen arraylen = UpperBound(iarr) FOR i = 1 to arraylen // Convert first character of pair to a char hold_str = Char(iarr[i]) // Add characters to string after converting // the integers high byte to char str_from_int = & str_from_int + hold_str + & Char((iarr[i] - Asc(hold_str)) / 256) NEXT
For sample code that builds the integer array from a string, see Mid.
See also
Char Mid Asc method for DataWindows in the DataWindow Reference or online Help
336
PowerBuilder
CHAPTER 10
PowerScript Functions
ASin
Description Syntax
Double. Returns the arcsine of n. This statement returns .999998 (rounded to six places):
ASin(.84147)
This code in the Clicked event of a button catches a runtime error that occurs when an arcsine is taken for a user-entered valuepassed in a variablethat is outside of the permitted range:
Double ld_num ld_num = Double (sle_1.text) TRY sle_2.text = string (asin (ld_num)) CATCH (runtimeerror er) MessageBox("Runtime Error", er.getmessage()) END TRY See also
Sin ACos ATan Pi ASin method for DataWindows in the DataWindow Reference or online Help
337
ATan
ATan
Description Syntax
Tan ASin ACos ATan method for DataWindows in the DataWindow Reference or online Help
Beep
Description Syntax
Integer. Returns 1 if it succeeds and -1 if it fails. If n is NULL, Beep returns NULL. The return value usually is not used.
338
PowerBuilder
CHAPTER 10
PowerScript Functions
BeginTransaction
Description Applies to Syntax
Creates an EAServer transaction and associates it with the calling thread. CORBACurrent objects
CORBACurrent.BeginTransaction ( ) Argument CORBACurrent Description Reference to the CORBACurrent service instance
Boolean. Returns TRUE if it succeeds and FALSE if the transaction could not be
created. The BeginTransaction function creates a transaction and modifies the transaction context of the calling thread so that it is associated with the transaction. This enables the calling thread to obtain information about the transaction and control commits and rollbacks. BeginTransaction can be called by a client or a component that is marked as OTS style. EAServer must be using the two-phase commit transaction coordinator (OTS/XA). If the calling thread is already associated with a transaction, BeginTransaction returns FALSE. Nested transactions are not supported.
Examples
This example shows the use of BeginTransaction to create a transaction from a client:
// Instance variables: // CORBACurrent corbcurr // Connection myconnect long ll_rc integer li_rc1, li_rc2 boolean lb_success ll_rc = myconnect.ConnectToServer() // insert error handling ... li_rc1 = this.GetContextService("CORBACurrent", & corbcurr) // insert error handling ... li_rc2 = corbcurr.Init( myconnect ) // insert error handling ... lb_success = corbcurr.BeginTransaction() IF NOT lb_success THEN MessageBox ("Create Transaction Failed", & "The client may already be in a transaction") RETURN
339
BeginTransaction
CommitTransaction GetContextService GetStatus GetTransactionName Init ResumeTransaction RollbackOnly RollbackTransaction SetTimeout SuspendTransaction
340
PowerBuilder
CHAPTER 10
PowerScript Functions
Blob
Description Syntax
Blob. Returns the converted string. If text is NULL, Blob returns NULL.
See also
341
BlobEdit
BlobEdit
Description Syntax
Return value
Unsigned long. Returns the position at which the next data can be copied if it succeeds, and returns NULL if there is not enough space in blobvariable to copy the data. If any arguments value is NULL, BlobEdit returns NULL. If the data argument is a string, the position in the blobvariable in which you want to copy data will be the length of the string + 2. If the data argument is a string converted to a blob, the position will be the length of the string + 1. This is because a string contains a null terminating character that it loses when it is converted to a blob. Thus, BlobEdit (blob_var, 1, "ZZZ) returns 5, while BlobEdit (blob_var, 1, blob (ZZZ) ) returns 4.
Examples
This example copies a bitmap in the blob emp_photo starting at position 1, stores the position at which the next copy can begin in nbr, and then copies a date into the blob emp_photo after the bitmap data:
blob{1000} emp_photo blob temp date pic_date ulong nbr ... // Read BMP file containing employee picture ... // into temp using FileOpen and FileRead. pic_date = Today() nbr = BlobEdit(emp_photo, 1, temp) BlobEdit(emp_photo, nbr, pic_date) UPDATEBLOB Employee SET pic = :emp_photo WHERE ...
See also
Blob BlobMid
342
PowerBuilder
CHAPTER 10
PowerScript Functions
BlobMid
Description Syntax
Return value
Blob. Returns length bytes from data starting at byte n. If n is greater than the number of bytes in data, BlobMid returns an empty blob. If together length and n add up to more bytes than the blob contains, BlobMid returns the remaining bytes, and the returned blob will be shorter than the specified length. If any arguments value is NULL, BlobMid returns NULL.
Include terminator character
String variables contain a zero terminator, which accounts for one byte. Include the terminator character when calculating how much data to extract.
Examples
In this example, the first call to BlobMid stores 10 bytes of the blob datablob starting at position 5 in the blob data_1; the second call stores the bytes of datablob from position 5 to the end in data_2:
blob data_1, data_2, datablob ... // Read a blob datatype into datablob. data_1 = BlobMid(datablob, 5, 10) data_2 = BlobMid(datablob, 5)
This code copies a bitmap in the blob emp_photo starting at position 1, stores the position at which the next copy can begin in nbr, and then copies a date into the blob emp_photo after the bitmap data. Then, using the dates start position, it extracts the date from the blob and displays it in the StaticText st_1:
blob{1000} emp_photo blob temp date pic_date ulong nbr ... // Read BMP file containing employee picture ... // into temp using FileOpen and FileRead.
343
BlobMid
pic_date = Today() nbr = BlobEdit(emp_photo, 1, temp) BlobEdit(emp_photo, nbr, pic_date) st_1.Text = String(Date(BlobMid(emp_photo, nbr))) See also
Blob BlobEdit
344
PowerBuilder
CHAPTER 10
PowerScript Functions
BuildModel
Description
Builds either a performance analysis or trace tree model based on the trace file you have specified with the SetTraceFileName function. Optional arguments let you monitor the progress of the build or interrupt it. You must specify the trace file to be modeled using the SetTraceFileName function before calling BuildModel.
Applies to Syntax
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded FileNotSetError!TraceFileName has not been set ModelExistsError!A model has already been built EnterpriseOnlyFeature!This function is supported only in the Enterprise edition of PowerBuilder EventNotFoundError!The event cannot be found on the passed progressobject, so the model cannot be built EventWrongPrototypeError!The event was found but does not have the proper prototype, so the model cannot be built SourcePBLError!The source libraries cannot be found, so the model cannot be built
Usage
The BuildModel function extracts raw data from a trace file and maps it to objects that can be acted upon by PowerScript functions. If you want to build a model of your trace file without recording the progress of the build, call BuildModel without any of its optional arguments. If you want to receive progress information while the model is being created or if you want to be able to interrupt a BuildModel that is taking too long to complete, call BuildModel with its optional arguments.
345
BuildModel
The event eventname on the passed progressobject is triggered when the number of activities indicated by the triggerpercent argument are processed. If the value of triggerpercent is 0, eventname is triggered for every activity. If the value of triggerpercent is greater than 100, eventname is never triggered. You define this event using this syntax:
eventname ( currentactivity, totalnumberofactivities ) Argument eventname currentactivity totalnumberofactivities Description Name of the event A long identifying the number of the current activity A long identifying the total number of activities in the trace file
Eventname returns a boolean value. If it returns FALSE, the processing initiated by the BuildModel function is canceled and any temporary storage is cleaned up. If you need to stop BuildModel processing that is taking too long, you can return a FALSE value from eventname. The script you write for eventname determines how progress is monitored. For example, you might display progress or simply check whether the processing must be canceled.
Examples
346
PowerBuilder
CHAPTER 10
PowerScript Functions
This example creates a performance analysis model that provides progress information as the model is built. The eventname argument to BuildModel is called ue_progress and is triggered each time five percent of the activities have been processed. The progress of the build is shown in a window called w_progress that includes a Cancel button:
Profiling lpro_model String ls_filename Boolean lb_cancel lpro_model = CREATE Profiling lb_cancel = false lpro_model.SetTraceFileName(ls_filename) Open(w_progress) // Call the of_init window function to initialize // the w_progress window w_progress.of_init(lpro_model.NumberOfActivities, & Building Model, This, ue_cancel) lpro_model.BuildModel(This, ue_progress, 5) // // // IF Clicking the cancel button in w_progress sets lb_cancel to true and returns false to ue_progress lb_cancel THEN & Close(w_progress) RETURN -1 END IF See also
SetTraceFileName DestroyModel
347
Cancel
Cancel
Description Applies to Syntax
Call this function only when Start or Repair is executing. When you stop a pipeline with Cancel, data is committed as if the pipeline had reached the maximum errors limit. You control how the pipeline behaves when it reaches the limit in the Data Pipeline painter (see the PowerBuilder Users Guide).
Examples
This statement for a CommandButtons Clicked script allows the user to stop the execution of the pipeline i_pipe:
i_pipe.Cancel()
See also
Repair Start
348
PowerBuilder
CHAPTER 10
PowerScript Functions
CanUndo
Description Applies to Syntax
Tests whether Undo can reverse the most recent edit for an editable control. Any editable control (DataWindow, MultiLineEdit, SingleLineEdit, RichTextEdit)
editname.CanUndo ( ) Argument editname Description The name of the DataWindow control, MultiLineEdit, SingleLineEdit, or RichTextEdit for which you want to determine whether the last edit can be reversed by the Undo function. In a DataWindow, CanUndo applies to the edit control over the current row and column.
Return value
Boolean. Returns TRUE if the last edit can be reversed (undone) using the Undo function and FALSE if the last edit cannot be reversed. If editname is NULL, CanUndo returns NULL. These statements check to see if the last edit in mle_contact can be reversed; if yes the statements reverse it, and if no they display a message:
IF mle_contact.CanUndo() THEN mle_contact.Undo() ELSE MessageBox(Parent.Title, "Nothing to Undo") END IF
Examples
See also
Undo
349
CategoryCount
CategoryCount
Description Applies to Syntax
Counts the number of categories on the category axis of a graph. Graph controls in windows and user objects, and graphs in DataWindow controls
controlname.CategoryCount ( { graphcontrol } ) Argument controlname Description The name of the graph for which you want the number of categories, or the name of a DataWindow control containing the graph. A string whose value is the name of the graph in the DataWindow for which you want the number of categories. Graphcontrol is required if controlname is a DataWindow control.
Integer. Returns the count if it succeeds and -1 if an error occurs. If any arguments value is NULL, CategoryCount returns NULL.
These statements get the number of categories in the graph gr_revenues in the DataWindow control dw_findata:
integer li_count li_count = & dw_findata.CategoryCount("gr_revenues")
DataCount SeriesCount
350
PowerBuilder
CHAPTER 10
PowerScript Functions
CategoryName
Description Applies to Syntax
Obtains the category name associated with the specified category number. Graph controls in windows and user objects, and graphs in DataWindow controls .
controlname.CategoryName ( { graphcontrol, } categorynumber ) Argument controlname Description The name of the graph in which you want to find the name of a specific category, or the name of the DataWindow control containing the graph. A string whose value is the name of the graph in the DataWindow for which you want the name of a specific category. Graphcontrol is required if controlname is a DataWindow control. The number of the category for which you want the name.
String. Returns the name of categorynumber in controlname. If an error occurs, it returns the empty string (""). If any arguments value is NULL, CategoryName returns NULL.
Usage
Categories are numbered consecutively, from 1 to the value returned by CategoryCount. When you delete a category, the categories are renumbered to keep the numbering consecutive. You can use CategoryName to find out the named category associated with a category number. These statements obtain the name of category 5 in the graph gr_product_data:
string ls_name ls_name = gr_product_data.CategoryName(5)
Examples
These statements obtain the name of category 5 in the graph gr_revenues in the DataWindow control dw_findata:
string ls_name ls_name = & dw_findata.CategoryName("gr_revenues", 5) See also
AddCategory SeriesName
351
Ceiling
Ceiling
Description Syntax
Determines the smallest whole number that is greater than or equal to a specified limit.
Ceiling ( n ) Argument n Description The number for which you want the smallest whole number that is greater than or equal to it
The datatype of n. Returns the smallest whole number that is greater than or equal to n. If n is NULL, Ceiling returns NULL. These statements set num to 5:
decimal dec, num dec = 4.8 num = Ceiling(dec)
Int Round Truncate Ceiling method for DataWindows in the DataWindow Reference or online Help
352
PowerBuilder
CHAPTER 10
PowerScript Functions
ChangeDirectory
Description Syntax
This example changes the current directory to the parent directory of the current directory and displays the new current directory in a SingleLineEdit control:
ChangeDirectory( ".." ) sle_1.text= GetCurrentDirectory( )
See also
CreateDirectory GetCurrentDirectory
353
ChangeMenu
ChangeMenu
Description
Changes the menu associated with a window. If the window is an MDI frame window, ChangeMenu appends the list of open sheets to the currently active menu. Window objects
windowname.ChangeMenu ( menuname {, position } ) Argument windowname menuname position (MDI frame windows only) Description The name of the window for which you want to change the menu. The name of the menu you want to make the current menu. The number of the item on the menu bar to which you want to append the names of the open sheets. Items on the menu bar are numbered from the left, beginning with 1. The default is 0, which lists the open sheets on the menu bars next-to-last menu (or the last menu if there is only one available).
Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, ChangeMenu returns NULL. The return value is usually not used.
If you are changing the menu associated with an MDI frame window, the new menu will not be visible if an open sheet with its own menu is active. When a sheet has its own menu, the list of open sheets appears on its menu, as well as on the hidden menu for the frame. This statement changes the top-level menu of the w_Employee window to m_Emp1:
w_Employee.ChangeMenu(m_Emp1)
Examples
354
PowerBuilder
CHAPTER 10
PowerScript Functions
Char
Description Syntax
This example sets ls_S to an asterisk, the character corresponding to the ASCII value 42:
string ls_S ls_S = Char(42)
These statements generate delivery codes A to F for the values 1 through 6 of li_DeliveryNbr:
string ls_Delivery integer li_DeliveryNbr FOR li_DeliveryNbr = 1 to 6 ls_Delivery = Char(64 + li_DeliveryNbr) ... // Additional processing of ls_Delivery NEXT See also
Asc
Char method for DataWindows in the DataWindow Reference or online Help
355
Check
Check
Description Applies to Syntax
Displays a checkmark next to a menu item in a drop-down or cascading menu and sets the menu items Checked property to TRUE. Menu objects
menuname.Check ( ) Argument menuname Description The fully qualified name of the menu next to which you want to display a checkmark. The item must be in a drop-down or cascading menu, not an item on a menu bar.
Integer. Returns 1 if it succeeds and -1 if an error occurs. If menuname is NULL, Check returns NULL.
A checkmark next to a menu item indicates that the menu option is currently on and that the user can turn the option on and off by choosing it. For example, in the Window painters Design menu, a checkmark is displayed next to Grid when the grid is on. You can use Check in an items Clicked script to mark a menu item when the user turns the option on and Uncheck to remove the check when the user turns the option off.
Equivalent syntax You can set a menu objects Checked property instead of
calling Check.
menuname.Checked = TRUE
This statement:
Menu_Appl.M_View.M_Grid.Checked = TRUE
is equivalent to:
Menu_Appl.M_View.M_Grid.Check() Examples
This statement displays a checkmark next to the menu item m_Grid in the m_View drop-down menu on the menu bar m_Appl:
m_Appl.m_View.m_Grid.Check()
See also
Uncheck
356
PowerBuilder
CHAPTER 10
PowerScript Functions
ChooseColor
Description Syntax
Integer. Returns 1 if the function succeeds, 0 if the user selects cancel (or the dialog box is closed), -1 if an error occurs.
This example displays the color selection dialog box with a base color of red and with two different custom colors defined:
long red, green, blue long custom[ ] integer li_color red = 255 custom[1]=rgb(red, 200, blue) custom[2]=8344736 li_color = ChooseColor( red, custom [ ] )
See also
RGB
357
ClassList
ClassList
Description Applies to Syntax
Provides a list of the classes included in a performance analysis model. Profiling object
instancename.ClassList ( list ) Argument instancename list Description Instance name of the Profiling object. An unbounded array variable of datatype ProfileClass in which ClassList stores a ProfileClass object for each class included in the model. This argument is passed by reference.
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded ModelNotExistsError!The function failed because no model exists
Usage
You use the ClassList function to extract a list of the classes included in a performance analysis model. You must have previously created the performance analysis model from a trace file using the BuildModel function. Each class listed is defined as a ProfileClass object and provides the class name, its parent class and type, and a list of the routines associated with that class. The classes are listed in no particular order. This example lists the classes included in the performance analysis model:
ProfileClass lproclass_list[], lproclass_class Profiling lpro_model Long ll_limitclass, ll_indexclass lpro_model = CREATE Profiling lpro_model.BuildModel() lpro_model.ClassList(lproclass_list) ll_limitclass = UpperBound(lproclass_list) FOR ll_indexclass = 1 TO ll_limitclass lproclass_class = lproclass_list[ll_indexclass] ... NEXT
Examples
See also
BuildModel
358
PowerBuilder
CHAPTER 10
PowerScript Functions
ClassName
Determines the class of an object or the datatype of a variable.
To determine The class of an object The class (or datatype) of a variable Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
Return value
String. Returns the class of controlname, the name assigned to the control. Returns the empty string ("") if an error occurs. If controlname is NULL, ClassName returns NULL. The class is the name of an object. You assign the name when you save the object in its painter. Usually the class and the object itself appear to be the same (because PowerBuilder declares a variable with the same name as the class for the object). However, if you have declared multiple instances of an object, it is clear that the objects class and the objects variable are different. If an ancestor object has been instantiated with one of its descendants, you can use ClassName to find the name of the descendant. TypeOf reports an objects built-in object type. The types are values of the Object enumerated datatype, such as Window! or CheckBox!. ClassName reports the class of the object in the ancestor-descendant hierarchy.
Usage
Examples
359
ClassName
These statements return the class of the objects in the control array and store them in the_class array:
string the_class[] windowobject the_object[] integer i FOR i = 1 TO UpperBound(control[]) the_object[i] = control[i] the_class[i] = the_object[i].ClassName() NEXT
Suppose your object hierarchy has a window named ancestor_window and it has descendants called win1 and win2, and the user can choose which descendant to open as a sheet. The following code tests which descendent window class is currently active (the MDI frame is w_frame):
ancestor_window active_window active_window = w_frame.GetActiveSheet() IF ClassName(active_window) = "win1" THEN . . . END IF See also
DraggedObject TypeOf
Syntax 2
Description Syntax
For variables
Provides the datatype of a variable.
ClassName ( variable ) Argument variable Description The name of the variable for which you want to know its name (that is, its datatype)
Return value
String. Returns the name of variable. Returns the empty string ("") if variable is an enumerated datatype or if an error occurs. If variable is NULL, ClassName returns NULL.
ClassName cannot determine the datatype if variable is an enumerated datatype. In this case, ClassName returns the empty string.
Usage Examples
360
PowerBuilder
CHAPTER 10
PowerScript Functions
Clear
Description Applies to
Deletes selected text or an OLE object from the specified control, but does not store it in the clipboard. DataWindow, EditMask, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox, DropDownPictureListBox, OLE controls, and OLEStorage objects
objectname.Clear ( ) Argument objectname Description One of the following: The name of the DataWindow control, EditMask, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox or DropDownPictureListBox from which you want to delete (clear) selected text. The name of an OLE control or storage object variable (type OLEStorage) from which you want to release its OLE object. If objectname is a DropDownListBox or DropDownPictureListBox, its AllowEdit property must be TRUE.
Syntax
Return value
Long.
For edit controls, returns the number of characters that Clear removed from objectname. If no text is selected, no characters are removed and Clear returns 0. If an error occurs, Clear returns -1. For OLE controls and storage variables, returns 0 if it succeeds and -9 if an error occurs. If objectname is NULL, Clear returns NULL.
Usage
To select text for deleting, the user can use the mouse or keyboard. You can also call the SelectText function in a script. To delete selected text and store it in the clipboard, use the Cut function. Clearing the OLE object from an OLE control deletes all references to it. Any changes to the object are not saved in its storage object or file. Clearing an OLEStorage object variable breaks any connections established by Open or SaveAs between it and a storage file (when Open or SaveAs is called for the OLEStorage object variable). It also breaks connections between it and any OLE controls that have called Open or SaveAs to connect to the object in the storage variable.
361
Clear
Examples
If the text in sle_comment1 is Draft and it is selected, this statement clears Draft from sle_comment1 and returns 5:
sle_comment1.Clear()
If the text in sle_comment1 is Draft, the first statement selects the D and the second clears D from sle_comment1 and returns 1:
sle_comment1.SelectText(1,1) sle_comment1.Clear()
This example clears the object associated with the OLE control ole_1, leaving the control empty:
integer result result = ole_1.Clear()
This example clears the object in the OLEStorage object variable olest_stuff. It also leaves any OLE controls that have opened the object in olest_stuff empty:
integer result result = olest_stuff.Clear() See also
362
PowerBuilder
CHAPTER 10
PowerScript Functions
Clipboard
Retrieves or replaces the contents of the system clipboard.
To Retrieve or replace the contents of the system clipboard with text Replace the contents of the system clipboard with a bitmap image of a graph Use Syntax 1 Syntax 2
Syntax 1
Description Syntax
For text
Retrieves or replaces the contents of the system clipboard with text.
Clipboard ( { string } ) Argument string (optional) Description A string whose value is the text you want to place in the clipboard. The string replaces the current contents of the clipboard, if any.
Return value
String. Returns the current contents of the clipboard if the clipboard contains text. If string is specified, Clipboard returns the current contents and replaces it with string.
Returns the empty string ("") if the clipboard is empty or it contains nontext data, such as a bitmap. If string is specified, the nontext data is replaced with string. If string is NULL, Clipboard returns NULL.
Usage
You can use Syntax 1 with the Paste, Replace, or ReplaceText function to insert the clipboard contents in an editable control or StaticText control.
Calling Clipboard in a DataWIndow control or DataStore object To retrieve or replace the contents of the system clipboard with text from a DataWindow item (cell value), you must first assign the value to a string and then call the system Clipboard function as follows: string ls_data = dw_1.object.column_name[row_number] ::Clipboard(ls_data)
The DataWindow version of Clipboard, documented in Syntax 2 (and in the DataWindow Reference), is only applicable to graphs.
Examples
These statements put the contents of the clipboard in the variable ls_CoName:
string ls_CoName ls_CoName = Clipboard()
363
Clipboard
The following statements place the contents of the clipboard in Heading, and then replace the contents of the clipboard with the string Employee Data:
string Heading Heading = Clipboard("Employee Data")
The following statement replaces the selected text in the MultiLineEdit mle_terms with the contents of the clipboard:
mle_terms.ReplaceText(Clipboard())
The following statement exchanges the contents of the StaticText st_welcome with the contents of the clipboard:
st_welcome.Text = Clipboard(st_welcome.Text) See also
Syntax 2
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, Clipboard returns NULL.
364
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This statement copies the graph gr_employees in the DataWindow control dw_emp_data to the clipboard:
dw_emp_data.Clipboard("gr_employees")
365
Close
Close
Closes a window, an OLE storage or stream, or a trace file.
To close A window An OLEStorage object variable, saving the object and clearing connections between it and a storage file or object A stream associated with the specified OLEStream object variable A trace file Use Syntax 1 Syntax 2 Syntax 3 Syntax 4
Syntax 1
Description Applies to Syntax
For windows
Closes a window and releases the storage occupied by the window and all the controls in the window. Window objects
Close ( windowname ) Argument windowname Description The name of the window you want to close
Integer. Returns 1 if it succeeds and -1 if an error occurs. If windowname is NULL, Close returns NULL. The return value is usually not used.
Use Syntax 1 to close a window and release the storage occupied by the window and all the controls in the window. When you call Close, PowerBuilder removes the window from view, closes it, executes the scripts for the CloseQuery and Close events (if any), and then executes the rest of the statements in the script that called the Close function. After a window is closed, its properties, instance variables, and controls can no longer be referenced in scripts. If a statement in the script references the closed window or its properties or instance variables, an execution error will result.
Preventing a window from closing
You can prevent a window from being closed with a return code of 1 in the script for the CloseQuery event. Use the RETURN statement.
366
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
These statements close the window w_employee and then open the window w_departments:
Close(w_employee) Open(w_departments)
After you call Close, the following statements in the script for the CloseQuery event prompt the user for confirmation and prevent the window from closing:
IF MessageBox(ExitApplication, & Exit?, Question!, YesNo!) = 2 THEN // If no, stop window from closing RETURN 1 END IF See also
Hide Open
Syntax 2
Description
Applies to Syntax
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 The storage is not open -9 Other error If olestorage is NULL, Close returns NULL.
Examples
This example saves and clears the object in the OLEStorage object variable olest_stuff. It also leaves any OLE controls that have opened the object in olest_stuff empty:
integer result result = olest_stuff.Close()
See also
Close
Syntax 3
Description Applies to Syntax
Return value
error occurs: -1 The storage is not open -9 Other error If olestream is NULL, Close returns NULL.
Examples
This example closes the OLEStream object stm_pic_label and releases the variables memory:
integer result result = stm_pic_label.Close() DESTROY stm_pic_label
See also
Open
Syntax 4
Description Applies to Syntax
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded FileNotOpenError!A trace file has not been opened
368
PowerBuilder
CHAPTER 10
PowerScript Functions
Usage
You use the Close function to close a trace file you previously opened with the Open function. You use the Close and Open functions as well as the properties and functions of the TraceFile object to access the contents of a trace file directly. You use these functions if you want to perform your own analysis of the tracing data instead of building a model with the Profiling or TraceTree object and the BuildModel function. This example closes a trace file:
ift_file.Close() DESTROY ift_file
Examples
See also
369
CloseChannel
CloseChannel
Description Syntax
Open failed The channel refuses to close No confirmation from the server Handle is NULL
Use CloseChannel to close a channel to a DDE server application that was opened by calling the OpenChannel function. Although you can usually close the DDE channel by specifying just the channels handle, it is a good idea to also specify the handle for PowerBuilder window associated with the channel. If you specify windowhandle, CloseChannel closes the DDE channel in the window identified by windowhandle. If you do not specify windowhandle, CloseChannel only closes the channel if it is associated with the active window. You can use the Handle function to obtain a windows handle.
Examples
These statements open and close the channel identified by handle. The channel is associated with the window w_sheet:
long handle handle = OpenChannel("Excel", "REGION.XLS", & Handle(w_sheet) ) ... // Some processing CloseChannel(handle, Handle(w_sheet))
See also
370
PowerBuilder
CHAPTER 10
PowerScript Functions
CloseTab
Description
Removes a tab page from a Tab control that was opened previously with the OpenTab or OpenTabWithParm function. CloseTab executes the scripts for the user objects Destructor event. Tab controls
tabcontrolname.CloseTab ( userobjectvar ) Argument tabcontrolname userobjectvar Description The name of the Tab control containing the tab page you want to close The name of the user object you want to close
Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, CloseTab returns NULL. The return value is usually not used. CloseTab closes a user object that has been opened as a tab page and releases
the storage occupied by the object and its controls. When you call CloseTab, PowerBuilder removes the tab page from the control, closes it, executes the script for the Destructor event (if any), and then executes the rest of the statements in the script that called the CloseTab function.
CloseTab also removes the user object from the Tab controls Control array, which is a property that lists the tab pages within the Tab control. If the closed tab page was not the last element in the array, the index for all subsequent tab pages is reduced by one.
After a user object is closed, its properties, instance variables, and controls can no longer be referenced in scripts. If a statement in the script references the closed user object or its properties or instance variables, an execution error will result.
Examples
These statements close the tab page user object u_employee and then open the user object u_departments in the Tab control tab_personnel:
tab_personnel.CloseTab(u_employee) tab_personnel.OpenTab(u_departments)
371
CloseTab
When the user chooses a menu item that closes a user object, the following excerpt from the menu items script prompts the user for confirmation before closing the u_employee user object in the window to which the menu is attached:
IF MessageBox("Close ", "Close?", & Question!, YesNo!) = 1 THEN // User chose Yes, close user object. ParentWindow.CloseTab(u_employee) // If user chose No, take no action. END IF See also
OpenTab
372
PowerBuilder
CHAPTER 10
PowerScript Functions
CloseUserObject
Description Applies to Syntax
Closes a user object by removing it from view and executing the scripts for its Destructor event. Window objects
windowname.CloseUserObject ( userobjectname ) Argument windowname userobjectname Description The name of the window that contains the user object The name of the user object you want to close
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, CloseUserObject returns NULL. The return value is usually not used.
Usage
Use CloseUserObject to close a user object and release the storage occupied by the object and its controls. When you call CloseUserObject, PowerBuilder removes the object from view, closes it, executes the script for the Destructor event (if any), and then executes the rest of the statements in the script that called the CloseUserObject function.
CloseUserObject also removes the user object from the windows Control array,
which is a property that lists the windows controls. If the closed user object was not the last element in the array, the index for all subsequent user objects is reduced by one. After a user object is closed, its properties, instance variables, and controls can no longer be referenced in scripts. If a statement in the script references the closed user object or its properties or instance variables, an execution error will result.
Examples
These statements close the user object u_employee and then open the user object u_departments in the window w_personnel:
w_personnel.CloseUserObject(u_employee) w_personnel.OpenUserObject(u_departments)
373
CloseUserObject
When the user chooses a menu item that closes a user object, the following excerpt from the menu items script prompts the user for confirmation before closing the u_employee user object in the window to which the menu is attached:
IF MessageBox("Close ", "Close?", & Question!, YesNo!) = 1 THEN // User chose Yes, close user object. ParentWindow.CloseUserObject(u_employee) // If user chose No, take no action. END IF See also
OpenUserObject
374
PowerBuilder
CHAPTER 10
PowerScript Functions
CloseWithReturn
Description Applies to Syntax
Closes a window and stores a return value in the Message object. You should use CloseWithReturn only for response windows. Window objects
CloseWithReturn ( windowname, returnvalue ) Argument windowname returnvalue Description The name of the window you want to close. The value you want to store in the Message object when the window is closed. Returnvalue must be one of these datatypes: String Numeric PowerObject
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, CloseWithReturn returns NULL. The return value is usually not used.
Usage
The purpose of CloseWithReturn is to close a response window and return information from the response window to the window that opened it. Use CloseWithReturn to close a window, release the storage occupied by the window and all the controls in the window, and return a value. Just as with Close, CloseWithReturn removes a window from view, closes it, and executes the script for the CloseQuery and Close events, if any. Before executing the event scripts, it also stores returnvalue in the Message object. Then PowerBuilder executes the rest of the script that called the CloseWithReturn function. After a window is closed, its properties, instance variables, and controls can no longer be referenced in scripts. If a statement in the script references the closed window or its properties or instance variables, an execution error results. PowerBuilder stores returnvalue in the Message object properties according to its datatype. In the script that called CloseWithReturn, you can access the returned value by specifying the property of the Message object that corresponds to the return values datatype.
375
CloseWithReturn
Message object properties where return values are stored Return value datatype Numeric PowerObject (such as a structure) String Message object property Message.DoubleParm Message.PowerObjectParm Message.StringParm
To return several values, create a user-defined structure to hold the values and access the PowerObjectParm property of the Message object in the script that opened the response window. The structure is passed by value so you can access the information even if the original variable has been destroyed.
Referencing controls
User objects and controls are passed by reference, not by value. You cannot use CloseWithReturn to return a reference to a control on the closed window (because the control no longer exists after the window is closed). Instead, return the value of one or more properties of that control.
You can prevent a window from being closed with a return code of 1 in the script for the CloseQuery event. Use a RETURN statement.
Examples
This statement closes the response window w_employee_response, returning the string emp_name to the window that opened it:
CloseWithReturn(Parent, "emp_name")
Suppose that a menu item opens one window if the user is a novice and another window if the user is experienced. The menu item displays a response window called w_signon to prompt for the users experience level. The user types an experience level in the SingleLineEdit control sle_signon_id. The OK button in the response window passes the text in sle_signon_id back to the menu item script. The menu item script checks the StringParm property of the Message object and opens the desired window. The script for the Clicked event of the OK button in the w_signon response window is a single line:
CloseWithReturn(Parent, sle_signon_id.Text)
376
PowerBuilder
CHAPTER 10
PowerScript Functions
377
CollapseItem
CollapseItem
Description Applies to Syntax
To collapse an entire tree, use the RootTreeItem handle as the argument. This example collapses an item in a TreeView control:
long ll_tvi ll_tvi = tv_list.FindItem(currenttreeitem!, 0) tv_list.CollapseItem(ll_tvi)
ExpandItem ExpandAll
378
PowerBuilder
CHAPTER 10
PowerScript Functions
CommandParm
Description Syntax Return value Usage
Retrieves the argument string, if any, that followed the program name when the application was executed.
CommandParm ( )
String. Returns the applications argument string if it succeeds and the empty string ("") if it fails or if there were no arguments.
Command arguments can follow the program name in the command line of a Windows program item or in the Program Managers Run response window. For example, when the user chooses File>Run in the Program Manager and enters:
MyAppl C:\EMPLOYEE\EMPLIST.TXT
CommandParm retrieves the string C:\EMPLOYEE\EMPLIST.TXT.
If the applications command line includes several arguments, CommandParm returns them all as a single string. You can use string functions, such as Mid and Pos, to parse the string. You do not need to call CommandParm in the applications Open event. Use the commandline argument instead.
Examples
These statements retrieve the command line arguments and save them in the variable ls_command_line:
string ls_command_line ls_command_line = CommandParm()
If the command line holds several arguments, you can use string functions to separate the arguments. This example stores a variable number of arguments, obtained with CommandParm, in an array. The code assumes each argument is separated by one space. For each argument, the Pos function searches for a space; the Left function copies the argument to the array; and Replace removes the argument from the original string so the next argument moves to the first position:
string ls_cmd, ls_arg[] integer i, li_argcnt // Get the arguments and strip blanks // from start and end of string ls_cmd = Trim(CommandParm()) li_argcnt = 1
379
CommandParm
DO WHILE Len(ls_cmd) > 0 // Find the first blank i = Pos( ls_cmd, " ") // // // if If no set i after i = 0 blanks (only one argument), to point to the hypothetical character the end of the string then i = Len(ls_cmd) + 1
// Assign the arg to the argument array. // Number of chars copied is one less than the // position of the space found with Pos ls_arg[li_argcnt] = Left(ls_cmd, i - 1) // Increment the argument count for the next loop li_argcnt = li_argcnt + 1 // Remove the argument from the string // so the next argument becomes first ls_cmd = Replace(ls_cmd, 1, i, "") LOOP
380
PowerBuilder
CHAPTER 10
PowerScript Functions
CommitTransaction
Description Applies to Syntax
Declares that the EAServer transaction associated with the calling thread should be committed. CORBACurrent objects
CORBACurrent.CommitTransaction (breportheuristics ) Argument CORBACurrent breportheuristics Description Reference to the CORBACurrent service instance A boolean specifying whether heuristic decisions should be reported for the transaction associated with the calling thread
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -2 -3 -4 -5 -6 Usage
Failed for unknown reason No transaction is associated with the calling thread The calling thread does not have permission to commit the transaction The HeuristicRollback exception was raised The HeuristicMixed exception was raised The HeuristicHazard exception was raised
The CommitTransaction function completes the transaction associated with the calling thread. Use the BeginTransaction function to begin a transaction and associate it with the calling thread. The transaction is not completed if any other participants in the transaction vote to roll back the transaction.
CommitTransaction can be called by a client or a component that is marked as OTS style. EAServer must be using the two-phase commit transaction coordinator (OTS/XA).
Examples
In this example, the client calls the dopayroll method on the CmpnyAcct EAServer component, which processes a company payroll. The method returns 1 if the company has sufficient funds to meet the payroll, and the client then commits the transaction:
// Instance variables: // CORBACurrent corbcurr integer li_rc boolean lb_rv long ll_rc
381
CommitTransaction
// Create an instance of the CORBACurrent object // and initialize it ... lb_rv = corbcurr.BeginTransaction() IF lb_rv THEN ll_rc = myconnect.CreateInstance(CmpnyAcct) // handle error li_rc = CmpnyAcct.dopayroll() IF li_rc = 1 THEN corbcurr.CommitTransaction( ELSE corbcurr.RollbackTransaction() END IF ELSE // handle error END IF See also
BeginTransaction GetContextService GetStatus GetTransactionName Init ResumeTransaction RollbackOnly RollbackTransaction SetTimeout SuspendTransaction
382
PowerBuilder
CHAPTER 10
PowerScript Functions
ConnectToNewObject
Description
Creates a new object in the specified server application and associates it with a PowerBuilder OLEObject variable. ConnectToNewObject starts the server application if necessary. OLEObject objects, OLETxnObject objects
oleobject.ConnectToNewObject ( classname ) Argument oleobject Description The name of an OLEObject variable that you want to connect to an automation server or COM object. You cannot specify an OLEObject that is the Object property of an OLE control. A string whose value is a programmatic identifier or class ID that identifies an automation server or COM server.
Applies to Syntax
classname
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -2 -3 -4 -9 -15 -16
Invalid Call: the argument is the Object property of a control Class name not found Object could not be created Could not connect to object Other error MTS is not loaded on this computer Invalid Call: this function not applicable
The OLEObject variable can be used for automation, in which the PowerBuilder application asks the server application to manipulate the OLE object programmatically. It can also be used to connect to a COM object that is registered on a local or remote computer or that is installed in MTS. The OLETxnObject variable is used to provide MTS transaction control to PowerBuilder clients. Calling ConnectToNewObject with an OLETxnObject variable creates a new object instance within the transaction context associated with the variable. If MTS is not loaded on the client computer, the ConnectToNewObject call fails. Use SetAbort to abort the transaction or SetComplete to complete it if all other participants in the transaction concur. For more information about automation and connecting to COM objects, see ConnectToObject.
383
ConnectToNewObject
Examples
This example creates an OLEObject variable and calls ConnectToNewObject to create a new Excel object and connect to it:
integer result OLEObject myoleobject myoleobject = CREATE OLEObject result = myoleobject.ConnectToNewObject( & "excel.application")
This example creates an OLETxnObject variable and calls ConnectToNewObject to create and connect to a new instance of a PowerBuilder COM object on an MTS server:
OLETxnObject EmpObj Integer li_rc EmpObj = CREATE OLETxnObject li_rc = EmpObj.ConnectToNewObject("PB70COM.employee") IF li_rc < 0 THEN DESTROY EmpObj MessageBox("Connecting to COM Object Failed", & "Error: " + String(li_rc)) Return END IF // Perform some work with the COM object ... // If the work completed successfully, commit // the transaction and disconnect the object EmpObj.SetComplete() EmpObj.DisconnectObject() See also
384
PowerBuilder
CHAPTER 10
PowerScript Functions
ConnectToNewRemoteObject
Description
Creates a new OLE object in the specified remote server application (if security on the server allows it) and associates the new object with a PowerBuilder OLEObject variable. ConnectToNewRemoteObject starts the server application if necessary. OLEObject objects
oleobject.ConnectToNewRemoteObject ( hostname, classname ) Argument oleobject Description The name of an OLEObject variable which you want to connect to an OLE object. You cannot specify an OLEObject that is the Object property of an OLE control. A string whose value is the name of the remote host where the COM server is located. A string whose value is the name of an OLE class, which identifies an OLE server application and a type of object that the server can manipulate via OLE.
Applies to Syntax
hostname classname
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 Invalid call: the argument is the Object property of a control -2 Class name not found -3 Object could not be created -4 Could not connect to object -9 Other error -10 Feature not supported on this platform -11 Server name is invalid -12 Server does not support operation -13 Access to remote host denied -14 Server unavailable -15 MTS is not loaded on this computer -16 Invalid Call: this function not applicable to OLETxnObject
Usage
The OLEObject variable is used for OLE automation, in which the PowerBuilder application asks the server application to manipulate the OLE object programmatically. ConnectToNewRemoteObject can only be used with servers that support remote activation. For more information about OLE automation, see ConnectToObject. For information about connecting to objects on a remote host, see ConnectToRemoteObject.
385
ConnectToNewRemoteObject
Examples
This example creates an OLEObject variable and calls ConnectToNewRemoteObject to create and connect to a new Excel object on a remote host named ulysses:
integer result OLEObject myoleobject myoleobject = CREATE OLEObject result = myoleobject.ConnectToNewRemoteObject( & "ulysses", "Excel.application")
See also
ConnectToObject ConnectToRemoteObject
386
PowerBuilder
CHAPTER 10
PowerScript Functions
ConnectToObject
Description
Associates an OLE object with a PowerBuilder OLEObject variable and starts the server application. The OLEObject variable and ConnectToObject are used for OLE automation, in which the PowerBuilder application asks the server application to manipulate the OLE object programmatically. OLEObject objects
oleobject.ConnectToObject ( filename {, classname } ) Argument oleobject Description The name of an OLEObject variable which you want to connect to an OLE object. You cannot specify an OLEObject that is the Object property of an OLE control. A string whose value is the name of an OLE storage file. You can specify the empty string for filename, in which case you must specify classname. Oleobject is connected to the active object in the server application specified in classname. A string whose value is the name of an OLE class, which identifies an OLE server application and a type of object that the server can manipulate via OLE. If you omit classname, PowerBuilder uses the extension of filename to determine what server application to start.
Applies to Syntax
filename
classname (optional)
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -2 -3 -4 -5 -6 -7 -8 -9 -15 -16
Invalid call: the argument is the Object property of a control Class name not found Object could not be created Could not connect to object Ca not connect to the currently active object Filename is not valid File not found or file could not be opened Load from file not supported by server Other error MTS is not loaded on this computer Invalid Call: this function not applicable to OLETxnObject
387
ConnectToObject
Usage
After you have created an OLEObject variable and connected it to an OLE object and its server application, you can set properties and call functions supported by the OLE server. PowerBuilders compiler will not check the syntax of functions that you call for an OLEObject variable. If the functions are not present when the application is run or the property names are invalid, an execution error occurs.
Declare and create an OLEObject variable You must use the CREATE statement to allocate memory for an OLEObject
variable, as shown in the example below. When you create an OLEObject variable, make sure you destroy the object before it goes out of scope. When the object is destroyed it is disconnected from the server and the server is closed. If the object goes out of scope without disconnecting, there will be no way to halt the server application. Check the documentation for the server application to find out what properties and functions it supports. Some applications support a large number. For example, Excel has approximately 4000 operations you can automate. The OLEObject datatype supports OLE automation as a background activity in your application. You can also invoke server functions and properties for an OLE object in an OLE control. To do so, specify the Object property of the control before the server function name. When you want to automate an object in a control, you do not need an OLEObject variable. For example, the following changes a value in an Excel cell for the object in the OLE control ole_1:
ole_1.Object.application.cells(1,1).value = 14 Examples
This example declares and creates an OLEObject variable and connects to an Excel worksheet, which is opened in Excel. It then sets a value in the worksheet, saves it, and destroys the OLEObject variable, which exits the Excel:
integer result OLEObject myoleobject myoleobject = CREATE OLEObject result = myoleobject.ConnectToObject( & "c:\excel\expense.xls")
388
PowerBuilder
CHAPTER 10
PowerScript Functions
This example connects to the currently active object in Excel, which is already running:
integer result OLEObject myoleobject myoleobject = CREATE OLEObject result = myoleobject.ConnectToObject("", & "excel.application") See also
ConnectToNewObject DisconnectObject
389
ConnectToRemoteObject
ConnectToRemoteObject
Description Applies to Syntax
Associates an OLE object with a PowerBuilder OLEObject variable and starts the server application. OLEObject objects
oleobject.ConnectToRemoteObject ( hostname, filename {, classname } ) Argument oleobject Description The name of an OLEObject variable that you want to connect to an OLE object. You cannot specify an OLEObject that is the Object property of an OLE control. A string whose value is the name of the remote host where the COM server is located. A string whose value is the name of an OLE storage file. You cannot specify an empty string. COM looks for filename on the local (client) machine. If filename is located on the remote host, its location must be made available to the local host by sharing. Use the share name for the remote drive to specify a file on a remote host for example, \\hostname\shared_directory\test.ext. A string whose value is the name of an OLE class, which identifies an OLE server application and a type of object that the server can manipulate via OLE. If you omit classname and filename, is an OLE structured storage file, PowerBuilder uses the class ID in filename. Otherwise, PowerBuilder uses the filename extension to determine what server application to start.
hostname filename
classname (optional)
Return value
error occurs: -1 Invalid call: the argument is the Object property of a control -2 Class name not found -3 Object could not be created -4 Could not connect to object -5 Could not connect to the currently active object -6 File name is invalid -7 File not found or could not be opened -8 Load from file not supported by server -9 Other error -10 Feature not supported on this platform -11 Server name is invalid -12 Server does not support operation -13 Access to remote host denied
390
PowerBuilder
CHAPTER 10
PowerScript Functions
-14 Server unavailable -15 MTS is not loaded on this computer -16 Invalid Call: this function not applicable to OLETxnObject
Usage
The OLEObject variable is used for OLE automation, in which the PowerBuilder application asks the server application to manipulate the OLE object programmatically. ConnectToRemoteObject can only be used with servers that support remote activation. The following information applies to creating or instantiating and binding to OLE objects on remote hosts. For general information about OLE automation, see ConnectToObject. Security Security on the server must be configured correctly to launch objects on remote hosts. Security is configured using registry keys. You must specify attributes for allowing and disallowing launching of servers and connections to running objects to allow client access. You can update the registry manually or with a tool such as DCOMCNFG.EXE or OLE Viewer. Registry entries and the client. The server application must be registered on both the server
To find files other than OLE structured storage files, registry entries must include a file extension entry, such as .xls for Excel. If the file is a structured storage file, then COM reads the file and extracts the server identity from the file; otherwise, the registry entry for the file extension is used and the appropriate server application is launched. If the DCOM server uses a custom interface, the proxy/stub DLL for the interface must be registered on the client. The proxy/stub DLL is created by the designer of the custom interface. It handles the marshaling of parameters through the proxy on the client and the stub on the server so that a remote procedure call can take place.
Examples
This example declares and creates an OLEObject variable and connects to an Excel worksheet on a remote host named falco. The drive where the worksheet resides is mapped as f:\excel on the local host:
integer result OLEObject myoleobject myoleobject = CREATE OLEObject result = myoleobject.ConnectToRemoteObject( & "falco", "f:\excel\expense.xls")
391
ConnectToRemoteObject
This example connects to the same object on the remote host but opens it as an Excel chart:
integer result OLEObject myoleobject myoleobject = CREATE OLEObject result = myoleobject.ConnectToRemoteObject( & "falco", "f:\excel\expense.xls", "Excel.chart") See also
392
PowerBuilder
CHAPTER 10
PowerScript Functions
ConnectToServer
Description
Connects a client application to a server component. The client application must call ConnectToServer before it can use a remote object on the server. This function applies to distributed applications only.
Applies to Syntax
Connection objects
connection.ConnectToServer ( ) Argument connection Description The name of the Connection object you want to use to establish the connection. The Connection object has properties that specify how the connection will be established.
Return value
Long. Returns 0 if it succeeds and one of the following values if an error occurs: 50 52 53 54 55 56 57 62 92 Distributed service error Distributed communications error Requested server not active Server not accepting requests Request terminated abnormally Response to request incomplete Connection object not connected to server Server busy Required property is missing or invalid
Usage Examples
Before calling ConnectToServer, you assign values to the properties of the Connection object. In this example, the client application connects to a server application using the Connection object myconnect:
// Global variable: // connection myconnect long ll_rc myconnect = create connection myconnect.driver = "jaguar" myconnect.location = "Jagserver1:9000" myconnect.application = "PB_pkg_1" myconnect.userID = "bjones" myconnect.password = "mypass" ll_rc = myconnect.ConnectToServer() IF ll_rc <> 0 THEN MessageBox("Connection failed", ll_rc) END IF
393
ConnectToServer
You can enclose the ConnectToServer function in a try-catch block to catch exceptions thrown during the attempt to connect. This example uses SSLServiceProvider and SSLCallBack objects to create a secure connection. An exception or other error in any of the SSLCallback functions raises the CTSSecurity::UserAbortedException. The error-handling code shown in the example displays a message box with the text of the error message, but your code should take additional appropriate action:
SSLServiceProvider sp // set QOP getcontextservice( "SSLServiceProvider", sp ) sp.setglobalproperty( "QOP", "sybpks_simple" ) // set PB callback handler sp.setglobalproperty( "CallbackImpl", & "uo_sslcallback_handler" ) // connect to the server connection cxn cxn.userid = "jagadmin" cxn.password = "sybase" cxn.driver = "jaguar" cxn.application = "dbgpkg" cxn.options = "ORBLogFile=d:\PBJagClient.Log" cxn.location = "iiops://localhost:9001" TRY l_rc = cxn.ConnectToServer() CATCH (userabortedexception uae) MessageBox("UserAbortedException Caught", & "ConnectToServer caught: " + uae.getMessage() ) l_rc = 999 CATCH ( CORBASystemException cse ) MessageBox("CORBASystemException Caught", & "ConnectToServer caught: " + cse.getMessage() ) l_rc = 998 CATCH ( RuntimeError re ) MessageBox("RuntimeError Exception Caught", & "ConnectToServer caught: " + re.getMessage() ) l_rc = 997 CATCH ( Exception ex ) MessageBox("Exception Caught", & "ConnectToServer caught: " + ex.getMessage() ) l_rc = 996 END TRY
394
PowerBuilder
CHAPTER 10
PowerScript Functions
IF l_rc <> 0 THEN MessageBox("Error", "Connection Failed - code: " & + string(l_rc) ) MessageBox("Error Info", "ErrorCode= " + & string(cxn.ErrCode) + "~nErrText= " + & cxn.ErrText) ELSE MessageBox("OK", "Connection Established") END IF See also
DisconnectServer
395
Copy
Copy
Description Applies to
Puts selected text or an OLE object on the clipboard. Copy does not change the source text or object. DataWindow, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox, DropDownPictureListBox, OLE controls, and OLE DWObjects (objects within a DataWindow object that is within a DataWindow control)
objectref.Copy ( ) Argument objectref Description One of the following: The name of the DataWindow control, EditMask, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox or DropDownPictureListBox containing the text you want to copy to the clipboard. The name of the OLE control or the fully qualified name of a OLE DWObject within a DataWindow control that contains the object you want to copy to the clipboard. The fully qualified name for a DWObject has this syntax:
dwcontrol.Object.dwobjectname
Syntax
If objectref is a DataWindow, text is copied from the edit control over the current row and column. If objectref is a DropDownListBox or DropDownPictureListBox, its AllowEdit property must be TRUE. Return value
Long.
For RichTextEdit controls, Copy returns a long. For other edit controls and OLE objects, Copy returns an integer. For edit controls, Copy returns the number of characters that were copied to the clipboard. If no text is selected in objectref, no characters are copied and Copy returns 0. If an error occurs, Copy returns -1. For OLE controls and OLE DWObjects, Copy returns 0 if it succeeds and one of the following negative values if an error occurs: -1 -2 -9 Container is empty Copy Failed Other error
396
PowerBuilder
CHAPTER 10
PowerScript Functions
Usage
To select text for copying, the user can use the mouse or keyboard. You can also call the SelectText function in a script. For RichTextEdit controls, there are several additional functions for selecting text: SelectTextAll, SelectTextLine, and SelectTextWord. To insert the contents of the clipboard into a control, use the Paste function.
Copy does not delete the selected text or OLE object. To delete the data, use the Clear or Cut function.
Examples
Assuming the selected text in mle_emp_address is Temporary Address, these statements copy Temporary Address from mle_emp_address to the clipboard and store 17 in copy_amt:
integer copy_amt copy_amt = mle_emp_address.Copy()
This example copies the OLE object in the OLE control ole_1 to the clipboard:
integer result result = ole_1.Copy() See also
397
CopyRTF
CopyRTF
Description
Returns the selected text, pictures, and input fields in a RichTextEdit control or RichText DataWindow as a string with rich text formatting. Bitmaps and input fields are included in the string. DataWindow controls, DataStore objects, and RichTextEdit controls
rtename.CopyRTF ( { selected {, band } } ) Argument rtename Description The name of the DataWindow control, DataStore object, or RichTextEdit control from which you want to copy the selection in rich text format. The DataWindow object in the DataWindow control or DataStore must be a RichText DataWindow. A boolean value indicated whether to copy selected text only. Values are: TRUE (Default) Copy selected text only FALSE Copy the entire contents of the band band (optional) A value of the Band enumerated datatype specifying the band from which to copy text. Values are: Detail! Copy text from the detail band Header! Copy text from the header band Footer! Copy text from the footer band The default is the band that contains the insertion point.
Applies to Syntax
selected (optional)
Return value
String. Returns the selected text as a string. CopyRTF returns an empty string ("") if:
Usage
CopyRTF does not involve the clipboard. The copied information is stored in a string. If you use the standard clipboard functions (Copy and Cut) the clipboard will contain the text without any formatting.
To incorporate the text with RTF formatting into another RichTextEdit control, use PasteRTF. For more information about rich text format, see the chapter about implementing rich text in Application Techniques.
398
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This statement returns the text that is selected in the RichTextEdit rte_message and stores it in the string ls_richtext:
string ls_richtext ls_richtext = rte_message.CopyRTF()
This example copies the text in rte_1, saving it in ls_richtext, and pastes it into rte_2. The user clicks the RadioButton rb_true to copy selected text and rb_false to copy all the text. The number of characters pasted is saved in ll_numchars reported in the StaticText st_status:
string ls_richtext boolean lb_selected long ll_numchars IF rb_true.Checked = TRUE THEN lb_selected = TRUE ELSE lb_selected = FALSE END IF ls_richtext = rte_1.CopyRTF(lb_selected) ll_numchars = rte_2.PasteRTF(ls_richtext) st_status.Text = String(ll_numchars) See also
PasteRTF
399
Cos
Cos
Description Syntax
ACos Pi Sin Tan Cos method for DataWindows in the DataWindow Reference or online Help
400
PowerBuilder
CHAPTER 10
PowerScript Functions
Cpu
Description Syntax Return value Examples
Reports the amount of CPU time that has elapsed since the application started.
Cpu ( )
Long. Returns the number of milliseconds of CPU time elapsed since the start
of your PowerBuilder application. These statements determine the amount of CPU time that elapsed while a group of statements executed:
// Declare ll_start and ll_used as long integers. long ll_start, ll_used // Set the start equal to the current CPU usage. ll_start = Cpu() ... // Executable statements being timed // Set ll_used to the number of CPU seconds // that were used (current CPU time - start). ll_used = Cpu() - ll_start
CreateDirectory
Description Applies to Syntax
This example creates a new subdirectory in the current path and then makes the new subdirectory the current directory:
string ls_path="my targets" integer li_filenum CreateDirectory ( ls_path ) li_filenum = ChangeDirectory( ls_path )
See also
GetCurrentDirectory RemoveDirectory
401
CreateInstance
CreateInstance
Creates an instance of a remote object running on a middle-tier server.
To create a remote object instance From a PowerBuilder client From within an EAServer or MTS component Use Syntax 1 Syntax 2
Syntax 1
Description
Applies to Syntax
Return value
Long. Returns 0 if it succeeds and one of the following values if an error occurs: 50 52 53 54 55 56 57 62 Distributed service error Distributed communications error Requested server not active Server not accepting requests Request terminated abnormally Response to request incomplete Not connected Server busy
Usage
Before calling CreateInstance, you need to connect to a server. To do this, you need to call the ConnectToServer function.
CreateInstance allows you to create an object on a remote server. If you want to create an object locally, you need to use the CREATE statement.
402
PowerBuilder
CHAPTER 10
PowerScript Functions
When you deploy a remote objects class definition in a client application, the definition on the client has the same name as the remote object definition deployed in the server application. Variables declared with this type are able to hold a reference to a local object or a remote object. Therefore, at execution time you can instantiate the object locally (with the CREATE statement) or remotely (with the CreateInstance function) depending on your application requirements. In either case, once you have created the object, its physical location is transparent to client-side scripts that use the object.
Examples
The following statements create an object locally or remotely depending on the outcome of a test. The statements use the CreateInstance function to create a remote object and the CREATE statement to create a local object:
boolean bWantRemote connection myconnect uo_customer iuo_customer //Determine whether you want a remote //object or a local object. ... //Then create the object. IF bWantRemote THEN //Create a remote object IF myconnect.CreateInstance(iuo_customer) <> 0 THEN //deal with the error ... END IF ELSE //Create a local object iuo_customer = CREATE uo_customer END IF //Call a function of the object. //The function call is the same whether the object was //created on the server or the client. IF isValid(iou_customer) THEN iuo_customer.GetCustomerData() END IF
See also
ConnectToServer
403
CreateInstance
Syntax 2
Description
Applies to Syntax
Return value
Long. Returns 0 if it succeeds and one of the following values if an error occurs:
50 52 53 54 55 56 57 62
Usage
Distributed service error Distributed communications error Requested server not active Server not accepting requests Request terminated abnormally Response to request incomplete Not connected Server busy
The CreateInstance function on the TransactionServer context object allows you to access other EAServer or MTS components running on the current server. To access an EAServer component on a different server, you need to use the CreateInstance function on the Connection object. The CreateInstance function on the TransactionServer context object uses the same user and password information that applies to the component from which it is called. Before you can use the transaction context service, you need to declare a variable of type TransactionServer and call the GetContextService function to create an instance of the service.
404
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
The following statements show how an EAServer component might instantiate another component in the same server and call one of its methods:
Integer rc rc = this.GetContextService("TransactionServer", & ts) IF rc <> 1 THEN // handle the error END IF rc = this.CreateInstance(mycomp2, & "mypackage/nvo_comp2") IF IsValid(mycomp2) = FALSE THEN // handle the error END IF mycomp2.method1()
This example shows the syntax for creating an instance of a COM component:
Integer rc OleObject lole TransactionServer lts lole = create OleObject rc = this.GetContextService("TransactionServer", lts) IF rc <> 1 THEN return "Error from GetContextService " + String (rc) END IF // PBCOM is the ProgID, n_genapp is the class name rc = lts.CreateInstance(lole, "PBCOM.n_genapp") IF rc <> 0 THEN return "Error from CreateInstance " + String (rc) END IF iole.my_func () See also
405
CreatePage
CreatePage
Description Applies to Syntax
Creates a tab page if it has not already been created. User objects used as tab pages
userobject.CreatePage ( ) Argument userobject Description The name of the tab page you want to create
Return value
created and -1 if the page was already created or if it is not a tab page. 1 The tab page was successfully created 0 The tab page has already been created -1 The user object is not a tab page
Usage
A window will open more quickly if the creation of graphical representations is delayed for tab pages with many controls. However, scripts cannot refer to a control on a tab page until the controls Constructor event has run and a graphical representation of the control has been created. When the CreateOnDemand property of the Tab control is selected, scripts cannot reference controls on tab pages that the user has not viewed. CreatePage allows you to create a tab page if it has not already been created. This example tests whether tabpage_2 has been created and, if not, creates it:
IF tab_1.CreateOnDemand = True THEN IF tab_1.tabpage_2.PageCreated() = False THEN tab_1.tabpage_2.CreatePage() END IF END IF
Examples
See also
PageCreated
406
PowerBuilder
CHAPTER 10
PowerScript Functions
Cut
Description
Deletes selected text or an OLE object from the specified control and stores it on the clipboard, replacing the clipboard contents with the deleted text or object. DataWindow, MultiLineEdit, SingleLineEdit, DropDownListBox, DropDownPictureListBox, and OLE controls
controlname.Cut ( ) Argument controlname Description The name of the DataWindow, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox, DropDownPictureListBox, or OLE control containing the text or object to be cut. If controlname is a DataWindow, text is cut from the edit control over the current row and column. If controlname is a DropDownListBox or DropDownPictureListBox, the AllowEdit property must be TRUE.
Applies to Syntax
Return value
Long.
For editable controls, Cut returns the number of characters that were cut from controlname and stored in the clipboard. If no text is selected, no characters are cut and Cut returns 0. If an error occurs, Cut returns -1. For OLE controls, Cut returns 0 if it succeeds and one of the following negative values if an error occurs: -1 -2 -9 Container is empty Cut failed Other error
To select text for deleting, the user can use the mouse or keyboard. You can also call the SelectText function in a script. For RichTextEdit controls, there are several additional functions for selecting text: SelectTextAll, SelectTextLine, and SelectTextWord. To insert the contents of the clipboard into a control, use the Paste function. To delete selected text or an OLE object but not store it in the clipboard, use the Clear function. Cutting an OLE object breaks any connections between it and its source file or storage, just as Clear does.
407
Cut
Examples
Assuming the selected text in mle_emp_address is Temporary, this statement deletes Temporary from mle_emp_address, stores it in the clipboard, and returns 9:
mle_emp_address.Cut()
This example cuts the OLE object in the OLE control ole_1 and puts it on the clipboard:
integer result result = ole_1.Cut() See also
408
PowerBuilder
CHAPTER 10
PowerScript Functions
DataCount
Description Applies to Syntax
Reports the number of data points in the specified series in a graph. Graph controls in windows and user objects, and graphs in DataWindow controls and DataStore objects
controlname.DataCount ( { graphcontrol, } seriesname ) Argument controlname Description The name of the graph in which you want the number of data points in a specific series, or the name of the DataWindow control or DataStore containing the graph (Optional) The name of the graph in the DataWindow control or DataStore for which you want the data point count for the series
A string whose value is the name of the series for which you want the number of data points
Return value
Long. Returns the number of data points in the specified series if it succeeds and -1 if an error occurs. If any arguments value is NULL, DataCount returns NULL.
Examples
These statements store in ll_count the number of data points in the series named Costs in the graph gr_product_data:
long ll_count ll_count = gr_product_data.DataCount("Costs")
These statements store in ll_count the number of data points in the series named Salary in the graph gr_dept in the DataWindow control dw_employees:
long ll_count ll_count = & dw_employees.DataCount("gr_dept", "Salary") See also
409
DataSource
DataSource
Description
Allows a RichTextEdit control to share data with a DataWindow and display the data in its input fields. If there are input fields in the RichTextEdit control that match the names of columns in the DataWindow, the data in the DataWindow is assigned to those input fields. The document in the RichTextEdit control is repeated so that there is an instance of the document for each row in the DataWindow. RichTextEdit controls
rtename.DataSource ( dwsource ) Argument rtename dwsource Description The name of the RichTextEdit control for which you want to get data in a DataWindow The name of the DataWindow control, DataStore, or child DataWindow that contains the data to be connected with input fields in rtename
Applies to Syntax
When names of input fields match names of columns in the DataWindow object, the data in the columns is assigned to the matching input fields. The document in the RichTextEdit control is associated with one row in the DataWindow. There is an instance of the document for each retrieved row. The text in the RichTextEdit control is repeated, with all its formatting, in every document instance. The content of the input fields changes as the data in each row changes. Except for the contents of the input fields, the contents of each instance is the sameyou cannot make changes to the surrounding text that affect individual instances only. If the InputFieldNamesVisible property of the RichTextEdit control is TRUE, the fields will show their names instead of the data they contain. Change the property value to FALSE to see the data.
410
PowerBuilder
CHAPTER 10
PowerScript Functions
The following RichTextEdit functions operate on or report information about an instance of the document:
LineCount PageCount InsertDocument SaveDocument SelectedPage SelectedStart SelectedLine SelectText SelectTextAll
Examples
This example establishes the DataWindow control dw_1 as the data source for the RichTextEdit rte_1:
rte_1.DataSource(dw_1)
This example inserts a document called LETTER.RTF into the RichTextEdit rte_letter (the names of the documents input fields match the columns in a DataWindow object d_emp), creates a DataStore, associates it with d_emp, and retrieves data. Then it inserts the document in rte_letter and sets up the DataStore as the data source for rte_1:
DataStore ds_empinfo ds_empinfo = CREATE DataStore ds_empinfo.DataObject = "d_emp" ds_empinfo.SetTransObject(SQLCA) ds_empinfo.Retrieve() rte_letter.InsertDocument("LETTER.RTF", TRUE) rte_letter.DataSource(ds_empinfo) See also
411
Date
Date
Converts DateTime, string, or numeric data to data of type date or extracts a date value from a blob. You can use one of several syntaxes, depending on the datatype of the source data.
To Extract the date from DateTime data or extract a date stored in a blob Convert a string to a date Combine numeric data into a date Use Syntax 1 Syntax 2 Syntax 3
To make sure you get correct return values for the year, you must verify that yyyy is the Short Date Style for year in the Regional Settings of the users Control Panel. Your program can check this with the RegistryGet function. If the setting is not correct, you can ask the user to change it manually or have the application change it (by calling the RegistrySet function). The user may need to reboot after the setting is changed.
Syntax 1
Description Syntax
Return value
Date. Returns the date in datetime as a date. If datetime contains an invalid date or an incompatible datatype, Date returns 1900-01-01. If datetime is NULL, Date returns NULL.
412
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
After a value for the DateTime variable ldt_StartDateTime has been retrieved from the database, this example sets ld_StartDate equal to the date in ldt_StartDateTime:
DateTime ldt_StartDateTime date ld_StartDate ld_StartDate = Date(ldt_StartDateTime)
Assuming the value of a blob variable ib_blob contains a DateTime value beginning at byte 32, the following statement converts it to a date value:
date ld_date ld_date = Date(BlobMid(ib_blob, 32)) See also
DateTime
Syntax 2
Description Syntax
For strings
Converts a string whose value is a valid date to a date value.
Date ( string ) Argument string Description A string containing a valid date (such as January 1, 1998, or 12-3199) that you want returned as a date. Datetime can also be an Any variable containing a string.
Return value
Date. Returns the date in string as a date. If string contains an invalid date or an incompatible datatype, Date returns 1900-01-01. If string is NULL, Date returns NULL.
Usage
Valid dates in strings can include any combination of day (1 to 31), month (1 to 12 or the name or abbreviation of a month), and year (2 or 4 digits). PowerBuilder assumes a 4-digit number is a year. Leading zeros are optional for month and day. The month, whether a name, an abbreviation, or a number, must be in the month location specified in the system setting for a dates format. If you do not know the system setting, use the standard datatype date format yyyy-mm-dd. Date literals do not need to be converted with the Date function.
413
Date
Examples
Example 1
These statements all return the date datatype for text expressing the date July 4, 1994 (1994-07-04). The system setting for a dates format is set with the months position in the middle:
Date("1994/07/04") Date("1994 July 4") Date("04 July 1994")
Example 2 The following groups of statements check to be sure the date in sle_start_date is a valid date and display a message if it is not. The first version checks the result of the Date function to see if the date was valid. The second uses the IsDate function to check the text before using Date to convert it:
Version 1:
// Windows Control Panel date format is YY/MM/DD date ld_my_date ld_my_date = Date(sle_start_date.Text) IF ld_my_date = Date("1900-01-01") THEN MessageBox("Error", "This date is invalid: " & + sle_start_date.Text) END IF
Version 2:
date ld_my_date IF IsDate(sle_start_date.Text) THEN ld_my_date = Date(sle_start_date.Text) ELSE MessageBox("Error", "This date is invalid: " & + sle_start_date.Text) END IF See also
DateTime IsDate RelativeDate RelativeTime Date method for DataWindows in the DataWindow Reference or the online Help
414
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 3
Description Syntax
Return value
Date. Returns the date specified by the integers for year, month, and day as a date datatype. If any value is invalid (out of the range of values for dates), Date returns 1900-01-01. If any arguments value is NULL, Date returns NULL.
Examples
See also
415
DateTime
DateTime
Manipulates DateTime values. There are two syntaxes.
To Combine a date and a time value into a DateTime value Obtain a DateTime value that is stored in a blob Use Syntax 1 Syntax 2
Syntax 1
Description Syntax
DateTime. Returns a DateTime value based on the values in date and optionally time. If any arguments value is NULL, DateTime returns NULL.
DateTime data is used only for reading and writing DateTime values to and from a database. To use the date and time values in scripts, use the Date and Time functions to assign values to date and time variables. These statements convert the date and time stored in ld_OrderDate and lt_OrderTime to a DateTime value that can be used to update the database:
DateTime ldt_OrderDateTime date ld_OrderDate time lt_OrderTime ld_OrderDate = Date(sle_orderdate.Text) lt_OrderTime = Time(sle_ordertime.Text) ldt_OrderDateTime = DateTime( & ld_OrderDate, lt_OrderTime)
Examples
See also
Date Time
DateTime method for DataWindows in the DataWindow Reference or the online Help
416
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 2
Description Syntax
DateTime. Returns the DateTime value stored in blob. If blob is NULL, DateTime returns NULL.
DateTime data is used only for reading and writing DateTime values to and from a database. To use the date and time values in scripts, use the Date and Time functions to assign values to date and time variables. After assigning blob data from the database to lb_blob, the following example obtains the DateTime value stored at position 20 in the blob (the length you specify for BlobMid must be at least as long as the DateTime value but can be longer):
DateTime dt dt = DateTime(BlobMid(lb_blob, 20, 40))
Examples
See also
Date Time
417
Day
Day
Description Syntax
Integer. Returns an integer (1 to 31) representing the day of the month in date. If date is NULL, Day returns NULL.
These statements extract the day (31) from the date literal 1994-01-31 and set li_day_portion to that value:
integer li_day_portion li_day_portion = Day(1994-01-31)
These statements check to be sure the date in sle_date is valid, and if so set li_day_portion to the day in the sle_date:
integer li_day_portion IF IsDate(sle_date.Text) THEN li_day_portion = Day(Date(sle_date.Text)) ELSE MessageBox("Error", & "This date is invalid: " & + sle_date.Text) END IF See also
Date IsDate Month Year Day method for DataWindows in the DataWindow Reference or the online Help
418
PowerBuilder
CHAPTER 10
PowerScript Functions
DayName
Description Syntax
Determines the day of the week in a date value and returns the weekdays name.
DayName ( date ) Argument date Description A date value for which you want the name of the day
String. Returns a string whose value is the weekday (Sunday, Monday, and so on) of date. If date is NULL, DayName returns NULL. DayName returns a name in the language of the runtime files available on the machine where the application is run. If you have installed localized runtime files in the development environment or on a users machine, then on that machine the name returned by DayName is in the language of the localized files.
For information about localized runtime files, which are available in French, German, Italian, Spanish, Dutch, Danish, Norwegian, and Swedish, see Application Techniques.
Examples
These statements evaluate the date literal 1993-07-04 and set day_name to Sunday:
string day_name day_name = DayName(1993-07-04)
These statements check to be sure the date in sle_date is valid, and if so set day_name to the day in sle_date:
string day_name IF IsDate(sle_date.Text) THEN day_name = DayName(Date(sle_date.Text)) ELSE MessageBox("Error", & "This date is invalid: " & + sle_date.Text) END IF See also
419
DayNumber
DayNumber
Description Syntax
Determines the day of the week of a date value and returns the number of the weekday.
DayNumber ( date ) Argument date Description The date value from which you want the number of the day of the week
Return value
Integer. Returns an integer (1-7) representing the day of the week of date. Sunday is day 1, Monday is day 2, and so on. If date is NULL, DayNumber returns NULL.
Examples
These statements evaluate the date literal 1990-01-31 and set day_nbr to 4 (January 31, 1990, was a Wednesday):
integer day_nbr day_nbr = DayNumber(1990-01-31)
These statements check to be sure the date in sle_date is valid, and if so set day_nbr to the number of the day in the sle_date:
integer day_nbr IF IsDate(sle_date.Text) THEN day_nbr = DayNumber(Date(sle_date.Text)) ELSE MessageBox("Error", & "This date is invalid: " & + sle_date.Text) END IF See also
420
PowerBuilder
CHAPTER 10
PowerScript Functions
DaysAfter
Description Syntax
Return value
Long. Returns a long whose value is the number of days date2 occurs after date1. If date2 occurs before date1, DaysAfter returns a negative number. If any arguments value is NULL, DaysAfter returns NULL.
Examples
If you declare date1 and date2 date variables and assign February 16, 2003, to date1 and April 28, 2003, to date2 as follows:
date date1, date2 date1 = 2003-02-16 date2 = 2003-04-28
421
DBHandle
DBHandle
Description Applies to Syntax
Return value
UnsignedLong. Returns the handle for your DBMS. Transactionobject must exist, and the database must be connected. If transactionobject is NULL, DBHandle returns NULL. If transactionobject does not exist, an execution error occurs. If there is not enough memory to connect to your DBMS, DBHandle
not able to determine if the database connection does not exist or has been lost. PowerBuilder uses the database handle internally to communicate with the database. If your database supports an API with functions that PowerBuilder does not support, you can use DBHandle to provide the handle as an argument to one of these external functions.
Examples
DebugBreak
Description Syntax Return value Usage
None Insert a call to the DebugBreak function into a script at a point at which you want to suspend execution and examine the application. Then enable just-in-time debugging and run the application in the development environment. When PowerBuilder encounters the DebugBreak function, the Debug window opens showing the current context.
Examples
This statement tests whether a variable is NULL and opens the Debug window if it is:
IF IsNull(auo_ext) THEN DebugBreak()
422
PowerBuilder
CHAPTER 10
PowerScript Functions
Dec
Description Syntax
Return value
Decimal. Returns the value of stringorblob as a decimal. If stringorblob is not a valid PowerScript number or if it contains an incompatible datatype, Dec returns 0. If stringorblob is NULL, Dec returns NULL.
Examples
This statement returns the contents of the SingleLineEdit sle_salary as a decimal number:
Dec(sle_salary.Text)
For an example of assigning and extracting values from a blob, see Real.
See also
423
DeleteCategory
DeleteCategory
Description
Deletes a category and the data values for that category from the category axis of a graph. Graph controls in windows and user objects. Does not apply to graphs within DataWindow objects (because their data comes directly from the DataWindow).
Syntax
controlname.DeleteCategory ( categoryvalue ) Argument controlname categoryvalue Description The graph in which you want to delete a category. A value that is the category you want to delete from controlname. The value you specify must be the same datatype as the datatype of the category axis.
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, DeleteCategory returns NULL.
These statements delete the category whose name is entered in the SingleLineEdit sle_delete from the graph gr_product_data:
string CategName CategName = sle_delete.Text gr_product_data.DeleteCategory(CategName)
See also
DeleteData DeleteSeries
424
PowerBuilder
CHAPTER 10
PowerScript Functions
DeleteColumn
Description
Syntax
listviewname.DeleteColumn ( index ) Argument listviewname index Description The name of the ListView control from which you want to delete a column The index number of the column you want to delete
See also
DeleteColumns
DeleteColumns
Description Applies to Syntax
See also
DeleteColumn
425
DeleteData
DeleteData
Description Applies to
Deletes a data point from a series of a graph. The remaining data points in the series are shifted left to fill the data points category. Graph controls in windows and user objects. Does not apply to graphs within DataWindow objects (because their data comes directly from the DataWindow).
controlname.DeleteData ( seriesnumber, datapointnumber ) Argument controlname seriesnumber datapointnumber Description The name of the graph in which you want to delete a data value The number of the series containing the data value you want to delete from controlname The number of the data point containing the data you want to delete
Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, DeleteData returns NULL.
These statements delete the data at data point 7 in the series named Costs in the graph gr_product_data:
integer SeriesNbr // Get the number of the series. SeriesNbr = gr_product_data.FindSeries("Costs") gr_product_data.DeleteData(SeriesNbr, 7)
See also
426
PowerBuilder
CHAPTER 10
PowerScript Functions
DeleteItem
Deletes an item from a ListBox, DropDownListBox, or ListView control.
To delete an item from A ListBox or DropDownListBox control A ListView control A TreeView control Use Syntax 1 Syntax 2 Syntax 3
Syntax 1
Description Applies to Syntax
Return value
Integer. Returns the number of items remaining in the list of values after the item is deleted. If an error occurs, DeleteItem returns -1. If any arguments value is NULL, DeleteItem returns NULL.
Usage
If the controls Sorted property is set, the order of the list is probably different from the order you specified when you defined the control. If you know the items text, use FindItem to determine the items index. Assuming lb_actions contains 10 items, this statement deletes item 5 from lb_actions and returns 9:
lb_actions.DeleteItem(5)
Examples
This statement deletes the item "Personal" from the ListBox lb_purpose:
lb_purpose.DeleteItem( & lb_purpose.FindItem("Personal", 1))
427
DeleteItem
See also
Syntax 2
Description Applies to Syntax
This example uses SelectedIndex to find the index of the selected ListView item and then deletes the corresponding item:
integer index index = lv_list.selectedindex() lv_list.DeleteItem(index)
See also
428
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 3
Description Applies to Syntax
If all items are children of a single item at the root level, you can delete all items in the TreeView with the handle for RootTreeItem as the argument for DeleteItem. Otherwise, you need to loop through the items at the first level. This example deletes an item from a TreeView control:
long ll_tvi ll_tvi = tv_list.FindItem(CurrentTreeItem!, 0) tv_list.DeleteItem(ll_tvi)
Examples
This example deletes all items from a TreeView control when there are several items at the first level:
long tvi_hdl = 0 DO UNTIL tv_1.FindItem(RootTreeItem!, 0) = -1 tv_1.DeleteItem(tvi_hdl) LOOP See also
429
DeleteItems
DeleteItems
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. This example deletes all the items in a ListView control:
lv_list.DeleteItems()
See also
DeleteItem
430
PowerBuilder
CHAPTER 10
PowerScript Functions
DeleteLargePicture
Description Applies to Syntax
See also
DeleteLargePictures
DeleteLargePictures
Description Applies to Syntax
See also
DeleteLargePicture
431
DeletePicture
DeletePicture
Description Applies to Syntax
Deletes a picture from the image list. PictureListBox, DropDownPictureListBox, and TreeView controls
controlname.DeletePicture ( index ) Argument controlname index Description The control from which you want to delete a picture The index number of the picture you want to delete from the TreeView controls image list
When you delete a picture from the image list for a control, all subsequent pictures in the list are renumbered to fill the gap. Because the picture index for an item does not change, the pictures for items that use the affected index numbers will change. This example deletes the sixth image from the image list:
tv_list.DeletePicture(6)
Examples
See also
DeletePictures AddPicture
DeletePictures
Description Applies to Syntax
Deletes all pictures from an image list. PictureListBox, DropDownPictureListBox, and TreeView controls
controlname.DeletePictures ( ) Argument controlname Description The control in which you want to delete all pictures from the image list
Integer. Returns 1 if it succeeds and -1 if an error occurs. This example deletes all images from a TreeView control image list:
tv_list.DeletePictures()
See also
DeletePicture AddPicture
432
PowerBuilder
CHAPTER 10
PowerScript Functions
DeleteSeries
Description Applies to
Deletes a series and its data values from a graph. Graph controls in windows and user objects. Does not apply to graphs within DataWindow objects (because their data comes directly from the DataWindow).
controlname.DeleteSeries ( seriesname ) Argument controlname seriesname Description The graph in which you want to delete a series A string whose value is the name of the series you want to delete from controlname
Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, DeleteSeries returns NULL.
The series in a graph are numbered consecutively, in the order they were added to the graph. When a series is deleted, the remaining series are renumbered. This script for the SelectionChanged event of a DropDownListBox assumes that the list box lists the series in the graph gr_data. When the user chooses an item, DeleteSeries deletes the series from the graph and DeleteItem deletes the name from the list box:
string ls_name ls_name = This.Text gr_data.DeleteSeries(ls_name) This.DeleteItem(This.FindItem(ls_name, 0))
See also
433
DeleteSmallPicture
DeleteSmallPicture
Description Applies to Syntax
See also
DeleteSmallPictures
DeleteSmallPictures
Description Applies to Syntax
See also
DeleteSmallPicture
434
PowerBuilder
CHAPTER 10
PowerScript Functions
DeleteStatePicture
Description Applies to Syntax
See also
DeleteStatePictures
DeleteStatePictures
Description Applies to Syntax
Deletes all state pictures from a control. ListView and TreeView controls
controlname.DeleteStatePictures ( ) Argument controlname Description The name of the ListView or TreeView control from which you want to delete all state pictures
See also
DeleteStatePicture
435
DestroyModel
DestroyModel
Description Applies to Syntax
Destroys the current performance analysis or trace tree model. Profiling and TraceTree objects
instancename.DestroyModel ( ) Argument instancename Description Instance name of the Profiling or TraceTree object
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded ModelNotExistsError!The function failed because no model exists
Usage
When you are finished with the performance analysis or trace tree model you created using the BuildModel function, you must call DestroyModel to destroy the model as well as all the objects associated with that model. The memory allocated to a model will not be released until the object is destroyed. This example destroys the performance analysis model previously created using the BuildModel function:
lpro_model.DestroyModel() DESTROY lpro_model
Examples
See also
BuildModel
436
PowerBuilder
CHAPTER 10
PowerScript Functions
DirectoryExists
Description Syntax
Returns TRUE if the directory exists. Returns FALSE if the directory does not exist or if you pass a file name in the directoryname argument. You can use this method before attempting to move a file or delete a directory using other file system methods. This example determines if a directory exists before attempting to move a file to it; otherwise it displays a message box indicating that the path does not exist:
string ls_path="monthly targets"
If DirectoryExists ( ls_path ) Then FileMove ("2000\may.csv", ls_path+"\may.csv" ) MessageBox ("File Mgr", "File moved to "& + ls_path + ".") Else MessageBox ("File Mgr", "Directory " + ls_path+& " does not exist" ) End If See also
437
DirList
DirList
Description
Populates a ListBox with a list of files. You can specify a path, a mask, and a file type to restrict the set of files displayed. If the window has an associated StaticText control, DirList can display the current drive and directory as well. ListBox, DropDownListBox, PictureListBox, and DropDownPictureListBox controls
listboxname.DirList ( filespec, filetype {, statictext } ) Argument listboxname filespec Description The name of the ListBox control you want to populate. A string whose value is the file pattern. This is usually a mask (for example, *.INI or *.TXT). If you include a path, it becomes the current drive and directory. An unsigned integer representing one or more types of files you want to list in the ListBox. Types are: 0 Read/write files 1 Read-only files 2 Hidden files 4 System files 16 Subdirectories 32 Archive (modified) files 16384 Drives 32768 Exclude read/write files from the list To list several types, add the numbers associated with the types. For example, to list read-write files, subdirectories, and drives, use 0+16+16384 or 16400 for filetype. statictext (optional) The name of the StaticText in which you want to display the current drive and directory.
Applies to Syntax
filetype
Return value
Boolean. Returns TRUE if the search path is valid so that the ListBox is populated or the list is empty. DirList returns FALSE if the ListBox cannot be
populated (for example, filespec is a file, not a directory, or specifies an invalid path). If any arguments value is NULL, DirList returns NULL.
Usage
You can call DirList when the window opens to populate the list initially. You should also call DirList in the script for the SelectionChanged event to repopulate the list box based on the new selection. (See the example in DirSelect.)
438
PowerBuilder
CHAPTER 10
PowerScript Functions
Alternatives Although DirLists features allow you to emulate the standard File Open and
File Save windows, you can get the full functionality of these standard windows by calling GetFileOpenName and GetFileSaveName instead of DirList.
Examples
This statement populates the ListBox lb_emp with a list of read/write files with the file extension TXT in the search path C:\EMPLOYEE\*.TXT:
lb_emp.DirList("C:\EMPLOYEE\*.TXT", 0)
This statement populates the ListBox lb_emp with a list of read-only files with the file extension DOC in the search path C:\EMPLOYEE\*.DOC and displays the path specification in the StaticText st_path:
lb_emp.DirList("C:\EMPLOYEE\*.DOC", 1, st_path)
These statements in the script for a window Open event initialize a ListBox to all files in the current directory that match *.TXT:
String s_filespec s_filespec = "*.TXT" lb_filelist.DirList(s_filespec, 16400, st_filepath) See also
DirSelect
439
DirSelect
DirSelect
Description Applies to Syntax
When a ListBox has been populated with the DirList function, DirSelect retrieves the current selection and stores it in a string variable. ListBox, DropDownListBox, PictureListBox, and DropDownPictureListBox controls
listboxname.DirSelect ( selection ) Argument listboxname Description The name of the ListBox control from which you want to retrieve the current selection. The ListBox must have been populated using DirList, and the selection must be a drive letter, a file, or the name of a directory. A string variable in which the selected path name will be put.
Boolean. Returns TRUE if the current selection is a drive letter or a directory name (which can contain files and other directories) and FALSE if it is a file (indicating the users final choice). If any arguments value is NULL, DirSelect returns NULL.
Usage
Use DirSelect in the SelectionChanged event to find out what the user chose. When the users selection is a drive or directory, use the selection as a new directory specification for DirList. The following script for the SelectionChanged event for the ListBox lb_FileList calls DirSelect to test whether the users selection is a file. If not, the script joins the directory name with the file pattern, and calls DirList to populate the ListBox and display the current drive and directory in the StaticText st_FilePath. If the current selection is a file, other code processes the file name:
string ls_filename, ls_filespec = "*.TXT" IF lb_FileList.DirSelect(ls_filename) THEN //If ls_filename is not a file, //append directory to ls_filespec. ls_filename = ls_filename + ls_filespec lb_filelist.DirList(ls_filename, & 16400, st_FilePath) ELSE ... //Process the file. END IF
Examples
See also
DirList
440
PowerBuilder
CHAPTER 10
PowerScript Functions
Disable
Description Applies to Syntax
Disables an item on a menu. The menu item is dimmed (its color is changed to the users disabled text color, usually gray), and the user cannot select it. Menu objects
menuname.Disable ( ) Argument menuname Description The name of the menu selection you want to deactivate (disable)
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. If menuname is NULL, Disable returns NULL.
menuname.Enabled = FALSE
This statement:
m_appl.m_edit.Enabled = FALSE
is equivalent to:
m_appl.m_edit.Disable() Examples
This statement disables the m_edit menu item on the menu m_appl:
m_appl.m_edit.Disable()
See also
Enable
441
DisableCommit
DisableCommit
Description Applies to Syntax
Declares that a components transaction updates are inconsistent and cannot be committed in their present state. TransactionServer objects
transactionserver.DisableCommit ( ) Argument transactionserver Description Reference to the TransactionServer service instance
The DisableCommit function indicates that the current transaction cannot be committed because the components work has not been completed; the instance remains active after the current method returns. The DisableCommit function corresponds to the disallowCommit transaction primitive in EAServer. The following example shows the use of the DisableCommit in a component method that performs database updates:
// Instance variables: // DataStore ids_datastore // TransactionServer ts Integer li_rc long ll_rv li_rc = this.GetContextService("TransactionServer", & ts) IF li_rc <> 1 THEN // handle the error END IF ... ll_rv = ids_datastore.Update() IF ll_rv = 1 THEN ts.EnableCommit() ELSE ts.DisableCommit() END IF
Examples
See also
442
PowerBuilder
CHAPTER 10
PowerScript Functions
DisconnectObject
Description Applies to Syntax
Releases any object that is connected to the specified OLEObject variable. OLEObject objects
oleobject.DisconnectObject ( ) Argument oleobject Description The name of an OLEObject variable that you want to disconnect from an OLE object. You cannot specify an OLEObject that is the Object property of an OLE control.
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -9
Invalid call: the argument is the Object property of a control Other error
The OLEObject variable is used for OLE automation, in which the PowerBuilder application asks the server application to manipulate the OLE object programmatically. For more information about OLE automation, see ConnectToObject.
Examples
This example creates an OLEObject variable and connects it to a new Excel object; then after some unspecified code, it disconnects:
integer result OLEObject myoleobject myoleobject = CREATE OLEObject result = myoleobject.ConnectToNewObject( & "excel.application") . . . result = myoleobject.DisconnectObject()
See also
ConnectToObject ConnectToNewObject
443
DisconnectServer
DisconnectServer
Description
Disconnects a client application from a server application. This function applies to distributed applications only.
Applies to Syntax
Connection objects
connection.DisconnectServer ( ) Argument connection Description The name of the Connection object used to establish the connection you want to delete
Return value
Long. Returns 0 if it succeeds and one of the following values if an error occurs:
50 52 53 54 55 56 57 62
Usage
Distributed service error Distributed communications error Requested server not active Server not accepting requests Request terminated abnormally Response to request incomplete Not connected Server busy
After disconnecting from the server application, the client application needs to destroy the Connection object.
DisconnectServer causes all remote objects and proxy objects created for the client connection to be destroyed.
Examples
In this example, the client application disconnects from the server application using the Connection object myconnect:
myconnect.DisconnectServer() destroy myconnect
See also
ConnectToServer
444
PowerBuilder
CHAPTER 10
PowerScript Functions
Double
Description Syntax
Return value
Double. Returns the contents of stringorblob as a double. If stringorblob is not a valid PowerScript number or if it contains a non-numeric datatype, Double returns 0. If stringorblob is NULL, Double returns NULL.
Usage
To distinguish between a string whose value is the number 0 and a string whose value is not a number, use the IsNumber function before calling the Double function. This statement returns 24.372 as a double:
Double("24.372")
Examples
After assigning blob data from the database to lb_blob, this example obtains the double value stored at position 20 in the blob (the length you specify for BlobMid must be at least as long as the value but can be longer):
double lb_num lb_num = Double(BlobMid(lb_blob, 20, 40))
For an example of assigning and extracting values from a blob, see Real.
See also
445
DoVerb
DoVerb
Description Applies to Syntax
Requests the OLE server application to execute the specified verb for the OLE object in an OLE control or OLE DWObject. OLE controls and OLE DWObjects (objects within a DataWindow object that is within a DataWindow control)
objectref.DoVerb ( verb ) Argument objectref Description The name of the OLE control or the fully qualified name of a OLE DWObject within a DataWindow control for which you want to execute a verb. The fully qualified name for a DWObject has this syntax:
dwcontrol.Object.dwobjectname
verb
An integer identifying a verb known to the OLE server application. Verbs are operations that the server can perform on the OLE object. Check the documentation for the servers OLE implementation to find out what verbs it supports.
Return value
occurs: -1 -2 -3 -4 -5 -9 Container is empty Invalid verb for object Verb not implemented by object No verbs supported by object Object cannot execute verb now Other error
This example executes verb 7 for the object in the OLE control ole_1:
integer result result = ole_1.DoVerb(7)
This example executes verb 7 for the object in the OLE DWObject ole_graph:
integer result result = dw_1.Object.ole_graph.DoVerb(7) See also
Activate
OLEActivate in the DataWindow Reference SelectObject
446
PowerBuilder
CHAPTER 10
PowerScript Functions
Drag
Description Applies to Syntax
Starts or ends the dragging of a control. All controls except drawing objects (Lines, Ovals, Rectangles, and Rounded Rectangles)
control.Drag ( dragmode ) Argument control dragmode Description The name of the control you want to drag or stop dragging A value of the DragMode datatype indicating the action you want to take on control: Begin! Put control in drag mode Cancel! Stop dragging control but do not cause a DragDrop event End! Stop dragging control and if control is over a target object, cause a DragDrop event
Return value
Integer. For all controls except OLE controls, returns 1 if it succeeds and -1 if you try to nest drag events or try to cancel the drag when control is not in drag mode. The return value is usually not used.
For OLE controls, returns the following values: 2 Object was moved 1 Drag was canceled 0 Drag succeeded -1 Control is empty -9 Unspecified error If any arguments value is NULL, Drag returns NULL.
Usage
To see the list of draggable controls, open the Browser. All the objects in the hierarchy below dragobject are draggable. If you set the controls DragAuto property to TRUE, PowerBuilder automatically puts the control in drag mode when the user clicks it. The user must hold the mouse button down to drag. When you use Drag(Begin!) in a controls Clicked event to manually put the control in drag mode, the user can drag the control by moving the mouse without holding down the mouse button. Clicking the left mouse button ends the drag. CANCEL! and END! are required only if you want to end the drag without requiring the user to click the left mouse button.
447
Drag
The Clicked event of a DataWindow control occurs when the user presses the mouse button, not when the mouse button is released. If you place Drag(Begin!) in a DataWindow controls Clicked event, releasing the mouse button ends the drag. To achieve the same behavior as with other controls, define a userdefined event for the DataWindow control called lbuttonup and map it to the pbm_lbuttonup event ID. Then place the following code in the lbuttonup event script (ib_dragflag is a boolean instance variable):
IF NOT ib_dragflag THEN this.Drag(Begin!) ib_dragflag = TRUE ELSE ib_dragflag = FALSE END IF
To make something happen when the user drags a control onto a target object, write scripts for one or more of the targets drag events (DragDrop, DragEnter, DragLeave, and DragWithin).
Examples
See also
DraggedObject
448
PowerBuilder
CHAPTER 10
PowerScript Functions
DraggedObject
Description Syntax Return value
DragObject, a special datatype that includes all draggable controls (all the controls but no drawing objects). Returns a reference to the control that is currently being dragged.
No control
Call DraggedObject in a drag event for the target object. The drag events are DragDrop, DragEnter, DragLeave, and DragWithin. Use TypeOf to obtain the datatype of the control. To access the properties of the control, you can assign the DragObject reference to a variable of that controls datatype (see the example).
Examples
These statements set which_control equal to the datatype of the control that is currently being dragged, and then set ls_text_value to the text property of the dragged control:
SingleLineEdit sle_which CommandButton cb_which string ls_text_value DragObject which_control which_control = DraggedObject() CHOOSE CASE TypeOf(which_control) CASE CommandButton! cb_which = which_control ls_text_value = cb_which.Text CASE SingleLineEdit! sle_which = which_control ls_text_value = sle_which.Text END CHOOSE
See also
Drag TypeOf
449
Draw
Draw
Description Applies to Syntax
Draws a picture control at a specified location in the current window. Picture controls
picture.Draw ( xlocation, ylocation ) Argument picture xlocation ylocation Description The name of the picture control you want to draw in the current window The x coordinate of the location (in PowerBuilder units) at which you want to draw the picture The y coordinate of the location (in PowerBuilder units) at which you want to draw the picture
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, Draw returns NULL. The return value is usually not used.
Using the Draw function is faster and produces less flicker than successively changing the X property of a picture. This is because the Draw function draws directly on the window rather than recreating a small window with the picture in it for each change. Therefore, use Draw to draw pictures in animation. To create animation, you can place a picture outside the visible portion of the window and then use the Draw function to draw it at different locations in the window. However, the image remains at all the positions where you draw it. If you change the position by small increments, each new drawing of the picture covers up most of the previous image. Using Draw does not change the position of the picture controlit just displays the controls image at the specified location. Use the Move function to actually change the position of the control.
Examples
This statement draws the bitmap p_Train at the location specified by the X and Y coordinates 100 and 200:
p_Train.Draw(100, 200)
These statements draw the bitmap p_ Train in many different locations so it appears to move from left to right across the window:
integer horizontal FOR horizontal = 1 TO 2000 STEP 8 p_Train.Draw(horizontal, 100) NEXT See also
Move
450
PowerBuilder
CHAPTER 10
PowerScript Functions
EditLabel
Put a label in a ListView or TreeView control into edit mode.
To enable editing of a label in a ListView control TreeView control Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
The EditLabels property for the ListView must be set to TRUE to enable editing of labels. When this property is TRUE, calling the EditLabel function sets focus on the item and enables editing. To disable editing when the user has finished editing the label, set the EditLabels property to FALSE in the EndLabelEdit event. If the EditLabels property is set to FALSE, the EditLabel function does not enable editing.
Examples
This example allows the user to edit the label of the first selected item in the ListView control lv_1:
integer li_selected li_selected = lv_1.SelectedIndex() lv_1.EditLabels = TRUE lv_1.EditLabel(li_selected)
See also
FindItem
451
EditLabel
Syntax 2
Description Applies to Syntax
The EditLabels property for the TreeView must be set to TRUE to enable editing of labels. When this property is TRUE, calling the EditLabel function sets focus on the item and enables editing. To disable editing when the user has finished editing the label, set the EditLabels property to FALSE in the EndLabelEdit event. If the EditLabels property is set to FALSE, the EditLabel function does not enable editing.
Examples
This example allows the user to edit the label of the current TreeView item:
long ll_tvi ll_tvi = tv_list.FindItem(CurrentTreeItem!, 0) tv_list.EditLabels = TRUE tv_list.EditLabel(ll_tvi)
See also
FindItem
452
PowerBuilder
CHAPTER 10
PowerScript Functions
Enable
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If menuname is NULL, Enable returns NULL.
Enabling a menu item changes its color to the active color (not the dimmed, or disabled, color). Calling Enable sets the items Enabled property to TRUE.
Equivalent syntax calling Enable.
menuname.Enabled = TRUE
This statement:
menu_appl.m_delete.Enabled = TRUE
is equivalent to:
menu_appl.m_delete.Enable() Examples
This statement enables the m_delete menu selection on the menu m_appl:
m_appl.m_delete.Enable()
See also
Disable
453
EnableCommit
EnableCommit
Description Applies to Syntax
Declares that a components work may be incomplete but its transaction updates are consistent and can be committed. TransactionServer objects
transactionserver.EnableCommit ( ) Argument transactionserver Description Reference to the TransactionServer service instance
The EnableCommit function indicates that the component should not be deactivated after the current method invocation. However, if the component instance is deactivated, the current transaction can be committed. The EnableCommit function corresponds to the continueWork transaction primitive in EAServer. The following example shows the use of EnableCommit in a component method that performs database updates:
// Instance variables: // DataStore ids_datastore // TransactionServer ts Integer li_rc long ll_rv li_rc = this.GetContextService("TransactionServer",ts) IF li_rc <> 1 THEN // handle the error END IF ... ll_rv = ids_datastore.Update() IF ll_rv = 1 THEN ts.EnableCommit() ELSE ts.DisableCommit() END IF
Examples
See also
454
PowerBuilder
CHAPTER 10
PowerScript Functions
EntryList
Description Applies to Syntax
Provides a list of the top-level entries included in a trace tree model. TraceTree objects
instancename.EntryList ( list ) Argument instancename list Description Instance name of the TraceTree object. An unbounded array variable of datatype TraceTreeNode in which EntryList stores a TraceTreeNode object for each top-level entry in the trace tree model. This argument is passed by reference.
Return value
ErrorReturn. Returns the following values: Success!The function succeeded ModelNotExistsError!The function failed because no model exists
Usage
You use the EntryList function to extract a list of the top-level entries or nodes included in a trace tree model. Each top-level entry listed is defined as a TraceTreeNode object and provides the type of activity represented by that node. You must have previously created the trace tree model from a trace file using the BuildModel function.
Examples
This example gets the top-level entries or nodes in a trace tree model and then loops through the list extracting information about each node. The of_dumpnode function takes a TraceTreeNode object and a level as arguments and returns a string containing information about the node:
TraceTree ltct_model TraceTreeNode ltctn_list[], ltctn_node Long ll_index,ll_limit String ls_line ltct_model = CREATE TraceTree ltct_model.BuildModel() ltct_model.EntryList(ltctn_list) ll_limit = UpperBound(ltctn_list) FOR ll_index = 1 TO ll_limit ltctn_node = ltctn_list[ll_index] ls_line += of_dumpnode(ltctn_node,0) NEXT ...
See also
BuildModel
455
ExecRemote
ExecRemote
Asks a DDE server application to execute the specified command.
To send A single command to a DDE server application (a cold link) A command to a DDE server application after you have opened a channel (a warm link) Use Syntax 1 Syntax 2
Syntax 1
Description Syntax
applname topicname
Return value
values are: -1 -2 -3 Link was not started Request denied Could not terminate server
The DDE server application must already be running when you call a DDE function. Use the Run function to start the application if necessary. The ExecRemote function allows you to start a cold link or use a warm link between the PowerBuilder client application and the DDE server application. A cold link is a single DDE command and is not associated with a DDE channel. Each time you call ExecRemote without opening a channel (Syntax 1), Windows polls all running applications to find one that acknowledges the request. The is also true for the related functions GetRemote and SetRemote. A warm link is associated with a DDE channel (see Syntax 2).
456
PowerBuilder
CHAPTER 10
PowerScript Functions
A DDE hot link, which enables automatic updating of data in the PowerBuilder client application, involves other functions. For more information, see the StartHotLink function.
Examples
This statement asks Microsoft Excel to save the active spreadsheet as file REGION.XLS. A channel is not open, so the function arguments specify the application and topic (the name of the spreadsheet):
ExecRemote("[Save()]", "Excel", "REGION.XLS")
See also
Syntax 2
Description Syntax
handle
windowhandle (optional)
Return value
The DDE server application must already be running when you call a DDE function. Use the Run function to start the application if necessary.
457
ExecRemote
The ExecRemote function allows you start a cold link or use warm link between the PowerBuilder client application and the DDE server application. A cold link is a single DDE command and is not associated with a DDE channel (see Syntax 1). A warm link is associated with a DDE channel. You establish a channel for the DDE conversation with OpenChannel before sending commands with this syntax of ExecRemote. A warm link is useful when you need to send several commands to the DDE server application. Because the channel is open, ExecRemote does not need to have Windows poll all running applications again. After you have called ExecRemote or the related functions GetRemote or SetRemote, and finished the work with the DDE server, call CloseChannel to end the DDE conversation. A DDE hot link, which enables automatic updating of data in the PowerBuilder client application, involves other functions. For more information, see the StartHotLink function.
Examples
This excerpt from a script asks the DDE channel to Microsoft Excel to save the active spreadsheet as file REGION.XLS. The OpenChannel function names the server application and the topic, so ExecRemote only needs to specify the channel handle. The script is associated with a button on a window, whose handle is specified as the last argument of OpenChannel:
long handle handle = OpenChannel("Excel", "REGION.XLS", & Handle(Parent)) . . . // Some processing ExecRemote("[Save]", handle) CloseChannel(handle, Handle(Parent))
See also
458
PowerBuilder
CHAPTER 10
PowerScript Functions
Exp
Description Syntax
Return value
Inverse of Exp
These statements convert a natural logarithm (base e) back to a regular number. When executed, Exp sets value to 200:
double value, x = log(200) value = Exp(x) See also
Log LogTen Exp method for DataWindows in the DataWindow Reference or online Help.
459
ExpandAll
ExpandAll
Description Applies to Syntax
To expand all levels in a TreeViewItem, use the ExpandAll function for the RootTreeItem. This example expands all levels of a TreeView control:
long ll_tvi ll_tvi = tv_list.FindItem(RootTreeItem! , 0) tv_list.ExpandAll(ll_tvi)
See also
ExpandItem CollapseItem
460
PowerBuilder
CHAPTER 10
PowerScript Functions
ExpandItem
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. ExpandItem expands only a single item. To expand a specified item including its children, use ExpandAll.
See also
ExpandAll CollapseItem
Fact
Description Syntax
461
FileClose
FileClose
Description Syntax
Closes the file associated with the specified file number. The file number was assigned to the file with the FileOpen function.
FileClose ( file# ) Argument file# Description The integer assigned to the file you want to close. The FileOpen function returns the file number when it opens the file.
Integer. Returns 1 if it succeeds and -1 if an error occurs. If file# is NULL, FileClose returns NULL.
These statements open and then close the file EMPLOYEE.DAT. The variable li_FileNum stores the number assigned to the file when FileOpen opens the file. FileClose uses that number to close the file:
integer li_FileNum li_FileNum = FileOpen("EMPLOYEE.DAT") . . . // Some processing FileClose(li_FileNum)
See also
462
PowerBuilder
CHAPTER 10
PowerScript Functions
FileCopy
Description Syntax
Return value
If you do not specify a fully qualified path for sourcefile or for targetfile, the function works relative to the current directory. If you do not specify the replace argument, the FileCopy function does not replace a file in the target directory that has the same name as the name you specify in the targetfile argument (This is equivalent to setting the replace value to FALSE). The following example copies a file from the current directory to a different directory and saves the return value in a variable. It does not replace a file of the same name if one already exists in the target directory:
integer li_FileNum li_FileNum = FileCopy ("jazz.gif" , & "C:\emusic\jazz.gif", FALSE)
Examples
See also
FileMove GetCurrentDirectory
463
FileDelete
FileDelete
Description Syntax
Boolean. Returns TRUE if it succeeds, FALSE if an error occurs. If filename is NULL, FileDelete returns NULL.
These statements delete the file the user selected in the Open File window:
integer ret, value string docname, named value = GetFileOpenName("Select File," & docname, named, "DOC", & "Doc Files (*.DOC),*.DOC") IF value = 1 THEN ret = MessageBox("Delete", & "Delete file?", Question!, OKCancel!) IF ret = 1 THEN FileDelete(docname)
See also
FileExists
464
PowerBuilder
CHAPTER 10
PowerScript Functions
FileExists
Description Syntax
Boolean. Returns TRUE if the file exists, FALSE if it does not exist. If filename is NULL, FileExists returns NULL.
If filename is locked by another application, causing a sharing violation, FileExists also returns FALSE. This example determines if the file the user selected in the Save File window exists and, if so, asks the user if the file can be overwritten:
string ls_docname, ls_named integer li_ret boolean lb_exist GetFileSaveName("Select File," ls_docname, & ls_named, "pbl", & "Doc Files (*.DOC),*.DOC") lb_exist = FileExists(ls_docname) IF lb_exist THEN li_ret = MessageBox("Save", & "OK to write over" + ls_docname, & Question!, YesNo!)
See also
FileDelete
465
FileLength
FileLength
Description Syntax
Return value
Long. Returns the length in bytes of the file identified by filename. If the file does not exist, FileLength returns -1. If filename is NULL, FileLength returns NULL.
Usage
Call FileLength before or after you call FileOpen to check the length of a file before you call FileRead. The FileRead function can read a maximum of 32,765 characters at a time.
File security
If any security is set for the file (for example, if you are sharing the file on a network), you must call FileLength before FileOpen or after FileClose. Otherwise, you get a sharing violation.
Examples
This statement returns the length of the file EMPLOYEE.DAT in the current directory:
FileLength("EMPLOYEE.DAT")
These statements determine the length of the EMP.TXT file in the EAST directory and open the file:
long LengthA integer li_FileNum LengthA = FileLength("C:\EAST\EMP.TXT") li_FileNum = FileOpen("C:\EAST\EMP.TXT", & StreamMode!, Read!, LockReadWrite!)
466
PowerBuilder
CHAPTER 10
PowerScript Functions
FileMove
Description Syntax
Moves a file.
FileMove ( sourcefile, targetfile ) Argument sourcefile targetfile Description String for the name of the file you want to move String for the name of the location you are moving the file
Return value
You cannot write to a target file if a file with the same name already exists in the target directory. If you want to copy over a target file, you can use FileCopy and set the replace argument to TRUE. This example moves a file from the current directory to a different directory and saves the return value in the li_FileNum variable:
integer li_FileNum li_FileNum = FileMove ("june.csv", & "H:/project/june2000.csv" )
Examples
See also
FileCopy GetCurrentDirectory
467
FileOpen
FileOpen
Description
Opens the specified file for reading or writing and assigns it a unique integer file number. You use this integer to identify the file when you read, write, or close the file. The optional arguments filemode, fileaccess, filelock, and writemode determine the mode in which the file is opened.
FileOpen ( filename {, filemode {, fileaccess {, filelock {, writemode { creator, filetype }}}}} ) Argument filename Description A string whose value is the name of the file you want to open. If filename is not on the current directorys relative search path, you must enter the fully qualified name. A value of the FileMode enumerated type that specifies how the end of a FileRead or FileWrite is determined. Values are: LineMode! (Default) Read or write the file a line at a time StreamMode! Read the file in 32K chunks For more information, see Usage below. fileaccess (optional) A value of the FileAccess enumerated type that specifies whether the file is opened for reading or writing. Values are: Read! (Default) Read-only access Write! Write-only access If PowerBuilder does not find the file, a new file is created if the fileaccess argument is set to Write! filelock (optional) A value of the FileLock enumerated type specifying whether others have access to the opened file. Values are: LockReadWrite! (Default) Only the user who opened the file has access LockRead! Only the user who opened the file can read it, but everyone has write access LockWrite! Only the user who opened the file can write to it, but everyone has read access Shared! All users have read and write access. writemode (optional) A value of the WriteMode enumerated datatype. When fileaccess is Write!, specifies whether existing data in the file is overwritten. Values are: Append! (Default) Write data to the end of the file Replace! Replace all existing data in the file Writemode is ignored if the fileaccess argument is Read!
Syntax
filemode (optional)
468
PowerBuilder
CHAPTER 10
PowerScript Functions
Integer. Returns the file number assigned to filename if it succeeds and -1 if an error occurs. If any arguments value is NULL, FileOpen returns NULL.
When a file has been opened in line mode, each call to the FileRead function reads until it encounters a carriage return (CR), linefeed (LF), or end-of-file mark (EOF). Each call to FileWrite adds a CR and LF at the end of each string it writes. When a file has been opened in stream mode, a call to FileRead reads the whole file (until it encounters an EOF) or 32,765 bytes, whichever is less. FileWrite writes a maximum of 32,765 bytes in a single call and does not add CR and LF characters.
File not found
If PowerBuilder does not find the file, it creates a new file, giving it the specified name, if the fileaccess argument is set to Write!.
Examples
This example uses the default arguments and opens the file EMPLOYEE.DAT for reading. The default settings are LineMode!, Read!, and LockReadWrite!. FileRead reads the file line by line and no other user is able to access the file until it is closed:
integer li_FileNum li_FileNum = FileOpen("EMPLOYEE.DAT")
This example opens the file EMPLOYEE.DAT in the DEPT directory in stream mode (StreamMode!) for write only access (Write!). Existing data is overwritten (Replace!). No other users can write to the file (LockWrite!):
integer li_FileNum li_FileNum = FileOpen("C:\DEPT\EMPLOYEE.DAT", & StreamMode!, Write!, LockWrite!, Replace!) See also
469
FileRead
FileRead
Description Syntax
Reads data from the file associated with the specified file number, which was assigned to the file with the FileOpen function.
FileRead ( file#, variable ) Argument file# variable Description The integer assigned to the file when it was opened The name of the string or blob variable into which you want to read the data
Return value
Integer. Returns the number of characters or bytes read. If an end-of-file mark (EOF) is encountered before any characters are read, FileRead returns -100. If
the file is opened in LineMode and a CR or LF is encountered before any characters are read, FileRead returns 0. If an error occurs, FileRead returns -1. If any arguments value is NULL, FileRead returns NULL.
Usage
If the file is opened in Line mode, FileRead reads a line of the file (that is, until it encounters a CR, LF, or EOF). It stores the contents of the line in the specified variable, skips the line-end characters, and positions the file pointer at the beginning of the next line. If the file was opened in Stream mode, FileRead reads to the end of the file or the next 32,765 bytes, whichever is shorter. FileRead begins reading at the file pointer, which is positioned at the beginning of the file when the file is opened for reading. If the file is longer than 32,765 bytes, FileRead automatically positions the pointer after each read operation so that it is ready to read the next chunk of data.
FileRead can read a maximum of 32,765 characters at a time. Therefore, before calling the FileRead function, call the FileLength function to check the file length. If your system has file sharing or security restrictions, you may need to call FileLength before you call FileOpen.
An end-of-file mark is a NULL character (ASCII value 0). Therefore, if the file being read contains null characters, FileRead stops reading at the first null character, interpreting it as the end of the file.
Examples
This example reads the file EMP_DATA.TXT if it is short enough to be read with one call to FileRead:
integer li_FileNum string ls_Emp_Input long ll_FLength ll_FLength = FileLength("C:\HR\EMP_DATA.TXT")
470
PowerBuilder
CHAPTER 10
PowerScript Functions
li_FileNum = FileOpen("C:\HR\EMP_DATA.TXT", & StreamMode!) IF ll_FLength < 32767 THEN FileRead(li_FileNum, ls_Emp_Input) END IF
This example reads the file EMP_PIC1.BMP and stores the data in the blob Emp_Id_Pic. The number of bytes read is stored in li_bytes:
integer li_fnum, li_bytes blob Emp_Id_Pic li_fnum = FileOpen("C:\HR\EMP_PIC1.BMP", & StreamMode!) li_bytes = FileRead(li_fnum, Emp_Id_Pic)
This example reads a file exceeding 32,765 bytes. After the script has read the file into the blob tot_b, you can call the SetPicture or String function to make use of the data, depending on the contents of the file:
integer li_FileNum, loops, i long flen, bytes_read, new_pos blob b, tot_b // Set a wait cursor SetPointer(HourGlass!) // Get the file length, and open the file flen = FileLength(sle_filename.Text) li_FileNum = FileOpen(sle_filename.Text, & StreamMode!, Read!, LockRead!) // Determine how many times to call FileRead IF flen > 32765 THEN IF Mod(flen, 32765) = 0 THEN loops = flen/32765 ELSE loops = (flen/32765) + 1 END IF ELSE loops = 1 END IF // Read the file new_pos = 1
471
FileRead
FOR i = 1 to loops bytes_read = FileRead(li_FileNum, b) tot_b = tot_b + b NEXT FileClose(li_FileNum) See also
472
PowerBuilder
CHAPTER 10
PowerScript Functions
FileSeek
Description Syntax
Moves the file pointer to the specified position in a file. The file pointer is the position in the file at which the next read or write begins.
FileSeek ( file#, position, origin ) Argument file# position origin Description The integer assigned to the file when it was opened. A long whose value is the new position of the file pointer relative to the position specified in origin, in bytes. The value of the SeekType enumerated datatype specifying where you want to start the seek. Values are: FromBeginning! (Default) At the beginning of the file FromCurrent! At the current position FromEnd! At the end of the file
Long. Returns the file position after the seek operation has been performed. If any arguments value is NULL, FileSeek returns NULL.
Use FileSeek to move within a binary file that you have opened in stream mode. FileSeek positions the file pointer so that the next FileRead or FileWrite occurs at that position within the file. This example positions the file pointer 14 bytes from the end of the file:
integer li_FileNum li_FileNum = FileOpen("emp_data") FileSeek(li_FileNum, -14, FromEnd!)
Examples
This example moves the file pointer from its current position 14 bytes toward the end of the file. In this case, if no processing has occurred after FileOpen to affect the file pointer, specifying FromCurrent! is the same as specifying FromBeginning!:
integer li_FileNum li_FileNum = FileOpen("emp_data") FileSeek(li_FileNum, 14, FromCurrent!) See also
FileRead FileWrite
473
FileWrite
FileWrite
Description Syntax
Writes data to the file associated with the specified file number. The file number was assigned to the file with the FileOpen function.
FileWrite ( file#, variable ) Argument file# variable Description The integer assigned to the file when the file was opened A string or blob whose value is the data you want to write to the file
Return value
Integer. Returns the number of characters or bytes written if it succeeds and it returns -1 if an error occurs. If any arguments value is NULL, FileWrite returns NULL. FileWrite writes its data at the position identified by the file pointer. If the file was opened with the writemode argument set to Replace!, the file pointer is initially at the beginning of the file. After each call to FileWrite, the pointer is immediately after the last write. If the file was opened with the writemode argument set to Append!, the file pointer is initially at the end of the file and moves to the end of the file after each write. FileWrite sets the file pointer following the last character written. If the file was opened in line mode, FileWrite writes a carriage return (CR) and linefeed (LF) after the last character in variable and places the file pointer after the CR and LF.
Usage
Length limit FileWrite can write only 32,766 bytes at a time, which includes the string terminator character. If the length of variable exceeds 32,765, FileWrite writes
This script excerpt opens EMP_DATA.TXT and writes the string New Employees at the end of the file. The variable li_FileNum stores the number of the opened file:
integer li_FileNum li_FileNum = FileOpen("C:\HR\EMP_DATA.TXT", & LineMode!, Write!, LockWrite!, Append!) FileWrite(li_FileNum, "New Employees")
474
PowerBuilder
CHAPTER 10
PowerScript Functions
The following example reads a blob from the database and writes it to a file. The SQL SELECT statement assigns the picture data to the blob Emp_Id_Pic. Then FileOpen opens a file for writing in stream mode and FileWrite writes the blob to the file. You could use the Len function to test whether the blob was too big for a single FileWrite call:
integer li_FileNum blob emp_id_pic SELECTBLOB salary_hist INTO : emp_id_pic FROM Employee WHERE Employee.Emp_Num = 100 USING Emp_tran; li_FileNum = FileOpen( & "C:\EMPLOYEE\EMP_PICS.BMP", & StreamMode!, Write!, Shared!, Replace!) FileWrite(li_FileNum, emp_id_pic) See also
475
Fill
Fill
Description
Builds a string of the specified length by repeating the specified characters until the result string is long enough.
FillW
String. Returns a string n characters long filled with the characters in the argument chars. If the argument chars has more than n characters, the first n characters of chars are used to fill the return string. If the argument chars has fewer than n characters, the characters in chars are repeated until the return string has n characters. If any arguments value is NULL, Fill or FillW return NULL.
Usage
Use Fill in printing routines to create a line or other special effect. For example, you can fill the amount line of a check with asterisks, or simulate a total line in a screen display by repeating hyphens below a column of figures. Characters in DBCS environments can be single byte, double byte, or mixed. In these environments, you must use the FillW syntax to fill the return string with double-byte or mixed single-byte and double-byte characters. Although you can use the Fill syntax in DBCS environments, the string returned by this syntax is based exclusively on single-byte computation.
Examples
Space Fill method for DataWindows in the DataWindow Reference or online Help
476
PowerBuilder
CHAPTER 10
PowerScript Functions
FillW
Description Syntax
Builds a string of the specified length by repeating the specified characters until the result string is long enough. For more information, see Fill.
FillW ( chars, n)
Find
Description
Finds data in a DataWindow control or DataStore, or text in a RichTextEdit control or RichTextEdit DataWindow or DataStore. You can specify search direction and whether to match whole words and case. Finds the specified text in the control and highlights the text if found. For syntax for DataWindows and DataStores, see the Find method for DataWindows in the DataWindow Reference or online Help.
Applies to Syntax
RichTextEdit controls and DataWindow controls (or DataStore objects) whose content has the RichTextEdit presentation style
controlname.Find ( searchtext, forward, insensitive, wholeword, cursor ) Argument controlname searchtext forward Description The name of the RichTextEdit, DataWindow control, or DataStore whose contents you want to search. A string whose value is the text you want to find. A boolean value indicating the direction you want to search. Values are: TRUE The search proceeds forward from the cursor position or, if cursor is false, from the start of the document. FALSE The search proceeds backward from the cursor position or, if cursor is false, from the end of the document. insensitive A boolean value indicating the search string and the found text must match case. Values are: TRUE The search is not sensitive to case. wholeword FALSE The search is case-sensitive. A boolean value indicating that the found text must be a whole word. Values are: TRUE The found text must be a whole word. FALSE The found text can be a partial word.
477
Find
Argument cursor
Description A boolean value indicating where the search begins. Values are: TRUE The search begins at the cursor position. FALSE The search begins at the start of the document if forward is TRUE or at the end if forward is FALSE.
Return value
text is found, and returns -1 if the DataWindows presentation style is not RichTextEdit or an error occurs.
Examples
This example searches the RichTextEdit rte_1 for text the user specifies in the SingleLineEdit sle_search. The search proceeds forward from the cursor position. The search is case insensitive and not limited to whole words:
integer li_charsfound li_charsfound = rte_1.Find(sle_search.Text, & TRUE, TRUE, FALSE, TRUE)
See also
FindNext
478
PowerBuilder
CHAPTER 10
PowerScript Functions
FindCategory
Description Applies to Syntax
Obtains the number of a category in a graph when you know the categorys label. Graph controls in windows and user objects, and graphs in DataWindow controls
controlname.FindCategory ( { graphcontrol, } categoryvalue ) Argument controlname Description A string whose value is the name of the graph in which you want to find a specific category, or the name of the DataWindow control containing the graph. (Optional) A string whose value is the name of the graph in the DataWindow control in which you want to find a specific category. A value that is the category for which you want the number. The value you specify must be the same datatype as the datatype of the category axis.
Return value
Integer. Returns the number of the category named in categoryvalue in the graph controlname, or if controlname is a DataWindow control, in graphcontrol. If an error occurs, FindCategory returns -1. If any arguments value is NULL, FindCategory returns NULL.
Usage
Most of the category manipulation functions require a category number, rather than a name. However, when you delete and insert categories, existing categories are renumbered to keep the numbering consecutive. Use FindCategory when you know only a categorys label or when the numbering may have changed. These statements obtain the number of a category in the graph gr_prod_data. The category name is the text in the SingleLineEdit sle_ctory:
integer CtgryNbr CtgryNbr =gr_prod_data.FindCategory(sle_ctgry.Text)
Examples
These statements obtain the number of the category named Qty in the graph gr_computers in the DataWindow control dw_equip:
integer CtgryNbr CtgryNbr = dw_equip.FindCategory("gr_computers", "Qty") See also
479
FindClassDefinition
FindClassDefinition
Description Syntax
Searches for an object in one or more PowerBuilder libraries (PBLs) and provides information about its class definition.
FindClassDefinition ( classname {, librarylist } ) Argument classname librarylist (optional) Description The name of an object (also called a class or class definition) for which you want information. An array of strings whose values are the fully qualified pathnames of PBLs. If you omit librarylist, FindClassDefinition searches the library list associated with the running application.
Return value
ClassDefinition. Returns an object reference with information about the definition of classname. If any arguments are NULL, FindClassDefinition returns NULL. There are two ways to get a ClassDefinition object containing class definition information: For an instantiated object in your application, use its ClassDefinition property For an object stored in a PBL, call FindClassDefinition
Usage
Examples
This example searches the libraries for the running application to find the class definition for w_genapp_frame:
ClassDefinition cd_windef cd_windef = FindClassDefinition("w_genapp_frame")
This example searches the libraries in the array ls_libraries to find the class definition for w_genapp_frame:
ClassDefinition cd_windef string ls_libraries[ ] ls_libraries[1] = "c:\pwrs\bizapp\windows.pbl" ls_libraries[2] = "c:\pwrs\framewk\windows.pbl" ls_libraries[3] = "c:\pwrs\framewk\ancestor.pbl" cd_windef = FindClassDefinition( "w_genapp_frame", ls_libraries) See also
480
PowerBuilder
CHAPTER 10
PowerScript Functions
FindFunctionDefinition
Description Syntax
Searches for a global function in one or more PowerBuilder libraries (PBLs) and provides information about the script definition.
FindFunctionDefinition ( functionname {, librarylist } ) Argument functionname librarylist (optional) Description The name of a global function for which you want information. An array of strings whose values are the fully qualified pathnames of PBLs. If you omit librarylist, FindFunctionDefinition searches the library list associated with the running application.
Return value
ScriptDefinition. Returns an object reference with information about the script of functionname. If any arguments are NULL, FindFunctionDefinition returns NULL. You can call FindClassDefinition to get a class definition for a global function. However, the ScriptDefinition object provides information tailored for functions. This example searches the libraries for the running application to find the function definition for f_myfunction:
ScriptDefinition sd_myfunc sd_myfunc = FindFunctionDefinition("f_myfunction")
Usage
Examples
This example searches the libraries in the array ls_libraries to find the class definition for w_genapp_frame:
ScriptDefinition sd_myfunc string ls_libraries[ ] ls_libraries[1] = "c:\pwrs\bizapp\windows.pbl" ls_libraries[2] = "c:\pwrs\framewk\windows.pbl" ls_libraries[3] = "c:\pwrs\framewk\ancestor.pbl" sd_myfunc = FindFunctionDefinition( & "f_myfunction", ls_libraries) See also
481
FindItem
FindItem
Finds the next item in a list.
To find the next item In a ListBox, DropDownListBox, PictureListBox, or DropDownPictureListBox In a ListView control based upon its label By relative position in a ListView control By relative position in a TreeView control Use Syntax 1 Syntax 2 Syntax 3 Syntax 4
Syntax 1
Description Applies to Syntax
Return value
Integer. Returns the index of the first matching item. To match, the item must
start with the specified text; however, the text in the item can be longer than the specified text. If no match is found or if an error occurs, FindItem returns -1. If any arguments value is NULL, FindItem returns NULL.
Usage
When FindItem finds the matching item, it returns the index of the item but does not select (highlight) the item. To find and select the item, use the SelectItem function. Assume the ListBox lb_actions contains the following list:
Index number 1 2 3 4 Item text Open files Close files Copy files Delete files
Examples
482
PowerBuilder
CHAPTER 10
PowerScript Functions
Then these statements start searching for Delete starting with item 2 (Close files). FindItem sets Index to 4:
integer Index Index = lb_actions.FindItem("Delete", 1) See also
Syntax 2
Description Applies to Syntax
Integer. Returns the index of the item found if it succeeds and -1 if an error occurs.
The search starts from startindex + 1 by default. To search from the beginning, specify 0. If partial is set to TRUE, the search string matches any label that begins with the specified text. If partial is set to FALSE, the search string must match the entire label. If wrap is set to TRUE, the search wraps around to the first index item after searching to the end. If wrap is set to FALSE, the search stops at the last index item in the ListView.
FindItem does not select the item it finds. You must use the items selected property in conjunction with FindItem to select the resulting match.
483
FindItem
Examples
This example takes the value from a SingleLineEdit control and passes it to FindItem:
listviewitem l_lvi integer li_index string ls_label ls_label = sle_find.Text IF ls_label = "" THEN MessageBox("Error" , & "Enter the name of a list item") sle_find.SetFocus() ELSE li_index = lv_list.FindItem(0,ls_label, TRUE,TRUE) END IF IF li_index = -1 THEN MessageBox("Error", "Item not found.") ELSE lv_list.GetItem (li_index, l_lvi ) l_lvi.HasFocus = TRUE l_lvi.Selected = TRUE lv_list.SetItem(li_index,l_lvi) END IF
See also
Syntax 3
Description Applies to Syntax
484
PowerBuilder
CHAPTER 10
PowerScript Functions
Argument direction
Description The direction in which to search. Values are: DirectionAll! DirectionUp! DirectionDown! DirectionLeft! DirectionRight! If set to TRUE, the search looks for the next ListView item that has focus. If set to TRUE, the search looks for the next ListView item that is selected. If set to TRUE, the search looks for the next ListView item that is the target of a cut operation. If set to TRUE, the search looks for next ListView item that is the target of a drag and drop operation.
Integer. Returns the index of the item found if it succeeds and -1 if an error occurs.
The search starts from startindex + 1 by default. If you want to search from the beginning, specify 0.
FindItem does not select the item it finds. You must use the items selected property in conjunction with FindItem to select the resulting match.
If focused, selected, cuthighlighted, and drophighlighted are set to FALSE, the search finds the next item in the ListView control.
Examples
This example uses FindItem to search from the selected ListView item:
listviewitem l_lvi integer li_index li_startindex li_startindex = lv_list.SelectedIndex() li_index = lv_list.FindItem(li_startindex, & DirectionDown!, FALSE, FALSE ,FALSE, FALSE) IF li_index = -1 THEN MessageBox("Error", "Item not found.") ELSE lv_list.GetItem (li_index, l_lvi) l_lvi.HasFocus = TRUE l_lvi.Selected = TRUE lv_list.SetItem(li_index,l_lvi) END IF
485
FindItem
See also
Syntax 4
Description Applies to Syntax
itemhandle
Long. Returns the item handle if it succeeds and -1 if an error occurs. FindItem does not select the item it finds. You must use the items selected property in conjunction with FindItem to select the result of the FindItem search. FindItem never finds a collapsed item, except when looking for ChildTreeItem!, which causes an item to expand. CurrentItem! is not changed until after the clicked event occurs. To return the correct handle for the current item when the user clicks it, create a custom event to return the handle and post it in the clicked event.
If navigationcode is RootTreeItem!, FirstVisibleTreeItem!, CurrentTreeItem!, or DropHighlightTreeItem!, set itemhandle to 0. The following table shows valid values for the navigationcode argument.
Table 10-1: Valid values for the navigationcode argument of FindItem Navigationcode value RootTreeItem! NextTreeItem! What FindItem finds The first item at level 1. Returns -1 if no items have been inserted into the control. The sibling after itemhandle. A sibling is an item at the same level with the same parent. Returns -1 if there are no more siblings.
486
PowerBuilder
CHAPTER 10
PowerScript Functions
What FindItem finds The sibling before itemhandle. Returns -1 if there are no more siblings. The parent of itemhandle. Returns -1 if the item is at level 1. The first child of itemhandle. If the item is collapsed, ChildtreeItem! causes the node to expand. Returns -1 if the item has no children or if the item is not populated yet. The first item visible in the control, regardless of level. The position of the scrollbar determines the first visible item. The next expanded item after itemhandle, regardless of level. NextVisible and PreviousVisible allows you to walk through all the children and branches of an expanded node. When the next item is beyond the visible area of the control, NextVisible causes the control to scroll to reach the next item. Returns -1 if the item is the last expanded item in the control. The next expanded item before itemhandle, regardless of level. When the next item is beyond the visible area of the control, PreviousVisible causes the control to scroll to reach the next item. Returns -1 if the item is the first root item. The selected item. Returns -1 if the control never had focus and nothing has been selected. The item whose DropHighlighted property was most recently set. Returns -1 if the property was never set or if it has been set back to FALSE because of other activity in the control.
FirstVisibleTreeItem!
NextVisibleTreeItem!
PreviousVisibleTreeItem!
CurrentTreeItem! DropHighlightTreeItem!
Examples
To return the correct handle when the current item is clicked, place this code in a custom event that is posted in the items clicked event:
long ll_tvi ll_tvi = tv_list.FindItem(CurrentTreeItem!, 0)
This example finds the first item on the first level of a TreeView control:
long ll_tvi ll_tvi = tv_list.FindItem(RootTreeItem!, 0) See also
FindMatchingFunction
FindMatchingFunction
Description Applies to Syntax
Finds out what function in a class matches a specified signature. The signature is a combination of a script name and an argument list. ClassDefinition objects
classdefobject.FindMatchingFunction ( scriptname, argumentlist ) Argument classdefobject scriptname argumentlist Description The name of the ClassDefinition object describing the class in which you want to find a function. A string whose value is the name of the function. An unbounded array of strings whose values are the datatypes of the function arguments. If the variable is passed by reference, the string must include "ref" before the datatype. If the variable is an array, you must include array brackets after the datatype. The format is:
{ ref } datatype { [] }
For a bounded array, the argument must include the range, as in:
ref integer[1 TO 10]
Return value
ScriptDefinition. Returns an object instance with information about the matching function. If no matching function is found, FindMatchingFunction returns NULL. If any argument is NULL, it also returns NULL. In searching for the function, PowerBuilder examines the collapsed inheritance hierarchy. The found function may be defined in the current object or in any of its ancestors. Arguments passed by reference To find a function with an argument that is passed by reference, you must specify the REF keyword. If you have a VariableDefinition object for a function argument, check the CallingConvention argument to determine if the argument is passed by reference. In documentation for PowerBuilder functions, arguments passed by reference are described as a variable, rather than simply a value. The PowerBuilder Browser does not report which arguments are passed by reference.
Usage
Examples
This example gets the ScriptDefinition object that matches the PowerBuilder window object function OpenUserObjectWithParm and looks for the version with four arguments. If it finds a match, the example calls the function uf_scriptinfo, which creates a report about the script:
488
PowerBuilder
CHAPTER 10
PowerScript Functions
string ls_args[] ScriptDefinition sd ls_args[1] ls_args[2] ls_args[3] ls_args[4] = = = = "ref dragobject" "double" "integer" "integer"
sd = c_obj.FindMatchingFunction( & "OpenUserObjectWithParm", ls_args) IF NOT IsValid(sd) THEN mle_1.Text = "No matching script" ELSE mle_1.Text = uf_scriptinfo(sd) END IF
The uf_scriptinfo function gets information about the function that matched the signature and builds a string. Scriptobj is the ScriptDefinition object passed to the function:
string s, lineend integer li lineend = "~r~n" // Script name s = s + scriptobj.Name + lineend // datatype of the return value s = s + scriptobj.ReturnType.DataTypeOf + lineend // List argument names s = s + "Arguments:" + lineend FOR li = 1 to UpperBound(scriptobj.ArgumentList) s = s + scriptobj.ArgumentList[li].Name + lineend NEXT // List local variables s = s + "Local variables:" + lineend FOR li = 1 to UpperBound(scriptobj.LocalVariableList) s = s + scriptobj.LocalVariableList[li].Name & + lineend NEXT RETURN s See also
489
FindNext
FindNext
Description Applies to Syntax
Finds the next occurrence of text in the control and highlights it, using criteria set up in a previous call of the Find function. RichTextEdit controls and DataWindow controls whose content has the RichTextEdit presentation style
controlname.FindNext ( ) Argument controlname Description The name of the RichTextEdit or DataWindow control whose contents you want to search
Return value
Integer. Returns the number of characters found. FindNext returns 0 if no matching text is found and -1 if the DataWindows presentation style is not RichTextEdit or an error occurs.
Examples
This example searches the RichTextEdit rte_1 for text the user specifies in the SingleLineEdit sle_search. The search proceeds forward from the cursor position, is case insensitive, and is not limited to whole words:
integer li_charsfound li_charsfound = rte_1.Find(sle_search.Text, & TRUE, TRUE, FALSE, TRUE)
Find
490
PowerBuilder
CHAPTER 10
PowerScript Functions
FindSeries
Description Applies to Syntax
Obtains the number of a series in a graph when you know the series name. Graph controls in windows and user objects, and graphs in DataWindow controls
controlname.FindSeries ( { graphcontrol, } seriesname ) Argument controlname Description The name of the graph containing the series for which you want the number, or the name of the DataWindow control containing the graph (Optional) A string whose value is the name of the graph in the DataWindow control containing the series A string whose value is the name of the series for which you want the number
Return value
Integer. Returns the number of the series named in seriesname in the graph controlname, or if controlname is a DataWindow control, in graphcontrol. If an error occurs, FindSeries returns -1. If any arguments value is NULL, FindSeries returns NULL.
Usage
Most of the series manipulation functions require a series number, rather than a name. However, when you delete and insert series, existing series are renumbered so that the series are numbered consecutively. Use FindSeries when you know only a series name or when the numbering may have changed. These statements store the number of the series in the graph gr_product_data that was entered in the SingleLineEdit sle_series in SeriesNbr:
integer SeriesNbr SeriesNbr = & gr_product_data.FindSeries(sle_series.Text)
Examples
These statements obtain the number of the series named PCs in the graph gr_computers in the DataWindow control dw_equipment and store it in SeriesNbr:
integer SeriesNbr SeriesNbr = & dw_equipment.FindSeries("gr_computers", "PCs") See also
491
FindTypeDefinition
FindTypeDefinition
Description
Searches for a type in one or more PowerBuilder libraries (PBLs) and provides information about its type definition. You can also get type definitions for system types.
FindTypeDefinition ( typename {, librarylist } ) Argument typename Description The name of a simple datatype, enumerated datatype, or class for which you want information. To find a type definition for a nested type, use this form:
libraryEntryName typename
Syntax
librarylist (optional)
An array of strings whose values are the fully qualified pathnames of PBLs. If you omit librarylist, FindTypeDefinition searches the library list associated with the running application. PowerBuilder also searches its own libraries for built-in definitions, such as enumerated datatypes and system classes.
Return value
TypeDefinition. Returns an object reference with information about the definition of typename. If any arguments are NULL, FindTypeDefinition returns NULL. The returned TypeDefinition object is a ClassDefinition, SimpleTypeDefinition, or EnumerationDefinition object. You can test the Category property to find out which one it is. If you want to get information for a class, call FindClassDefinition instead. The arguments are the same and you are saved the step of checking that the returned object is a ClassDefinition object. If you want to get information for a global function, call FindFunctionDefinition.
Usage
Examples
This example gets a TypeDefinition object for the grGraphType enumerated datatype. It checks the category of the type definition and, since it is an enumeration, assigns it to an EnumerationDefinition object type and saves the name in a string:
TypeDefinition td_graphtype EnumerationDefinition ed_graphtype string enumname
492
PowerBuilder
CHAPTER 10
PowerScript Functions
td_graphtype = FindTypeDefinition("grgraphtype") IF td_graphtype.Category = EnumeratedType! THEN ed_graphtype = td_graphtype enumname = ed_graphtype.Enumeration[1].Name END IF
This example is a function that takes a definition name as an argument. The argument is typename. It finds the named TypeDefinition object, checks its category, and assigns it to the appropriate definition object:
TypeDefinition td_def SimpleTypeDefinition std_def EnumerationDefinition ed_def ClassDefinition cd_def td_def = FindTypeDefinition(typename) CHOOSE CASE td_def.Category CASE SimpleType! std_def = td_def CASE EnumeratedType! ed_def = td_def CASE ClassOrStructureType! cd_def = td_def END CHOOSE
This example searches the libraries in the array ls_libraries to find the class definition for w_genapp_frame:
TypeDefinition td_windef string ls_libraries[ ] ls_libraries[1] = "c:\pwrs\bizapp\windows.pbl" ls_libraries[2] = "c:\pwrs\framewk\windows.pbl" ls_libraries[3] = "c:\pwrs\framewk\ancestor.pbl" td_windef = FindTypeDefinition( "w_genapp_frame", ls_libraries) See also
493
FromAnsi
FromAnsi
Description Syntax
Converts a blob containing an ANSI character string to a string in the file format of the current version of PowerBuilder.
FromAnsi ( blob ) Argument blob Description A blob containing an ANSI character string you want to convert to a string in the file format of the current version of PowerBuilder
String. Returns a character string if it succeeds and an empty string if it fails. FromAnsi function converts an ANSI blob to a character string. In PowerBuilder, FromAnsi has the same result as String(blob).
Unicode files have two extra bytes at the start of the file to indicate that they are Unicode files.
Examples
This example reads a blob containing an ANSI character string from a file called ansi.txt and converts it into a string:
integer li_filenum blob lb_text string ls_native, ls_dbg li_filenum = FileOpen("ansi.txt", StreamMode!) FileRead(li_filenum, lb_text) ls_dbg = string(lb_text) ls_native = FromAnsi(lb_text) FileClose(li_filenum)
See also
494
PowerBuilder
CHAPTER 10
PowerScript Functions
FromUnicode
Description Syntax
Converts a blob containing a Unicode character string to a string in the file format of the current version of PowerBuilder.
FromUnicode ( blob ) Argument blob Description A blob containing a Unicode character string you want to convert to a string in the file format of the current version of PowerBuilder
The FromUnicode function converts a Unicode character string contained in a blob to an ANSI character string.
Unicode file format
Unicode files have two extra bytes at the start of the file to indicate that they are Unicode files. If you are opening a Unicode file in stream mode, skip the first two bytes.
Examples
This example converts a Unicode blob that contains the definition of a PowerBuilder window into an ANSI string so that it can be imported into PowerBuilder.
integer li_fileone, li_filetwo blob lb_text string ls_native li_fileone = FileOpen("D:\tst\w_one.srw", StreamMode!) // Move the file pointer so that Unicode // identifying characters arent copied FileSeek(li_Fileone, 2) // Read the data in the file into a blob FileRead(li_fileone, lb_text) FileClose(li_fileone) // Convert the Unicode blob to a string ls_native = FromUnicode(lb_text) // Open a second file to copy the string to li_filetwo = FileOpen("w_one.srw", & StreamMode!, Write!)
495
FromUnicode
496
PowerBuilder
CHAPTER 10
PowerScript Functions
GarbageCollect
Description Syntax Return value Usage
None Forces garbage collection to occur immediately. PowerBuilder makes a pass to identify unused objects, including those with circular references, then deletes unused objects and classes. This statement initiates garbage collection:
GarbageCollect()
Examples
See also
GarbageCollectGetTimeLimit GarbageCollectSetTimeLimit
GarbageCollectGetTimeLimit
Description Syntax Return value Usage Examples
Reads the current minimum period between garbage collection passes. This statement returns the interval between garbage collection passes in the variable CollectTime:
long CollectTime CollectTime = GarbageCollectGetTimeLimit()
See also
GarbageCollect GarbageCollectSetTimeLimit
497
GarbageCollectSetTimeLimit
GarbageCollectSetTimeLimit
Description Syntax
Long. Returns the interval that existed before this function was called. If newTime is NULL, then NULL is returned and the current interval is not changed.
Specifies the minimum interval between garbage collection passes: garbage collection passes will not happen before this interval has expired. Garbage collection can effectively be disabled by setting the minimum limit to a very large number. If garbage collection is disabled, unused classes will not be flushed out of the class cache.
Examples
This example sets the interval between garbage collection passes to 1 second and sets the variable OldTime to the length of the previous interval:
long OldTime, NewTime NewTime = 1000 /* 1 second */ OldTime = GarbageCollectSetTimeLimit(NewTime)
See also
GarbageCollect GarbageCollectGetTimeLimit
498
PowerBuilder
CHAPTER 10
PowerScript Functions
GetActiveSheet
Description Applies to Syntax
Returns the currently active sheet in an MDI frame window. MDI frame windows
mdiframewindow.GetActiveSheet ( ) Argument mdiframewindow Description The MDI frame window for which you want the active sheet
Return value
Window. Returns the sheet that is currently active in mdiframewindow. If no sheet is active, GetActiveSheet returns an invalid value. If mdiframewindow is NULL, GetActiveSheet returns NULL. Use the IsValid function to determine whether GetActiveSheet has returned a valid window value. These statements determine the active sheet in the MDI frame window w_frame and change the text of the menu selection m_close on the menu m_file on the menu bar m_main. If no sheet is active, the text is Close Window:
// Declare variable for active sheet window activesheet string mtext activesheet = w_frame.GetActiveSheet() IF IsValid(activesheet) THEN // There is an active sheet, so get its title; // change the text of the menu to read // Close plus the title of the active sheet mtext = "Close " + activesheet.Title m_main.m_file.m_close.Text = mtext ELSE // No sheet is active, menu says Close Window m_main.m_file.m_close.Text = "Close Window" END IF
Usage Examples
See also
IsValid
499
GetAlignment
GetAlignment
Description Applies to Syntax
Obtains the alignment of the paragraph containing the insertion point in a RichTextEdit control. RichTextEdit controls
rtename.GetAlignment ( ) Argument rtename Description The name of the RichTextEdit control in which you want to find out the alignment of the paragraph containing the insertion point
Alignment. A value of the Alignment enumerated datatype indicating the alignment of the paragraph containing the insertion point. When several paragraphs are selected, the insertion point is at the beginning or end of the selection, depending on how the user made the selection. The value reported depends on the location of the insertion point. This examples saves the alignment setting of the paragraph that contains the insertion point:
alignment l_align l_align = rte_1.GetAlignment()
Examples
See also
500
PowerBuilder
CHAPTER 10
PowerScript Functions
GetApplication
Description Syntax Return value Usage
Gets the handle of the current Application object so you can get and set properties of the application.
GetApplication ( )
Application. Returns the handle of the current application object. The GetApplication function lets you write generic code for an application, making it reusable in other applications. You do not have to code the actual name of the application when you want to set application properties. To change whether Toolbar Tips are displayed, you can get the handle of the application object and set the ToolbarTips property:
application app app = GetApplication() app.ToolbarTips = FALSE
Examples
501
GetArgElement
GetArgElement
Description Applies to Syntax
Call this function after calling InvokePBFunction or TriggerPBEvent to access the updated value in an argument passed by reference. JavaScript scripts must use this function to access arguments passed by reference. VBScript scripts can use this function if they established the argument list via calls to SetArgElement.
Examples
See also
502
PowerBuilder
CHAPTER 10
PowerScript Functions
GetAutomationNativePointer
Description Applies to Syntax
Gets a pointer to the OLE object associated with the OLEObject variable. The pointer lets you call OLE functions in an external DLL for the object. OLEObject
oleobject.GetAutomationNativePointer ( pointer ) Argument oleobject pointer Description The name of an OLEObject variable containing the object for which you want the native pointer. An UnsignedLong variable in which you want to store the pointer. If GetAutomationNativePointer cannot get a valid pointer, pointer is set to 0.
Pointer is a pointer to OLEs IUnknown interface. You can use it with the OLE QueryInterface function to get other interface pointers. When you call GetAutomationNativePointer, PowerBuilder calls OLEs AddRef function, which locks the pointer. You can release the pointer in your DLL function or in a PowerBuilder script with the ReleaseAutomationNativePointer function. This function is useful only for external DLL calls. It is not related to the
SetAutomationPointer function.
Examples
This example creates an OLEObject object, connects to an automation server, and gets a pointer for making external function calls. After processing, the pointer is released:
OLEObject oleobj_report UnsignedLong lul_oleptr integer li_rtn oleobj_report = CREATE OLEObject oleobj_report.ConnectToObject("report.doc") li_rtn = & oleobj_report.GetAutomationNativePointer(lul_oleptr) IF li_rtn = 0 THEN ... // Call external functions for automation oleobj_report.& ReleaseAutomationNativePointer(lul_oleptr) END IF
See also
503
GetCertificateLabel
GetCertificateLabel
Description
Called by EAServer to allow the user to select one of the available SSL certificate labels for authentication. This function is used by PowerBuilder clients connecting to EAServer. SSLCallBack objects
sslcallback.GetCertificateLabel ( thesessioninfo, labels ) Argument sslcallback thesessioninfo Description An instance of a customized SSLCallBack object. A CORBAObject that contains information about the SSL session. This information can optionally be displayed to the user to provide details about the session. An array of string values that contains the available certificate labels. The user must select one of these labels.
Applies to Syntax
labels
A PowerBuilder application does not usually call the GetCertificateLabel function directly. GetCertificateLabel is called by EAServer when an EAServer client has not specified a certificate label for an SSL connection that requires it. To override the behavior of any of the functions of the SSLCallBack object, create a standard class user object that descends from SSLCallBack and customize this object as necessary. To let EAServer know which object to use when a callback is required, specify the name of the object in the callbackImpl SSL property. You can set this property value by calling the SetGlobalProperty function. If you do not provide an implementation of GetCertificateLabel, EAServer receives the CORBA::NO_IMPLEMENT exception and the default implementation of this callback is used. The default implementation always returns the first certificate in the list of labels. If no labels are supplied, the CtsSecurity::NoCertificateException is raised. Any exceptions that may be raised by the function should be added to its prototype. If your implementation of the callback returns an empty string, the default implementation described above is used and the first certificate label in the list is returned. If the server requires mutual authentication and that certificate is acceptable to the server, the connection proceeds. If the certificate is not acceptable, the connection is refused.
504
PowerBuilder
CHAPTER 10
PowerScript Functions
To obtain a useful return value, provide the user with available certificate labels from the labels array passed to the function and ask the user to select one of them. You can also supply additional information obtained from the passed thesessioninfo object. You can enable the user to cancel the attempt to connect by throwing an exception in this callback function. All exceptions thrown in SSLCallback functions return a CTSSecurity::UserAbortedException to the server. You need to catch the exception by wrapping the ConnectToServer function in a try-catch block.
Examples
This example checks whether any certificate labels are available. To give the user more context, it displays host and port information obtained from the SSL session information object in the message box that informs the user that no certificates are available. If certificates are available, it opens a response window that displays available certificate labels. The response window returns the text of the selected item using CloseWithReturn:
int idx, numLabels long rc String ls_rc, sText, sLocation w_response w_ssl_response CTSSecurity_sslSessionInfo mySessionInfo rc = thesessioninfo._narrow(mySessionInfo, & "SessionInfo" ) sLocation = mySessionInfo.getProperty( "host" ) + & ":" + mySessionInfo.getProperty( "port" ) numLabels = upperbound(labels) IF numLabels <= 0 THEN MessageBox ("Personal certificate required", & "A certificate is required for connection to " & + sLocation + "~nNo certificates are available") ls_rc = "" ELSE sText = "Available certificates: " FOR idx=1 to numLabels sText += "~nCertificate[" + & string(idx) + "]: " + labels[idx] NEXT OpenWithParm( w_ssl_response, SText ) ls_rc = Message.StringParm
505
GetCertificateLabel
IF ls_rc = "cancel" then userabortedexception uae uae = create userabortedexception uae.setmessage("User cancelled connection" & + " when asked for certificate") throw uae END IF END IF RETURN ls_rc See also
506
PowerBuilder
CHAPTER 10
PowerScript Functions
GetChildrenList
Description Applies to Syntax
Provides a list of the children of a routine included in a trace tree model. TraceTreeObject, TraceTreeRoutine, and TraceTreeGarbageCollect objects
instancename.GetChildrenList ( list ) Argument instancename list Description Instance name of the TraceTreeObject, TraceTreeRoutine, or TraceTreeGarbageCollect object. An unbounded array variable of datatype TraceTreeNode in which GetChildrenList stores a TraceTreeNode object for each child of a routine. This argument is passed by reference.
Return value
ErrorReturn. Returns the following values: Success!The function succeeded ModelNotExistsError!The model does not exist
Usage
You use the GetChildrenList function to extract a list of the children of a routine (the classes and routines it calls) included in a trace tree model. Each child listed is defined as a TraceTreeNode object and provides the type of activity represented by that child. You must have previously created the trace tree model from a trace file using the BuildModel function. When the GetChildrenList function is called for TraceTreeGarbageCollect objects, each child listed usually represents the destruction of a garbage collected object.
Examples
This example checks the activity type of a node included in the trace tree model. If the activity type is an occurrence of a routine, it determines the name of the class that contains the routine and provides a list of the classes and routines called by that routine:
TraceTree ltct_node TraceTreeNode ltctn_list ... CHOOSE CASE node.ActivityType CASE ActRoutine! TraceTreeRoutine ltctrt_rout ltctrt_rout = ltct_node result += "Enter " + ltctrt_rout.ClassName & + "." + ltctrt_rout.name + " " & + String(ltctrt_rout.ObjectID) + " " &
507
GetChildrenList
BuildModel
508
PowerBuilder
CHAPTER 10
PowerScript Functions
GetColumn
Description
Retrieves column information for a DataWindow, child DataWindow, or ListView control. For syntax for a DataWindow or a child DataWindow, see the GetColumn method for DataWindows in the DataWindow Reference or the online Help.
Applies to Syntax
ListView controls
listviewname.GetColumn ( index, label, alignment, width ) Argument listviewname index label alignment Description The name of the ListView control from which you want to find the properties for a column. An integer whose value is the index of the column for which you want to find properties. A string identifying the label of the column for which you want to find properties. This argument is passed by reference. A value of the enumerated datatype Alignment specifying the alignment of the column for which you want to find properties. Values are: Center! Justify! Left! Right! This argument is passed by reference. width An integer whose value is the width of the column for which you want to find properties. This argument is passed by reference.
Use label, alignment, and width to retrieve the properties for a specified column. This example uses the instance variable li_col to pass the column number to GetColumn and retrieve the properties for the column. The script uses SetColumn to change the columns alignment:
string ls_label,ls_align int li_width alignment la_align IF lv_list.View <> ListViewReport! THEN lv_list.View = ListViewReport! END IF
509
GetColumn
IF li_col = 0 THEN MessageBox("Error!","Click on a Column bar.", & StopSign!) ELSE lv_list.GetColumn(li_col, ls_label, la_align, & li_width) lv_list.SetColumn(li_col, ls_label, Right!, & li_width) END IF See also
SetColumn
510
PowerBuilder
CHAPTER 10
PowerScript Functions
GetCommandDDE
Description Syntax
Obtains the command sent by the client application when your application is a DDE server.
GetCommandDDE ( string ) Argument string Description A string variable in which GetCommandDDE will store the command
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs (such as the function was called in the wrong context). If string is NULL, GetCommandDDE returns NULL.
Usage
When a DDE client application sends a command to your application, the action triggers a RemoteExec event in the active window. In that events script, you call GetCommandDDE to find out what command has been sent. You decide how your application will respond to the command. To enable DDE server mode, use the function StartServerDDE, in which you decide how your application will be known to other applications.
Examples
This excerpt from a script for the RemoteExec event checks to see if the action requested by the DDE client is Open Next Sheet. If it is, the DDE server opens another instance of the sheet DataSheet. If the requested action is Shut Down, the DDE server shuts itself down. Otherwise, it lets the DDE client know the requested action was invalid. The variables ii_sheetnum and i_DataSheet[ ] are instance variables for the window that responds to the DDE event:
integer ii_sheetnum DataSheet i_DataSheet[ ]
This script that follows uses the local variable ls_Action to store the command sent by the client application:
string ls_Action GetCommandDDE(ls_Action) IF ls_Action = "Open Next Sheet" THEN ii_sheetnum = ii_sheetnum + 1 OpenSheet(i_DataSheet[ii_sheetnum], w_frame_emp) ELSEIF ls_Action = "Shut Down" THEN HALT CLOSE ELSE RespondRemote(FALSE) END IF
511
GetCommandDDEOrigin
See also
GetCommandDDEOrigin
Description Syntax
When called by the DDE server application, obtains the application name parameter used by the DDE client sending the command.
GetCommandDDEOrigin ( applstring ) Argument applstring Description A string variable in which GetCommandDDEOrigin will store the name of the server application
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs (such as the function was called in the wrong context). If applstring is NULL, GetCommandDDEOrigin returns NULL.
Usage
The server application calling this function can use the application name (its own DDEname) to determine if it wants to respond to this command. Otherwise, the function provides no additional information about the client. This script uses the local variable ls_name to store the name the client application used to identify the server application:
string ls_name GetCommandDDEOrigin(ls_name)
Examples
See also
512
PowerBuilder
CHAPTER 10
PowerScript Functions
GetCompanyName
Description Applies to Syntax
Returns the company name for the current execution context. ContextInformation objects
servicereference.GetCompanyName ( name ) Argument servicereference name Description Reference to the ContextInformation service instance. String into which the function places the company name. This argument is passed by reference.
Call this function to determine the company name (such as Sybase, Inc.). This example calls the GetCompanyName function:
String ls_company Integer li_return ContextInformation ci li_return = ci.GetCompanyName(ls_company) IF li_return = 1 THEN sle_co_name.text = ls_company END IF
See also
513
GetContextKeywords
GetContextKeywords
Description Applies to Syntax
Retrieves one or more values associated with a specified keyword. ContextKeyword objects
servicereference.GetContextKeywords ( name, values ) Argument servicereference name values Description Reference to the ContextKeyword service instance. String specifying the keyword for which the function returns corresponding values. Unbounded String array into which the function places the values that correspond to name. This argument is passed by reference.
Integer. Returns the number of elements in values if the function succeeds and
-1 if an error occurs. Call this function to access environment variables. Environment-variable availability differs by execution context:
PowerBuilder runtime
The function accesses DOS environment variables, each of which has a unique keyword. specified in the EMBED tag. These keywords need not be unique. If there is no keyword specified in the EMBED tag, the function attempts to access a DOS environment variable with the specified name.
Examples
environment variables, each of which has a unique keyword. This example calls the GetContextKeywords function:
String ls_keyword Integer li_count, li_return ContextKeyword lcx_key li_return = this.GetContextService & ("Keyword", lcx_key) ls_keyword = sle_name.Text lcx_key.GetContextKeywords & (ls_keyword, is_values) FOR li_count = 1 to UpperBound(is_values) lb_parms.AddItem(is_values[li_count]) NEXT See also
GetContextService
514
PowerBuilder
CHAPTER 10
PowerScript Functions
GetContextService
Description Applies to Syntax
Integer. Returns 1 if the function succeeds and a negative integer if an error occurs. The return value -1 indicates an unspecified error.
Call this function to establish a reference to a service object, allowing you to access methods and properties in the service object. You must call this function before calling service object functions.
Using a CREATE statement
You can instantiate these objects with a PowerScript CREATE statement. However, this always creates an object for the default context (native PowerBuilder execution environment), regardless of where the application is running.
515
GetContextService
Examples
See also
BeginTransaction GetCompanyName GetContextKeywords GetHostObject GetMajorVersion GetMinorVersion GetName GetShortName GetURL GetVersionName HyperLinkToURL Init PostURL
516
PowerBuilder
CHAPTER 10
PowerScript Functions
GetCredentialAttribute
Description Applies to Syntax
Called by EAServer to allow the user to supply user credentials dynamically. This function is used by PowerBuilder clients connecting to EAServer. SSLCallBack objects
sslcallback.GetCredentialAttribute ( thesessioninfo, attr, attrvalues ) Argument sslcallback thesessioninfo Description An instance of a customized SSLCallBack object. A CORBAObject that contains information about the SSL session. This information can optionally be displayed to the user to provide details about the session. A long indicating whether the user needs to specify the path name of an INI file or a profile file. Values are: 1 CRED_ATTR_ENTRUST_INIFILE attrvalues 2 CRED_ATTR_ENTRUST_USERPROFILE An array of string values that contains the available attribute values.
attr
A PowerBuilder application does not usually call the GetCredentialAttribute function directly. GetCredentialAttribute is called by EAServer if the useEntrustID property has been set and the EAServer client has not specified the path name of an Entrust INI file or profile. To override the behavior of any of the functions of the SSLCallBack object, create a standard class user object that descends from SSLCallBack and customize this object as necessary. To let EAServer know which object to use when a callback is required, specify the name of the object in the callbackImpl SSL property. You can set this property value by calling the SetGlobalProperty function. If you do not provide an implementation of GetCredentialAttribute, EAServer receives the CORBA::NO_IMPLEMENT exception and the default implementation of this callback is used. The default implementation always returns the first value in the list of values supplied. If there are no values supplied, it raises CtsSecurity::NoValueException. Any exceptions that may be raised by the function should be added to its prototype. If your implementation of the callback returns an empty string, the default implementation described above is used and the first value in the list is returned. If that value is acceptable to the server, the connection proceeds. If the value is not acceptable, the connection is refused.
517
GetCredentialAttribute
To obtain a useful return value, provide the user with available attribute values from the attrvalues array passed to the function and ask the user to select one of them. You can also supply additional information, such as the server certificate, obtained from the passed thesessioninfo object. You can enable the user to cancel the attempt to connect by throwing an exception in this callback function. All exceptions thrown in SSLCallback functions return a CTSSecurity::UserAbortedException to the server. You need to catch the exception by wrapping the ConnectToServer function in a try-catch block.
Examples
This example checks whether the server requires the location of an INI file or an Entrust user profile and displays an appropriate message. If the attrvalues array provides a list of choices, it displays the choices in a message box and prompts the user to enter a selection in a text box:
int idx, numAttrs String sText, sLocation numAttrs = upperbound(attrValues) w_response w_ssl_response IF attr = 1 THEN MessageBox("Entrust INI file required", & "Please specify the location of the INI file") ELSEIF attr = 2 THEN MessageBox("Entrust profile required", & "Please specify the location of the profile") END IF IF numAttrs <> 0 THEN sText = "Locations available: " FOR idx = 1 to numAttrs sText += "~nattrValues[" + string(idx) + "]: " & + attrvalues[idx] NEXT OpenWithParm( w_ssl_response, SText ) ls_rc = Message.StringParm IF ls_rc = "cancel" then userabortedexception uae uae = create userabortedexception uae.setmessage("User cancelled connection") throw uae END IF END IF RETURN ls_rc
518
PowerBuilder
CHAPTER 10
PowerScript Functions
See also
GetCurrentDirectory
Description Syntax Return value Examples
String. Returns the full path name for the current directory. This example puts the current directory name in a SingleLineEdit control:
sle_1.text = GetCurrentDirectory( )
See also
519
GetData
GetData
Obtains data from a control.
To obtain The value of a data point in a series in a graph The unformatted data from an EditMask control Data from an OLE server Use Syntax 1 Syntax 2 Syntax 3
Syntax 1
Description Applies to Syntax
Double. Returns the value of the data in datapoint if it succeeds and 0 if an error occurs. If any arguments value is NULL, GetData returns NULL.
You can use GetData only for graphs whose values axis is numeric. For graphs with other types of values axes, use the GetDataValue function instead.
520
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
These statements obtain the data value of data point 3 in the series named Costs in the graph gr_computers in the DataWindow control dw_equipment:
integer SeriesNbr double data_value // Get the number of the series. SeriesNbr = & dw_equipment.FindSeries("gr_computers", "Costs") data_value = dw_equipment.GetData( & "gr_computers" , SeriesNbr, 3)
These statements obtain the data value of the data point under the mouse pointer in the graph gr_prod_data and store it in data_value:
integer SeriesNbr, ItemNbr double data_value grObjectType MouseHit MouseHit = & gr_prod_data.ObjectAtPointer(SeriesNbr, ItemNbr) IF MouseHit = TypeSeries! THEN data_value = & gr_prod_data.GetData(SeriesNbr, ItemNbr) END IF
These statements obtain the x value of the data point in the scatter graph gr_sales_yr and store it in data_value:
integer SeriesNbr, ItemNbr double data_value gr_product_data.ObjectAtPointer(SeriesNbr, ItemNbr) data_value = & gr_sales_yr.GetData(SeriesNbr, ItemNbr, xValue!) See also
521
GetData
Syntax 2
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, GetData returns NULL.
You can find out the datatype of an EditMask control by looking at its MaskDataType property, which holds a value of the MaskDataType enumerated datatype. This example gets data of datatype date from the EditMask control em_date. Formatting characters for the date are ignored. The String function converts the date to a string so it can be assigned to the SingleLineEdit sle_date:
date d em_date.GetData(d) sle_date.Text = String(d, "mm-dd-yy")
Examples
This example gets string data from the EditMask control em_string and assigns the result to sle_string. Characters in the edit mask are ignored:
string s em_string.GetData(s) sle_string.Text = s
522
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 3
Description Applies to Syntax
data
Integer. Returns 0 if it succeeds and -1 if an error occurs. GetData will return an error if you specify a clipboard format that the OLE
server does not support. To find out what formats it supports, see the documentation for the OLE server.
523
GetData
GetData operates via Uniform Data Transfer, a mechanism defined by Microsoft for exchanging data with container applications. PowerBuilder enables data transfer via a global handle. The OLE server must also support data transfer via a global handle. If it does not, you cannot transfer data to or from that server.
Examples
After the user has activated a Microsoft Word document and edited its contents, this example gets the contents from the OLE control ole_word6 and stores the contents in the string ls_oledata. The contents of the string are then displayed in the MultiLineEdit mle_text:
string ls_oledata integer li_rtn li_rtn = ole_word6.GetData( & ClipFormatText!, ls_oledata) mle_text.Text = ls_oledata
One OLE control displays a Microsoft Word document containing a table of data. This example gets the data in the report and assigns it to a graph in a second OLE control. Microsoft Graph in the second control interprets the first row in the table as headings, and subsequent rows as categories or series, depending on the settings on the Data menu:
string ls_data integer li_rtn li_rtn = ole_word.GetData(ClipFormatText!, ls_data) IF li_rtn <> 1 THEN RETURN li_rtn = ole_graph.SetData(ClipFormatText!, ls_data) See also
SetData
524
PowerBuilder
CHAPTER 10
PowerScript Functions
GetDataDDE
Description
Obtains data sent from another DDE application and stores it in the specified string variable. PowerBuilder can use GetDataDDE when acting as a DDE client or a DDE server application.
GetDataDDE ( string ) Argument string Description A string variable in which GetDataDDE will put the data received from a remote DDE application
Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs (such as the function was called in the wrong context). If string is NULL, GetDataDDE returns NULL. GetDataDDE is usually called in the window-level script for a RemoteSend
event when your application is a DDE server or HotLinkAlarm event when your application is a DDE client.
Examples
Assuming that your PowerBuilder DDE client application has established a hot link with row 7, column 15 of an Excel spreadsheet, and that the value in that row and column address has changed from red to green (which triggers the HotLinkAlarm event in your application), this script for the HotLinkAlarm event calls GetDataDDE to store the new value in the variable Str20:
// In the script for a HotLinkAlarm event string Str20 GetDataDDE(Str20)
See also
525
GetDataDDEOrigin
GetDataDDEOrigin
Description
Determines the origin of data from a hot-linked DDE server application or a DDE client application, and if successful, stores the applications DDE identifiers in the specified strings. PowerBuilder can use GetDataDDEOrigin when it is acting as a DDE client or as a DDE server application.
GetDataDDEOrigin ( applstring, topicstring, itemstring ) Argument applstring topicstring itemstring Description A string variable in which GetDataDDEOrigin will store the name of the server application A string variable in which GetDataDDEOrigin will store the topic (for example, in Microsoft Excel, the topic could be REGION.XLS) A string variable in which GetDataDDEOrigin will store the item identification (for example, in Microsoft Excel, the item could be R1C2)
Syntax
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs (such as the function was called in the wrong context). If any arguments value is NULL, GetDataDDEOrigin returns NULL.
Usage
Call GetDataDDEOrigin in the window-level script for a RemoteSend event or a HotLinkAlarm event. When your application is a DDE server, call GetDataDDEOrigin in the script for the RemoteSend event. Use it to determine the topic and item requested by the client. The application name is the application specified by the client (the servers own DDEname). When your application is a DDE client, call GetDataDDEOrigin in the script for the HotLinkAlarm event. Use it to identify the source of the data when hot links may exist for more than one topic within the server application or for more than one application.
Examples
See also
526
PowerBuilder
CHAPTER 10
PowerScript Functions
GetDataPieExplode
Description
Reports the percentage that a pie slice is exploded in a pie graph. An exploded slice is moved away from the center of the pie in order to draw attention to the data. Graph controls in windows and user objects, and graphs in DataWindow controls
controlname.GetDataPieExplode ( { graphcontrol, } series, datapoint, percentage ) Argument controlname Description The name of the graph for which you want the percentage a pie slice is exploded, or the name of the DataWindow control containing the graph (Optional) A string whose value is the name of the graph in the DataWindow control for which you want the percentage a pie slice is exploded The number that identifies the series The number of the exploded data point (that is, the pie slice) An integer variable in which you want to store the percentage that the pie slice is exploded
Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, GetDataPieExplode returns NULL.
This example reports the percentage that a pie slice is exploded when the user clicks on that slice. The code checks whether the graph is a pie graph using the property Graphite. It then finds out whether the user clicked on a pie slice by checking the series and data point values set by ObjectAtPointer. The script is for the DoubleClicked event of a graph object:
integer series, datapoint grObjectType clickedtype integer percentage percentage = 50 IF (This.GraphType <> PieGraph! and & This.GraphType <> Pie3D!) THEN RETURN clickedtype = This.ObjectAtPointer(series, & datapoint)
527
GetDataPieExplode
IF (series > 0 and datapoint > 0) THEN This.GetDataPieExplode(series, datapoint, & percentage) MessageBox("Explosion Percentage", & "Data point " + This.CategoryName(datapoint) & + " in series " + This.SeriesName(series) & + " is exploded " + String(percentage) + "%") END IF See also
SetDataPieExplode
528
PowerBuilder
CHAPTER 10
PowerScript Functions
GetDataStyle
Finds out the appearance of a data point in a graph. Each data point in a series can have individual appearance settings. There are different syntaxes, depending on what settings you want to check.
To get the Data points colors Line style and width used by the data point Fill pattern or symbol for the data point Use Syntax 1 Syntax 2 Syntax 3
GetDataStyle provides information about a single data point. The series to which the data point belongs has its own style settings. In general, the style values for the data point are the same as its series settings. Use SetDataStyle to change the style values for individual data points. Use GetSeriesStyle and SetSeriesStyle to get and set style information for the series.
The graph stores style information for properties that do not apply to the current graph type. For example, you can find out the fill pattern for a data point or a series in a 2-dimensional line graph, but that fill pattern will not be visible. For the enumerated datatype values that GetDataStyle stores in linestyle and enumvariable, see SetDataStyle.
Syntax 1
Description Applies to Syntax
529
GetDataStyle
Description The number of the data point for which you want the color. A value of the grColorType enumerated datatype specifying the aspect of the data point for which you want the color. Values are: Background! The background color Foreground! Text (fill color) LineColor! The color of the line Shade! The shaded area of three-dimensional graphics
Integer. Returns 1 if it succeeds and -1 if an error occurs. Stores a color value in colorvariable. If any arguments value is NULL, GetDataStyle returns NULL.
This example gets the text (foreground) color used for data point 6 in the series named Salary in the graph gr_emp_data. It stores the color value in the variable color_nbr:
long color_nbr integer SeriesNbr // Get the number of the series SeriesNbr = gr_emp_data.FindSeries("Salary") // Get the color gr_emp_data.GetDataStyle(SeriesNbr, 6, & Foreground!, color_nbr)
This example gets the background color used for data point 6 in the series entered in the SingleLineEdit sle_series in the DataWindow graph gr_emp_data. It stores the color value in the variable color_nbr:
long color_nbr integer SeriesNbr // Get the number of the series SeriesNbr = FindSeries("gr_emp_data", sle_series.Text)
530
PowerBuilder
CHAPTER 10
PowerScript Functions
See also
Syntax 2
Description Applies to Syntax
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. For the specified series and data point, stores its line style in linestyle and the lines width in linewidth. If any arguments value is NULL, GetDataStyle returns NULL.
Usage Examples
For the enumerated datatype values that GetDataStyle will store in linestyle, see SetDataStyle. This example gets the line style and width of data point 10 in the series named Costs in the graph gr_product_data. It stores the information in the variables line_style and line_width:
integer SeriesNbr, line_width LineStyle line_style
531
GetDataStyle
// Get the number of the series SeriesNbr = gr_product_data.FindSeries("Costs") gr_product_data.GetDataStyle(SeriesNbr, 10, & line_style, line_width)
This example gets the line style and width for data point 6 in the series entered in the SingleLineEdit sle_series in the graph gr_depts in the DataWindow control dw_employees. The information is stored in the variables line_style and line_width:
integer SeriesNbr, line_width LineStyle line_style // Get the number of the series SeriesNbr = dw_employees.FindSeries( & " gr_depts " , sle_series.Text) // Get the line style and width dw_employees.GetDataStyle("gr_depts", SeriesNbr, & 6, line_style, line_width) See also
Syntax 3
Description Applies to Syntax
532
PowerBuilder
CHAPTER 10
PowerScript Functions
Description The number of the data point for which you want the fill pattern or symbol type. The variable in which you want to store the data style. You can specify a FillPattern or grSymbolType variable. The data style information stored will depend on the variable type.
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. Stores, according to the type of enumvariable, a value of that enumerated datatype representing the fill pattern or symbol used for the specified data point. If any arguments value is NULL, GetDataStyle returns NULL.
Usage Examples
For the enumerated datatype values that GetDataStyle will store in enumvariable, see SetDataStyle. This example gets the pattern used to fill data point 10 in the series named Costs in the graph gr_product_data. The information is stored in the variable data_pattern:
integer SeriesNbr FillPattern data_pattern // Get the number of the series SeriesNbr = gr_product_data.FindSeries("Costs") gr_product_data.GetDataStyle(SeriesNbr, 10, & data_pattern)
This example gets the pattern used to fill data point 6 in the series entered in the SingleLineEdit sle_series in the graph gr_depts in the DataWindow control dw_employees. The information is assigned to the variable data_pattern:
integer SeriesNbr FillPattern data_pattern // Get the number of the series SeriesNbr = dw_employees.FindSeries("gr_depts", & sle_series.Text) // Get the pattern dw_employees.GetDataStyle("gr_depts", SeriesNbr, & 6, data_pattern)
533
GetDataStyle
These statements store in the variable symbol_type the symbol of data point 10 in the series named Costs in the graph gr_product_data:
integer SeriesNbr grSymbolType symbol_type // Get the number of the series SeriesNbr = gr_product_data.FindSeries("Costs") gr_product_data.GetDataStyle(SeriesNbr, 10, & symbol_type)
These statements store the symbol for a data point in the variable symbol_type. The data point is the sixth point in the series named in the SingleLineEdit sle_series in the graph gr_depts in the DataWindow control dw_employees:
integer SeriesNbr grSymbolType symbol_type // Get the number of the series SeriesNbr = dw_employees.FindSeries("gr_depts", & sle_series.Text) // Get the symbol dw_employees.GetDataStyle("gr_depts", SeriesNbr, & 6, symbol_type) See also
534
PowerBuilder
CHAPTER 10
PowerScript Functions
GetDataValue
Description Applies to Syntax
Obtains the value of a data point in a series in a graph. Graph controls in windows and user objects, and graphs in DataWindow controls
controlname.GetDataValue ( { graphcontrol, } seriesnumber, datapoint, datavariable {, xory } ) Argument controlname graphcontrol (DataWindow control only) seriesnumber datapoint datavariable Description The name of the graph from which you want data, or the name of the DataWindow control containing the graph. (Optional) A string whose value is the name of the graph in the DataWindow control from which you want the data. The number that identifies the series from which you want data. The number of the data point for which you want the value. The name of a variable that will hold the data value. The variables datatype can be date, DateTime, double, string, or time. The variable must have the same datatype as the values axis of the graph. (Optional) A value of the grDataType enumerated datatype specifying whether you want the x or y value of the data point in a scatter graph. Values are: xValue! The x value of the data point yValue! (Default) The y value of the data point
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, GetDataValue returns NULL. GetDataValue retrieves data from any graph. The data is stored in datavariable, whose datatype must match the datatype of the graphs values axis. If the values axis is numeric, you can also use the GetData function.
Examples
These statements obtain the data value of data point 3 in the series named Costs in the graph gr_computers in the DataWindow control dw_equipment:
integer SeriesNbr, rtn double data_value // Get the number of the series. SeriesNbr = dw_equipment.FindSeries( & "gr_computers", "Costs") rtn = dw_equipment.GetDataValue( & "gr_computers" , SeriesNbr, 3, data_value)
535
GetDataValue
These statements obtain the data value of the data point under the mouse pointer in the graph gr_prod_data and store it in data_value. If the user does not click on a data point, then ItemNbr is set to 0. The categories of the graph are time values:
integer SeriesNbr, ItemNbr, rtn time data_value grObjectType MouseHit MouseHit = & gr_prod_data.ObjectAtPointer(SeriesNbr, ItemNbr) IF ItemNbr > 0 THEN rtn = gr_prod_data.GetDataValue( & SeriesNbr, ItemNbr, data_value) END IF
These statements obtain the x value of the data point in the scatter graph gr_sales_yr and store it in data_value. If the user does not click on a data point, then ItemNbr is set to 0. The datatype of the category axis is Date:
integer SeriesNbr, ItemNbr, rtn date data_value gr_product_data.ObjectAtPointer(SeriesNbr, ItemNbr) IF ItemNbr > 0 THEN rtn = gr_sales_yr.GetDataValue( & SeriesNbr, ItemNbr, data_value, xValue!) END IF See also
536
PowerBuilder
CHAPTER 10
PowerScript Functions
GetDynamicDate
Description
Obtains data of type Date from the DynamicDescriptionArea after you have executed a dynamic SQL statement.
Restriction
You can use this function only after executing Format 4 dynamic SQL statements.
Syntax DynamicDescriptionArea.GetDynamicDate ( index ) Argument DynamicDescriptionArea index Description The name of the DynamicDescriptionArea, usually SQLDA. An integer identifying the output parameter descriptor from which you want to get the data. Index must be less than or equal to the value in NumOutputs in DynamicDescriptionArea.
Return value
Date. Returns the Date data in the output parameter descriptor identified by index in DynamicDescriptionArea. Returns 1900-01-01 if an error occurs. If any arguments value is NULL, GetDynamicDate returns NULL.
Usage
After you fetch data using Format 4 dynamic SQL statements, the DynamicDescriptionArea, usually SQLDA, contains information about the data retrieved. The SQLDA property NumOutputs specifies the number of data descriptors returned. The property array OutParmType contains values of the ParmType enumerated datatype specifying the datatype of each value returned. Use GetDynamicDate when the value of OutParmType is TypeDate! for the value in the array that you want to retrieve.
Examples
These statements set Today to the Date data in the second output parameter descriptor:
Date Today Today = GetDynamicDate(SQLDA, 2)
If you have executed Format 4 dynamic SQL statements, data is stored in the DynamicDescriptionArea. This example finds out the datatype of the stored data and uses a CHOOSE CASE statement to assign it to local variables. If the SELECT statement is:
SELECT emp_start_date FROM employee;
537
GetDynamicDate
For each case, other processing could assign the value to a DataWindow so that the value would not be overwritten when another value has the same ParmType:
Date Datevar Time Timevar DateTime Datetimevar Double Doublevar String Stringvar FOR n = 1 to SQLDA.NumOutputs CHOOSE CASE SQLDA.OutParmType[n] CASE TypeString! Stringvar = SQLDA.GetDynamicString(n) ... // Other processing CASE TypeDecimal!, TypeDouble!, & TypeInteger!, TypeLong!, & TypeReal!, TypeBoolean! Doublevar = SQLDA.GetDynamicNumber(n) ... // Other processing CASE TypeDate! Datevar = SQLDA.GetDynamicDate(n) ... // Other processing CASE TypeDateTime! Datetimevar = SQLDA.GetDynamicDateTime(n) ... // Other processing CASE TypeTime! Timevar = SQLDA.GetDynamicTime(n) ... // Other processing CASE ELSE MessageBox("Dynamic SQL", & "datatype unknown.") END CHOOSE NEXT See also
538
PowerBuilder
CHAPTER 10
PowerScript Functions
GetDynamicDateTime
Description
Obtains data of type DateTime from the DynamicDescriptionArea after you have executed a dynamic SQL statement.
Restriction
You can use this function only after executing Format 4 dynamic SQL statements.
Syntax DynamicDescriptionArea.GetDynamicDateTime ( index ) Argument DynamicDescriptionArea index Description The name of the DynamicDescriptionArea, usually SQLDA. An integer identifying the output parameter descriptor from which you want to get the data. Index must be less than or equal to the value in NumOutputs in DynamicDescriptionArea.
Return value
DateTime. Returns the DateTime data in the output parameter descriptor identified by index in DynamicDescriptionArea. Returns 1900-01-01 00:00:00.000000 if an error occurs. If any arguments value is NULL, GetDynamicDateTime returns NULL.
Usage
Use GetDynamicDateTime when the value of OutParmType is TypeDateTime! for the value that you want to retrieve from the array. To test for the error value, you must use the DateTime function to construct the value to which you want to compare the returned value. PowerBuilder does not support DateTime literals.
Examples
These statements set SystemDateTime to the DateTime data in the second output parameter descriptor:
DateTime SystemDateTime SystemDateTime = SQLDA.GetDynamicDateTime(2) IF SystemDateTime = & DateTime(1900-01-01, 00:00:00) THEN ... // Error handling END IF
539
GetDynamicDateTime
See also
540
PowerBuilder
CHAPTER 10
PowerScript Functions
GetDynamicNumber
Description
Obtains numeric data from the DynamicDescriptionArea after you have executed a dynamic SQL statement.
Restriction
You can use this function only after executing Format 4 dynamic SQL statements.
Syntax DynamicDescriptionArea.GetDynamicNumber ( index ) Argument DynamicDescriptionArea index Description The name of the DynamicDescriptionArea, usually SQLDA. An integer identifying the output parameter descriptor from which you want to get the data. Index must be less than or equal to the value in NumOutputs in DynamicDescriptionArea.
Return value
Double. Returns the numeric data in the output parameter descriptor identified by index in DynamicDescriptionArea. Returns 0 if an error occurs. If any arguments value is NULL, GetDynamicNumber returns NULL.
Usage
Use GetDynamicNumber when the value of OutParmType is TypeInteger!, TypeDecimal!, TypeDouble!, TypeLong!, TypeReal!, or TypeBoolean! for the value that you want to retrieve from the array. If you use this function to return a decimal value, expect the value to be rounded when you convert the double datatype back to a decimal. Doubles do not support the same precision as decimals.
Examples
These statements set DeptId to the numeric data in the second output parameter descriptor:
Integer DeptId DeptId = SQLDA.GetDynamicNumber(2)
541
GetDynamicString
GetDynamicString
Description
Obtains data of type String from the DynamicDescriptionArea after you have executed a dynamic SQL statement.
Restriction
You can use this function only after executing Format 4 dynamic SQL statements.
Syntax DynamicDescriptionArea.GetDynamicString ( index ) Argument DynamicDescriptionArea index Description The name of the DynamicDescriptionArea, usually SQLDA. An integer identifying the output parameter descriptor from which you want to get the data. Index must be less than or equal to the value in NumOutputs in DynamicDescriptionArea.
Return value
String. Returns the string data in the output parameter descriptor identified by index in DynamicDescriptionArea. Returns the empty string ("") if an error occurs. If any arguments value is NULL, GetDynamicString returns NULL. Use GetDynamicString when the value of OutParmType is TypeString! for the value that you want to retrieve from the array. These statements set LName to the String data in the second output descriptor:
String LName LName = SQLDA.GetDynamicString(2)
Usage Examples
542
PowerBuilder
CHAPTER 10
PowerScript Functions
GetDynamicTime
Description
Obtains data of type Time from the DynamicDescriptionArea after you have executed a dynamic SQL statement.
Restriction
You can use this function only after executing Format 4 dynamic SQL statements.
Syntax DynamicDescriptionArea.GetDynamicTime ( index ) Argument DynamicDescriptionArea index Description The name of the DynamicDescriptionArea, usually SQLDA. An integer identifying the output parameter descriptor from which you want to get the data. Index must be less than or equal to the value in NumOutputs in DynamicDescriptionArea.
Return value
Time. Returns the Time data in the output parameter descriptor identified by index in DynamicDescriptionArea. Returns 00:00:00.000000 if an error occurs. If any arguments value is NULL, GetDynamicTime returns NULL.
Usage Examples
Use GetDynamicTime when the value of OutParmType is TypeTime! for the value that you want to retrieve from the array. These statements set Start to the Time data in the first output parameter descriptor:
Time Start Start = SQLDA.GetDynamicTime(1)
543
GetEnvironment
GetEnvironment
Description Syntax
Gets information about the operating system, processor, and screen display of the system.
GetEnvironment ( environmentinfo ) Argument environmentinfo Description The name of the Environment object that will hold the information about the environment
Integer. Returns 1 if it succeeds and -1 if an error occurs. If environmentinfo is NULL, GetEnvironment returns NULL.
In cross-platform development projects, you can call GetEnvironment in scripts and take actions based on the operating system. You can also find out the processor (Intel 386 or 486, 68000, and so on). The information also includes version numbers of the operating system and PowerBuilder. You can call GetEnvironment to find out the number of colors supported by the system and the size of the screen. You can use the size information in a windows Open script to reset its X and Y properties.
Examples
This script runs another PowerBuilder application and uses the OSType property of the Environment object to determine how to specify the path:
string path environment env integer rtn rtn = GetEnvironment(env) IF rtn <> 1 THEN RETURN CHOOSE CASE env.OSType CASE aix! path = "/export/home/pb_apps/analyze.exe" CASE Windows!, WindowsNT! path = "C:\PB_apps\analyze.exe" CASE ELSE RETURN END CHOOSE Run(path)
544
PowerBuilder
CHAPTER 10
PowerScript Functions
This example displays a message box that shows the major, minor, and fixes versions and the build number of PowerBuilder:
string ls_version environment env integer rtn rtn = GetEnvironment(env) IF rtn <> 1 THEN RETURN ls_version = "Version: "+ string(env.pbmajorrevision) ls_version += "." + string(env.pbminorrevision) ls_version += "." + string(env.pbfixesrevision) ls_version += " Build: " + string(env.pbbuildnumber) MessageBox("PowerBuilder Version", ls_version)
545
GetFileOpenName
GetFileOpenName
Description Syntax
Displays the systems Open File dialog box and allows the user to select a file or enter a file name.
GetFileOpenName ( title, pathname, filename {, extension {, filter { , initdir { , aFlag } } } } ) GetFileOpenName ( title, pathname, filename[ ] {, extension {, filter { , initdir { , aFlag } } } } ) Argument title pathname filename, filename[ ] Description A string whose value is the title of the dialog box. A string variable in which you want to store the returned path and file name. A string variable in which the returned file name is stored or an array of string variables in which multiple selected file names are stored. Specifying an array of string variables enables multiple selection in the dialog box. A string whose value is a 1- to 3-character default file extension. The default is no extension. A string whose value is a text description of the files to include in the list box and the file mask that you want to use to select the displayed files (for example, *.* or *.exe). The format for filter is:
description,*. ext
A string whose value is the initial directory name. The default is the current directory. An unsigned long whose value determines which options are enabled in the dialog box. The value of each options flag is calculated as 2 to the power of (index -1), where index is the integer associated with the option. The value of the aggregate flag passed to GetOpenFileName is the sum of the individual option flags. See the table in the Usage section for a list of options, the index associated with each option, and the options meaning.
Return value
Integer. Returns 1 if it succeeds, 0 if the user clicks the Cancel button or Windows cancels the display, and -1 if an error occurs. If any arguments value is NULL, GetFileOpenName returns NULL.
Usage
If you specify a DOS-style file extension and the user enters a file name with no extension, PowerBuilder appends the default extension to the file name. If you specify a file mask to act as a filter, PowerBuilder displays only files that match the mask.
546
PowerBuilder
CHAPTER 10
PowerScript Functions
You use the filter argument to limit the types of files displayed in the list box and to let the user know what those limits are. For example, to display the description Text Files (*.TXT) and only files with the extension .TXT, specify the following for filter:
"Text Files (*.TXT),*.TXT"
To specify more than one file extension in filter, enter multiple descriptions and extension combinations and separate them with commas. For example:
"PIF files, *.PIF, Batch files, *.BAT"
The dialog boxes presented by GetFileOpenName and GetFileSaveName are system dialog boxes. They provide standard system behavior, including control over the current directory. When users change the drive, directory, or folder in the dialog box, they change the current directory or folder. The newly selected directory or folder becomes the default for file operations until they exit the application, unless the optional initdir argument is passed. The aFlag argument is used to pass one or more options that determine the appearance of the dialog box. For each option, the value of the flag is 2^(index -1), where index is an integer associated with each option as shown in the following table.You can pass multiple options by passing an aggregate flag, calculated by adding the values of the individual flags. If you do not pass an aFlag, the Explorer-style open file dialog box is used. If you do pass a flag, the old-style dialog box is used by default. Some options do not apply when the Explorer-style dialog box is used. For those that do apply, add the option value for using the Explorer-style dialog box (2) to the value of the option if you want to display an Explorer-style dialog box. For example, passing the flag 32768 (2^15) to the GetFileSaveName function opens the old-style dialog box with the Read Only check box selected by default. Passing the flag 32770 opens the Explorer-style dialog box with the Read Only check box selected by default.
Table 10-2: Option values for GetFileOpenName and GetFileSaveName Index 1 Constant name OFN_CREATEPROMPT Description If the specified file does not exist, prompt for permission to create the file. If the user chooses to create the file, the dialog box closes; otherwise the dialog box remains open. Use an Explorer-style dialog box. The file extension entered differed from the extensions specified in extension. Only the names of existing files can be entered. Hide the Read Only check box.
2 3 4 5
547
GetFileOpenName
Index 6 7
Description Use long file names. Ignored for Explorer-style dialog boxes. Restore the current directory to its original value if the user changed the directory while searching for files. This option has no effect for GetOpenFileName on Windows NT, 2000, and XP. Return the path and file name of the selected shortcut (.lnk file); otherwise the path and file name pointed to by the shortcut are returned. Use short file names (8.3 format). Ignored for Explorer-style dialog boxes. Hide the Network button. Ignored for Explorer-style dialog boxes. The file returned is not read only and is not in a write-protected directory. Do not create the file before the dialog box is closed. This option should be specified if the application saves the file on a netwrok share where files can be created but not modified. No check is made for write protection, a full disk, an open drive door, or network protection. A file cannot be reopened once it is closed. Invalid characters are allowed in file names. Used in Save As dialog boxes. Generates a message box if the selected file already exists. Only valid paths and file names can be entered. Select the Read Only check box when the Save dialog box is created.
OFN_NODEREFERENCELINKS
9 10 11 12
13 14 15 16
548
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
The following example displays a Select File dialog box that allows multiple selection. The file types are TXT, DOC, and all files, and the initial directory is C:\Program Files\Sybase. The option flag 18 specifies that the Explorer-style dialog box is used (2^1 = 2), and the Read Only check box is hidden (2^4 = 16). The selected filenames are displayed in a MultiLineEdit control.
string docpath, docname[] integer i, li_cnt, li_rtn, li_filenum li_rtn = GetFileOpenName("Select File", & docpath, docname[], "DOC", & + "Text Files (*.TXT),*.TXT," & + "Doc Files (*.DOC),*.DOC," & + "All Files (*.*), *.*", & "C:\Program Files\Sybase", 18) IF li_rtn < 1 THEN return li_cnt = Upperbound(docname) for i=1 to li_cnt mle_selected.text += string(docpath)+"\"+(string(docname[i]))+"~r~n" next
In the following example, the dialog box has the title Open and displays text files, batch files, and INI files in the Files of Type drop-down list. The initial directory is d:\temp. The option flag 512 specifies that the old-style dialog box is used and the Network button is hidden (2^9 = 512).
// instance variables // string is_filename, is_fullname int li_fileid if GetFileOpenName ("Open", is_fullname, is_filename, & "txt", "Text Files (*.txt),*.txt,INI Files " & + "(*.ini), *.ini,Batch Files (*.bat),*.bat", & "d:\temp", 512) < 1 then return li_fileid = FileOpen (is_fullname, StreamMode!) FileRead (li_fileid, mle_notepad.text) FileClose (li_fileid) See also
549
GetFileSaveName
GetFileSaveName
Description
Displays the systems Save File dialog box with the specified file name displayed in the File name box. The user can enter a file name or select a file from the grayed list.
GetFileSaveName ( title, pathname, filename {, extension {, filter { , initdir { , aFlag } } } } ) GetFileSaveName ( title, pathname, filename [ ] {, extension {, filter { , initdir { , aFlag } } } } ) Argument title pathname Description A string whose value is the title of the dialog box. A string variable whose value is the default file name and which stores the returned path and file name. The default file name is displayed in the File name box; the user can specify another name. A string variable in which the returned file name is stored or an array of string variables in which multiple selected file names are stored. Specifying an array of string variables enables multiple selection in the dialog box. A string whose value is a 1- to 3-character default file extension. The default is no extension. A string whose value is the description of the displayed files and the file extension that you want use to select the displayed files (the filter). The format for filter is: description,*. ext The default is: "All Files (*.*),*.*" initdir (optional) aFlag (optional) A string whose value is the initial directory name. The default is the current directory. An unsigned long whose value determines which options are enabled in the dialog box. The value of each options flag is calculated as 2 to the power of (index -1), where index is the integer associated with the option. The value of the aggregate flag passed to GetOpenFileName is the sum of the individual option flags. See the table in the Usage section for GetOpenFileName for a list of options, the index associated with each option, and the options meaning.
Syntax
filename, filename[ ]
Return value
Integer. Returns 1 if it succeeds, 0 if the user clicks the Cancel button or Windows cancels the display, and -1 if an error occurs. If any arguments value is NULL, GetFileSaveName returns NULL.
Usage
If you specify a DOS-style extension and the user enters a file name with no extension, PowerBuilder appends the default extension to the file name. If you specify a file mask to act as a filter, PowerBuilder displays only files that match the mask.
550
PowerBuilder
CHAPTER 10
PowerScript Functions
For usage notes on the filter, initdir, and aFlag arguments, see the GetFileOpenName function.
Examples
These statements display the Select File dialog box. The default file extension is .DOC, the filter is all files, and the initial directory is C:\My Documents. The aFlag option 32770 specifies that an Explorer-style dialog box is used with the Read Only check box selected when the dialog box is created. If a file is selected successfully, its path displays in a SingleLineEdit control:
string ls_path, ls_file int li_rc ls_path = sle_1.Text li_rc = GetFileSaveName ( "Select File", & ls_path, ls_file, "DOC", & "All Files (*.*),*.*" , "C:\My Documents", & 32770) IF li_rc = 1 Then sle_1.Text = ls_path + "\" + ls_file End If
See also
551
GetFirstSheet
GetFirstSheet
Description Applies to Syntax
Obtains the top sheet in the MDI frame, which may or may not be active. MDI frame windows
mdiframewindow.GetFirstSheet ( ) Argument mdiframewindow Description The MDI frame window for which you want the top sheet
Return value
Window. Returns the first (top) sheet in the MDI frame. If no sheet is open in the frame, GetFirstSheet returns an invalid value. If mdiframewindow is NULL, GetFirstSheet returns NULL. To cycle through the open sheets in a frame, use GetFirstSheet and GetNextSheet. Do not use these functions in combination with GetActiveSheet.
Did GetFirstSheet return a valid window? Use the IsValid function to find out if the return value is valid. If it is not, then
Usage
no sheet is open.
Examples
This script for a menu selection returns the top sheet in the MDI frame:
window wSheet string wName wSheet = ParentWindow.GetFirstSheet() IF IsValid(wSheet) THEN // There is an open sheet wName = wsheet.ClassName() MessageBox("First Sheet is", wName) END IF
See also
GetNextSheet IsValid
552
PowerBuilder
CHAPTER 10
PowerScript Functions
GetFixesVersion
Description Applies to Syntax
Returns the fix level for the current PowerBuilder execution context. For example, at maintenance level 8.0.3, the fix version is 3. ContextInformation objects
servicereference.GetFixesVersion ( fixversion ) Argument servicereference fixversion Description Reference to the ContextInformation service instance. Integer into which the function places the fix version. This argument is passed by reference.
Call this function to determine the current fix version. This example calls the GetFixesVersion function:
String ls_name Constant String ls_currver = "8.0.3" Integer li_majver, li_minver, li_fixver ContextInformation ci this.GetContextService ("ContextInformation", ci) ci.GetMajorVersion(li_majver) ci.GetMinorVersion(li_minver) ci.GetFixesVersion(li_fixver) IF li_majver <> 8 THEN MessageBox("Error", & "Must be at Version " + ls_currver) ELSEIF li_minver <> 0 THEN MessageBox("Error", & "Must be at Version " + ls_currver) ELSEIF li_fixver <> 3 THEN MessageBox("Error", & "Must be at Version " + ls_currver) END IF
See also
553
GetFocus
GetFocus
Description Syntax Return value
GraphicObject. Returns the control that currently has focus. Returns an invalid control reference if an error occurs. Use the IsValid function to determine whether GetFocus has returned a valid control.
Examples
These statements set which_control equal to the datatype of the control that currently has focus, and then set text_value to the text property of the control:
GraphicObject which_control SingleLineEdit sle_which CommandButton cb_which string text_value which_control = GetFocus() CHOOSE CASE TypeOf(which_control) CASE CommandButton! cb_which = which_control text_value = cb_which.Text CASE SingleLineEdit! sle_which = which_control text_value = sle_which.Text CASE ELSE text_value = "" END CHOOSE
See also
IsValid SetFocus
554
PowerBuilder
CHAPTER 10
PowerScript Functions
GetFolder
Description Syntax
Integer. Returns 1 if the function succeeds, 0 if the user selects cancel (or the dialog box is closed), -1 if an error occurs.
The directory selected by the user is returned in the same variable that is passed to the folder selection dialog box. This example displays the folder contents of the Sybase directory in a folder selection dialog box. The string passed in the title argument displays above the tree view:
string ls_path = "d:\program files\sybase" integer li_result li_result = GetFolder( "my targets", ls_path ) sle_1.text=ls_path // puts the user-selected path in a SingleLineEdit box.
See also
DirectoryExists GetCurrentDirectory
555
GetGlobalProperty
GetGlobalProperty
Description Applies to Syntax
Returns the value of an SSL global property. This function is used by PowerBuilder clients connecting to EAServer. SSLServiceProvider object
sslserviceprovider.GetGlobalProperty ( property, values) Argument sslserviceprovider property Description Reference to the SSLServiceProvider service instance. The name of the SSL property for which you want to return values. For a complete list of supported SSL properties, see your EAServer documentation or the online Help for the Connection object. An array of string values for the specified SSL property.
0 -1 -3 -10 -11
Usage
Success Unknown property Property has no value An EAServer or SSL failure has occurred Bad argument list
The GetGlobalProperty function allows PowerBuilder clients that connect to EAServer through SSL to access global SSL properties. Any properties set using the SSLServiceProvider interface are global to all connections made by the client to all EAServer servers. You can override any of the global settings at the connection level by specifying them as options to the Connection object or JaguarORB object. Only clients can get and set SSL properties. Server components do not have permission to use the SSLServiceProvider service.
Examples
The following example shows the use of the GetGlobalProperty function to get the value of the sessLingerTime property:
SSLServiceProvider ssl string ls_values[] long rc ... this.GetContextService("SSLServiceProvider", ssl) rc = ssl.GetGlobalProperty("sessLingerTime", ls_values) ...
See also
SetGlobalProperty
556
PowerBuilder
CHAPTER 10
PowerScript Functions
GetHostObject
Description
Currently, host object support is implemented only in the window ActiveX when running under Internet Explorer. In this situation GetHostObject returns a reference to the IWebBrowserApp ActiveX automation server object.
Applies to Syntax
ContextInformation objects
servicereference.GetHostObject ( hostobject ) Argument servicereference hostobject Description Reference to the Context Information service instance PowerObject into which the function places a reference to the ActiveX automation server object
Call this function to obtain a reference to the context object model. If running the window ActiveX under Internet Explorer 3.0 or greater and hostobject is an uninstantiated OleObject variable, the function returns a reference to an ActiveX automation server object, which you can use to control the hosting browser. If host object support is not available, the function returns -1 and hostobject is NULL. This example calls the GetHostObject function. Ici_info is an instance variable of type ContextInformation, which has been populated using the GetContextService function; ole1 is an instance variable of type OLEObject:
Integer li_return li_return = ici_info.GetHostObject(ole1) IF li_return = 1 THEN sle_1.Text = "GetHostObject succeeded" ELSE sle_1.Text = "GetHostObject failed" cb_goback.Enabled = FALSE cb_navigate.Enabled = FALSE END IF
Examples
See also
557
GetItem
GetItem
Retrieves data associated with a specified item in ListView and TreeView controls.
To retrieve data associated with a specified ListView control item ListView control item and column TreeView item Use Syntax 1 Syntax 2 Syntax 3
Syntax 1
Description Applies to Syntax
object in a ListViewItem variable. You can retrieve properties for any ListView item with this syntax. If you do not specify a column, GetItem retrieves properties for the first column of an item. Only report views display multiple columns. To retrieve labels only, use syntax 2. You can use GetColumn to obtain column properties that are not specific to a ListView item. To change pictures and other property values associated with a ListView item, use GetItem, change the property values, and use SetItem to apply the changes back to the ListView.
558
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This example uses GetItem to move the second item in the lv_list ListView control to the fifth item. It retrieves item 2, inserts it into the ListView control as item 5, and then deletes the original item:
listviewitem l_lvi lv_list.GetItem(2, l_lvi) lv_list.InsertItem(5, l_lvi) lv_list.DeleteItem(2)
See also
GetColumn SetItem
Syntax 2
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. Stores the displayed value of the ListView column in a string variable.
To retrieve property values for a ListView item, use Syntax 1. This example gets the displayed values from column 1 and column 3 of the first row of the lv_list ListView and displays them in the sle_info SingleLineEdit control.
string ls_artist, ls_comp lv_list.GetItem(1, 1 , ls_comp) lv_list.GetItem(1, 3 , ls_artist) sle_info.text = ls_artist +" wrote " + ls_comp + "."
See also
SetItem
559
GetItem
Syntax 3
Description Applies to Syntax
Use GetItem to retrieve the state information associated with a specific item in a TreeView (such as label, handle, or picture index). After you have retrieved the information, you can use it in your application. To change a property of an item, call GetItem to assign the item to a TreeViewItem variable, change its properties, and call SetItem to copy the changes back to the TreeView. This code for the Clicked event gets the clicked item and changes it overlay picture. The SetItem function copies the change back to the TreeView:
treeviewitem tvi This.SetItem(handle, tvi) tvi.OverlayPictureIndex = 1 This.SetItem(handle, tvi)
Examples
This example tracks items in the SelectionChanged event. If there is no prior selection, the value of l_tviold is zero:
treeviewitem l_tvinew, l_tviold // Get the treeview item that was the old selection tv_list.GetItem(oldhandle, l_tviold) // Get the treeview item that is currently selected tv_list.GetItem(newhandle, l_tvinew) // Print the labels for the two items in the // SingleLineEdit sle_get.Text = "Selection changed from " & + String(l_tviold.Label) + " to " & + String(l_tvinew.Label) See also
InsertItem
560
PowerBuilder
CHAPTER 10
PowerScript Functions
GetItemAtPointer
Description Applies to Syntax Return value Usage
Gets the handle or the index of the item under the cursor. ListView controls, TreeView controls
GetItemAtPointer ( )
Long. Returns the index (ListView) or handle (TreeView) of the item under the
cursor. Returns -1 for failure. System events that select an item in a ListView or TreeView control, such as the Clicked event, already have an argument that passes the index for the ListView or the handle for the TreeView. The GetItemAtPointer function allows you to retrieve the index or handle in user events (or system events without an index or handle argument) for a ListView or TreeView control. This example places the handle of a TreeView item in a SingleLineEdit box:
integer li_index li_index= tv_1.GetItematPointer ( ) sle_1.text = string (li_index) See also
Examples
FindItem SelectItem
561
GetLastReturn
GetLastReturn
Description Applies to Syntax
Returns the return value from the last InvokePBFunction or TriggerPBEvent function. Window ActiveX controls
activexcontrol.GetLastReturn ( ) Argument activexcontrol Description Identifier for the instance of the PowerBuilder window ActiveX control. When used in HTML, the ActiveX control is the NAME attribute of the object element. When used in other environments, this references the control that contains the PowerBuilder window ActiveX.
Call this function after calling InvokePBFunction or TriggerPBEvent to access the return value. JavaScript scripts must use this function to access return values from InvokePBFunction and TriggerPBEvent. VBScript scripts can either use this function or access the return value using an argument in InvokePBFunction or TriggerPBEvent. This JavaScript example calls the GetLastReturn function:
... retcd = PBRX1.TriggerPBEvent(theEvent, numargs); rc = parseInt(PBRX1.GetLastReturn()); if (rc != 1) { alert("Error. Empty string."); } ...
Examples
562
PowerBuilder
CHAPTER 10
PowerScript Functions
GetLibraryList
Description Syntax Return value Usage Examples
You should call GetLibraryList and append any libraries you want to add to the list before updating the search path using the SetLibraryList function. This example obtains the list of libraries, adds a library to the list, then resets the list:
string ls_list, ls_newlist ls_list = getlibrarylist () ls_newlist = ls_list + ",c:\my_library.pbl" setlibrarylist (ls_newlist)
See also
AddToLibraryList SetLibraryList
563
GetMajorVersion
GetMajorVersion
Description Applies to Syntax
Returns the major version for the current PowerBuilder execution context. For example, at maintenance level 8.0.3 the major version is 8. ContextInformation objects
servicereference.GetMajorVersion ( majorversion ) Argument servicereference majorversion Description Reference to the ContextInformation service instance. Integer into which the function places the major version. This argument is passed by reference.
Call this function to determine the current major version. This example calls the GetMajorVersion function:
String ls_name Constant String ls_currver = "8.0.3" Integer li_majver, li_minver, li_fixver ContextInformation ci this.GetContextService ("ContextInformation", ci) GetMajorVersion(li_majver) ci.GetMinorVersion(li_minver) ci.GetFixesVersion(li_fixver) IF li_majver <> 8 THEN MessageBox("Error", & "Must be at Version " + ls_currver) ELSEIF li_minver <> 0 THEN MessageBox("Error", & "Must be at Version " + ls_currver) ELSEIF li_fixver <> 3 THEN MessageBox("Error", & "Must be at Version " + ls_currver) END IF
See also
564
PowerBuilder
CHAPTER 10
PowerScript Functions
GetMessage
Description Syntax
String. The error text for system error objects, such as RuntimeError, is preset.
You can set the error message for an object of type Throwable using the SetMessage function. This example catches a system error message and displays that error in a message box. Catching the system error prevents the application from terminating when the arccosine argument, entered by the application user, is not in the required range:
Double ld_num ld_num = Double (sle_1.text) TRY sle_2.text = string (acos (ld_num)) CATCH (runtimeerror er) MessageBox("Runtime Error", er.GetMessage()) END TRY
This example catches and displays a user error message from the Clicked event of a button that calls the user-defined function, wf_acos. The user-defined function catches a runtime errorpreventing the application from terminatingand then sets the message for a user object, uo_exception, that inherits from the Exception object type:
TRY wf_acos() CATCH (uo_exception u_ex) messageBox("Out of Range", u_ex.GetMessage()) END TRY
SetMessage
565
GetMinorVersion
GetMinorVersion
Description Applies to Syntax
Returns the minor version for the current PowerBuilder execution context. For example, at maintenance level 8.0.3 the minor version is 0. ContextInformation objects
servicereference.GetMinorVersion ( minorversion ) Argument servicereference minorversion Description Reference to the ContextInformation service instance. Integer into which the function places the minor version. This argument is passed by reference.
Call this function to determine the current minor version. This example calls the GetMinorVersion function:
String ls_name Constant String ls_currver = "8.0.3" Integer li_majver, li_minver, li_fixver ContextInformation ci this.GetContextService("ContextInformation", ci) ci.GetMajorVersion(li_majver) ci.GetMinorVersion(li_minver) ci.GetFixesVersion(li_fixver) IF li_majver <> 8 THEN MessageBox("Error", & "Must be at Version " + ls_currver) ELSEIF li_minver <> 0 THEN MessageBox("Error", & "Must be at Version " + ls_currver) ELSEIF li_fixver <> 3 THEN MessageBox("Error", & "Must be at Version " + ls_currver) END IF
See also
566
PowerBuilder
CHAPTER 10
PowerScript Functions
GetName
Description Applies to Syntax
Gets the name for the current execution context. ContextInformation objects
servicereference.GetName ( name ) Argument servicereference name Description Reference to the ContextInformation service instance. String into which the function places the name. This argument is passed by reference.
Return value
Integer. Returns 1 if the function succeeds and -1 if an error occurs. The function returns values as follows:
Usage Examples
PowerBuilder runtime:
PowerBuilder Runtime
Call this function to determine the current execution environment. This example calls the GetName function. ci is an instance variable of type ContextInformation:
String ls_name this.GetContextService("ContextInformation", ci) ci.GetName(ls_name) IF ls_name <> "PowerBuilder Runtime" THEN cb_close.visible = FALSE END IF
See also
567
GetNativePointer
GetNativePointer
Description Applies to Syntax
Gets a pointer to the OLE object associated with the OLE control. The pointer lets you call OLE functions in an external DLL for the object. OLE controls and OLE custom controls
olename.GetNativePointer ( pointer ) Argument olename pointer Description The name of the OLE control containing the object for which you want the native pointer. A UnsignedLong variable in which you want to store the pointer. If GetNativePointer cannot get a valid pointer, pointer is set to 0.
Pointer is a pointer to OLEs IUnknown interface. You can use it with the OLE QueryInterface function to get other interface pointers. When you call GetNativePointer, PowerBuilder calls OLEs AddRef function, which locks the pointer. You must release the pointer in your DLL function or in a PowerBuilder script with the ReleaseNativePointer function.
Only for external DLL calls
This function is only useful for external DLL calls. It is not related to the SetAutomationPointer function.
Examples
This example gets a pointer for the OLECustomControl ocx_spell for making external function calls for OLE automation:
UnsignedLong lul_oleptr integer li_rtn li_rtn = ocx_spell.GetNativePointer(lul_oleptr) IF li_rtn = 0 THEN ... // Call external functions for automation ocx_spell.ReleaseNativePointer(lul_oleptr) END IF
See also
568
PowerBuilder
CHAPTER 10
PowerScript Functions
GetNextSheet
Description Applies to Syntax
Obtains the sheet that is behind the specified sheet in the MDI frame. MDI frame windows
mdiframewindow.GetNextSheet ( sheet ) Argument mdiframewindow sheet Description The MDI frame window in which you want the next sheet The sheet for which you want the sheet that is behind it
Return value
Window. Returns the sheet that is behind sheet in the MDI frame. If there is no sheet behind sheet, GetNextSheet returns an invalid value. If any arguments value is NULL, GetNextSheet returns NULL. To cycle through the open sheets in a frame, use GetFirstSheet to get the front sheet and GetNextSheet one or more times to get the rest of the sheets. Test each return value with IsValid to see if you have reached the last sheet. Do not use GetFirstSheet and GetNextSheet in combination with GetActiveSheet.
Did GetNextSheet return a valid window? Use the IsValid function to find out if GetNextSheet returned a valid window. If
Usage
there is no sheet behind the one you specified, the return value is not valid.
Examples
The following script for a menu selection loops through the open sheets in front-to-back order and displays the names of the open sheets in the ListBox lb_sheets:
boolean bValid window wSheet lb_sheets.Reset() wSheet = ParentWindow.GetFirstSheet() IF IsValid(wSheet) THEN lb_sheets.AddItem(wSheet.Title) DO wSheet = ParentWindow.GetNextSheet(wSheet) bValid = IsValid (wSheet) IF bValid THEN lb_sheets.AddItem(wSheet.Title) LOOP WHILE bValid END IF
See also
GetFirstSheet IsValid
569
GetOrigin
GetOrigin
Description Applies to Syntax
Finds the X and Y coordinates of the upper-left corner of the ListView item. ListView controls
listviewname.GetOrigin ( x , y ) Argument listviewname x y Description The ListView control for which you want to find the coordinates of the upper-left corner An integer variable in which you want to store the X coordinate for the ListView control An integer variable in which you want to store the Y coordinate for the ListView control
Use GetOrigin to find the position of a dragged object relative to the upper left corner of a ListView control. This example moves a static text clock to the upper-left coordinates of the selected ListView item:
integer li_index listviewitem l_lvi li_index = lv_list.SelectedIndex() lv_list.GetItem(li_index, l_lvi) lv_list.GetOrigin(l_lvi.ItemX, l_lvi.ItemY) sle_info.Text = "X is "+ String(l_lvi.ItemX) & + " and Y is " + String(l_lvi.ItemY) st_clock.Move(l_lvi.itemx , l_lvi.ItemY) MessageBox("Clock Location", "X is " & + String(st_clock.X) & + ", and Y is " & + String(st_clock.Y)+".")
570
PowerBuilder
CHAPTER 10
PowerScript Functions
GetParagraphSetting
Description Applies to Syntax
Gets the size of the indentation, left margin, or right margin of the paragraph containing the insertion point in a RichTextEdit control. RichTextEdit controls
rtecontrol.GetParagraphSetting ( whichsetting ) Argument rtecontrol whichsetting Description The name of the control for which you want paragraph information. A value of the ParagraphSetting enumerated datatype specifying the setting for which you want the value. Values are: Indent! Returns the indentation of the paragraph LeftMargin! Returns the left margin of the paragraph RightMargin! Returns the right margin of the paragraph
Return value
Long. Returns the size of the specified setting in thousandths of an inch. GetParagraphSetting returns -1 if an error occurs. If whichsetting is NULL, it returns NULL.
Examples
This example gets the indentation setting for the current paragraph:
long ll_indent ll_indent = rte_1.GetParagraphSetting(Indent!))
See also
571
GetParent
GetParent
Description Applies to Syntax
PowerObject. Returns a reference to the parent of objectname. In event scripts for a user object that will be used as a tab page, you can use code like the following to make references to the parent Tab control generic:
// a_tab is generic; // it does not know about specific pages tab a_tab // a_tab_page is generic; // it does not know about specific controls userobject a_tab_page // Get values for the Tab control and the tab page a_tab = this.GetParent( ) // Somewhat redundant, for illustration only a_tab_page = this // Set properties for the tab page a_tab_page.PowerTipText = "Important property page" // Set properties for the Tab control a_tab.PowerTips = TRUE // Run Tab control functions a_tab.SelectTab(a_tab_page)
You cannot refer to controls on the user object because a_tab_page does not know about them. You cannot refer to specific pages in the Tab control because a_tab does not know about them either.
572
PowerBuilder
CHAPTER 10
PowerScript Functions
In event scripts for controls on the tab page user object, you can use two levels of GetParent to refer to the user object and the Tab control containing the user object as a tab page:
// For a control, add one more level of GetParent() // and you can make the same settings as above tab a_tab userobject a_tab_page a_tab_page = this.GetParent() a_tab = a_tab_page.GetParent() a_tab_page.PowerTipText = "Important property page" a_tab.PowerTips = TRUE a_tab.SelectTab(a_tab_page) See also
573
GetPin
GetPin
Description Applies to Syntax
Called by EAServer to obtain a PIN for use with an SSL connection. This function is used by PowerBuilder clients connecting to EAServer. SSLCallBack objects
sslcallback.GetPin ( thesessioninfo, timedout ) Argument sslcallback thesessioninfo Description An instance of a customized SSLCallBack object. A CORBAObject that contains information about the SSL session. This information can optionally be displayed to the user to provide details about the session. A boolean value that indicates the reason for the callback. A value of TRUE indicates that the PIN timed out and must be obtained again. A value of FALSE indicates that the PIN was not specified at the time of the SSL connection.
timedout
A PowerBuilder application does not usually call the GetPin function directly. GetPin is called by EAServer when an EAServer client has not specified a PIN for logging in to a PKCS 11 token for an SSL connection. To override the behavior of any of the functions of the SSLCallBack object, create a standard class user object that descends from SSLCallBack and customize this object as necessary. To let EAServer know which object to use when a callback is required, specify the name of the object in the callbackImpl SSL property. You can set this property value by calling the SetGlobalProperty function. If you do not provide an implementation of GetPin, EAServer receives the CORBA::NO_IMPLEMENT exception and an empty string is returned. To obtain a useful return value, code the function to request the user to provide a PIN. You can supply information to the user such as the token name from the passed thesessioninfo object. If an incorrect PIN or an empty string is returned, EAServer invokes the TrustVerify callback. You can enable the user to cancel the attempt to connect by throwing an exception in this callback function. All exceptions thrown in SSLCallback functions return a CTSSecurity::UserAbortedException to the server. You need to catch the exception by wrapping the ConnectToServer function in a try-catch block.
574
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This example prompts the user to enter a PIN for a new SSL session or when a session has timed out. In practice you would want to replace the users entry in the text box with asterisks and allow the user more than one attempt to enter a correct PIN:
//instance variables //string is_tokenName // SSLServiceProvider issp_jag CTSSecurity_sslSessionInfo mySessionInfo is_tokenName = mySessionInfo.getProperty( "tokenName" ) w_response w_pin IF timedout THEN MessageBox("The SSL session has expired", & "Please reenter the PIN for access to the " + & ls_tokenName + " certificate database.") ELSE MessageBox("The SSL session requires a PIN", & "Please enter the PIN for access to the " + & ls_tokenName + " certificate database.") END IF string s_PIN userabortedexception ue_cancelled // open prompt for PIN Open(w_pin) // get value entered s_PIN = Message.StringParm // set property if were not to abort if s_PIN <> ABORT_VALUE then issp_jag.setglobalproperty("pin", s_PIN) // otherwise, abort.. else ue_cancelled = CREATE userabortedexception ue_cancelled.text = "User cancelled request when " & + "asked for PIN." throw ue_cancelled end if return s_PIN
See also
575
GetRecordSet
GetRecordSet
Description Applies to Syntax
Use the GetRecordSet function to return an ADO Recordset as an OLEObject object that can be used in PowerBuilder as a native ADO Recordset. The ADOResultSet object that contains the ADO Recordset must first have been populated using the SetRecordSet or SetResultSet function. This example generates a result set in a ResultSet object from an existing DataStore object. The ResultSet object is used to populate a new ADOResultSet object. The GetRecordSet function on the ADOResultSet object is used to return an ADO Recordset as an OLEObject that can be used with ADO Recordset methods.
resultset lrs_resultset ADOresultset lrs_ADOresultset OLEObject loo_ADOrecordset // Generate a result set from an existing DataStore ds_source.GenerateResultSet(lrs_resultset) // Create a new ADOResultSet object and populate it // from the generated result set lrs_ADOresultset = CREATE ADOResultSet lrs_ADOresultset.SetResultSet(lrs_resultset) // Pass the data in the ADOResultSet object // to an OLEObject you can use as an ADO Recordset loo_ADOrecordset = CREATE OLEObject lrs_ADOresultset.GetRecordSet(loo_ADOrecordset) // Call native ADO Recordset methods on the OLEObject loo_ADOrecordset.MoveFirst()
Examples
See also
576
PowerBuilder
CHAPTER 10
PowerScript Functions
GetRemote
Asks a DDE server application to provide data and stores that data in the specified variable. There are two ways of calling GetRemote, depending on the type of DDE connection you have established.
To Make a single request of a DDE server application (called a cold link) Request data from a DDE server application after you have opened a channel (called a warm link) Use Syntax 1 Syntax 2
Syntax 1
Description
Syntax
target applname
topicname
Return value
577
GetRemote
Usage
When using DDE, your PowerBuilder application must have an open window, which will be the client window. For this syntax, the active window is the DDE client window. For more information about DDE channels and warm and cold links, see the two syntaxes of the ExecRemote function.
Examples
These statements ask Microsoft Excel to get the data in row 1 column 2 of a worksheet called PROFIT.XLS and put it in a PowerBuilder string called ls_ProfData. The single GetRemote call establishes a cold link, gets the data, and ends the link:
string ls_ProfData GetRemote("R1C2", ls_ProfData, & "Excel", "PROFIT.XLS")
See also
ExecRemote SetRemote
Syntax 2
Description
Syntax
target handle
windowhandle (optional)
578
PowerBuilder
CHAPTER 10
PowerScript Functions
Return value
are: -1 -2 -9
Usage
When using DDE, your PowerBuilder application must have an open window, which will be the client window. For this syntax, you can specify the client window with the windowhandle argument. Before using this syntax, call OpenChannel to establish a DDE channel. For more information about DDE channels and warm and cold links, see the
ExecRemote function.
Examples
These statements ask the channel identified by handle (a Microsoft Excel worksheet) to get the data in row 1 column 2 and save it in a PowerBuilder string called ls_ProfData. GetRemote utilizes the warm link established by the OpenChannel function:
String ls_ProfData long handle handle = OpenChannel("Excel", "REGION.XLS") ... GetRemote("R1C2", ls_ProfData, handle) ... CloseChannel(handle)
The following example is similar to the previous one. However, it specifically associates the DDE channel with the window w_rpt:
String ls_ProfData long handle handle = OpenChannel("Excel", "REGION.XLS", & Handle(w_rpt)) ... GetRemote("R1C2", ls_ProfData, & handle, Handle(w_rpt)) ... CloseChannel(handle, Handle(w_rpt)) See also
579
GetSeriesStyle
GetSeriesStyle
Finds out the appearance of a series in a graph. The appearance settings for individual data points can override the series settings, so the values obtained from GetSeriesStyle may not reflect the current state of the graph. There are several syntaxes, depending on what settings you want.
To Get the series colors Get the line style and width used by the series Get the fill pattern or symbol for the series Find out if the series is an overlay (a series shown as a line on top of another graph type) Use Syntax 1 Syntax 2 Syntax 3 Syntax 4
GetSeriesStyle provides information about a series. The data points in the series can have their own style settings. Use SetSeriesStyle to change the style values for a series. Use GetDataStyle to get style information for a data point and SetDataStyle to override series settings and set style information for individual
data points. The graph stores style information for properties that do not apply to the current graph type. For example, you can find out the fill pattern for a data point or a series in a two-dimensional line graph, but that fill pattern will not be visible.
Syntax 1
Description Applies to Syntax
580
PowerBuilder
CHAPTER 10
PowerScript Functions
Argument colortype
Description A value of the grColorType enumerated datatype specifying the aspect of the series for which you want the color: Foreground! Text color Background! Background color LineColor! Line color Shade! Shade (for graphs that are 3-dimensional or have solid data markers) A long variable in which you want to store the colors RGB value.
colorvariable
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. Stores in colorvariable the RGB value of the specified series and item. If any arguments value is NULL, GetSeriesStyle returns NULL.
Examples
These statements store in the variable color_nbr the text (foreground) color used for a series in the graph gr_emp_data. The series name is the text in the SingleLineEdit sle_series:
long color_nbr gr_emp_data.GetSeriesStyle(sle_series.Text, & Foreground!, color_nbr)
These statements store in the variable color_nbr the background color used for the series PCs in the graph gr_computers in the DataWindow control dw_equipment:
long color_nbr // Get the color. dw_equipment.GetSeriesStyle("gr_computers", & "PCs", Background!, color_nbr)
These statements store the color for the series under the mouse pointer in the graph gr_product_data in line_color:
string SeriesName integer SeriesNbr, Data_Point long line_color grObjectType MouseHit MouseHit = ObjectAtPointer(SeriesNbr, Data_Point) IF MouseHit = TypeSeries! THEN SeriesName = & gr_product_data.SeriesName(SeriesNbr)
581
GetSeriesStyle
Syntax 2
Description Applies to Syntax
Return value
value of the LineStyle enumerated datatype and in linewidth the width of the line used for the specified series. If any arguments value is NULL, GetSeriesStyle returns NULL.
Examples
These statements store in the variables line_style and line_width the line style and width for the series under the mouse pointer in the graph gr_product_data:
string SeriesName integer SeriesNbr, Data_Point, line_width LineStyle line_style
582
PowerBuilder
CHAPTER 10
PowerScript Functions
grObjectType MouseHit MouseHit = ObjectAtPointer(SeriesNbr, Data_Point) IF MouseHit = TypeSeries! THEN SeriesName = & gr_product_data.SeriesName(SeriesNbr) gr_product_data.GetSeriesStyle(SeriesName, & line_style, line_width) END IF See also
Syntax 3
Description Applies to Syntax
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. Stores in enumvariable a value of the appropriate enumerated datatype for the fill pattern or symbol used for the specified series. If any arguments value is NULL, GetSeriesStyle returns NULL.
583
GetSeriesStyle
Usage Examples
See SetSeriesStyle for a list of the enumerated datatype values that GetSeriesStyle stores in enumvariable. These statements store in the variable data_pattern the fill pattern for the series under the mouse pointer in the graph gr_product_data:
string SeriesName integer SeriesNbr, Data_Point FillPattern data_pattern grObjectType MouseHit MouseHit = ObjectAtPointer(SeriesNbr, Data_Point) IF MouseHit = TypeSeries! THEN SeriesName = & gr_product_data.SeriesName(SeriesNbr) gr_product_data.GetSeriesStyle(SeriesName, & data_pattern) END IF
This example stores in the variable data_pattern the fill pattern for the series under the pointer in the graph gr_depts in the DataWindow control dw_employees. It then sets the fill pattern for the series Total Salary in the graph gr_dept_data to that pattern:
string SeriesName integer SeriesNbr, Data_Point FillPattern data_pattern grObjectType MouseHit MouseHit = & ObjectAtPointer("gr_depts" , SeriesNbr, & Data_Point) IF MouseHit = TypeSeries! THEN SeriesName = & dw_employees.SeriesName("gr_depts" , SeriesNbr) dw_employees.GetSeriesStyle("gr_depts" , & SeriesName, data_pattern) gr_dept_data.SetSeriesStyle("Total Salary", & data_pattern) END IF
In these examples, you can change the datatype of data_pattern (the variable specified as the last argument) to find out the symbol type.
584
PowerBuilder
CHAPTER 10
PowerScript Functions
See also
Syntax 4
Description Applies to Syntax
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. Stores in overlayindicator TRUE if the specified series is an overlay and FALSE if it is not. If any arguments value is NULL, GetSeriesStyle returns NULL. These statements find out whether a series in the graph gr_emp_data is an overlay. The series name is the text in the SingleLineEdit sle_series:
boolean is_overlay gr_emp_data.GetSeriesStyle(sle_series.Text, & is_overlay)
Examples
585
GetShortName
GetShortName
Description Applies to Syntax
Gets the short name for the current PowerBuilder execution context. ContextInformation objects
servicereference.GetShortName ( shortname ) Argument servicereference shortname Description Reference to the ContextInformation service instance. String into which the function places the short name. This argument is passed by reference.
Return value
Integer. Returns 1 if the function succeeds and -1 if an error occurs. The function returns values as follows:
Usage Examples
PowerBuilder runtime
PBRun
Call this function to determine the current execution environment. This example calls the GetShortName function. ci is an instance variable of type ContextInformation:
String ls_name this.GetContextService("ContextInformation", ci) ci.GetShortName(ls_name) IF ls_name <> "PBRun" THEN cb_close.visible = FALSE END IF
See also
586
PowerBuilder
CHAPTER 10
PowerScript Functions
GetSpacing
Description Applies to Syntax
Obtains the line spacing of the paragraph containing the insertion point in a RichTextEdit control. RichTextEdit controls
rtename.GetSpacing ( ) Argument rtename Description The name of the RichTextEdit control in which you want to find out the line spacing of the paragraph containing the insertion point
Spacing. A value of the Spacing enumerated datatype indicating the line spacing of the paragraph containing the insertion point. When the user selects several paragraphs, the insertion point is at the beginning or end of the selection, depending on how the user made the selection. The value reported depends on the location of the insertion point. This example stores a value of the enumerated datatype spacing in the variable l_spacing. The value is the spacing for the paragraph with the insertion point:
spacing l_spacing l_spacing = rte_1.GetSpacing()
Examples
See also
587
GetStatus
GetStatus
Description Applies to Syntax
Returns the status of the EAServer transaction associated with the calling thread. CORBACurrent objects
CORBACurrent.GetStatus ( ) Argument CORBACurrent Description Reference to the CORBACurrent service instance
Return value
Integer. Returns -1 if an error occurs and one of the following positive integers
if it succeeds:
1 2 3 4 5 6 7 8 9 10 Usage
Status active Status marked rollback Status prepared Status committed Status rolled back Status unknown Status no transaction Status preparing Status committing Status rolling back
The GetStatus function can be used to determine the current status of a transaction by the client or component that initiated the transaction using the BeginTransaction function. EAServer must be using the two-phase commit transaction coordinator (OTS/XA).
GetStatus returns 1 when the transaction has started and no prepares have been
issued. When GetStatus returns 4 or 5, heuristics may exist; otherwise, the transaction would have been completed and destroyed and the value 7 returned. A return value of 6 indicates that the transaction is in a transient condition and a subsequent call will eventually return another status. I If GetStatus returns 8, 9, or 10, the transaction has begun but not yet completed the process of preparing, committing, or rolling back, probably because responses from participants in the transaction are pending.
588
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This example shows the use of GetStatus to obtain the state of the current transaction:
// Instance variable: // CORBACurrent corbcurr integer li_rc, li_status li_rc = this.GetContextService("CORBACurrent", & corbcurr) IF li_rc <> 1 THEN // handle the error END IF li_rc = corbcurr.Init( "iiop://jagserver:9000") IF li_rc <> 1 THEN // handle the error ELSE li_status = corbcurr.GetStatus() CHOOSE CASE li_status CASE 1 // take appropriate action for each value ... END CHOOSE END IF
See also
BeginTransaction CommitTransaction GetContextService GetTransactionName Init ResumeTransaction RollbackOnly RollbackTransaction SetTimeout SuspendTransaction
589
GetTextColor
GetTextColor
Description Applies to Syntax
Return value
Long. Returns the long value that specifies the color of the currently selected text. If text of different colors is selected, GetTextColor returns the color of the first selected character. GetTextColor returns -1 if an error occurs.
Examples
This example stores a long representing the color of the selected text in rte_1:
long ll_color ll_color = rte_1.GetTextColor()
See also
590
PowerBuilder
CHAPTER 10
PowerScript Functions
GetTextStyle
Description Applies to Syntax
Finds out whether selected text has text styles (such as bold or italic) assigned to it. RichTextEdit controls
rtename.GetTextStyle ( textstyle ) Argument rtename textstyle Description The name of the RichTextEdit control in which you want to find the formatting of selected text. A value of the enumerated datatype TextStyle specifying the text style you want to check for. Values are: Bold! Italic! Strikeout! Subscript! Superscript! Underlined!
Boolean. Returns TRUE if the selected text is formatted with the specified text style and FALSE if it is not. If textstyle is NULL, GetTextStyle returns NULL. Text can be formatted with more than one text style. To test for different styles, call GetTextStyle more than once. A previously defined structure is an instance variable istr_text for the current window. The structure contains the boolean fields: b_isBold, b_isItalic, and b_isUnderlined. This example checks whether the selected text has these styles and stores TRUE or FALSE values in the structure for each style:
istr_text.b_isBold = rte_fancy.GetTextStyle(Bold!) istr_text.b_isItalic = rte_fancy.GetTextStyle(Italic!) istr_text.b_isUnderlined = & rte_fancy.GetTextStyle(Underlined!)
See also
591
GetToolbar
GetToolbar
Description Applies to Syntax
Gets the current values for alignment, visibility, and title of the specified toolbar. MDI frame and sheet windows
window.GetToolbar ( toolbarindex, visible {, alignment {, floatingtitle } } ) Argument window toolbarindex visible alignment (optional) floatingtitle (optional) Description The MDI frame or sheet to which the toolbar belongs An integer whose value is the index of the toolbar for which you want the current settings A boolean variable in which you want to store a value indicating whether the toolbar is visible A variable of the ToolbarAlignment enumerated datatype in which you want to store the current alignment of the toolbar A string variable in which you want to store the toolbar title that is displayed when the alignment is Floating!
Return value
Integer. Returns 1 if it succeeds. GetToolbar returns -1 if there is no toolbar for the index you specify or if an error occurs. If any arguments value is NULL, returns NULL.
Usage Examples
To find out the position of the docked or floating toolbar, call GetToolbarPos. This example finds out whether toolbar 1 is visible. It also gets the alignment and title of toolbar 1. The values are stored in the variables lb_visible, lta_align, and ls_title:
integer li_rtn boolean lb_visible toolbaralignment lta_align li_rtn = w_frame.GetToolbar(1, lb_visible, & lta_align, ls_title)
This example displays the settings for the toolbar index the user specifies in sle_index. The IF and CHOOSE CASE statements convert the values to strings so they can be displayed in mle_toolbar:
integer li_index, li_rtn boolean lb_visible toolbaralignment lta_align string ls_visible, ls_align, ls_title
592
PowerBuilder
CHAPTER 10
PowerScript Functions
li_index = Integer(sle_index.Text) li_rtn = w_frame.GetToolbar(li_index, & lb_visible, lta_align, ls_title) IF li_rtn = -1 THEN MessageBox("Toolbars", "Cant get" & + " toolbar settings.") RETURN -1 END IF IF lb_visible = TRUE THEN ls_visible = "TRUE" ELSE ls_visible = "FALSE" END IF CHOOSE CASE lta_align CASE AlignAtTop! ls_align = "top" CASE AlignAtLeft! ls_align = "left" CASE AlignAtRight! ls_align = "right" CASE AlignAtBottom! ls_align = "bottom" CASE Floating! ls_align = "floating" END CHOOSE mle_1.Text = ls_visible + "~r~n" & + ls_align + "~r~n" & + ls_title See also
593
GetToolbarPos
GetToolbarPos
Gets position information for the specified toolbar.
To get Docking position of a docked toolbar Coordinates and size of a floating toolbar Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
offset
Return value
Integer. Returns 1 if it succeeds. GetToolbarPos returns -1 if there is no toolbar for the index you specify or if an error occurs. If any arguments value is NULL, GetToolbarPos returns NULL.
Usage
To find out whether the docked toolbar is at the top, bottom, left, or right edge of the window, call GetToolbar. Syntax 1 for GetToolbarPos gets the most recent docked position, even if the toolbar is currently floating.
Examples
In this example, the user has specified a toolbar index in sle_2. The example gets the toolbar position information and displays it in a MultiLineEdit mle_1:
integer li_index, li_rtn integer li_dockrow, li_offset
594
PowerBuilder
CHAPTER 10
PowerScript Functions
li_index = Integer(sle_2.Text) li_rtn = w_frame.GetToolbarPos(li_index, & li_dockrow, li_offset) // Report the position settings IF li_rtn = 1 THEN mle_1.Text = String(li_dockrow) + "~r~n" & + String(li_offset) ELSE mle_1.Text = "Cant get toolbar position" END IF See also
Syntax 2
Description Applies to Syntax
width
height
Return value
Integer. Returns 1 if it succeeds. GetToolbarPos returns -1 if there is no toolbar for the index you specify or if an error occurs. If any arguments value is NULL, returns NULL.
595
GetToolbarPos
Usage
To find out whether the toolbar is floating, call GetToolbar. Syntax 2 for GetToolbarPos gets the most recent floating position, even if the toolbar is currently docked.
Examples
This example gets the x and y coordinates and the width and height of toolbar 1:
int ix, iy, iw, ih, li_rtn li_rtn = w_frame.GetToolbarPos(1, ix, iy, iw, ih) IF li_rtn = -1 THEN mle_1.Text = "Cant get toolbar position" ELSE mle_1.Text = String(ix) + "~r~n" & + String(iy) + "~r~n" & + String(iw) + "~r~n" & + String(ih) END IF
See also
596
PowerBuilder
CHAPTER 10
PowerScript Functions
GetTransactionName
Description Applies to Syntax
Returns a string describing the EAServer transaction associated with the calling thread. CORBACurrent objects
CORBACurrent.GetTransactionName ( ) Argument CORBACurrent Description Reference to the CORBACurrent service instance
String. Returns a printable string describing the transaction if a transaction exists and an empty string otherwise.
The GetTransactionName function returns a string identifying the transaction associated with the calling thread. This string is typically used for debugging.
GetTransactionName can be called by a client or a component that is marked as OTS style. EAServer must be using the two-phase commit transaction coordinator (OTS/XA).
Examples
This example shows the use of GetTransactionName to return information about a transaction to a client:
// Instance variables: // CORBACurrent corbcurr string ls_transacname // Get an instance of the CORBACurrent object // and initialize it ... ls_transacname = corbcurr.GetTransactionName() MessageBox("Transaction Name", ls_transacname)
See also
BeginTransaction CommitTransaction GetContextService GetStatus Init ResumeTransaction RollbackOnly RollbackTransaction SetTimeout SuspendTransaction
597
GetURL
GetURL
Description Applies to Syntax
Return value
Call this function to access HTML source for a URL. Data references a standard class user object that descends from InternetResult and that has an overridden InternetData function. This overridden function then performs the processing you want with the returned HTML. Because the Internet returns data asynchronously, data must reference a variable that remains in scope after the function executes (such as a window-level instance variable). For more information on the InternetResult standard class user object and the InternetData function, use the PowerBuilder Browser.
Examples
This example calls the GetURL function. Iinet_base is an instance variable of type inet:
iir_msgbox = CREATE n_ir_msgbox iinet_base.GetURL(sle_url.text, iir_msgbox)
See also
598
PowerBuilder
CHAPTER 10
PowerScript Functions
GetVersionName
Description
Gets complete version information for the current PowerBuilder execution context. A complete version includes a major version, a minor version, and a fix level (such as 8.0.3). ContextInformation objects
servicereference.GetVersionName ( name ) Argument servicereference name Description Reference to the ContextInformation service instance. String into which the function places the version name. This argument is passed by reference.
Applies to Syntax
Call this function to determine the maintenance level of the current context. This example calls the GetVersionName function. ci is an instance variable of type ContextInformation:
String ls_name String ls_version Constant String ls_currver = "8.0.3" GetContextService("ContextInformation", ci) ci.GetVersionName(ls_version) IF ls_version <> ls_currver THEN MessageBox("Error", & "Must be at Version " + ls_currver) END IF
See also
599
Handle
Handle
Description Syntax
Obtains the Windows handle of a PowerBuilder object. You can get the handle of the application, a window, or a control, but not a drawing object.
Handle ( objectname {, previous } ) Argument objectname Description The name of the PowerBuilder object for which you want the handle. Objectname can be any PowerBuilder object, including an application or control, but cannot be a drawing object. A boolean indicating whether you want the handle of the previous instance of an application. Values are: FALSE (Default) Return the handle of the current instance TRUE Return the handle of the previous instance
previous (optional)
Return value
Long. Returns the handle of objectname. If objectname is an application and previous is TRUE, Handle returns 0 if there is no previous instance. If objectname cannot be referenced during execution, Handle returns 0 (for example, if objectname is a window and is not open).
Usage
Use Handle when you need an object handle as an argument to Windows Software Development Kit (SDK) functions or the PowerBuilder Send function. Use IsValid instead of the Handle function to determine whether a window is open. When you ask for the handle of the application, Handle returns 0 when you are using the PowerBuilder Run command. As far as Windows is concerned, your application does not have a handle when it is run from PowerBuilder. When you build and run an executable version of your application, the Handle function returns a valid handle for the application. When you ask for the handle of a previous instance of the application, Handle returns 0 if no other instance is running. For Windows, this is always the case when the previous flag is TRUE.
Examples
600
PowerBuilder
CHAPTER 10
PowerScript Functions
These statements use an external function in Windows called FlashWindow to change the title bar of a window to inactive and then return it to active. The external function declaration is:
function boolean flashwindow(uint hnd, boolean inst) & library "user.exe"
For applications on Windows, the Handle function does not return a useful value when the previous flag is TRUE. You can use the FindWindowA Windows function to determine whether a Windows application is already running. Declare FindWindowA as a global external function:
FUNCTION uint FindWindowA (long classname, string windowname) LIBRARY "user32.dll" &
Then add code like the following to your applications open event:
uint val val = FindWindowA(0, "MyApp Main Window") IF val > 0 THEN MessageBox("Application already running", & "MyApp is already running. You cannot & start it again") HALT CLOSE ELSE open(w_main) END IF See also
Send
601
Hide
Hide
Description
Makes an object or control invisible. Users cannot interact with an invisible object. It does not respond to any events, so the object is also, in effect, disabled. Any object
objectname.Hide ( ) Argument objectname Description The name of the object or control you want to make invisible
Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If objectname is NULL, Hide returns NULL.
If the object you want to hide is already invisible, then Hide has no effect. You cannot use Hide to hide a drop-down or cascading menu or any menu that has an MDI frame window as its parent window. Nor can you hide a window that has been opened as an MDI sheet. You can use the Disable function to disable menu items, which displays them in the disabled color and makes them inactive. To disable an object so that it does not respond to events, but is still visible, set its Enabled property. You can set an objects Visible property instead of calling Hide:
objectname.Visible = FALSE
This statement:
lb_Options.Visible = FALSE
is equivalent to:
lb_Options.Hide() Examples
In the script for a menu item, this statement hides the CommandButton cb_delete on the active sheet in the MDI frame w_mdi. The active sheets are of type w_sheet:
w_sheet w_active w_active = w_mdi.GetActiveSheet() IF IsValid(w_active) THEN w_active.cb_delete.Hide() See also
Show
602
PowerBuilder
CHAPTER 10
PowerScript Functions
Hour
Description Syntax
Obtains the hour in a time value. The hour is based on a 24-hour clock.
Hour ( time ) Argument time Description The time from which you want to obtain the hour
Integer. Returns an integer (00 to 23) whose value is the hour portion of time. If time is NULL, Hour returns NULL.
Minute Now Second Hour method for DataWindows in the DataWindow Reference or the online Help
603
HyperLinkToURL
HyperLinkToURL
Description Applies to Syntax
Opens the default Web browser, displaying the specified URL. Inet objects
servicereference.HyperlinkToURL ( url ) Argument servicereference url Description Reference to the Internet service instance String specifying the URL to open in the default Web browser
Call this function to display a URL from a PowerBuilder application. This example calls the HyperlinkToURL function. Iinet_base is an instance variable of type inet:
GetContextService("Internet", iinet_base) iinet_base.HyperlinkToURL(sle_url.text)
See also
GetURL PostURL
604
PowerBuilder
CHAPTER 10
PowerScript Functions
Idle
Description Syntax
Sets a timer so that PowerBuilder triggers an Application Idle event when there has been no user activity for a specified number of seconds.
Idle ( n ) Argument n Description The number of seconds of user inactivity allowed before PowerBuilder triggers an Application Idle event. A value of 0 terminates Idle detection.
Return value
Integer. Returns 1 if it starts the timer, and -1 if it cannot start the timer or n is
0 and the timer has not been started. Note that when the timer has been started and you change n, Idle does not start a new timer; it resets the current timer interval to the new number of seconds. If n is NULL, Idle returns NULL. The return value is usually not used.
Usage
Use Idle to shut off or restart an application when there is no user activity. This is often done for security reasons.
Idle starts a timer after each user activity (such as a keystroke or a mouse click),
and after n seconds of inactivity it triggers an Idle event. The Idle event script for an application typically closes some windows, logs off the database, and exits the application or calls the Restart function. The timer is reset when any of the following activities occur: A mouse movement or mouse click in any window of the application Any keyboard activity when a window of the PowerBuilder application is current A mouse click or any mouse movement over the icon when a PowerBuilder application is minimized Any keyboard activity when the PowerBuilder application is minimized and is current (its name is highlighted) Any retrieval on a visible DataWindow that causes the edit control to be painted
Tip
To capture movement, write script in the MouseMove or Key events of the window or sheet. (Keyboard activity does not trigger MouseMove events.) Disable the DataWindow control and tab ordering during iterative retrieves so the Idle timer is not reset.
605
Idle
Examples
This example shows how to use the Idle event to stop the application and restart it after two minutes of inactivity. This is often used for computers that provide information in a public place. Include this statement in the script for the applications Open event:
Idle(120) // Sends an Idle event after 2 minutes.
Include these statements in the script for the applications Idle event to terminate the application and then restart it:
// Statements to set the database to the desired // state ... Restart() // Restarts the application See also
Restart Timer
606
PowerBuilder
CHAPTER 10
PowerScript Functions
ImpersonateClient
Description Applies to Syntax
Allows a COM object running on MTS to take on the security attributes of the client for the duration of a call. TransactionServer objects
transactionserver.ImpersonateClient ( ) Argument transactionserver Description Reference to the TransactionServer service instance
Integer. Returns 1 if it succeeds and -1 if an error occurs. ImpersonateClient allows a COM object to run in the clients security context
for the duration of a call. Running in the client's security context gives the server process access to the same resources as the client. This can either restrict or expand the servers access to resources. For example, if the client does not have update rights to a database but the server does, impersonating the client before accessing the database prevents the client from updating the database. After completing the processing that requires the clients security context, call
RevertToSelf to revert to the servers security context.
Examples
This example creates an instance of the transaction server context object and impersonates the client to perform some processing:
TransactionServer txninfo_test integer li_rc li_rc = GetContextService( "TransactionServer", txninfo_test ) // Handle error if necessary
&
// Impersonate the client txninfo_test.ImpersonateClient() // Perform processing with client security context ... // Revert to servers security context txninfo_test.RevertToSelf() See also
607
ImportClipboard
ImportClipboard
Description
Inserts data into a DataWindow control, DataStore object, or graph control from tab-separated, comma-separated, or XML data on the clipboard. For DataWindow and DataStore syntax, see the ImportClipboard method for DataWindows in the DataWindow Reference or the online Help.
Applies to Syntax
Graph controls in windows and user objects. Does not apply to graphs within DataWindow objects, because their data comes directly from the DataWindow.
graphname.ImportClipboard ( { importtype}, { startrow {, endrow {, startcolumn } } } ) Argument importtype (optional) Description An enumerated value of the SaveAsType DataWindow constant. Valid type arguments for ImportClipboard are: Text! CSV! XML! The name of the graph control to which you want to copy data from the clipboard. The number of the first detail row in the clipboard that you want to copy. The default is 1. For default XML import, if startrow is supplied, the first N (startrow -1) elements are skipped, where N is the DataWindow row size. For template XML import, if startrow is supplied, the first (startrow -1) occurrences of the repetitive row mapping defined in the template are skipped. endrow (optional) The number of the last detail row in the clipboard that you want to copy. The default is the rest of the rows. For default XML import, if endrow is supplied, import stops when N * endrow elements have been imported, where N is the DataWindow row size. For template XML import, if endrow is supplied, import stops after endrow occurrences of the repetitive row mapping defined in the template have been imported. startcolumn (optional) The number of the first column in the clipboard that you want to copy. The default is 1. For default XML import, if startcolumn is supplied, import skips the first (startcolumn - 1) elements in each row. This argument has no effect on template XML import.
608
PowerBuilder
CHAPTER 10
PowerScript Functions
Return value
Returns the number of rows that were imported if it succeeds and one of the following negative integers if an error occurs:
-1 -2 -3 -4
No rows or startrow value supplied is greater than the number of rows in the string Input data does not match number of columns or required column type Invalid argument Invalid input formed
-11 XML Parsing Error; XML parser libraries not found, or XML not well -12 XML Template does not exist or does not match the DataWindow
If any arguments value is NULL, ImportClipboard returns NULL. If the optional importtype argument is specified and is not a valid type, ImportClipboard returns -3.
Usage
The clipboard data must be formatted in tab-separated or comma-separated columns or in XML. The datatypes and order of the DataWindow objects columns must match the data on the clipboard. For graphs, ImportClipboard uses only three columns and ignores other columns. Each row of data must contain three pieces of information. The information depends on the type of graph: For all graph types except scatter, the first column to be imported is the series name, the second column contains the category, and the third column contains the data. For scatter graphs, the first column to be imported is the series name, the second column is the datas x value, and the third column is the y value.
If a series or category already exists in the graph, the data is assigned to it. Otherwise, the series and categories are added to the graph. You can add data to more than one series by specifying different series names in the first column.
609
ImportClipboard
Examples
If the clipboard contains the data shown below and the graph does not have any data yet, then the next statement produces a graph with two series and three categories. The clipboard data is:
Sales Sales Sales Sales Sales Sales 94Jan3000 94Mar2200 94May2500 95Jan4000 95Mar3200 95May3500
This statement copies all the data in the clipboard, as shown above, to gr_employee:
gr_employee.ImportClipboard()
This statement copies the data from the clipboard starting with row 2 column 3 and copying to row 30 column 5 to the graph gr_employee:
gr_employee.ImportClipboard(2, 30, 3) See also
ImportFile ImportString
610
PowerBuilder
CHAPTER 10
PowerScript Functions
ImportFile
Description
Inserts data into a DataWindow control, DataStore object, or graph control from data in a file. The data can be tab-separated text, comma-separated text, XML, or dBase format 2 or 3. The format of the file depends on whether the target is a DataWindow (or DataStore) or a graph and on the type of graph. For DataWindow and DataStore syntax, see the ImportFile method for DataWindows in the DataWindow Reference or the online Help.
Applies to Syntax
Graph controls in windows and user objects. Does not apply to graphs within DataWindow objects, because their data comes directly from the DataWindow.
graphname.ImportFile ( { importtype}, filename {, startrow {, endrow {, startcolumn } } } ) Argument graphname importtype (optional) Description The name of the graph control to which you want to copy data from the specified file. An enumerated value of the SaveAsType DataWindow constant. If this argument is specified, the importtype argument can be specified without an extension. Valid type arguments for ImportFile are: Text! CSV! XML! DBase2! DBase3! filename A string whose value is the name of the file from which you want to copy data. The file must be an ASCII, tab-separated file (TXT), comma-separated file (CSV), Extensible ), or dBase format 2 or 3 file (DBF). Specify the files full name. If the optional importtype is not specified, the name must end in the appropriate extension. If you do not specify filename or if it is NULL, ImportFile prompts the user for a file name. The remaining arguments are ignored. The number of the first detail row in the file that you want to copy. The default is 1. For default XML import, if startrow is supplied, the first N (startrow -1) elements are skipped, where N is the DataWindow row size. For template XML import, if startrow is supplied, the first (startrow -1) occurrences of the repetitive row mapping defined in the template are skipped.
startrow (optional)
611
ImportFile
Description The number of the last detail row in the file that you want to copy. The default is the rest of the rows. For default XML import, if endrow is supplied, import stops when N * endrow elements have been imported, where N is the DataWindow row size. For template XML import, if endrow is supplied, import stops after endrow occurrences of the repetitive row mapping defined in the template have been imported.
startcolumn (optional)
The number of the first column in the file that you want to copy. The default is 1. For default XML import, if startcolumn is supplied, import skips the first (startcolumn - 1) elements in each row. This argument has no effect on template XML import.
Return value
Long. Returns the number of rows that were imported if it succeeds and one of the following negative integers if an error occurs:
-1 -2 -3 -4 -5 -6 -7 -8 -10 -11 -12
No rows or startrow value supplied is greater than the number of rows in the file Empty file or input data does not match number of columns or required column type Invalid argument Invalid input Could not open the file Could not close the file Error reading the text Unsupported file name suffix (must be *.txt, *.csv, *.dbf or *.xml) Unsupported dBase file format (not version 2 or 3) XML Parsing Error; XML parser libraries not found or XML not well formed XML Template does not exist or does not match the DataWindow
If any arguments value is NULL, ImportFile returns NULL. If the optional importtype argument is specified and is not a valid type, ImportFile returns -3.
612
PowerBuilder
CHAPTER 10
PowerScript Functions
Usage
The format of the file can be indicated by specifying the optional importtype parameter, or by including the appropriate file extension. For graph controls, ImportFile only uses three columns and ignores other columns. Each row of data must contain three pieces of information. The information depends on the type of graph: For all graph types except scatter, the first column to be imported is the series name, the second column contains the category, and the third column contains the data. For scatter graphs, the first column to be imported is the series name, the second column is the datas x value, and the third column is the y value.
You can add data to more than one series by specifying different series names in the first column. To let users select the file to import, specify a NULL string for filename. PowerBuilder displays the Select Import File dialog box. Double quotes The location and number of double quote marks in a field in a tab delimited file affect how they are handled when the file is imported. If a string is enclosed in one pair of double quotes, the quotes are discarded. If it is enclosed in three pairs of double quotes, one pair is retained when the string is imported. If the string is enclosed in two pairs of double quotes, the first pair is considered to enclose a null string, and the rest of the string is discarded. When there is a double quote at the beginning of a string, any characters after the second double quote are discarded. If there is no second double quote, the tab character delimiting the fields is not recognized as a field separator and all characters up to the next occurrence of a double quote, including a carriage return, are considered to be part of the string. A validation error is generated if the combined strings exceed the length of the first string. Double quotes after the first character in the string are rendered literally. Here are some examples of how tab-delimited strings are imported into a two-column DataWindow:
Text in file "Joe" TAB "Donaldson" Bernice TAB """Ramakrishnan""" ""Mary"" TAB ""Li"" "Mich"ael TAB """Lopes""" "Amy TAB Doherty" 3""" TAB 4" Result Joe Donaldson Bernice "Ramakrishnan" Empty cells Mich "Lopes" Amy<TAB>Doherty in first cell, second cell empty 3""" 4"
613
ImportFile
Specifying a NULL string for file name If you specify a NULL string for filename, the remaining arguments are ignored.
This statement copies all the data in the file D:\EMPLOYEE.TXT to gr_employee starting at the first row:
gr_employee.ImportFile("D:\EMPLOYEE.TXT")
This statement copies the data from the file D:\EMPLOYEE.TXT starting with row 2 column 3 and ending with row 30 column 5 to the graph gr_employee:
gr_employee.ImportFile("D:\EMPLOYEE.TXT", 2, 30, 3)
The following statements are equivalent. Both import the contents of the XML file named myxmldata:
gr_control.ImportFile(myxmldata.xml) gr_control.ImportFile(XML!, myxmldata)
This example causes PowerBuilder to display the Specify Import File dialog box:
string null_str SetNull(null_str) dw_main.ImportFile(null_str) See also
ImportClipboard ImportString
614
PowerBuilder
CHAPTER 10
PowerScript Functions
ImportString
Description
Inserts data into a DataWindow control, DataStore object, or graph control from tab-separated, comma-separated, or XML data in a string. The way data is arranged in the string in tab-delimited columns depends on whether the target is a DataWindow (or DataStore) or a graph, and on the type of graph. For DataWindow and DataStore syntax, see the ImportString method for DataWindows in the DataWindow Reference or the online Help.
Applies to Syntax
Graph controls in windows and user objects. Does not apply to graphs within DataWindow objects, because their data comes directly from the DataWindow.
graphname.ImportString ( { importtype}, string {, startrow {, endrow {, startcolumn } } } ) Argument graphname importtype (optional) Description The name of the graph control to which you want to copy data from the specified string. A value of the SaveAsType enumerated datatype (PowerBuilder) or a string (Web DataWindow) specifying the format of the imported string. Valid type arguments are: Text! CSV! XML! A string from which you want to copy the data. The string should contain tab-separated or comma-separated columns or XML with one row per line (see Usage). The number of the first detail row in the string that you want to copy. The default is 1. For default XML import, if startrow is supplied, the first N (startrow -1) elements are skipped, where N is the DataWindow row size. For template XML import, if startrow is supplied, the first (startrow -1) occurrences of the repetitive row mapping defined in the template are skipped. The number of the last detail row in the string that you want to copy. The default is the rest of the rows. For default XML import, if endrow is supplied, import stops when N * endrow elements have been imported, where N is the DataWindow row size. For template XML import, if endrow is supplied, import stops after endrow occurrences of the repetitive row mapping defined in the template have been imported.
string
startrow (optional)
endrow (optional)
615
ImportString
Description The number of the first column in the string that you want to copy. The default is 1. For default XML import, if startcolumn is supplied, import skips the first (startcolumn - 1) elements in each row. This argument has no effect on template XML import.
Return value
Returns the number of data points that were imported if it succeeds and one of the following negative integers if an error occurs:
-1 -2 -3 -4 -11 -12
No rows or startrow value supplied is greater than the number of rows in the string Empty string or input data does not match number of columns or required column type Invalid argument Invalid input XML Parsing Error; XML parser libraries not found or XML not well formed XML Template does not exist or does not match the DataWindow
If any arguments value is NULL, ImportString returns NULL. If the optional importtype argument is specified and is not a valid type, ImportString returns -3.
Usage
For graph controls, ImportString only uses three columns on each line and ignores other columns. The three columns must contain information that depends on the type of graph: For all graph types except scatter, the first column to be imported is the series name, the second column contains the category, and the third column contains the data. For scatter graphs, the first column to be imported is the series name, the second column is the datas x value, and the third column is the y value.
You can add data to more than one series by specifying different series names in the first column.
Examples
These statements copy the data from the string ls_Text starting with row 2 column 3 and ending with row 30 column 5 to the graph gr_employee:
string ls_Text ls_Text = . . . gr_employee.ImportString(ls_Text, 2, 30, 3)
616
PowerBuilder
CHAPTER 10
PowerScript Functions
The following script stores data for two series in the string ls_gr and imports the data into the graph gr_custbalance. The categories in the data are A, B, and C:
string ls_gr ls_gr ls_gr ls_gr ls_gr ls_gr ls_gr = = = = = = "series1~tA~t12~r~n" ls_gr + "series1~tB~t13~r~n" ls_gr + "series1~tC~t14~r~n" ls_gr + "series2~tA~t15~r~n" ls_gr + "series2~tB~t14~r~n" ls_gr + "series2~tC~t12.5~r~n"
ImportClipboard ImportFile
617
IncomingCallList
IncomingCallList
Description Applies to Syntax
Provides a list of the callers of a routine included in a performance analysis model. ProfileRoutine object
iinstancename.IncomingCallList ( list, aggregrateduplicateroutinecalls ) Argument instancename list Description Instance name of the ProfileRoutine object. An unbounded array variable of datatype ProfileCall in which IncomingCallList stores a ProfileCall object for each caller of the routine. This argument is passed by reference. A boolean indicating whether duplicate routine calls will result in the creation of a single or of multiple ProfileCall objects.
aggregateduplicateroutinecalls
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded ModelNotExistsError!The model does not exist
Usage
Use this function to extract a list of the callers of a routine included in a performance analysis model. Each caller is defined as a ProfileCall object and provides the called routine and the calling routine, the number of times the call was made, and the elapsed time. The callers are listed in no particular order. You must have previously created the performance analysis model from a trace file using the BuildModel function. The aggregateduplicateroutinecalls argument indicates whether duplicate routine calls will result in the creation of a single or of multiple ProfileCall objects. This argument has no effect unless line tracing is enabled and a calling routine calls the current routine from more than one line. If aggregateduplicateroutinecalls is TRUE, a new ProfileCall object is created that aggregates all calls from the calling routine to the current routine. If aggregateduplicateroutinecalls is FALSE, multiple ProfileCall objects are returned, one for each line from which the calling routine called the called routine.
618
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This example gets a list of the routines included in a performance analysis model and then gets a list of the routines that called each routine:
Long ll_cnt ProfileCall lproc_call[] lpro_model.BuildModel() lpro_model.RoutineList(i_routinelist) FOR ll_cnt = 1 TO UpperBound(iprort_list) iprort_list[ll_cnt].IncomingCallList(lproc_call, & TRUE) ... NEXT
See also
BuildModel OutgoingCallList
619
Init
Init
Sets ORB property values or initializes an instance of the CORBACurrent service object.
To Set ORB property values for client connections to EAServer using the JaguarORB object Initialize an instance of the CORBACurrent service object for client- or component-managed transactions Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
Long. Returns 0 if it succeeds and a negative number if an error occurs. ORB properties configure settings required by the EAServer ORB driver. You do not need to call the Init function to use the JaguarORB object. If you do not call Init, the EAServer ORB driver uses the default property values. The Init function can be called multiple times on the same JaguarORB object. PowerBuilder creates a new internal instance of the JaguarORB object the first time and uses this object for all subsequent calls. For additional examples, see the functions on the See also list.
620
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
The following example shows the use of the Init function to set the RetryCount and RetryDelay ORB properties:
JaguarORB my_orb CORBAObject my_corbaobj ... ... my_orb = CREATE JaguarORB my_orb.Init("ORBRetryCount=3,ORBRetryDelay=1000") ... ...
See also
Syntax 2
Description Applies to Syntax
URL
Return value
Integer. Returns 0 if it succeeds and one of the following values if the service object could not be initialized:
-1 -2 -3 -4 -5
Unknown error Service object not running in EAServer (no argument) or Connection object not connected to EAServer (argument is Connection object) ORB initialization error Error on a call to the ORB.resolve_initial_references("TransactionCurrent") method Error on a call to the narrow method
621
Init
Usage
The Init function can be called from a PowerBuilder component running in EAServer whose transaction property is marked as OTS style, or by a PowerBuilder client. The Init function must be called to initialize the CORBACurrent object before any other functions are called. EAServer must be using the two-phase commit transaction coordinator (OTS/XA) and a reference to the CORBACurrent object must first be obtained using the GetContextService function. When Init is called from a PowerBuilder component running in EAServer, no arguments are required. If the calling component is not marked as OTS style, the CORBACurrent object is not initialized. When Init is called from a PowerBuilder client and the client is responsible for the transaction, the CORBACurrent object must be initialized by calling Init with either a Connection object or a URL string as the argument. In the case of a Connection object, the client must already be connected to a valid EAServer host using that Connection object. Using a Connection object is preferred because the code is more portable.
Examples
This example shows the use of Init in a PowerBuilder EAServer component to initialize an instance of the CORBACurrent object:
// Instance variables: // CORBACurrent corbcurr int li_rc li_rc = this.GetContextService("CORBACurrent", corbcurr) IF li_rc <> 1 THEN // handle the error ELSE li_rc = corbcurr.init() IF li_rc <> 0 THEN // handle the error END IF END IF
In this example, Init is called by a PowerBuilder client application that has already connected to EAServer using the myconn Connection object and has created a reference called corbcurr to the CORBACurrent object:
li_rc = corbcurr.init( myconn ) IF li_rc <> 0 THEN // handle the error END IF
622
PowerBuilder
CHAPTER 10
PowerScript Functions
In this example, the PowerBuilder client application calls the Init function using a valid URL:
li_rc = corbcurr.init( "iiop://localhost:9000" ) IF li_rc <> 0 THEN // handle the error END IF See also
BeginTransaction CommitTransaction GetContextService GetStatus GetTransactionName ResumeTransaction RollbackOnly RollbackTransaction SetTimeout SuspendTransaction
623
InputFieldChangeData
InputFieldChangeData
Description Applies to Syntax
Modifies the data value of input fields in a RichTextEdit control. RichTextEdit controls
rtename.InputFieldChangeData ( inputfieldname, inputfieldvalue ) Argument rtename inputfieldname Description The name of the RichTextEdit control in which you want to change the data in the specified input fields. A string whose value is the name of input fields whose value you want to change. There can be more than one input field with a given name. A string whose value is the data to be assigned to the specified input fields.
inputfieldvalue
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, InputFieldChangeData returns NULL.
All the input fields that have the same name contain the same data. When you call InputFieldChangeData, you affect all the fields of the specified name. This script is part of the SelectionChanged event for the ListBox lb_instruments. When the user clicks on an item in the ListBox, the selected instrument name is assigned to the input field called instrument in the RichTextEdit rte_1:
integer rtn rtn = rte_1.InputFieldChangeData & ("instrument", lb_instruments.SelectedItem()) st_status.Text = String(rtn)
If the text in rte_1 looks like this: Dear {title} {lastname}: Were happy you have rented a {instrument} for your child. Please perform regular maintenance for the {instrument} as instructed by your childs teacher. You can buy {instrument} supplies and instruction books at your local music stores.
624
PowerBuilder
CHAPTER 10
PowerScript Functions
Then after the user picks trumpet in the ListBox, the script inserts trumpet for every occurrence of the {instrument} field. The other fields are not affected: Dear {title} {lastname}: Were happy you have rented a trumpet for your child. Please perform regular maintenance for the trumpet as instructed by your childs teacher. You can buy trumpet supplies and instruction books at your local music stores.
See also
625
InputFieldCurrentName
InputFieldCurrentName
Description Applies to Syntax
Gets the name of the input field when the insertion point is in an input field in a RichTextEdit control. RichTextEdit controls
rtename.InputFieldCurrentName ( ) Argument rtename Description The name of the RichTextEdit control in which you want to get the input fields name
String. Returns the name of the input field. If the insertion point is not in an input field or if an error occurs, it returns the empty string (""). This example gets the name of the input field containing the insertion point:
string ls_inputname ls_inputname = rte_1.InputFieldCurrentName()
See also
626
PowerBuilder
CHAPTER 10
PowerScript Functions
InputFieldDeleteCurrent
Description Applies to Syntax
Deletes the input field that is selected in a RichTextEdit control. RichTextEdit controls
rtename.InputFieldDeleteCurrent ( ) Argument rtename Description The name of the RichTextEdit control in which you want to delete the input field that is selected
Integer. Returns 1 if it succeeds and -1 if there is no input field at the insertion point, the input field is activated for editing, or an error occurs.
All the input fields that have the same name contain the same data but they can be deleted independently. If one of a group of input fields with the same name is deleted, the others are not affected. If all the input fields of the same name are deleted, the RichTextEdit control remembers the data from those input fields. It will use that data to initialize a new input field that has the same name as the deleted fields. The input field must be the only selection. If other text is selected too, InputFieldDeleteCurrent fails. When an input field is the current and only selection, the highlight flashes. InputFieldDeleteCurrent deletes only the current field. Other fields with the same name within the document are not affected. If the RichTextEdit control uses the DataSource function to share data with a DataWindow, the current field is deleted from all instances of the document.
Examples
This example deletes the input field containing the insertion point:
integer li_rtn li_rtn = rte_1.InputFieldDeleteCurrent()
See also
627
InputFieldGetData
InputFieldGetData
Description Applies to Syntax
Get the data in the specified input field in a RichTextEdit control. RichTextEdit controls
rtename.InputFieldGetData ( inputfieldname ) Argument rtename inputfieldname Description The name of the RichTextEdit control in which you want to get data from the selected input field A string whose value is the name of input field from which you want to get the data
String. The data in the input field. InputFieldGetData returns the empty string ("") if the field does not exist or an error occurs.
See also
628
PowerBuilder
CHAPTER 10
PowerScript Functions
InputFieldInsert
Description Applies to Syntax
Inserts a named input field at the insertion point in a RichTextEdit control. RichTextEdit controls
rtename.InputFieldInsert ( inputfieldname ) Argument rtename inputfieldname Description The name of the RichTextEdit control in which you want to insert an input field A string whose value is the name of input field to be inserted. The name does not have to be unique
Integer. Returns 1 if it succeeds and -1 if an error occurs. If inputfieldname is NULL, InputFieldInsert returns NULL.
There can be several input fields with the same name. Fields of a given name all have the same data value. When you call InputFieldChangeData for a named input field, all fields with that name are changed. If there is a selection, InputFieldInsert inserts the field at the beginning of the selection. The input field and the selection remain selected:
st_status.Text = String( & rte_1.InputFieldInsert("lastname"))
Examples
See also
629
InputFieldLocate
InputFieldLocate
Description Applies to Syntax
Locates an input field in a RichTextEdit control and moves the insertion point there. RichTextEdit controls
rtename.InputFieldLocate ( location {, inputfieldname } ) Argument rtename location Description The name of the RichTextEdit control in which you want to locate an input field. A value of the Location enumerated datatype that specifies the occurrence of the input field you want to locate. Values are: First! The first occurrence in the document of inputfieldname, or if no name is specified, the first input field in the document Last! The last occurrence in the document of inputfieldname, or if no name is specified, the last input field in the document Next! The occurrence of inputfieldname that is after the insertion point, or if no name is specified, the next input field of any name after the insertion point Prior! The occurrence of inputfieldname before the insertion point, or if no name is specified, the next input field of any name before the insertion point inputfieldname A string whose value is the name of the input field you want to locate. If there are multiple occurrences of inputfieldname in the control, location specifies the one to be located.
Return value
String. Returns the name of the input field it located if it succeeds. InputFieldLocate returns an empty string if no matching input field is found or if an error occurs. If any argument is NULL, InputFieldLocate returns NULL.
Usage Examples
There can be several input fields with the same name. Fields of a given name all have the same data value. This example locates the next input field after the insertion point. If found, ls_name is set to the name of the input field:
string ls_name ls_name = rte_1.InputFieldLocate(Next!)
630
PowerBuilder
CHAPTER 10
PowerScript Functions
This example locates the last occurrence in the document of the input field named address. If found, ls_name is set to the value "address":
string ls_name ls_name = rte_1.InputFieldLocate(Last!, "address") See also
631
InsertCategory
InsertCategory
Description Applies to Syntax
Inserts a category on the category axis of a graph at the specified position. Existing categories are renumbered to keep the category numbering sequential. Graph controls in windows and user objects. Does not apply to graphs within DataWindow objects, because their data comes directly from the DataWindow.
controlname.InsertCategory ( categoryvalue, categorynumber ) Argument controlname categoryvalue Description The name of the graph into which you want to insert a category. A value that is the category you want to insert. The category must be unique within the graph. The value you specify must be the same datatype as the datatype of the category axis. The number of the category before which you want to insert the new category. To add the category at the end, specify 0. If the axis is sorted, the category will be integrated into the existing order, ignoring categorynumber.
categorynumber
Return value
occurs. If the category already exists, it returns the number of the existing category. If any arguments value is NULL, InsertCategory returns NULL.
Usage
Categories are discrete. Even on a date or time axis, each category is separate with no timeline-style connection between categories. Only scatter graphs, which do not have discrete categories, have a continuous category axis. When the axis datatype is string, category names are unique if they have different capitalization. Also, you can specify the empty string ("") as the category name. However, because category names must be unique, there can be only one category with that name. When you use InsertCategory to create a new category, there will be holes in each of the series for that category. Use AddData or InsertData to create data points for the new category.
Equivalent syntax If you want to add a category to the end of a series, you can use AddCategory instead, which requires fewer arguments.
This statement:
gr_data.InsertCategory("Qty", 0)
is equivalent to:
gr_data.AddCategory("Qty")
632
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
These statements insert a category called Macs before the category named PCs in the graph gr_product_data:
integer CategoryNbr // Get the number of the category. CategoryNbr = FindCategory("PCs") gr_product_data.InsertCategory("Macs", CategoryNbr)
In a graph reporting mail volume in the afternoon, these statements add three categories to a time axis. If the axis is sorted, the order in which you add the categories does not matter:
catnum = gr_mail.InsertCategory(13:00, 0) catnum = gr_mail.InsertCategory(12:00, 0) catnum = gr_mail.InsertCategory(13:00, 0) See also
633
InsertClass
InsertClass
Description Syntax
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -9
Classnames are stored in the Registration database. Examples of classnames include: Excel.Sheet Excel.Chart Word.Document
Examples
This example inserts an empty Excel spreadsheet into the OLE control, ole_1:
integer result result = ole_1.InsertClass("excel.sheet")
See also
634
PowerBuilder
CHAPTER 10
PowerScript Functions
InsertColumn
Description Applies to Syntax
Inserts a column with the specified label, alignment, and width at the specified location. ListView controls
listviewname.InsertColumn ( index, label, alignment, width ) Argument listviewname index label alignment Description The name of the ListView control to which you want to insert a column. An integer whose value is the number of the column before which you are inserting a new column. A string whose value is the name of the column you are inserting. A value of the enumerated datatype Alignment specifying the alignment of the column you are inserting. Values are: Center! Justify! Left! Right! width An integer whose value is the width of the column you are inserting, in PowerBuilder units.
Integer. Returns the column index value if it succeeds and -1 if an error occurs.
You can insert a column anywhere in the control. If the index you specify is greater than the current number of columns, the column is inserted after the last column. This example inserts a column named Location, makes it right-aligned, and sets the column width to 300:
lv_list.InsertColumn(2 , "Location" , Right! , 300)
Examples
See also
AddColumn DeleteColumn
635
InsertData
InsertData
Description Applies to Syntax
Inserts a data point in a series of a graph. You can specify the category for the data point or its position in the series. Does not apply to scatter graphs. Graph controls in windows and user objects. Does not apply to graphs within DataWindow objects, because their data comes directly from the DataWindow.
controlname.InsertData ( seriesnumber, datapoint, datavalue {, categoryvalue } ) Argument controlname seriesnumber datapoint datavalue categoryvalue (optional) Description The name of the graph in which you want to insert data into a series. The number that identifies the series in which you want to insert data. The number of the data point before which you want to insert the data. The value of the data point you want to insert. The category for this data value on the category axis. The datatype of categoryvalue should match the datatype of the category axis. In most cases, you should include categoryvalue. Otherwise, an uncategorized value will be added to the series.
Integer. Returns the number of the data value if it succeeds and -1 if an error occurs. If any arguments value is NULL, InsertData returns NULL.
When you specify datapoint without specifying categoryvalue, InsertData inserts the data point in the category at that position, shifting existing data points to the following categories. The shift may cause there to be uncategorized data points at the end of the axis. When you specify categoryvalue, InsertData ignores the position in datapoint and puts the data point in the specified category, replacing any data value that is already there. If the category does not exist, InsertData creates the category at the end of the axis. To modify the value of a data point at a specified position, use ModifyData.
Scatter graphs
636
PowerBuilder
CHAPTER 10
PowerScript Functions
Equivalent syntax
If you want to add a data point to the end of a series or to an existing category in a series, you can use AddData instead, which requires fewer arguments.
indicate a position for inserting or modifying data. However, they behave the same as AddData when you specify a position of 0 and a category. All three modify the value of a data point when the category already exists. All three insert a category with a data value at the end of the axis when the category does not exist. When you specify a position as well as a category, and that category already exists, InsertData ignores the position and modifies the data of the specified category, but ModifyData changes the category label at that position. This statement:
gr_data.InsertData(1, 0, 44, "Qty")
is equivalent to:
gr_data.ModifyData(1, 0, 44, "Qty")
When you specify a position, the following statements are not equivalent:
InsertData ignores the position and modifies the data value of the Qty
category:
gr_data.InsertData(1, 4, 44, "Qty")
ModifyData changes the category label and the data value at position 4:
Assuming the category label Jan does not already exist, these statements insert a data value in the series named Costs before the data point for Mar and assign the data point the category label Jan in the graph gr_product_data:
integer SeriesNbr, CategoryNbr // Get the numbers of the series and category. SeriesNbr = gr_product_data.FindSeries("Costs") CategoryNbr = gr_product_data.FindCategory("Mar") gr_product_data.InsertData(SeriesNbr, & CategoryNbr, 1250, "Jan")
637
InsertData
These statements insert the data value 1250 after the data value for Apr in the series named Revenues in the graph gr_product_data. The data is inserted in the category after Apr, and the rest of the data, if any, moves over a category:
integer SeriesNbr, CategoryNbr // Get the number of the series and category. CategoryNbr = gr_product_data.FindCategory("Apr") SeriesNbr = gr_product_data.FindSeries("Revenues") gr_product_data.InsertData(SeriesNbr, & CategoryNbr + 1, 1250) See also
638
PowerBuilder
CHAPTER 10
PowerScript Functions
InsertDocument
Description
Inserts a rich text format or plain text file into a RichTextEdit control, DataWindow control, or DataStore object. The new content is added in one of two ways: The new content can be inserted at the insertion point. The new content can replace all existing content.
Applies to Syntax
filename
clearflag
filetype (optional)
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, InsertDocument returns NULL.
When the control supports headers and footer (the HeaderFooter property is set to TRUE), inserting a document affects existing header and footer text. If clearflag is set to FALSE, header and footer text from the inserted document is added to existing header and footer text.
639
InsertDocument
Not all RTF formatting is supported. PowerBuilder supports version 1.2 of the RTF standard, except for the following: No support for formatted tables No drawing objects No double-underline
This example inserts a document into rte_1 and reports the return value in a StaticText control:
integer rtn rtn = rte_1.InsertDocument("c:\pb\test.rtf", & TRUE, FileTypeRichText!) st_status.Text = String(rtn)
See also
640
PowerBuilder
CHAPTER 10
PowerScript Functions
InsertFile
Description Syntax
Inserts an object into an OLE control. A copy of the specified file is embedded in the OLE object.
olecontrol.InsertFile ( filename ) Argument olecontrol filename Description The name of the OLE control. A string whose value is the name of the file whose contents you want to be the data in the embedded OLE object. Filename should include the files path.
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -9
The contents of the specified file is embedded in the OLE object. There is no further link between the object in PowerBuilder and the file. This example creates a new OLE object in the control ole_1. It is an Excel object and contains data from the spreadsheet EXPENSE.XLS:
integer result result = ole_1.InsertFile("c:\xls\expense.xls")
See also
641
InsertItem
InsertItem
Inserts an item into a ListBox, DropDownListBox, ListView or TreeView control.
To insert an item into a ListBox or DropDownListBox control PictureListBox or DropDownPictureListBox control ListView control when only the label and picture index need to be specified ListView control when more than the label and picture index need to be specified TreeView control when only the label and picture index need to be specified TreeView control when more than the label and picture index need to be specified Use Syntax 1 Syntax 2 Syntax 3 Syntax 4 Syntax 5 Syntax 6
Syntax 1
Description Applies to Syntax
Integer. Returns the final position of the item. Returns -1 if an error occurs. If any arguments value is NULL, InsertItem returns NULL. InsertItem inserts the new item before the item identified by index. If the items in listboxname are sorted (its Sorted property is TRUE), PowerBuilder resorts
the items after the new item is inserted. The return value reflects the new items final position in the list.
AddItem and InsertItem do not update the Items property array. You can use
642
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This statement inserts the item Run Application before the fifth item in lb_actions:
lb_actions.InsertItem("Run Application", 5)
If the Sorted property is FALSE, the statement above returns 5 (the previous item 5 becomes item 6). If the Sorted property is TRUE, the list is sorted after the item is inserted and the function returns the index of the final position of the item. If the ListBox lb_Cities has the following items in its list and its Sorted property is set to TRUE, then the following example inserts Denver at the top, sorts the list, and sets li_pos to 4. If the ListBoxs Sorted property is FALSE, then the statement inserts Denver at the top of the list and sets li_pos to 1. The list is:
Albany Boston Chicago New York
Syntax 2
Description Applies to Syntax
643
InsertItem
Argument index
Description The number of the item in the list before which you want to insert the item
Integer. Returns the final position of the item. Returns -1 if an error occurs. If any arguments value is NULL, InsertItem returns NULL.
If you do not specify a picture index, the newly added item will not have a picture. If you specify a picture index that does not exist, that number is still stored with the picture. If you add pictures to the picture array so that the index becomes valid, the item will then show the corresponding picture. For additional notes about items in ListBoxes and examples of how the Sorted property affects the item order, see Syntax 1.
Examples
This statement inserts the item Run Application before the fifth item in lb_actions. The item has no picture assigned to it:
plb_actions.InsertItem("Run Application", 5)
This statement inserts the item Run Application before the fifth item in lb_actions and assigns it picture index 4:
plb_actions.InsertItem("Run Application", 4, 5) See also
Syntax 3
Description Applies to Syntax
644
PowerBuilder
CHAPTER 10
PowerScript Functions
Argument pictureindex
Description An integer whose value is the index number of the picture of the item you are adding
If you need to set more than the label and picture index, use Syntax 4. This example inserts an item in the ListView in position 11:
lv_list.InsertItem(11 , "Presentation" , 1)
See also
AddItem
Syntax 4
Description Applies to Syntax
The index you specify is the position of the item you are adding to a ListView. If you need to insert just the label and picture index into the ListView control, use Syntax 3.
Examples
This example moves a ListView item from the second position into the fifth position. It uses GetItem to retrieve the state information from item 2, inserts it into the ListView control as item 5, and then deletes the original item:
listviewitem l_lvi lv_list.GetItem(2 , l_lvi) lv_list.InsertItem(5 , l_lvi) lv_list.DeleteItem(2)
See also
AddItem
645
InsertItem
Syntax 5
Description Applies to Syntax
Long. Returns the handle of the inserted item if it succeeds and -1 if an error occurs.
Use this syntax to set just the label and picture index. Use the next syntax if you need to set additional properties for the item. If the TreeViews SortType property is set to a value other than Unsorted!, the inserted item is sorted with its siblings. If you are inserting the first child of an item, use InsertItemLast or InsertItemFirst instead. Those functions do not require a handleafter value.
Examples
This example inserts a TreeView item that is on the same level as the current TreeView item. It uses FindItem to get the current item and its parent, then inserts the new item beneath the parent item:
long ll_tvi, ll_tvparent ll_tvi = tv_list.FindItem(currenttreeitem! , 0) ll_tvparent = tv_list.FindItem(parenttreeitem!,ll_tvi) tv_list.InsertItem(ll_tvparent,ll_tvi,"Hindemith", 2)
See also
GetItem
646
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 6
Description Applies to Syntax
Long. Returns the handle of the item inserted if it succeeds and -1 if an error
occurs. Use the previous syntax to set just the label and picture index. Use this syntax if you need to set additional properties for the item. If the TreeViews SortType property is set to a value other than Unsorted!, the inserted item is sorted with its siblings. If you are inserting the first child of an item, use InsertItemLast or InsertItemFirst instead. Those functions do not require a handleafter value.
Examples
This example inserts a TreeView item that is on the same level as the current TreeView item. It uses FindItem to get the current item and its parent, then inserts the new item beneath the parent item:
long ll_tvi, ll_tvparent ll_tvi = tv_list.FindItem(currenttreeitem!, 0) ll_tvparent = tv_list.FindItem(parenttreeitem!,ll_tvi) tv_list.InsertItem(ll_tvparent,ll_tvi,"Hindemith")
See also
GetItem
647
InsertItemFirst
InsertItemFirst
Inserts an item as the first child of a parent item.
To insert an item as the first child of its parent When you only need to specify the item label and picture index When you need to specify more than the item label and picture index Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
Long. Returns the handle of the item inserted if it succeeds and -1 if an error occurs.
648
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 2
Description Applies to Syntax
Long. Returns the handle of the item inserted if it succeeds and -1 if an error
occurs. If SortType is anything except Unsorted!, items are sorted after they are added and the TreeView is always in a sorted state. Therefore, calling InsertItemFirst, InsertItemLast, and InsertItemSort produces the same result. This example inserts the current item as the first item beneath the root item in a TreeView control:
long ll_handle, ll_roothandle treeviewitem l_tvi ll_handle = tv_list.FindItem(CurrentTreeItem!, 0) ll_roothandle = tv_list.FindItem(RootTreeItem!, 0) tv_list.GetItem(ll_handle , l_tvi) tv_list.InsertItemFirst(ll_roothandle, l_tvi) See also
Examples
649
InsertItemLast
InsertItemLast
Inserts an item as the last child of a parent item.
To insert an item as the last child of its parent When you only need to specify the item label and picture index When you need to specify more than item label and picture index Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
Long. Returns the handle of the item inserted if it succeeds and -1 if an error occurs.
If more than the item label and Index need to be specified, use syntax 2. If SortType is anything except Unsorted!, items are sorted after they are added and the TreeView is always in a sorted state. Therefore, calling InsertItemFirst, InsertItemLast, and InsertItemSort produces the same result.
Examples
This example populates the first three levels of a TreeView using InsertItemLast:
long int ll_lev1, ll_lev2, ll_lev3, ll_lev4 index
tv_list.PictureHeight = 32 tv_list.PictureWidth = 32
650
PowerBuilder
CHAPTER 10
PowerScript Functions
ll_lev1 = tv_list.InsertItemLast(0,"Composers",1) ll_lev2 = tv_list.InsertItemLast(ll_lev1, & "Beethoven",2) ll_lev3 = tv_list.InsertItemLast(ll_lev2, & "Symphonies",3) FOR index = 1 to 9 ll_lev4 = tv_list.InsertItemSort(ll_lev3, & "Symphony # " String(index), 4) NEXT tv_list.ExpandItem(ll_lev3) tv_list.ExpandItem(ll_lev4) See also
Syntax 2
Description Applies to Syntax
Long. Returns the handle of the item inserted if it succeeds and -1 if an error
occurs. If SortType is anything except Unsorted!, items are sorted after they are added and the TreeView is always in a sorted state. Therefore, calling InsertItemFirst, InsertItemLast, and InsertItemSort produces the same result.
651
InsertItemLast
Examples
This example inserts the current item as the last item beneath the root item in a TreeView control:
long ll_handle, ll_roothandle treeviewitem l_tvi ll_handle = tv_list.FindItem(CurrentTreeItem!, 0) ll_roothandle = tv_list.FindItem(RootTreeItem!, 0) tv_list.GetItem(ll_handle , l_tvi) tv_list.InsertItemLast(ll_roothandle, l_tvi)
See also
652
PowerBuilder
CHAPTER 10
PowerScript Functions
InsertItemSort
Inserts a child item in sorted order under the parent item.
To insert an item in sorted order When you only need to specify the item label and picture index When you need to specify more than the item label and picture index Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
Long. Returns the handle of the item inserted if it succeeds and -1 if an error
occurs. If SortType is anything except Unsorted!, the TreeView is always in a sorted state and you do not need to use InsertItemSortyou can use any insert function. If SortType is Unsorted!, InsertItemSort attempts to insert the item at the correct place in alphabetic ascending order. If the list is out of order, it does its best to find the correct place, but results may be unpredictable.
Examples
653
InsertItemSort
ll_lev1 = tv_list.InsertItemLast(0,"Composers",1) ll_lev2 = tv_list.InsertItemLast(ll_lev1,& "Beethoven",2) ll_lev3 = tv_list.InsertItemLast(ll_lev2,& "Symphonies",3) FOR index = 1 to 9 ll_lev4 = tv_list.InsertItemSort(ll_lev3, & "Symphony # " + String(index), 4) NEXT tv_list.ExpandItem(ll_lev3) tv_list.ExpandItem(ll_lev4) See also
Syntax 2
Description Applies to Syntax
Long. Returns the handle of the item inserted if it succeeds and -1 if an error occurs.
If SortType is anything except Unsorted!, the TreeView is always in a sorted state and you do not need to use InsertItemSortyou can use any insert function. If SortType is Unsorted!, InsertItemSort attempts to insert the item at the correct place in alphabetic ascending order. If the list is out of order, it does its best to find the correct place, but results may be unpredictable.
654
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This example inserts the current item beneath the root item in a TreeView control and sorts it according to its label:
long ll_handle, ll_roothandle treeviewitem l_tvi ll_handle = tv_list.FindItem(CurrentTreeItem!, 0) ll_roothandle = tv_list.FindItem(RootTreeItem!, 0) tv_list.GetItem(ll_handle , l_tvi) tv_list.InsertItemSort(ll_roothandle, l_tvi)
See also
655
InsertObject
InsertObject
Description Syntax
Displays the standard Insert Object dialog box, allowing the user to choose a new or existing OLE object, and inserts the selected object in the OLE control.
olecontrol.InsertObject ( ) Argument olecontrol Description The name of the OLE control in which you want to insert an object
Return value
Integer. Returns 0 if it succeeds and one of the following values if an error occurs:
1 User canceled out of dialog box -9 Error If any arguments value is NULL, InsertObject returns NULL.
Examples
This example displays the standard Insert Object dialog box so that the user can select an OLE object. InsertObject inserts the selected object in the ole_1 control:
integer result result = ole_1.InsertObject()
See also
656
PowerBuilder
CHAPTER 10
PowerScript Functions
InsertPicture
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If filename is NULL, InsertPicture returns NULL.
If there is a selection, InsertPicture inserts the bitmap at the beginning of the selection. The bitmap and the selection remain selected. This example inserts a BMP file at the insertion point in the RichTextEdit control rte_1:
integer li_rtn li_rtn = rte_1.InsertPicture("c:\windows\earth.bmp")
See also
InputFieldInsert InsertDocument
657
InsertSeries
InsertSeries
Description Applies to Syntax
Inserts a series in a graph at the specified position. Existing series in the graph are renumbered to keep the numbering sequential. Graph controls in windows and user objects. Does not apply to graphs within DataWindow objects, because their data comes directly from the DataWindow.
controlname.InsertSeries ( seriesname, seriesnumber ) Argument controlname seriesname seriesnumber Description The name of the graph in which you want to insert a series. A string containing the name of the series you want to insert. The series name must be unique within the graph. The number of the series before which you want to insert the new series. To add the new series at the end, specify 0.
Return value
Integer. Returns the number of the series if it succeeds and -1 if an error occurs. If the series named in seriesname exists already, it returns the number of the existing series. If any arguments value is NULL, InsertSeries returns NULL.
Usage
This statement:
gr_data.InsertSeries("Costs", 0)
is equivalent to:
gr_data.AddSeries("Costs") Examples
These statements insert a series before the series named Income in the graph gr_product_data:
integer SeriesNbr // Get the number of the series. SeriesNbr = FindSeries("Income") gr_product_data.InsertSeries("Costs", SeriesNbr)
See also
658
PowerBuilder
CHAPTER 10
PowerScript Functions
Int
Description Syntax
Return value
Integer. Returns the largest whole number less than or equal to n. If n is too small or too large to be represented as an integer, Int returns 0. If n is NULL, Int returns NULL.
Usage Examples
When the result for Int would be smaller than -32768 or larger than 32767, Int returns 0 because the result cannot be represented as an integer. These statements return 3.0:
Int(3.2) Int(3.8)
These statements remove the decimal portion of the variable and store the resulting integer in li_nbr:
integer li_nbr li_nbr = Int(3.2) // li_nbr = 3 See also
Ceiling Round Truncate Int method for DataWindows in the DataWindow Reference or the online Help
659
Integer
Integer
Description Syntax
Converts the value of a string to an integer or obtains an integer value that is stored in a blob.
Integer ( stringorblob ) Argument stringorblob Description A string whose value you want returned as an integer or a blob in which the first value is the integer value. The rest of the contents of the blob is ignored. Stringorblob can also be an Any variable containing a string or blob.
Return value
stringorblob is not a valid number or is an incompatible datatype. If stringorblob is NULL, Integer returns NULL.
Usage
To distinguish between a string whose value is the number 0 and a string whose value is not a number, use the IsNumber function before calling the Integer function. This statement returns the string 24 as an integer:
Integer("24")
Examples
This example checks whether the text of sle_data is a number before converting, which is necessary if the user might legitimately enter 0:
integer li_new_data IF IsNumber(sle_data.Text) THEN li_new_data = Integer(sle_data.Text) ELSE SetNull(li_new_data) END IF
After assigning blob data from the database to lb_blob, this example obtains the integer value stored at position 20 in the blob:
integer i i = Integer(BlobMid(lb_blob, 20, 2))
660
PowerBuilder
CHAPTER 10
PowerScript Functions
See also
Double Dec IsNumber Long Real Integer method for DataWindows in the DataWindow Reference or the online Help
661
InternetData
InternetData
Description
Processes the HTML data returned by a GetURL or PostURL function. The Context object calls this function; you do not call this function explicitly. Instead, you override this function in a customized descendant of the InternetResult standard class user object. InternetResult objects
servicereference.InternetData ( data ) Argument servicereference data Description Reference to the Internet service instance Blob containing the complete data requested by a GetURL or PostURL function
Applies to Syntax
Override this function in a user object that is a descendant of InternetResult. The overridden function must contain one argument of type blob, which is passed by value. It should return an integer, processing data as appropriate for the situation.
Do not call this function explicitly
Do not code calls to this function. The GetURL and PostURL functions include an argument that references an instantiated InternetResult descendant. When these functions complete, the Context object calls the InternetData function, returning HTML in data.
Examples
This example shows code you might use in an overridden InternetData function to display data from a GetURL function:
MessageBox("HTML from GetURL", String(data)) RETURN 1
See also
GetURL PostURL
662
PowerBuilder
CHAPTER 10
PowerScript Functions
IntHigh
Description Syntax
Integer. Returns the high word of long if it succeeds and -1 if an error occurs. If long is NULL, IntHigh returns NULL.
One use for IntHigh is for decoding values returned by external C functions and Windows messages. These statements decode a long value LValue into its low and high integers:
integer nLow, nHigh long LValue = 274489 nLow = IntLow (LValue) //The Low Integer is 12345. nHigh = IntHigh(LValue) //The High Integer is 4.
See also
IntLow
IntLow
Description Syntax
Integer. Returns the low word of long if it succeeds and -1 if an error occurs. If long is NULL, IntLow returns NULL. One use for IntLow is for decoding values returned by external C functions and Windows messages. These statements decode a long value LValue into its low and high integers:
integer nLow, nHigh long LValue = 12345 nLow = IntLow(LValue) //The Low Integer is 12345. nHigh = IntHigh(LValue) //The High Integer is 0.
See also
IntHigh
663
InvokePBFunction
InvokePBFunction
Description Applies to Syntax
Invokes the specified user-defined window function in the child window contained in a PowerBuilder window ActiveX control. Window ActiveX controls
activexcontrol.InvokePBFunction ( name {, numarguments {, arguments } }) Argument activexcontrol Description Identifier for the instance of the PowerBuilder Window ActiveX control. When used in HTML, this is the NAME attribute of the object element. When used in other environments, this references the control that contains the PowerBuilder window ActiveX. String specifying the name of the user-defined window function. This argument is passed by reference. Integer specifying the number of elements in the arguments array. The default is zero. Variant array containing function arguments. In PowerBuilder, Variant maps to the Any datatype. This argument is passed by reference. If you specify this argument, you must also specify numarguments. If you do not specify this argument and the function contains arguments, populate the argument list by calling the SetArgElement function once for each argument. JavaScript cannot use this argument.
Call this function to invoke a user-defined window function in the child window contained in a PowerBuilder window ActiveX control. To check the PowerBuilder functions return value, call the GetLastReturn function. JavaScript cannot use the arguments argument.
Examples
664
PowerBuilder
CHAPTER 10
PowerScript Functions
theArg = f.textToPB.value; PBRX1.SetArgElement(1, theArg); theFunc = "of_args"; retcd = PBRX1.InvokePBFunction(theFunc, numargs); rc = parseInt(PBRX1.GetLastReturn()); IF (rc != 1) { alert("Error. Empty string."); } PBRX1.ResetArgElements(); }
665
_Is_A
_Is_A
Description
Checks to see whether a CORBA object is an instance of a class that implements a particular interface. This function is used by PowerBuilder clients connecting to EAServer.
Applies to Syntax
CORBAObject objects
corbaobject._Is_A ( classname ) Argument corbaobject classname Description An object of type CORBAObject that you want to test The interface that will be used for the test
Boolean. Returns TRUE if the class of the object implements the specified interface and FALSE if it does not.
Before making a call to _Narrow, you can call _Is_A to verify that a CORBA object is an instance of a class that implements the interface to which you want to narrow the object. The following example checks to see that a CORBA object reference is an instance of a class that implements n_Bank_Account:
CORBAObject my_corbaobj n_Bank_Account my_account ... ... if (my_corbaobj._is_a("n_Bank_Account")) then my_corbaobj._narrow(my_account,"n_Bank_Account") end if my_account.withdraw(100.0)
Examples
See also
_Narrow
666
PowerBuilder
CHAPTER 10
PowerScript Functions
IsAlive
Description Applies to Syntax
Determines whether a server object is still running. OLEObject objects, OLETxnObject objects
oleobject.IsAlive ( ) Argument oleobject Description The name of an OLEObject or OLETxnObject variable that is connected to an automation server or COM object
Boolean. Returns TRUE if the server object appears to be running and FALSE if it is dead.
Use the IsAlive function to determine whether a server process has died. This function does not replace the error-handling capability provided by the ExternalException and Error events. It provides a way to check the viability of the server at intervals or before specific operations to avoid runtime errors. If IsAlive returns TRUE, the server may only appear to be running, because the true state of the server may be masked. This is more likely to occur when the server is running on a different computer, because DCOM may be using cached information to determine the state of the server. A FALSE return value always indicates that the server is dead.
Examples
This example creates an OLEObject variable and calls ConnectToNewObject to create and connect to a new instance of a PowerBuilder COM object. After performing some processing, it checks whether the server is still running before performing additional processing:
OLETxnObject EmpObj Integer li_rc EmpObj = CREATE OLEObject li_rc = EmpObj.ConnectToNewObject("PB70COM.employee") // Perform some work with the COM object ... IF EmpObj.IsAlive()THEN // Continue processing END IF
667
IsAllArabic
IsAllArabic
Description Syntax
Return value
Boolean. Returns TRUE if string is composed entirely of Arabic characters and FALSE if it is not. The presence of numbers, spaces, and punctuation marks will also result in a return value of FALSE.
Usage Examples
If you are not running a version of Windows that supports right-to-left languages, IsAllArabic is set to FALSE. Under a version of Windows that supports right-to-left languages, this statement returns TRUE if the SingleLineEdit sle_name is composed entirely of Arabic characters:
IsAllArabic(sle_name.Text)
See also
668
PowerBuilder
CHAPTER 10
PowerScript Functions
IsAllHebrew
Description Syntax
Return value
Boolean. Returns TRUE if string is composed entirely of Hebrew characters and FALSE if it is not. The presence of numbers, spaces, and punctuation marks will also result in a return value of FALSE.
Usage Examples
If you are not running a version of Windows that supports right-to-left languages, IsAllHebrew is set to FALSE. Under a version of Windows that supports right-to-left languages, this statement returns TRUE if the SingleLineEdit sle_name is composed entirely of Hebrew characters:
IsAllHebrew(sle_name.Text)
See also
669
IsAnyArabic
IsAnyArabic
Description Syntax
Boolean. Returns TRUE if string contains at least one Arabic character and FALSE if it does not.
If you are not running a version of Windows that supports right-to-left languages, IsAnyArabic is set to FALSE. Under a version of Windows that supports right-to-left languages, this statement returns TRUE if the SingleLineEdit sle_name contains at least one Arabic character:
IsAnyArabic(sle_name.Text)
See also
670
PowerBuilder
CHAPTER 10
PowerScript Functions
IsAnyHebrew
Description Syntax
Boolean. Returns TRUE if string contains at least one Hebrew character and FALSE if it does not.
If you are not running a version of Windows that supports right-to-left languages, IsAnyHebrew is set to FALSE. Under a version of Windows that supports right-to-left languages, this statement returns TRUE if the SingleLineEdit sle_name contains at least one Hebrew character:
IsAnyHebrew(sle_name.Text)
See also
671
IsArabic
IsArabic
Description Syntax
Tests whether a particular character is an Arabic character. For a string, IsArabic tests only the first character on the left.
IsArabic ( character ) Argument character Description A character or string whose value you want to test to find out if it is an Arabic character.
not. If you are not running a version of Windows that supports right-to-left languages, IsArabic is set to FALSE. Under a version of Windows that supports right-to-left languages, this statement returns TRUE if the SingleLineEdit sle_name begins with an Arabic character:
IsArabic(sle_name.Text) See also
672
PowerBuilder
CHAPTER 10
PowerScript Functions
IsArabicAndNumbers
Description Syntax
Boolean. Returns TRUE if string is composed entirely of Arabic characters or numbers and FALSE if it is not.
If you are not running a version of Windows that supports right-to-left languages, IsArabicAndNumbers is set to FALSE. Under a version of Windows that supports right-to-left languages, this statement returns TRUE if the SingleLineEdit sle_name is composed entirely of Arabic characters and numbers:
IsArabicAndNumbers(sle_name.Text)
See also
673
IsCallerInRole
IsCallerInRole
Description Applies to Syntax
Indicates whether the direct caller of a COM object running on MTS is in a specified role (either individually or as part of a group). TransactionServer objects
transactionserver.IsCallerInRole ( role ) Argument transactionserver role Description Reference to the TransactionServer service instance A string expression containing the name of a role
Boolean. Returns TRUE if the direct caller is in the specified role and FALSE if
it is not. In MTS, a role is a name that represents the set of access permissions for a specific user or group of users. For example, a component that provides access to a sales database might have different roles for managers and salespersons. When a package is deployed to MTS, roles for the package and components can be specified in the MTS Explorer. In your code, you use IsCallerInRole to determine whether the caller of the current method is associated with a specific role before you execute code that performs a task restricted to users in that role.
IsCallerInRole only determines whether the direct caller of the current method
is in the specified role. The direct caller may be either a client process or a server process.
Package must run in a dedicated server process
To support role-checking, the MTS package must be activated as a Server package, not a Library package. Server packages run in a dedicated server process. Library packages run in the creators process and are used primarily for debugging. IsCallerInRole only returns a meaningful value when security checking is enabled. Security checking can be enabled in the COM/MTS Project wizard, the Project painter, or the MTS Explorer.
674
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
The following example shows a call to a function (f_checkrole) that takes the name of a role as an argument and returns an integer. In this example only managers can place orders with a value over $20,000:
integer rc long ordervalue IF ordervalue > 20,000 THEN rc = f_checkrole("Manager") IF rc <> 1 // handle negative values and exit ELSE // continue processing END IF END IF
The f_checkrole function checks whether a component is running on MTS and if security checking is enabled. Then it checks whether the direct caller is in the role passed in as an argument. If any of the checks fail, the function returns a negative value:
TransactionServer ts integer li_rc string str_role li_rc = GetContextService( "TransactionServer", ts) // handle error if necessary // Find out if running on MTS IF ts.which() <> 2 THEN RETURN -1 // Find out if security is enabled IF NOT ts.IsSecurityEnabled() THEN RETURN -2 // Find out if the caller is in the role IF NOT ts.IsCallerInRole(str_role) THEN RETURN -3 ELSE RETURN 1 END IF See also
675
IsDate
IsDate
Description Syntax
Boolean. Returns TRUE if datevalue is a valid date and FALSE if it is not. If datevalue is NULL, IsDate returns NULL.
You can use IsDate to test whether a user-entered date is valid before you convert it to a date datatype. To convert a value into a date value, use the Date function. This statement returns TRUE:
IsDate("Jan 1, 95")
Examples
If the SingleLineEdit sle_Date_Of_Hire contains 7/1/91, these statements store 1991-07-01 in HireDate:
Date HireDate IF IsDate(sle_Date_Of_Hire.text) THEN HireDate = Date(sle_Date_Of_Hire.text) END IF See also
IsDate method for DataWindows in the DataWindow Reference or the online
Help
676
PowerBuilder
CHAPTER 10
PowerScript Functions
IsHebrew
Description Syntax
Tests whether a particular character is a Hebrew character. For a string, IsHebrew tests only the first character on the left.
IsHebrew ( character ) Argument character Description A character or string whose value you want to test to find out if it is an Hebrew character
not. If you are not running a version of Windows that supports right-to-left languages, IsHebrew is set to FALSE. Under a version of Windows that supports right-to-left languages, this statement returns TRUE if the SingleLineEdit sle_name begins with a Hebrew character:
IsHebrew(sle_name.Text) See also
677
IsHebrewAndNumbers
IsHebrewAndNumbers
Description Syntax
Tests whether a particular string is composed entirely of Hebrew characters and numbers.
IsHebrewAndNumbers ( string ) Argument string Description A string whose value you want to test to find out if it is composed entirely of Hebrew characters and numbers
Boolean. Returns TRUE if string is composed entirely of Hebrew characters and numbers and FALSE if it is not.
If you are not running a version of Windows that supports right-to-left languages, IsHebrewAndNumbers is set to FALSE. Under a version of Windows that supports right-to-left languages, this statement returns TRUE if the SingleLineEdit sle_name is composed entirely of Hebrew characters and numbers:
IsHebrewAndNumbers(sle_name.Text)
See also
678
PowerBuilder
CHAPTER 10
PowerScript Functions
IsImpersonating
Description Applies to Syntax
Queries whether a COM object running on MTS is impersonating the client. TransactionServer objects
transactionserver.IsImpersonating ( ) Argument transactionserver Description Reference to the TransactionServer service instance
Boolean. Returns TRUE if the component is impersonating the client and FALSE if it is not.
COM objects running on MTS can use the ImpersonateClient function to run in the clients security context so that the server process has access to the same resources as the client. Use IsImpersonating to determine whether the ImpersonateClient function has been called without a matching call to RevertToSelf. The following example creates an instance of the TransactionServer service and checks whether the COM object is currently running on the clients security context. If it is not, it impersonates the client, performs some processing using the clients security context, then reverts to the objects security context:
TransactionServer txninfo_test integer li_rc li_rc = GetContextService( "TransactionServer", txninfo_test ) IF NOT txninfo_test.IsImpersonating() THEN txninfo_test.ImpersonateClient() END IF // continue processing as client txninfo_test.RevertToSelf() &
Examples
See also
679
IsInTransaction
IsInTransaction
Description Applies to Syntax
Boolean. Returns TRUE if the component is executing as part of a transaction and FALSE if it is not.
Component methods can call IsInTransaction to determine whether they are executing within a transaction. Methods in components that are declared to be transactional always execute as part of a transaction. Methods in components that have a transaction type of Supports Transaction may or may not be running in the context of an EAServer transaction, depending on whether the component is instantiated directly by a base client or by another component. In components that have this transaction type, you can use IsInTransaction to determine whether the component is running in a transaction. The IsInTransaction function corresponds to the isInTransaction transaction primitive in EAServer.
Examples
See also
680
PowerBuilder
CHAPTER 10
PowerScript Functions
IsNull
Description Syntax
Use IsNull to test whether a user-entered value or a value retrieved from the database is NULL. IsNull works for all datatypes but does not work for arrays. If one or more columns in a DataWindow are required columns, that is, they must contain data, you do not want to update the database if the columns have NULL values. You can use FindRequired to find rows in which those columns have NULL values, instead of using IsNull to evaluate each row and column.
Setting a variable to NULL To set a variable to NULL, use the SetNull function.
Examples
See also
SetNull IsNull method for DataWindows in the DataWindow Reference or the online Help
681
IsNumber
IsNumber
Description Syntax
Boolean. Returns TRUE if string is a valid PowerScript number and FALSE if it is not. If string is NULL, IsNumber returns NULL.
Use IsNumber to check that text in an edit control can be converted to a number. To convert a string to a specific numeric datatype, use the Double, Dec, Integer,
Long, or Real function.
Examples
682
PowerBuilder
CHAPTER 10
PowerScript Functions
IsPreview
Description Applies to Syntax
entry mode. This example switches the RichTextEdit control rte_1 to preview mode if it is not already in preview mode and then prints it:
IF NOT rte_1.IsPreview() THEN rte_1.Preview(TRUE) rte_1.Print(1, "1-4", FALSE, TRUE) END IF See also
Preview
683
IsSecurityEnabled
IsSecurityEnabled
Description Applies to Syntax
Indicates whether or not security checking is enabled for a COM object running on MTS. TransactionServer objects
transactionserver.IsSecurityEnabled ( ) Argument transactionserver Description Reference to the TransactionServer service instance
Use IsSecurityEnabled to determine whether security checking is enabled for the current COM object. If the COM object is running in the creators process, IsSecurityEnabled always returns FALSE.
Examples
The following example determines whether security checking is enabled and, if it is, checks whether the direct caller is in the Manager role before completing the call:
TransactionServer ts integer li_rc string str_role = "Admin" li_rc = GetContextService( "TransactionServer", & ts ) // Find out if security is enabled. IF ts.IsSecurityEnabled() THEN // Find out if the caller is in the role. IF NOT ts.IsCallerInRole(str_role) THEN // do not complete call ELSE // execute call normally END IF ELSE // security is not enabled // do not complete call END IF
See also
684
PowerBuilder
CHAPTER 10
PowerScript Functions
IsTime
Description Syntax
Boolean. Returns TRUE if timevalue is a valid time and FALSE if it is not. If timevalue is NULL, IsTime returns NULL.
Use IsTime to test to whether a value a user enters in an edit control is a valid time. To convert a string to an time value, use the Time function.
Examples
If the SingleLineEdit sle_EndTime contains 4:15 these statements store 04:15:00 in lt_QuitTime:
Time lt_QuitTime IF IsTime sle_EndTime.Text) THEN lt_QuitTime = Time(sle_EndTime.Text) END IF See also
Time
IsTime method for DataWindows in the DataWindow Reference or the online
Help
685
IsTransactionAborted
IsTransactionAborted
Description Applies to Syntax
Determines whether the current transaction, in which an EAServer component participates, has been aborted. TransactionServer objects
transactionserver.IsTransactionAborted ( ) Argument transactionserver Description Reference to the TransactionServer service instance
Boolean. Returns TRUE if the current transaction has been aborted and FALSE if it has not.
The IsTransactionAborted function allows a component to verify that the current transaction is still viable before performing updates to the database.The IsTransactionAborted function corresponds to the isRollbackOnly transaction primitive in EAServer. The following example checks to see whether the transaction has been aborted. If it has not, it updates the database and calls EnableCommit. If it has been aborted, it calls DisableCommit.
// Instance variables: ids_datastore, ts Integer li_rc long ll_rv li_rc = this.GetContextService("TransactionServer", ts) IF li_rc <> 1 THEN // handle the error END IF ... IF ts.IsTransactionAborted() = FALSE THEN ll_rv = ids_datastore.Update() IF ll_rv = 1 THEN ts.EnableCommit() ELSE ts.DisableCommit() END IF END IF
Examples
See also
686
PowerBuilder
CHAPTER 10
PowerScript Functions
IsValid
Description Syntax
Determines whether an object variable is instantiatedwhether its value is a valid object handle.
IsValid ( objectvariable ) Argument objectvariable Description An object variable or a variable of type Anytypically a reference to an object that you are testing for validity
Return value
Boolean. Returns TRUE if objectvariable is an instantiated object. Returns FALSE if objectvariable is not an object, or if it is an object that is not instantiated. If objectvariable is NULL, IsValid returns NULL.
Usage Examples
Use IsValid instead of the Handle function to determine whether a window is open. This statement determines whether the window w_emp is open and if it is not, opens it:
IF IsValid(w_emp) = FALSE THEN Open(w_emp)
This example returns -1 because the IsValid function returns FALSE. Although the objectvariable argument is a valid string, it is not an instantiated object. The IsValid method would return TRUE only if la_value was an instantiated object:
any la_value la_value = "Im a string" IF NOT IsValid(la_value) THEN return -1 See also
Handle
687
KeyDown
KeyDown
Description Syntax
Determines whether the user pressed the specified key on the computer keyboard.
KeyDown ( keycode ) Argument keycode Description A value of the KeyCode enumerated datatype that identifies a key on the computer keyboard or an integer whose value is the ASCII code for a key. Not all ASCII values are recognized; see Usage. See also the table of KeyCode values in Usage.
Boolean. Returns TRUE if keycode was pressed and FALSE if it was not. If keycode is NULL, KeyDown returns NULL. KeyDown does not report what character the user typedit reports whether the
user was pressing the specified key when the event whose script is calling
KeyDown was triggered.
Events You can call KeyDown in a windows Key event or a keypress event for a control to determine whether the user pressed a particular key. The Key event occurs whenever the user presses a key as long as the insertion point is not in a line edit. The Key event is triggered repeatedly if the user holds down a repeating key. For controls, you can define a user event for pbm_keydown or pbm_dwnkey (DataWindows), and call KeyDown in its script.
You can also call KeyDown in a mouse event, such as Clicked, to determine whether the user also pressed a modifier key, such as Ctrl.
KeyCodes and ASCII values KeyDown does not distinguish between
uppercase and lowercase letters or other characters and their shifted counterparts. For example, KeyA! refers to the A keythe user may have typed "A" or "a." Key9! refers to both "9" and "(". Instead, you can test whether a modifier key is also pressed.
KeyDown does not test whether Caps Lock or other toggle keys are in a
The following table categorizes KeyCode values by type of key and provides explanations of names that might not be obvious.
688
PowerBuilder
CHAPTER 10
PowerScript Functions
Table 10-3: KeyCode values for keyboard keys Type of key Mouse buttons KeyCode values and descriptions KeyLeftButton! Left mouse button KeyMiddleButton! Middle mouse button KeyRightButton! Right mouse button KeyA! - KeyZ! A - Z, uppercase or lowercase KeyQuote! and " KeyEqual! = and + KeyComma! , and < KeyDash! - and _ KeyPeriod! . and > KeySlash! / and ? KeyBackQuote! and ~ KeyLeftBracket! [ and { KeyBackSlash! \ and | KeyRightBracket! ] and } KeySemiColon! ; and : KeyBack! Backspace KeyTab! KeyEnter! KeySpaceBar! KeyF1! - KeyF12! Function keys F1 to F12 KeyShift! KeyControl! KeyAlt! KeyPause! KeyCapsLock! KeyEscape! KeyPrintScreen! KeyInsert! KeyDelete! KeyPageUp! KeyPageDown! KeyEnd! KeyHome! KeyLeftArrow! KeyUpArrow! KeyRightArrow! KeyDownArrow!
Non-printing characters
Navigation keys
689
KeyDown
KeyCode values and descriptions Key0! 0 and ) Key1! 1 and ! Key2! 2 and @ Key3! 3 and # Key4! 4 and $ Key5! 5 and % Key6! 6 and ^ Key7! 7 and & Key8! 8 and * Key9! 9 and ( KeyNumpad0! - KeyNumpad9! 0 - 9 on numeric keypad KeyMultiply! * on numeric keypad KeyAdd! + on numeric keypad KeySubtract! - on numeric keypad KeyDecimal! . on numeric keypad KeyDivide! / on numeric keypad KeyNumLock! KeyScrollLock!
Examples
The following code checks whether the user pressed the F1 key or the Ctrl key and executes some statements appropriate to the key pressed:
IF KeyDown(KeyF1!) THEN . . . // Statements for the F1 key ELSEIF KeyDown(KeyControl!) THEN . . . // Statements for the CTRL key END IF
This statement tests whether the user pressed Tab, Enter, or any of the scrolling keys:
IF (KeyDown(KeyTab!) OR KeyDown(KeyEnter!) OR & KeyDown(KeyDownArrow!) OR KeyDown(KeyUpArrow!) & OR KeyDown(KeyPageDown!) OR KeyDown(KeyPageUp!))& THEN ...
This statement tests whether the user pressed the A key (ASCII value 65):
IF KeyDown(65) THEN ...
This statement tests whether the user pressed the Shift key and the A key:
IF KeyDown(65) AND KeyDown(KeyShift!) THEN ...
This statement in a Clicked event checks whether the Shift is also pressed:
IF KeyDown(KeyShift!) THEN ...
690
PowerBuilder
CHAPTER 10
PowerScript Functions
LastPos
Description Syntax
Return value
Long. Returns a long whose value is the starting position of the last occurrence
of string2 in string1 within the characters specified in searchlength. If string2 is not found in string1 or if searchlength is 0, LastPos returns 0. If any arguments value is NULL, LastPos returns NULL.
Usage Examples
The LastPos function is case sensitive. The entire target string must be found in the source string. This statement returns 6, because the position of the last occurrence of RU is position 6:
LastPos("BABE RUTH", "RU")
This statement searches the leftmost 4 characters and returns 0, because the only occurrence of RU is after position 4:
LastPos("BABE RUTH", "RU", 2)
These statements change the text in the SingleLineEdit sle_group. The last instance of the text NY is changed to North East:
long place_nbr place_nbr = LastPos(sle_group.Text, "NY") sle_group.SelectText(place_nbr, 2 ) sle_group.ReplaceText("North East")
These statements separate the return value of GetBandAtPointer into the band name and row number. The LastPos function finds the position of the (last) tab in the string and the Left and Mid functions extract the information to the left and right of the tab:
691
LastPos
string s, ls_left, ls_right integer li_tab s = dw_groups.GetBandAtPointer() li_tab = LastPos(s, "~t") ls_left = Left(s, li_tab - 1) ls_right = Mid(s, li_tab + 1)
Pos
692
PowerBuilder
CHAPTER 10
PowerScript Functions
Left
Description
String. Returns the leftmost n characters in string if it succeeds and the empty string ("") if an error occurs. If any arguments value is NULL, Left returns NULL. If n is greater than or equal to the length of the string, Left returns the entire string. It does not add spaces to make the return values length equal to n.
Usage
In SBCS environments, the Left and LeftW functions return the same results. Although you can use the Left function in DBCS environments, the string returned by this function is based exclusively on single-byte computation. Since characters in DBCS environments can be single byte, double byte, or mixed, you must use the LeftW function to return a string with double-byte or mixed single-byte and double-byte characters. This statement returns BABE:
Left("BABE RUTH", 4)
Examples
These statements store the first 40 characters of the text in the SingleLineEdit sle_address in emp_address:
string emp_address emp_address = Left(sle_address.Text, 40)
For sample code that uses Left to parse two tab-separated values, see the Pos function.
See also
Mid Pos Right Left method for DataWindows in the DataWindow Reference or the online Help
693
LeftW
LeftW
Description Syntax
Obtains a specified number of characters from the beginning of a string. For more informationm, see Left.
LeftW ( string, n )
694
PowerBuilder
CHAPTER 10
PowerScript Functions
LeftTrim
Description
String. Returns a copy of string with leading spaces deleted if it succeeds and the empty string ("") if an error occurs. If string is NULL, LeftTrim returns NULL.
Usage
In SBCS environments, the LeftTrim and LeftTrimW functions return the same results. Although you can use the LeftTrim function in DBCS environments, it cannot remove double-byte spaces. You must use the LeftTrimW function to remove double-byte or mixed single-byte and double-byte spaces. This statement returns RUTH:
LeftTrim(" RUTH")
Examples
These statements delete leading spaces from the text in the MultiLineEdit mle_name and store the result in emp_name:
string emp_name emp_name = LeftTrim(mle_name.Text) See also
RightTrim Trim LeftTrim method for DataWindows in the DataWindow Reference or the online Help
LeftTrimW
Description Syntax
Removes spaces from the beginning of a string. For more information, see LeftTrim.
LeftTrimW ( string )
695
Len
Len
Description
Long. Returns a long whose value is the length of stringorblob if it succeeds and -1 if an error occurs. If stringorblob is NULL, Len returns NULL. Len and LenW count the number of characters in a string. The NULL that
terminates a string is not included in the count. For single-byte character set environments, the number of bytes is the same as the number of characters, and either function produces the same result. Characters in DBCS environments can be single byte, double byte, or mixed. In these environments, you must use the LenW function to return the length of a string as the number of characters it contains. Using the Len function in DBCS environments returns the length in number of bytes. If you specify a size when you declare a blob, that is the size reported by Len or LenW. If you do not specify a size for the blob, Len and LenW initially report the blobs length as 0. PowerBuilder assigns a size to the blob the first time you assign data to the blob. Len reports the length of the blob as the number of single-byte characters it can contain. In DBCS environments, LenW reports the size of the blob as the number of double-byte characters it can contain.
Examples
These statements store in the variable s_address_len the length of the text in the SingleLineEdit sle_address:
long s_address_len s_address_len = Len(sle_address.Text)
The following scenarios illustrate how the declaration of blobs affects their length, as reported by Len.
696
PowerBuilder
CHAPTER 10
PowerScript Functions
In the first example, an instance variable called ib_blob is declared but not initialized with a size. If you call Len before data is assigned to ib_blob, Len returns 0. After data is assigned, Len returns the blobs new length. The declaration of the instance variable is:
blob ib_blob
In the second example, ib_blob is initialized to the size 100 when it is declared. When you call Len for ib_blob, it always returns 100. This example uses BlobEdit, instead of Blob, to assign data to the blob because its size is already established. The declaration of the instance variable is:
blob{100} ib_blob
LenW
Description Syntax
Reports the length of a string or a blob. For more information, see Len.
LenW ( stringorblob )
697
Length
Length
Description Applies to Syntax
Return value
This example opens an OLE object in the file MYSTUFF.OLE and assigns it to the OLEStorage object stg_stuff. Then it opens the stream called info in stg_stuff and assigns it to the stream object olestr_info. Finally, it finds out the streams length and stores the value in the variable info_len. The example does not check the functions return values for success, but you should be sure to check the return values in your code:
boolean lb_memexists OLEStorage stg_stuff OLEStream olestr_info long info_len stg_stuff = CREATE oleStorage stg_stuff.Open("c:\ole2\mystuff.ole") olestr_info.Open(stg_stuff, "info", & stgRead!, stgExclusive!) olestr_info.Length(info_len)
See also
698
PowerBuilder
CHAPTER 10
PowerScript Functions
LibraryCreate
Description Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, LibraryCreate returns NULL. LibraryCreate creates a PowerBuilder library file (PBL) in the current directory,
unless you specify a directory path as part of libraryname. If you do not specify an extension, LibraryCreate adds the extension .PBL.
Examples
This statement in Windows NT creates a library named dwTemp in the PB directory on drive C and associates a comment with the library:
LibraryCreate("c:\pb\dwTemp.pbl", & "Temporary library for dynamic DataWindows")
See also
699
LibraryDelete
LibraryDelete
Description Syntax
Deletes a library file or, if you specify a DataWindow object, deletes the DataWindow object from the library.
LibraryDelete ( libraryname {, objectname, objecttype } ) Argument libraryname Description A string whose value is the name of the PowerBuilder library you want to delete or from which you want to delete a DataWindow object. If you do not specify a full path, LibraryDelete uses the systems standard file search order to find the file. A string whose value is the name of the DataWindow object you want to delete from libraryname. A value of the LibImportType enumerated datatype identifying the type of object you want to delete. The only supported object type is ImportDataWindow!.
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, LibraryDelete returns NULL.
You can delete DataWindow objects from a library in a script with the LibraryDelete function. To delete other types of objects, use the Library painter. This statement deletes a library called dwTemp in the current directory and on the current application library path:
LibraryDelete("dwTemp.pbl")
See also
700
PowerBuilder
CHAPTER 10
PowerScript Functions
LibraryDirectory
Description
Obtains a list of the objects in a PowerBuilder library. The information provided is the object name, the date and time it was last modified, and any comments for the object. You can get a list of all objects or just objects of a specified type.
LibraryDirectory ( libraryname, objecttype ) Argument libraryname Description A string whose value is the name of the PowerBuilder library for which you want the contents. If you do not specify a full path, LibraryDirectory uses the operating systems standard file search order to find the file. A value of the LibDirType enumerated datatype identifying the type of objects you want listed: DirAll! All objects DirApplication! Application objects DirDataWindow! DataWindow objects DirFunction! Function objects DirMenu! Menu objects DirPipeline! Pipeline objects DirProject! Project objects DirQuery! Query objects DirStructure! Structure objects DirUserObject! User objects DirWindow! Window objects
Syntax
objecttype
Return value
String. LibraryDirectory returns a tab-separated list with one object per line. The format of the list is:
Returns the empty string ("") if an error occurs. If any arguments value is NULL, LibraryDirectory returns NULL.
Usage
You can display the result of LibraryDirectory in a DataWindow control by passing the returned string to the ImportString function for that DataWindow. The DataWindow should contain three string columns. The columns must be wide enough to fit the data in the input string. If not, PowerBuilder reports validation errors. To return the objects type, use LibraryDirectoryEx. For an example of parsing tab-delimited data, see the Pos function.
701
LibraryDirectory
Examples
This code imports the string returned by LibraryDirectory to the DataWindow dw_list and then redraws the dw_list. The DataWindow was defined with an external source and three string columns:
String ls_entries ls_entries = LibraryDirectory( & "c:\pb\dwTemp.pbl", DirUserObject!) dw_list.SetRedraw(FALSE) dw_list.Reset( ) dw_list.ImportString(ls_Entries) dw_list.SetRedraw(TRUE)
See also
702
PowerBuilder
CHAPTER 10
PowerScript Functions
LibraryDirectoryEx
Description
Obtains a list of the objects in a PowerBuilder library. The information provided is the object name, the date and time it was last modified, any comments for the object, and the objects type. You can get a list of all objects or just objects of a specified type.
LibraryDirectoryEx ( libraryname, objecttype ) Argument libraryname Description A string whose value is the name of the PowerBuilder library for which you want the contents. If you do not specify a full path, LibraryDirectory uses the operating systems standard file search order to find the file. A value of the LibDirType enumerated datatype identifying the type of objects you want listed: DirAll! All objects DirApplication! Application objects DirDataWindow! DataWindow objects DirFunction! Function objects DirMenu! Menu objects DirPipeline! Pipeline objects DirProject! Project objects DirQuery! Query objects DirStructure! Structure objects DirUserObject! User objects DirWindow! Window objects
Syntax
objecttype
Return value
String. LibraryDirectoryEx returns a tab-separated list with one object per line.
Returns the empty string ("") if an error occurs. If any arguments value is NULL, LibraryDirectoryEx returns NULL.
Usage
You can display the result of LibraryDirectoryEx in a DataWindow control by passing the returned string to the ImportString function for that DataWindow. The DataWindow should contain four string columns. The columns must be wide enough to fit the data in the input string. If not, PowerBuilder reports validation errors. If you do not need to return the objects type, you can use LibraryDirectory. For an example of parsing tab-delimited data, see the Pos or LastPos function.
703
LibraryDirectoryEx
Examples
This code imports the string returned by LibraryDirectoryEx to the DataWindow dw_list and then redraws the dw_list. The DataWindow was defined with an external source and four string columns:
String ls_entries ls_entries = LibraryDirectoryEx( & "c:\pb\dwTemp.pbl", DirUserObject!) dw_list.SetRedraw(FALSE) dw_list.Reset( ) dw_list.ImportString(ls_Entries) dw_list.SetRedraw(TRUE)
See also
704
PowerBuilder
CHAPTER 10
PowerScript Functions
LibraryExport
Description Syntax
objectname objecttype
Return value
Examples
String. Returns the syntax of the object if it succeeds. The syntax is the same as the syntax returned when you export an object in the Library painter except that LibraryExport does not include an export header. Returns the empty string ("") if an error occurs. If any arguments value is NULL, LibraryExport returns NULL. These statements export the DataWindow object dw_emp from the library called dwTemp to a string named ls_dwsyn and then use it to create a DataWindow:
String ls_dwsyn, ls_errors ls_dwsyn = LibraryExport("c:\pb\dwTemp.pbl", & "d_emp", ExportDataWindow!) dw_1.Create(ls_dwsyn, ls_errors) See also
Create method for DataWindows in the DataWindow Reference or online Help LibraryCreate LibraryDelete LibraryDirectory LibraryImport
705
LibraryImport
LibraryImport
Description
Imports a DataWindow object into a library. LibraryImport uses the syntax of the DataWindow object, which is specified in text format, to recreate the object in the library.
LibraryImport ( libraryname, objectname, objecttype, syntax, errors {, comments } ) Argument libraryname Description A string specifying the name of the PowerBuilder library into which you want to import the entry. If you do not specify a full path, LibraryImport uses the systems standard file search order to find the file. A string specifying the name of the DataWindow object you want to import. A value of the LibImportType enumerated datatype identifying the type of object you want to import. The only supported object type is ImportDataWindow!. A string specifying the syntax of the DataWindow object you want to import. A string variable that you want to fill with any error messages that occur. A string specifying the comments you want to associate with the entry.
Syntax
objectname objecttype
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, LibraryImport returns NULL.
When you import a DataWindow, any errors that occur are stored in the string variable you specify for the error argument. When your application creates a DataWindow dynamically during execution, you can use LibraryImport to save that DataWindow object in a library.
Examples
These statements import the DataWindow object d_emp into the library called dwTemp and store any errors in ErrorBuffer. Note that the syntax is obtained by using the Describe function:
string dwsyntax, ErrorBuffer integer rtncode dwsyntax = dw_1.Describe("DataWindow.Syntax") rtncode = LibraryImport("c:\pb\dwTemp.pbl", & "d_emp", ImportDataWindow!, & dwsyntax, ErrorBuffer )
706
PowerBuilder
CHAPTER 10
PowerScript Functions
These statements import the DataWindow object d_emp into the library called dwTemp, store any errors in ErrorBuffer, and associate the comment Employee DataWindow 1 with the entry:
string dwsyntax, ErrorBuffer integer rtncode dwsyntax = dw_1.Describe("DataWindow.Syntax") rtncode = LibraryImport("c:\pb\dwTemp.pbl", & "d_emp", ImportDataWindow!, & dwsyntax, ErrorBuffer, & "Employee DataWindow 1") See also
Describe method for DataWindows in the DataWindow Reference or the online Help LibraryCreate LibraryDelete LibraryDirectory LibraryImport
707
LineCount
LineCount
Description Applies to Syntax
Determines the number of lines in an edit control that allows multiple lines. RichTextEdit, MultiLineEdit, EditMask, and DataWindow controls
editname.LineCount ( ) Argument editname Description The name of the DataWindow control, EditMask, MultiLineEdit, or RichTextEdit for which you want the number of lines
Long. Returns the number of lines in editname if it succeeds and -1 if an error occurs. If editname is NULL, LineCount returns NULL. LineCount counts each visible line, whether it was the result of wrapping or
carriage returns. When you call LineCount for a DataWindow, it reports the number of lines in the edit control over the current row and column. A user can enter multiple lines in a DataWindow column only if it has a text datatype and its box is large enough to display those lines. The size of the columns box determines the number of lines allowed in the column. When the user is typing, lines do not wrap automatically; the user must press enter to type additional lines. In a MultiLineEdit control, lines wrap when the users typing fills the control horizontally, unless either the HScrollBar or AutoHScroll property is TRUE. If horizontal scrolling is enabled with these properties, the user must press enter to type additional lines. A RichTextEdit control always contains an end-of-file mark even if there is no text in the control. Therefore, its line count is always at least 1. Other edit controls, when empty, have a line count of 0.
Examples
These statements display a MessageBox if fewer than two lines have been entered in the MultiLineEdit mle_Address:
integer li_Lines li_Lines = mle_Address.LineCount() IF li_Lines < 2 THEN MessageBox("Warning", "2 lines are required.") END IF
708
PowerBuilder
CHAPTER 10
PowerScript Functions
LineLength
Description Applies to Syntax
Determines the length of the line containing the insertion point in an edit control. RichTextEdit, MultiLineEdit, and EditMask controls
editname.LineLength ( ) Argument editname Description The name of the RichTextEdit, MultiLineEdit, or EditMask in which you want to determine the length of the line containing the insertion point
Long. Returns the length of the line containing the insertion point in editname. Returns -1 if an error occurs. If editname is NULL, LineLength returns NULL.
If the control contains a selection instead of a single insertion point, LineLength counts the line at the beginning of the selection. PowerBuilder remembers where the insertion point is in each editable control. When the user moves the focus to another control, you can still find out the length of the line most recently edited by calling the LineLength function for that control.
Insertion point in editable controls
Because PowerBuilder remembers the position of the insertion point, users can resume editing at the insertion point if they make the control active by tabbing to it. When users make a control active by clicking on it, they move the insertion point as well. For an EditMask control, LineLength reports the length of the mask, regardless of the number of characters the user has entered.
Examples
If the insertion point is positioned anywhere in line 5 of mle_Contact and line 5 contains the text Select All, il_linelength is set to 10 (the length of line 5):
integer li_linelength li_linelength = mle_Contact.LineLength()
See also
709
LineList
LineList
Description Applies to Syntax
Provides a list of the lines in a routine included in a performance analysis model. ProfileRoutine object
iinstancename.LineList ( list ) Argument instancename list Description Instance name of the ProfileRoutine object. An unbounded array variable of datatype ProfileLine in which LineList stores a ProfileLine object for each line in the routine. This argument is passed by reference.
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded ModelNotExistsError!The model does not exist
Usage
Use this function to extract a list of the lines in a routine included in the performance analysis model. You must have previously created the performance analysis model from a trace file using the BuildModel function. Each line is defined as a ProfileLine object and provides the number of times the line was hit, any calls made from the line, and the time spent on the line and in any called functions. The lines are listed in numeric order. Lines are not returned for database statements and objects. If line information was not logged in the trace file, lines are not returned.
Examples
This example gets a list of the routines included in a performance analysis model and then gets a list of the lines in each routine:
Long ll_cnt ProfileLine lproln_line[] lpro_model.BuildModel() lpro_model.RoutineList(iprort_list) FOR ll_cnt = 1 TO UpperBound(iprort_list) iprort_list[ll_cnt].LineList(lproln_line) ... NEXT
See also
BuildModel
710
PowerBuilder
CHAPTER 10
PowerScript Functions
LinkTo
Description Syntax
Establishes a link between an OLE control and a file or an item within the file.
olecontrol.LinkTo ( filename {, sourceitem } ) Argument olecontrol filename Description The name of the OLE control in which you want to insert a linked object. A string whose value is the file name containing the data that you want to insert in olecontrol, with a link connecting the object in PowerBuilder to the original data. If you do not specify sourceitem, a link is established with the whole file. A string that names an item within file name to which you want to link. The way you specify sourceitem is determined by the OLE server application.
sourceitem (optional)
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -2 -9
This example creates an object in the OLE control, ole_1. The object is linked to the file C:\XLS\EXPENSE.XLS:
integer result result = ole_1.LinkTo("c:\xls\expense.xls")
This example links to a section of rows and columns in the same spreadsheet as in the previous example:
integer result result = ole_1.LinkTo("c:\xls\expense.xls", & "R1C1:R5C5") See also
711
Log
Log
Returns the natural logarithm of a number. For an ErrorLogging object, this function can be used to write a string to the log file maintained by the objects container.
To Determine the natural logarithm of a number Write a string to a log file Use Syntax 1 Syntax 2
Syntax 1
Description Syntax
Return value
Double. Returns the natural logarithm of n. An execution error occurs if n is negative or zero. If n is NULL, Log returns NULL.
Inverse of Log
Exp LogTen Log method for DataWindows in the DataWindow Reference or the online Help
712
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 2
Description Applies to Syntax
None. The ErrorLogging object provides the ability to write messages to the log file used by the objects container, such as jaguar.log for EAServer or the NT system application log for Microsoft Transaction Server (MTS). Before you call the Log function, create an instance of the ErrorLogging service by calling the GetContextService function.
Examples
The following example shows how to write a string to the log for EAServer or MTS:
ErrorLogging el this.GetContextService("ErrorLogging", el) el.log("Write this string to log")
See also
GetContextService
713
LogTen
LogTen
Description Syntax
Usage
Double. Returns the base 10 logarithm of n. An execution error occurs if n is negative. If n is NULL, LogTen returns NULL.
The expression 10^n is the inverse of LogTen(n). To obtain the value of n in the equation r = LogTen(n), use n = 10^r.
Inverse of LogTen Examples
Exp LogTen LogTen method for DataWindows in the DataWindow Reference or the online Help
714
PowerBuilder
CHAPTER 10
PowerScript Functions
Long
Converts data into data of type long. There are two syntaxes.
To Combine two unsigned integers into a long value Convert a string whose value is a number into a long or to obtain a long value stored in a blob Use Syntax 1 Syntax 2
Syntax 1
Description Syntax
Long. Returns the long if it succeeds and -1 if an error occurs. If any arguments value is NULL, Long returns NULL.
Use Long for passing values to external C functions or specifying a value for the LongParm property of PowerBuilders Message object. These statements convert the UnsignedIntegers nLow and nHigh into a long value:
UnsignedInt nLow // Low integer 16 bits UnsignedInt nHigh // High integer 16 bits long LValue // Long value 32 bits nLow = 12345 nHigh = 0 LValue = Long(nLow, nHigh) MessageBox("Long Value", Lvalue)
Syntax 2
Description Syntax
715
Long
Argument stringorblob
Description The string you want returned as a long or a blob in which the first value is the long value. The rest of the contents of the blob is ignored. Stringorblob can also be an Any variable containing a string or blob.
Return value
Long. Returns the value of stringorblob as a long if it succeeds and 0 if stringorblob is not a valid PowerScript number or if it is an incompatible datatype. If stringorblob is NULL, Long returns NULL.
Usage
To distinguish between a string whose value is the number 0 and a string whose value is not a number, use the IsNumber function before calling the Long function. This statement returns 2167899876 as a long:
Long("2167899876")
Examples
After assigning blob data from the database to lb_blob, the following example obtains the long value stored at position 20 in the blob:
long lb_num lb_num = Long(BlobMid(lb_blob, 20, 4))
For an example of assigning and extracting values from a blob, see Real.
See also
Dec Double Integer LongLong Real Long method for DataWindows in the DataWindow Reference or the online Help
716
PowerBuilder
CHAPTER 10
PowerScript Functions
LongLong
Converts data into data of type longlong. There are two syntaxes.
To Combine two unsigned long values into a longlong value Convert a string whose value is a number into a longlong or obtain a longlong value stored in a blob Use Syntax 1 Syntax 2
Syntax 1
Description Syntax
LongLong. Returns the longlong if it succeeds and -1 if an error occurs. If any arguments value is NULL, LongLong returns NULL.
Use LongLong for passing values to external C++ and Java functions. These statements convert the UnsignedLongs lLow and lHigh into a long value:
UnsignedLong lLow UnsignedLong lHigh longlong LLValue //Low long 32 bits //High long 32 bits //LongLong value 64 bits
lLow = 1234567890 lHigh = 9876543210 LLValue = LongLong(lLow, lHigh) MessageBox("LongLong Value", LLValue)
Syntax 2
Description Syntax
717
LongLong
Argument stringorblob
Description The string you want returned as a longlong or a blob in which the first value is the longlong value. The rest of the contents of the blob is ignored. Stringorblob can also be an Any variable containing a string or blob.
Return value
if stringorblob is not a valid PowerScript number or if it is an incompatible datatype. If stringorblob is NULL, Long returns NULL.
Usage
To distinguish between a string whose value is the number 0 and a string whose value is not a number, use the IsNumber function before calling the LongLong function. This statement returns 216789987654321 as a longlong:
LongLong("216789987654321")
Examples
After assigning blob data from the database to lb_blob, the following example obtains the longlong value stored at position 20 in the blob:
longlong llb_num llb_num = LongLong(BlobMid(lb_blob, 20, 4))
For an example of assigning and extracting values from a blob, see Real.
See also
718
PowerBuilder
CHAPTER 10
PowerScript Functions
Lookup
Allows a PowerBuilder client or component to obtain a factory or home interface in order to create an instance of an EAServer component. This function is used by PowerBuilder clients connecting to components running in EAServer, and by PowerBuilder components connecting to other components running on the same server.
To Obtain the factory interface of a CORBA-compliant component running in EAServer Obtain the home interface of an EJB component running in EAServer Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
objectvariable componentname
The Lookup function can be used as an alternative to the CreateInstance function. It obtains a reference to a factory interface that you can use to create an instance of a component running in EAServer. Use the Connection objects Lookup function to enable a PowerBuilder client to access a component running in EAServer. You can supply a server name or a list of server names in the location property of the Connection object.
719
CHAPTER 10
PowerScript Functions
Use the TransactionServer objects Lookup function to enable a PowerBuilder component running in EAServer to access another component running on the same server. To use the Lookup function, you need to create an EAServer proxy library for the SessionManager package to obtain a proxy for the factory interface. Include this proxy library in your library list.
Examples
The following example uses Lookup to instantiate the factory interface for the n_Bank_Account component, then it uses the factorys create method to create an instance of the component:
// Instance variable: // Connection myconnect Factory my_Factory CORBAObject mycorbaobj n_Bank_Account my_account long ll_result ll_result = & myconnect.lookup(my_Factory,"Bank/n_Bank_Account") mycorbaobj = my_Factory.create() mycorbaobj._narrow(my_account, "Bank/n_Bank_Account") my_account.withdraw(100.0)
See also
CreateInstance
Syntax 2
Description Applies to Syntax
objectvariable componentname
720
CHAPTER 10
PowerScript Functions
Argument homeid
Description A string whose value is the name of the home interface to be created. This argument is optional
EJBConnection
You can also use the Lookup method of the EJBConnection PowerBuilder extension object to create an instance of an EJB component running on any J2EE compliant application server. For more information, see Lookup in the PowerBuilder Extension Reference. The Lookup function creates an instance of the home interface of an EJB component so that you can use it to create an instance of the EJB. Use the Connection objects Lookup function to enable a PowerBuilder client to access a component running in EAServer. You can supply a server name or a list of server names in the location property of the Connection object. Use the TransactionServer objects Lookup function to enable a PowerBuilder component running in EAServer to access an EJB component running on the same server. The Lookup function uses the standard CORBA naming service to resolve componentname to a CORBA object that is then narrowed to the home interface name of the component. If you do not specify the third argument to the Lookup function, PowerBuilder expects the home interface name to have the format PackageName/CompNameHome. However, most EJB components use a standard Java package directory structure and the home interface name has a format such as com/domain/project/CompNameHome. You can ensure that a PowerBuilder client or component can locate the components home interface by supplying the third argument to the Lookup function to specify the home interface name. A components home interface name is defined in the com.sybase.jaguar.component.home.ids property in the EAServer repository. The home.ids property has a format like this:
IDL:com/domain/project/CompNameHome:1.0
The third argument should be the value of the components home.ids string without the leading IDL: and trailing :1.0. For example:
ts.lookup(MyCartHome, "shopping/cart", & "com/sybase/shopping/CartHome")
721
Lookup
Alternatively, you can use the fully-qualified Java class name of the home interface specified in dot notation. For example:
ts.lookup(MyCartHome, "shopping/cart", & "com.sybase.shopping.CartHome") Lookup is case sensitive
Lookup in EAServer is case sensitive. Make sure that the case in the string you specify in the argument to the lookup function matches the case in the ejb.home property.
Examples
The following example uses Lookup with the Connection object to locate the home interface of the Multiply session EJB in the Java package abc.xyz.math:
// Instance variable: // Connection myconnect Multiply myMultiply MultiplyHome myMultiplyHome long ll_result, ll_product ll_result = & myconnect.lookup(myMultiplyHome,"Math/Multiply", & "abc.xyz.math.MultiplyHome) IF ll_result <> = 0 THEN MessageBox("Lookup failed", myconnect.errtext) ELSE try myMultiply = myMultiplyHome.create() catch (ctscomponents_createexception ce) MessageBox("Create exception", ce.getmessage()) // handle exception end try ll_product = myMultiply.multiply(1234, 4567) END IF
Entity beans have a findByPrimaryKey method that you can use to find an EJB saved in the previous session. This example uses that method to find a shopping cart saved for Dirk Dent:
// Instance variable: // Connection myconnect Cart myCart CartHome myCartHome long ll_result
722
PowerBuilder
CHAPTER 10
PowerScript Functions
ll_result = & myconnect.lookup(myCartHome,"Shopping/Cart", & "com.mybiz.shopping.CartHome") IF ll_result <> = 0 THEN MessageBox("Lookup failed", myconnect.errtext) ELSE TRY myCart = myCartHome.findByPrimaryKey("DirkDent") myCart.addItem(101) CATCH ( ctscomponents_finderexception fe ) MessageBox("Finder exception", & fe.getmessage()) END TRY END IF
Nonvisual objects deployed from PowerBuilder to EAServer can use an instance of the TransactionServer context object to locate the home interface of an EJB component in the same server:
CalcHome MyCalcHome Calc MyCalc TransactionServer ts ErrorLogging errlog long ll_result this.GetContextService("TransactionServer", ts) this.GetContextService("ErrorLogging", errlog) ll_result = ts.lookup(MyCalcHome, "Utilities/Calc", & "com.biz.access.utilities.CalcHome") IF ll_result <> 0 THEN errlog.log("Lookup failed: " + string(ll_result)) ELSE TRY MyCalc = MyCalcHome.create() MyCalc.square(12) CATCH (ctscomponents_createexception ce) errlog.log("Create exception: " + ce.getmessage()) END TRY END IF See also
ConnectToServer
723
Lower
Lower
Description Syntax
Return value
String. Returns string with uppercase letters changed to lowercase if it succeeds and the empty string ("") if an error occurs. If string is NULL, Lower returns NULL.
Examples
See also
Upper
Lower method for DataWindows in the DataWindow Reference or the online
Help
724
PowerBuilder
CHAPTER 10
PowerScript Functions
LowerBound
Description Syntax
Return value
Long. Returns the lower bound of dimension n of array and -1 if n is greater than the number of dimensions of the array. If any arguments value is NULL, LowerBound returns NULL.
Usage
For variable-size arrays, memory is allocated for the array when you assign values to it. Before you assign values, the lower bound is 1 and the upper bound is 0. The following statements illustrate the values LowerBound reports for fixed-size arrays and for variable-size arrays before and after memory has been allocated:
integer a[5], LowerBound(a) LowerBound(a, LowerBound(a, LowerBound(b, integer c[ ] LowerBound(c) c[50] = 900 LowerBound(c) b[2,5] // Returns 1) // Returns 2) // Returns 2) // Returns 1 1 -1, a has only 1 dim 1
Examples
// Returns 1 // Returns 1
- 10
UpperBound
725
mailAddress
mailAddress
Description Applies to Syntax
Return value
mailReturnCode. Returns one of the following values: mailReturnSuccess! mailReturnFailure! mailReturnInsufficientMemory! mailReturnUserAbort! If any arguments value is NULL, mailAddress returns NULL.
Usage
The mailRecipient array contains information about recipients of a mail message or the originator of a message. The originator is not used when you send a message. If there is an error in the mailRecipient array, mailAddress displays the Address dialog box so the user can fix the address. If you pass a mailMessage structure that is a validly addressed message (such as a message that the user received) nothing happens because the addresses are correct. If you do not specify a mailMessage, the mail system displays an Address dialog box that allows users to look for addresses and maintain their personal address list. The user cannot select addresses for addressing a message. Before calling mail functions, you must declare and create a mailSession object and call mailLogon to establish a mail session.
Examples
These statements create a mail session, send mail with an attached TXT file, and then log off the mail system and destroy the mail session object:
mailSession mSes mailReturnCode mRet mailMessage mMsg mailFileDescription mAttach
726
PowerBuilder
CHAPTER 10
PowerScript Functions
// Create a mail session mSes = CREATE mailSession // Log on to the session mRet = mSes.mailLogon(mailNewSession!) IF mRet <> mailReturnSuccess! THEN MessageBox("Mail", Logon failed.) RETURN END IF mMsg.AttachmentFile[1] = mAttach mRet = mSes.mailAddress(mMsg) IF mRet <> mailReturnSuccess! THEN MessageBox("Mail", Addressing failed.) RETURN END IF // Send the mail mRet = mSes.mailSend(mMsg) IF mRet <> mailReturnSuccess! THEN MessageBox("Mail", Sending mail failed.) RETURN END IF mSes.mailLogoff() DESTROY mSes See also
727
mailDeleteMessage
mailDeleteMessage
Description Applies to Syntax
Deletes a mail message from the users electronic mail inbox. mailSession object
mailsession.mailDeleteMessage ( messageid ) Argument mailsession messageid Description A mailSession object identifying the session in which you want to delete the message A string whose value is the ID of the mail message to be deleted
Return value
mailReturnCode. Returns one of the following values: mailReturnSuccess! mailReturnFailure! mailReturnInsufficientMemory! mailReturnInvalidMessage! mailReturnUserAbort! If any arguments value is NULL, mailDeleteMessage returns NULL.
Usage
To get a list of message IDs in the users inbox, call the mailGetMessages function. Before calling mail functions, you must declare and create a mailSession object and call mailLogon to establish a mail session. Assume the DataWindow dw_inbox contains a list of mail items (sender, subject, postmark, and message ID), and that the mail session mSes has been created and a successful logon has occurred. This script for the clicked event for dw_inbox deletes the selected message from the mail system:
string sID integer nRow mailReturnCode mRet nRow = GetClickedRow() IF nRow > 0 THEN sID = GetItemString(nRow, "messageID") mRet = mSes.mailDeleteMessage(sID) END IF
Examples
See also
mailGetMessages mailLogon
728
PowerBuilder
CHAPTER 10
PowerScript Functions
mailGetMessages
Description Applies to Syntax
Populates the messageID array of a mailSession object with the message IDs in the users inbox. mailSession object
mailsession.mailGetMessages ( { messagetype, } { unreadonly } ) Argument mailsession messagetype (optional) Description A mailSession object identifying the session in which you want to get the messages. A string whose value is a message type. The default message type is IPM or an empty string (""), which identifies interpersonal messages. The other standard type is IPC, which identifies hidden, interprocess messages. Your mail administrator may have established other user-defined message types. A boolean value indicating you want only the IDs of unread messages. Values are: TRUE Get IDs for unread messages only FALSE Get IDs for all messages
unreadonly (optional)
Return value
mailReturnCode. Returns one of the following values: mailReturnSuccess! mailReturnFailure! mailReturnInsufficientMemory! mailReturnNoMessages! mailReturnUserAbort! If any arguments value is NULL, mailGetMessages returns NULL.
Usage
mailSession objects MessageID array. A message ID serves as an argument for other mail functions. With mailReadMessage, for example, it identifies the message you want to read. Before calling mail functions, you must declare and create a mailSession object and call mailLogon to establish a mail session.
Examples
This example populates a DataWindow with the messages in the users inbox. The DataWindow is defined with an external data source and has three columns: msgid, msgdate, and msgsubject. MailGetMessages fills the MessageID array in the mailSession object and mailReadMessage gets the information for each ID.
729
mailGetMessages
The example assumes that the application has already created the mailSession object mSes and logged on:
mailMessage msg long n, c_row mSes.mailGetMessages() FOR n = 1 to UpperBound(mSes.MessageID[]) mSes.mailReadMessage(mSes.MessageID[n], & msg, mailEnvelopeOnly!, FALSE) c_row = dw_1.InsertRow(0) dw_1.SetItem(c_row, "msgid", mSes.MessageID[n]) dw_1.SetItem(c_row, "msgdate", msg.DateReceived) // Truncate subject to fit defined column size dw_1.SetItem(c_row, "msgsubject", & Left(msg.Subject, 50)) NEXT See also
mailDeleteMessage mailReadMessage
730
PowerBuilder
CHAPTER 10
PowerScript Functions
mailHandle
Description Applies to Syntax
UnsignedLong. Returns the internal handle of the mail session object. If mailsession is NULL, mailHandle returns NULL.
After you have logged on, your mailSession has a valid handle. You can use that handle to call external mail functions. MAPI has additional functions that PowerBuilder does not implement directly. Before calling mail functions, you must declare and create a mailSession object and call mailLogon to establish a mail session.
Examples
731
mailLogoff
mailLogoff
Description
Ends the mail session, breaking the connection between the PowerBuilder application and mail. If the mail application was already running when PowerBuilder began the mail session, it is left in the same state. mailSession object
mailsession.mailLogoff ( ) Argument mailsession Description A mailSession object identifying the session from which you want to log off
Applies to Syntax
Return value
Usage
To release the memory used by the mailSession object, use the DESTROY keyword after ending the mail session. Before calling mail functions, you must declare and create a mailSession object and call mailLogon to establish a mail session.
Examples
See also
mailLogon
732
PowerBuilder
CHAPTER 10
PowerScript Functions
mailLogon
Description Applies to Syntax
Establishes a mail session for the PowerBuilder application. The PowerBuilder application can start a new session or join an existing session. mailSession object
mailsession.mailLogon ( { profile, password } {, logonoption } ) Argument mailsession profile (optional) password (optional) logonoption (optional) Description A mailSession object identifying the session you want to logon to. A string whose value is the users mail system profile or user ID. A string whose value is the users mail system password. A value of the mailLogonOption enumerated datatype specifying the logon options: mailNewSession! Starts a new mail session, whether or not the mail application is already running mailDownLoad! Forces the mail application to download any new messages from the server to the users inbox. Starts a new mail session only if the mail application is not running mailNewSessionWithDownLoad! Starts a new mail session and forces new messages to be downloaded from the server to the users inbox The default is to use an existing session if possible and not to force new messages to be downloaded.
Return value
mailReturnCode. Returns one of the following values: mailReturnSuccess! mailReturnLoginFailure! mailReturnInsufficientMemory! mailReturnTooManySessions! mailReturnUserAbort! If any arguments value is NULL, mailLogon returns NULL.
Usage
If you do not direct mailLogon to start a new session and the mail application is already running on the users computer, then the PowerBuilder mail session attaches to the existing session. A profile and password are not necessary. When mailLogon establishes a new session, then the mail systems dialog box prompts for the profile and password if the script does not supply them.
733
mailLogon
The download option forces the mail server to download the latest messages to the users inbox. This ensures that the inbox is up to date; it does not make the messages available to PowerBuilder. To access messages, use mailGetMessages and mailReadMessage. Before calling mailLogon, you must declare and create a mailSession object.
Examples
In this example, the mailSession object new_session is an instance variable of the window. The windows Open event script allocates memory for the mailSession object and logs on. During the logon process, the mail application displays a dialog box prompting for the profile and password:
new_session = CREATE mailSession new_session.mailLogon(mailNewSession!)
This example establishes a new mail session and makes the users inbox up to date. The user wo not be prompted for an ID and password because user information is provided. Here the mailSession object is a local variable:
mailSession new_session new_session = CREATE mailSession new_session.mailLogon("jpl", "hotstuff", & mailNewSessionWithDownLoad!) See also
mailLogoff
734
PowerBuilder
CHAPTER 10
PowerScript Functions
mailReadMessage
Description
Opens a mail message whose ID is stored in the mail sessions message array. You can choose to read the entire message or the envelope (sender, date received, and so on) only. If a message has attachments, they are stored in a temporary file. You can also choose to have the message text written to in a temporary file. mailSession object
mailsession.mailReadMessage ( messageid, mailmessage, readoption, mark ) Argument mailsession messageid mailmessage readoption Description A mailSession object identifying the session in which you want to read a message. A string whose value is the ID of the mail message you want to read. A mailMessage structure in which mailReadMessage stores the message information. A value of the mailReadOption enumerated datatype: mailEntireMessage! Obtain header, text, and attachments mailEnvelopeOnly! Obtain header information only mailBodyAsFile! Obtain header, text, and attachments, and treat the message text as the first attachment, storing it in a temporary file mailSuppressAttachments! Obtain header and text, but no attachments A boolean indicating whether you want to mark the message as read in the users inbox. Values are: TRUE Mark the message as read FALSE Do not mark the message as read
Applies to Syntax
mark
Return value
MailReturnCode. Returns one of the following values: mailReturnSuccess! mailReturnFailure! mailReturnInsufficientMemory! If any arguments value is NULL, mailReadMessage returns NULL.
Usage
To obtain the message IDs for the messages in the users inbox, call mailGetMessages. Before calling mail functions, you must declare and create a mailSession object and call mailLogon to establish a mail session.
735
mailReadMessage
Reading attachments
If a message has an attachment and you do not suppress attachments, information about it is stored in the AttachmentFile property of the mailMessage object. The AttachmentFile property is a mailFileDescription object. Its PathName property has the location of the temporary file that mailReadMessage created for the attachment. By default, the temporary file is in the directory specified by the TEMP environment variable. Be sure to delete this temporary file when you no longer need it.
Examples
In this example, mail is displayed in a window with a DataWindow dw_inbox that lists mail messages and a MultiLineEdit mle_note that displays the message text. Assuming that the application has created the mailSession object mSes and successfully logged on, and that dw_inbox contains a list of mail items (sender, subject, postmark, and message ID); this script for the Clicked event for dw_inbox displays the text of the selected message in the MultiLineEdit mle_note:
integer nRow, nRet string sMessageID string sRet, sName // Find out what Mail Item was selected nRow = GetClickedRow() IF nRow > 0 THEN // Get the message ID from the row sMessageID = GetItemString(nRow, MessageID) // Reread the message to obtain entire contents // because previously we read only the envelope mRet = mSes.mailReadMessage(sMessageID, mMsg & mailEntireMessage!, TRUE) // Display the text mle_note.Text = mMsg.NoteText END IF
See mailGetMessages for an example that creates a list of mail messages in a DataWindow control, the type of setup that this example expects. See also the mail examples in the Code Examples sample application supplied with PowerBuilder.
See also
736
PowerBuilder
CHAPTER 10
PowerScript Functions
mailRecipientDetails
Description Applies to Syntax
Displays a dialog box with the specified recipients address information. mailSession object
mailsession.mailRecipientDetails ( mailrecipient {, allowupdates } ) Argument mailsession mailrecipient Description A mailSession identifying the session in which you want to display the detail information for a recipient. A mailRecipient structure containing valid address information. Mailrecipient must contain a recipient identifier returned by mailAddress, mailResolveRecipient, or mailReadMessage. A boolean indicating whether updates to the recipients name will be allowed. If the user does not have update privileges for the mail system, then allowupdates is ignored. The default is FALSE.
allowupdates (optional)
Return value
mailReturnCode. Returns one of the following values: mailReturnSuccess! mailReturnFailure! mailReturnInsufficientMemory! mailReturnUnknownRecipient! mailReturnUserAbort! If any arguments value is NULL, mailRecipientDetails returns NULL.
Usage
The effect of setting allowupdates to TRUE depends on the mail system and the users privileges. Before calling mail functions, you must declare and create a mailSession object and call mailLogon to establish a mail session.
Examples
This example gets the message IDs from the users inbox and reads the first message. It then calls mailRecipientDetails to display address information for the first recipient. Recipient is an array of structures and a property of mailMessage. Each array element is one of the messages recipients. The example does not check how many values there are in the message ID or recipient arrays and it assumes that the application has already created a mailSession object and logged on:
mailMessage msg integer n long c_row
737
mailRecipientDetails
mailResolveRecipient mailSend
738
PowerBuilder
CHAPTER 10
PowerScript Functions
mailResolveRecipient
Description
Obtains a valid e-mail address based on a partial or full user name and optionally updates information in the systems address list if the user has privileges to do so. mailSession object
mailsession.mailResolveRecipient ( recipient {, allowupdates } ) Argument mailsession recipient Description A mailSession object identifying the session in which you want to resolve the recipient. A mailRecipient structure or a string variable whose value is a recipients name. The recipients name is a property of the mailRecipient structure. MailResolveRecipient sets the value of the string to the recipients full name or the structure to the resolved address information. A boolean indicating whether updates to the recipients name will be allowed. If the user does not have update privileges for the mail system, then allowupdates is ignored. The default is FALSE.
Applies to Syntax
allowupdates (optional)
Return value
mailReturnCode. Returns one of the following values: mailReturnSuccess! mailReturnFailure! mailReturnInsufficientMemory! mailReturnUserAbort! If any arguments value is NULL, mailResolveRecipient returns NULL.
Usage
Use mailResolveRecipient to verify that a name is a valid address in the mail system. The function reports mailReturnFailure! if the name is not found. If you supply a mailRecipient structure, mailResolveRecipient fills the structure with valid address information when it resolves the address. If you supply a name as a string, mailResolveRecipient replaces the strings value with the full user name as recognized by the mail system. An address specified as a string is adequate for users in the local mail system. If you are sending mail through gateways to other systems, you should obtain full address details in a mailRecipient structure. If more than one address on the mail system matches the partial address information you supply to mailResolveRecipient, the mail system may display a dialog box allowing the user to choose the desired name.
739
mailResolveRecipient
If you supply a mailRecipient structure that already has address information, mailResolveRecipient corrects the information if it differs from the mail system. If you set allowupdates to TRUE and the information differs from the mail system, mailResolveRecipient corrects the mail systems information if the user has rights to do so. Be careful that the address information you have is correct when you allow updating. Before calling mail functions, you must declare and create a mailSession object and call mailLogon to establish a mail session.
Examples
This example checks whether there is a user J Smith is on the mail system. If there is a user whose name matches, such as Jane Smith or Jerry Smith, the variable mname is set to the full name. If both names are on the system, the mail system displays a dialog box from which the user chooses a name. Mname is set to the users choice. The application has already created the mailSession object mSes and logged on:
mailReturnCode mRet string mname mname = "Smith, J" mRet = mSes.mailResolveRecipient(mname) IF mRet = mailReturnSuccess! THEN MessageBox("Address", mname + " found.") ELSEIF mRet = mailReturnFailure! THEN MessageBox("Address", "J Smith not found.") ELSE MessageBox("Address", "Request not evaluated.") END IF
In this example, sle_to contains the full or partial name of a mail recipient. This example assigns the name to a mailRecipient object and calls mailResolveRecipient to find the name and get address details. If the name is found, mailRecipientDetails displays the information and the full name is assigned to sle_to. The application has already created the mailSession object mSes and logged on:
mailReturnCode mRet mailRecipient mRecip mRecip.Name = sle_to.Text mRet = mSes.mailResolveRecipient(mRecip) IF mRet <> mailReturnSuccess! THEN MessageBox ("Address", & sle_to.Text + "not found.")
740
PowerBuilder
CHAPTER 10
PowerScript Functions
741
mailSaveMessage
mailSaveMessage
Description Applies to Syntax
Creates a new message in the users inbox or replaces an existing message. mailSession object
mailsession.mailSaveMessage ( messageid, mailmessage ) Argument mailsession messageid Description A mailSession object identifying the session in which you want to save the mail message. A string whose value is the message ID of the message being replaced. If you are saving a new message, specify an empty string (""). A mailMessage structure containing the message being saved.
mailReturnCode. Returns one of the following values: mailReturnSuccess! mailReturnFailure! mailReturnInsufficientMemory! mailReturnInvalidMessage! mailReturnUserAbort! mailReturnDiskFull! If any arguments value is NULL, mailSaveMessage returns NULL.
Usage
Before saving a message, you must address the message even if you are replacing an existing message. The message can be addressed to someone else for sending later. Before calling mail functions, you must declare and create a mailSession object and call mailLogon to establish a mail session.
Examples
This example creates a new message in the inbox of the current user, which will be sent later to Jerry Smith. The application has already created the mailSession object mSes and logged on:
mailRecipient recip mailMessage msg mailReturnCode mRet recip.Name = "Smith, Jerry" mRet = mSes.mailResolveRecipient(recip) IF mRet <> mailReturnSuccess! THEN MessageBox("Save New Message", & "Invalid address.") RETURN END IF
742
PowerBuilder
CHAPTER 10
PowerScript Functions
msg.NoteText = mle_note.Text msg.Subject = sle_subject.Text msg.Recipient[1] = recip mRet = mSes.mailSaveMessage("", msg) IF mRet <> mailReturnSuccess! THEN MessageBox("Save New Message", & "Failed somehow.") END IF
This example replaces the last message in the user Jane Smiths inbox. It gets the message ID from the MessageID array in the mailSession object mSes. It changes the message subject, re-addresses the message to the user, and saves the message. The application has already created the mailSession object mSes and logged on:
mailRecipient recip mailMessage msg mailReturnCode mRet string s_ID mRet = mSes.mailGetMessages() IF mRet <> mailReturnSuccess! THEN MessageBox("No Messages", "Inbox empty.") RETURN END IF s_ID = mSes.MessageID[UpperBound(mSes.MessageID)] mRet = mSes.mailReadMessage(s, msg, & mailEntireMessage!, FALSE ) IF mRet <> mailReturnSuccess! THEN MessageBox("Message", "Cant read message.") RETURN END IF msg.Subject = msg.Subject + " Test" recip.Name = "Smith, Jane" mRet = mSes.mailResolveRecipient( recip ) msg.Recipient[1] = recip mRet = mSes.mailSaveMessage(s_ID, msg) IF mRet <> mailReturnSuccess! THEN MessageBox("Save Old Message", "Failed somehow.") END IF
See also the mail examples in the samples that are supplied with PowerBuilder.
See also
mailSend
mailSend
Description Applies to Syntax
Sends a mail message. If no message information is supplied, the mail system provides a dialog box for entering it before sending the message. mailSession object
mailsession.mailSend ( { mailmessage } ) Argument mailsession mailmessage (optional) Description A mailSession object identifying the session in which you want to send the mail message A mailMessage structure
Return value
mailReturnCode. Returns one of the following values: mailReturnSuccess! mailReturnFailure! mailReturnInsufficientMemory! mailReturnLogFailure! mailReturnUserAbort! mailReturnDiskFull! mailReturnTooManySessions! mailReturnTooManyFiles! mailReturnTooManyRecipients! mailReturnUnknownRecipient! mailReturnAttachmentNotFound! If any arguments value is NULL, mailSend returns NULL.
Usage
Before calling mail functions, you must declare and create a mailSession object and call mailLogon to establish a mail session. For mailSend, mailOriginator! is not a valid value for the Recipient property of the mailMessage object. The valid values are mailto!, mailcc!, and mailbcc!. To specify that the sender receive a copy of the message, use mailcc!.
Examples
These statements create a mail session, send a message, and then log off the mail system and destroy the mail session object:
mailSession mSes mailReturnCode mRet mailMessage mMsg // Create a mail session mSes = create mailSession
744
PowerBuilder
CHAPTER 10
PowerScript Functions
// Log on to the session mRet = mSes.mailLogon(mailNewSession!) IF mRet <> mailReturnSuccess! THEN MessageBox("Mail", Logon failed.) RETURN END IF // Populate the mailMessage structure mMsg.Subject = mle_subject.Text mMsg.NoteText = Luncheon at 12:15 mMsg.Recipient[1].name = Smith, John mMsg.Recipient[2].name = Shaw, Sue // Send the mail mRet = mSes.mailSend(mMsg) IF mRet <> mailReturnSuccess! THEN MessageBox("Mail Send", Mail not sent) RETURN END IF mSes.mailLogoff() DESTROY mSes
See also the mail examples in the samples supplied with PowerBuilder.
See also
mailReadMessage mailResolveRecipient
745
Match
Match
Description
Boolean. Returns TRUE if string matches textpattern and FALSE if it does not. Match also returns FALSE if either argument has not been assigned a value or the pattern is invalid. If any arguments value is NULL, Match returns NULL. Match enables you to evaluate whether a string contains a general pattern of characters. To find out whether a string contains a specific substring, use the Pos function.
Usage
Textpattern is similar to a regular expression. It consists of metacharacters, which have special meaning, and ordinary characters, which match themselves. You can specify that the string begin or end with one or more characters from a set, or that it contain any characters except those in a set. A text pattern consists of metacharacters, which have special meaning in the match string, and nonmetacharacters, which match the characters themselves.The following tables explain the meaning and use of these metacharacters.
Table 10-4: Metacharacters used by Match function Metacharacter Caret (^) Dollar sign ($) Period (.) Backslash (\) Meaning Matches the beginning of a string Matches the end of a string Matches any character Removes the following metacharacters special characteristics so that it matches itself Example ^C matches C at the beginning of a string. s$ matches s at the end of a string. . . . matches three consecutive characters. \$ matches $.
746
PowerBuilder
CHAPTER 10
PowerScript Functions
Example [AEIOU] matches A, E, I, O, or U. You can use hyphens to abbreviate ranges of characters in a character class. For example, [A-Za-z] matches any letter. [^0-9] matches any character except a digit, and [^A-Za-z] matches any character except a letter.
The metacharacters asterisk (*), plus (+), and question mark (?) are unary operators that are used to specify repetitions in a regular expression:
Table 10-5: Unary operators used as metacharacters by Match function Metacharacter * (asterisk) + (plus) ? (question mark) Meaning Indicates zero or more occurrences Indicates one or more occurrences Indicates zero or one occurrence Example A* matches zero or more As (no As, A, AA, AAA, and so on) A+ matches one A or more than one A (A, AAA, and so on) A? matches an empty string ("") or A
Sample patterns
The following table shows various text patterns and sample text that matches each pattern:
Table 10-6: Text pattern examples for Match function This pattern AB B* AB*C AB+C ABB*C ^AB AB?C ^[ABC] Matches Any string that contains AB; for example, ABA, DEABC, graphAB_one Any string that contains 0 or more Bs; for example, AC, B, BB, BBB, ABBBC, and so on Any string containing the pattern AC or ABC or ABBC, and so on (0 or more Bs) Any string containing the pattern ABC or ABBC or ABBBC, and so on (1 or more Bs) Any string containing the pattern ABC or ABBC or ABBBC, and so on (1 B plus 0 or more Bs) Any string starting with AB Any string containing the pattern AC or ABC (0 or 1 B) Any string starting with A, B, or C
747
Match
Matches A string containing any characters other than A, B, or C A string that begins with any character except a, b, or c Any single-character string that is not a lowercase letter (^ and $ indicate the beginning and end of the string) Any string with one or more uppercase letters Any string consisting only of digits Any string consisting of exactly three digits Any consisting of exactly three digits enclosed in parentheses
In SBCS environments, the Match and MatchW functions are equivalent. Although you can use the Match function in DBCS environments, the string evaluation is based exclusively on single-byte computation. Since characters in DBCS environments can be single byte, double byte, or mixed, you must use the MatchW function to evaluate a string with double-byte or mixed single-byte and double-byte characters.
Examples
This statement returns TRUE if the text in sle_ID begins with one or more uppercase or lowercase letters (^ at the beginning of the pattern means that the beginning of the string must match the characters that follow):
Match(sle_ID.Text, "^[A-Za-z]")
This statement returns FALSE if the text in sle_ID contains any digits (^ inside a bracket is a complement operator):
Match(sle_ID.Text, "[^0-9]")
This statement returns TRUE if the text in sle_ID contains one uppercase letter:
Match(sle_ID.Text, "[A-Z]")
This statement returns TRUE if the text in sle_ID contains one or more uppercase letters (+ indicates one or more occurrences of the pattern):
Match(sle_ID.Text, "[A-Z]+")
This statement returns FALSE if the text in sle_ID contains anything other than two digits followed by a letter (^ and $ indicate the beginning and end of the string):
Match(sle_ID.Text, "^[0-9][0-9][A-Za-z]$") See also
Pos
Match method for DataWindows in the DataWindow Reference or the online
Help
748
PowerBuilder
CHAPTER 10
PowerScript Functions
MatchW
Description Syntax
Determines whether a strings value contains a particular pattern of characters. For more information, see Match.
MatchW ( string, textpattern )
Max
Description Syntax
The datatype of x or y, whichever datatype is more precise. If any arguments value is NULL, Max returns NULL. If either of the values being compared is NULL, Max returns NULL. This statement returns 7:
Max(4,7)
Min
Max method for DataWindows in the DataWindow Reference or the online
Help
749
MemberDelete
MemberDelete
Description Applies to Syntax
Deletes a member from an OLE object in a storage. The member can be another OLE object (a substorage) or a stream. OLEStorage objects
olestorage.MemberDelete ( membername ) Argument olestorage membername Description The name of an object variable of type OLEStorage containing the member (substorage or stream) you want to delete A string specifying the name of the member you want to delete from the storage
Return value
error occurs: -1 The storage is not open -2 Member not found -3 Insufficient resources or too many files open -4 Access denied -5 Invalid storage state -9 Other error If any arguments value is NULL, MemberDelete returns NULL.
Examples
This example creates a storage object and opens an OLE object in a file. It checks whether wordobj is a substorage within that object and, if so, deletes it and saves the object back to the file:
boolean lb_memexists integer result stg_stuff = CREATE OLEStorage stg_stuff.Open("c:\ole2\mystuff.ole") stg_stuff.MemberExists("wordobj", lb_memexists) IF lb_memexists THEN result = stg_stuff.MemberDelete("wordobj") IF result = 0 THEN stg_stuff.Save() END IF
See also
750
PowerBuilder
CHAPTER 10
PowerScript Functions
MemberExists
Description Applies to Syntax
Determines whether the named member is part of an OLE object in a storage. The member can be another OLE object (a substorage) or a stream. OLEStorage objects
olestorage.MemberExists ( membername, exists ) Argument olestorage membername exists Description The name of an object variable of type OLEStorage that you want to check A string whose value is the name of the member that you want to check A boolean variable that will store whether or not the member exists
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 The storage is not open -9 Other error If any arguments value is NULL, MemberExists returns NULL.
Examples
This example creates a storage object and opens an OLE object in a file. It checks whether wordobj is a substorage within that object and, if so, deletes it and saves the object back to the file:
boolean lb_memexists integer result stg_stuff = CREATE OLEStorage stg_stuff.Open("c:\ole2\mystuff.ole") stg_stuff.MemberExists("wordobj", lb_memexists) IF lb_memexists THEN result = stg_stuff.MemberDelete("wordobj") IF result = 0 THEN stg_stuff.Save( ) END IF
See also
751
MemberRename
MemberRename
Description Applies to Syntax
Renames a member in an OLE storage. The member can be another OLE object (a substorage) or a stream. OLEStorage objects
olestorage.MemberRename ( membername, newname ) Argument olestorage membername newname Description The name of an object variable of type OLEStorage containing the member (substorage or stream) you want to rename A string whose value is the name of the member you want to rename A string whose value is the new name to be assigned to the member
Return value
error occurs: -1 The storage is not open -2 Member not found -3 Insufficient resources or too many files open -4 Access denied -5 Invalid storage state -6 Duplicate name -9 Other error If any arguments value is NULL, MemberRename returns NULL.
Examples
This example creates a storage object and opens an OLE object in a file. It checks whether wordobj is a substorage within that object, and if so renames it to memo and saves the object back to the file:
boolean lb_memexists integer result stg_stuff = CREATE OLEStorage stg_stuff.Open("c:\ole2\mystuff.ole") stg_stuff.MemberExists("wordobj", lb_memexists) IF lb_memexists THEN result = & stg_stuff.MemberRename("wordobj", "memo") IF result = 0 THEN stg_stuff.Save() END IF
See also
752
PowerBuilder
CHAPTER 10
PowerScript Functions
MessageBox
Description Syntax
Displays a system MessageBox with the title, text, icon, and buttons you specify.
MessageBox ( title, text {, icon {, button {, default } } } ) Argument title text icon (optional) Description A string specifying the title of the message box, which appears in the boxs title bar. The text you want to display in the message box. The text can be a numeric datatype, a string, or a boolean value. A value of the Icon enumerated datatype indicating the icon you want to display on the left side of the message box. Values are: Information! (Default) StopSign! Exclamation! Question! button (optional) None! A value of the Button enumerated datatype indicating the set of CommandButtons you want to display at the bottom of the message box. The buttons are numbered in the order listed in the enumerated datatype. Values are: OK! (Default) OK button OKCancel! OK and Cancel buttons YesNo! Yes and No buttons YesNoCancel! Yes, No, and Cancel buttons RetryCancel! Retry and Cancel buttons AbortRetryIgnore! Abort, Retry, and Ignore buttons default (optional) The number of the button you want to be the default button. The default is 1. If you specify a number larger than the number of buttons displayed, MessageBox uses the default.
Return value
Integer. Returns the number of the selected button (1, 2, or 3) if it succeeds and -1 if an error occurs. If any arguments value is NULL, MessageBox returns NULL.
Usage
If the value of title or text is NULL, the MessageBox does not display. Unless you specify otherwise, PowerBuilder continues executing the script when the user clicks the button or presses enter, which is appropriate when the MessageBox has one button. If the box has multiple buttons, you will need to include code in the script that checks the return value and takes an appropriate action.
753
MessageBox
Before continuing with the current application, the user must respond to the MessageBox. However, the user can switch to another application without responding to the MessageBox. When you are running a version of Windows that supports right-to-left languages and want to display Arabic or Hebrew text for the message and buttons, set the RightToLeft property of the application object to TRUE. The characters of the message will display from right to left. However, the button text will continue to display in English unless you are running a localized version of PowerBuilder.
When MessageBox does not work
Controls capture the mouse in order to perform certain operations. For instance, CommandButtons capture the mouse during mouse clicks, Edit controls capture for text selection, and scrollbars capture during scrolling. If a MessageBox is invoked while the mouse is captured, unexpected results can occur. Because MessageBox grabs focus, you should not use it when focus is changing, such as in a LoseFocus event. Instead, you might display a message in the windows title or a MultiLineEdit.
MessageBox also causes confusing behavior when called after PrintOpen. For details, see PrintOpen.
Examples
This statement displays a MessageBox with the title Greeting, the text Hello User, the default icon (Information!), and the default button (the OK button):
MessageBox("Greeting", "Hello User")
The following statements display a MessageBox titled Result and containing the result of a function, the Exclamation icon, and the OK and Cancel buttons (the Cancel button is the default):
integer Net long Distance = 3.457 Net = MessageBox("Result", Abs(Distance), & Exclamation!, OKCancel!, 2) IF Net = 1 THEN ... // Process OK. ELSE ... // Process CANCEL. END IF
754
PowerBuilder
CHAPTER 10
PowerScript Functions
Mid
Description
Return value
String. Returns characters specified in length of string starting at character start. If start is greater than the number of characters in string, the Mid function returns the empty string (""). If length is greater than the number of characters remaining after the start character, Mid returns the remaining characters. The return string is not filled with spaces to make it the specified length. If any arguments value is NULL, Mid returns NULL.
Usage
To search a string for the position of the substring that you want to extract, use the Pos function. Use the return value for the start argument of Mid. To extract a specified number of characters from the beginning or end of a string, use the Left or the Right function. In SBCS environments, the Mid and MidW functions return the same results. Although you can use the Mid function in DBCS environments, the string returned by this function is based exclusively on single-byte computation. Since characters in DBCS environments can be single byte, double byte, or mixed, you must use the MidW function to return a string with double-byte or mixed single-byte and double-byte characters.
Examples
755
Mid
These statements store the characters in the SingleLineEdit sle_address from the 40th character to the end in ls_address_extra:
string ls_address_extra ls_address_extra = Mid(sle_address.Text, 40)
The following user-defined function, called str_to_int_array, converts a string into an array of integers. Each integer in the array will contain two characters (one characters as the high byte (ASCII value * 256) and the second character as the low byte). The function arguments are str, a string passed by value, and iarr, an integer array passed by reference. The length of the array is initialized before the function is called. If the integer array is longer than the string, the script stores spaces. If the string is longer, the script ignores the extra characters. To call the function, use code like the following:
int rtn iarr[20]=0// Initialize the array, if necessary rtn = str_to_int_array("This is a test.", iarr)
756
PowerBuilder
CHAPTER 10
PowerScript Functions
ELSE // Use spaces if beyond the end of str char1 = " " char2 = " " END IF iarr[i] = Asc(char1) * 256 + Asc(char2) NEXT RETURN 1
For sample code that converts the integer array back to a string, see Asc.
See also
Asc Left Pos Right UpperBound Mid method for DataWindows in the DataWindow Reference or the online Help
MidW
Description Syntax
Obtains a specified number of characters from a specified position in a string. For more information, see Mid.
MidW ( string, start {, length } )
757
Min
Min
Description Syntax
The datatype of x or y, whichever datatype is more precise. If any arguments value is NULL, Min returns NULL. If either of the values being compared is NULL, Min returns NULL. This statement returns 4:
Min(4,7)
Max Min method for DataWindows in the DataWindow Reference or the online Help
Minute
Description Syntax
Integer. Returns the minutes portion of time (00 to 59). If time is NULL, Minute returns NULL.
See also
Hour Second Minute method for DataWindows in the DataWindow Reference or online Help
758
PowerBuilder
CHAPTER 10
PowerScript Functions
Mod
Description Syntax
The datatype of x or y, whichever datatype is more precise. If any arguments value is NULL, Mod returns NULL. This statement returns 2:
Mod(20, 6)
Help
759
ModifyData
ModifyData
Changes the value of a data point in a series on a graph. There are two syntaxes depending on the type of graph.
To modify a data point in All graph types except scatter Scatter graphs Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
Usage
When you specify categoryvalue, ModifyData changes the category value at the specified position, as well as the data value. If the name you specify already exists at another position, the data at that position is modified instead and the position in datapoint is ignored (the same behavior as InsertData). When you specify a position of 0, ModifyData always behaves the same as InsertData. For a comparison of AddData, InsertData, and ModifyData, see the Usage section in InsertData.
Examples
These statements change the data for Apr in the series named Costs in the graph gr_product_data:
integer SeriesNbr, CategoryNbr // Get the number of the series. SeriesNbr = gr_product_data.FindSeries("Costs")
760
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 2
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, ModifyData returns NULL.
For scatter graphs, there are no categories. You specify the position in the series whose data you want to modify and provide the x and y values for the data. These statements modify the data point 9 in the series named Test One in the scatter graph gr_product_data:
integer SeriesNbr SeriesNbr = gr_product.FindSeries("Test One") gr_product_data.ModifyData(SeriesNbr, & 9, 4.55, 86.38)
See also
AddData FindSeries
761
Month
Month
Description Syntax
Integer. Returns an integer (1 to 12) whose value is the month portion of date. If date is NULL, Month returns NULL.
These statements store in start_month the month entered in the SingleLineEdit sle_start_date:
integer start_month start_month = Month(date(sle_start_date.Text)) See also
Help
762
PowerBuilder
CHAPTER 10
PowerScript Functions
Move
Description Applies to Syntax
Moves a control or object to another position relative to its parent window, or for some window objects, relative to the screen. Any object or control
objectname.Move ( x, y ) Argument objectname x y Description The name of the object or control you want to move to a new location The x coordinate of the new location in PowerBuilder units The y coordinate of the new location in PowerBuilder units
Integer. Returns 1 if it succeeds and -1 if an error occurs or if objectname is a maximized window. If any arguments value is NULL, Move returns NULL.
The x and y coordinates you specify are the new coordinates of the upper-left corner of the object or control. If the shape of the object or control is not rectangular (such as, a RadioButton or Oval), x and y are the coordinates of the upper-left corner of the box enclosing it. When you move controls, drawing objects, and child windows, the coordinates you specify are relative to the upper-left corner of the parent window. When you use Move to position main, pop-up, and response windows, the coordinates you specify are relative to the upper-left corner of the display screen. Move does not move a maximized sheet or window. If the window is maximized, Move returns 1. You can use Move to move a line control but the results are unpredictable because the line has multiple x and y coordinates. You can specify coordinates outside the frame of the parent window or screen, which effectively makes the object or control invisible. To draw the image of a Picture control at a particular position, without actually moving the control, use the Draw function. The Move function changes the X and Y properties of the moved object.
Equivalent syntax
The syntax below directly sets the X and Y properties of an object or control. Although the result is equivalent to using the Move function, it causes PowerBuilder to redraw objectname twice, first at the new location of X and then at the new X and Y location:
objectname.X = x objectname.Y = y
763
Move
This statement has the same result but redraws gb_box1 once:
gb_box1.Move(150,200) Examples
This statement changes the X and Y properties of gb_box1 to 150 and 200, respectively, and moves gb_box1 to the new location:
gb_box1.Move(150, 200)
This statement moves the picture p_Train2 next to the picture p_Train1:
P_Train2.Move(P_Train1.X + P_Train1.Width, & P_Train1.Y)
764
PowerBuilder
CHAPTER 10
PowerScript Functions
MoveTab
Description Applies to Syntax
Moves a tab page to another position in a Tab control, changing its index number. Tab controls
tabcontrolname.MoveTab (source, destination ) Argument tabcontrolname source destination Description The name of the Tab control containing the tab you want to move. An integer whose value is the index of the tab you want to move. An integer whose value is the index of the destination tab before which source is moved. If destination is 0 or greater than the number of tabs, source is moved to the end.
Integer. Returns 1 if it succeeds and -1 if an error occurs. MoveTab also reorders the tab pages in the Tab controls Control array (which is a property that lists the tab pages within the Tab control) to match the new tab order.
Examples
OpenTab SelectTab
765
_Narrow
_Narrow
Description
Converts a CORBA object reference from a general supertype to a more specific subtype. This function is used by PowerBuilder clients connecting to EAServer.
Applies to Syntax
CORBAObject objects
corbaobject._Narrow ( newremoteobject, classname ) Argument corbaobject newremoteobject classname Description An object of type CORBAObject that you want to convert A variable that will contain the converted object reference The class name of the subtype to which you want to narrow the object reference
The _Narrow function allows you to narrow proxy objects in a CORBA-compatible client that connects to EAServer. For additional examples, see the functions on the See also list. The following example narrows a CORBA object reference to the n_Bank_Account interface:
CORBAObject my_corbaobj n_Bank_Account my_account ... ... my_corbaobj._narrow(my_account,"Bank/n_Bank_Account") my_account.withdraw(100.0)
Examples
In this example, the component is an EJB component that resides in a separate domain in EAServer. In this case, the SimpleBean components classes are in the ../classes/adomain/asimplepackage subdirectory:
CORBAObject my_corbaobj SimpleBean my_simplebean SimpleBeanHome my_simplebeanhome ... my_corbaobj._narrow(my_simplebeanhome, "adomain/asimplepackage/SimpleBeanHome") See also
766
PowerBuilder
CHAPTER 10
PowerScript Functions
NextActivity
Description Applies to Syntax
TraceActivityNode You use the NextActivity function to read the next activity in a trace file. The activity is returned as a TraceActivityNode object. If there are no more activities or if the file is not open, an invalid object is returned. You can then use the LastError property of the TraceFile object to determine what kind of error occurred. To use this function, you must have previously opened the trace file with the
Open function. You use the NextActivity and Open functions as well as the other
properties and functions provided by the TraceFile object to access the contents of a trace file directly. For example, you would use these functions if you want to perform your own analysis of the tracing data instead of using the available modeling objects.
Examples
This example opens a trace file and then uses a user-defined function called of_dumpactivitynode to report the appropriate information for each activity depending on its activity type:
String ls_filename, ls_line TraceFile ltf_file TraceActivityNode ltan_node ls_filename = sle_filename.text ltf_file = CREATE TraceFile ltf_file.Open(ls_filename) ls_line = "CollectionTime = " + & String(ltf_file.CollectionTime) + "~r~n" + & "Num Activities = " + & String(ltf_file.NumberOfActivities) + "~r~n mle_output.text = ls_line ltan_node = ltf_file.NextActivity()
767
NextActivity
DO WHILE IsValid(ltan_node) ls_line = of_dumpactivitynode(ltan_node) ltan_node = ltf_file.NextActivity() mle_output.text = ls_line LOOP See also
768
PowerBuilder
CHAPTER 10
PowerScript Functions
Now
Description Syntax Return value Usage
Obtains the current time based on the system time of the client machine.
Now ( )
Time. Returns the current time based on the system time of the client machine.
Use Now to compare a time to the system time or to display the system time on the screen. You can use the Timer function to trigger a Timer event which causes Now to refresh the display. This statement returns the current system time.
Now()
Examples
This example displays the current time in the StaticText st_time. It keeps the time up-to-date by setting a timer that triggers a Timer event every 60 seconds. Code in the windows Open event displays the initial time and starts the timer. Code in the Timer event displays the time again. The following code appears in the windows Open event script:
st_time.Text = String(Now(), "hh:mm") Timer(60)
A single line in the Timer event script refreshes the time display:
st_time.Text = String(Now(), "hh:mm") See also
Today Now method for DataWindows in the DataWindow Reference or the online Help
769
ObjectAtPointer
ObjectAtPointer
Description
Finds out where the user clicked in a graph. ObjectAtPointer reports the region of the graph under the pointer and stores the associated series and data point numbers in the designated variables. Graph controls in windows and user objects, and graphs in DataWindow controls
controlname.ObjectAtPointer ( { graphcontrol, } seriesnumber, datapoint ) Argument controlname graphcontrol (DataWindow control only) seriesnumber datapoint Description The name of the graph object for which you want the object under the pointer, or the DataWindow control containing the graph (Optional) A string whose value is the name of the graph in the DataWindow control for which you want the object under the pointer An integer variable in which you want to store the number of the series under the pointer An integer variable in which you want to store the number of the data point under the pointer
Applies to Syntax
Return value
grObjectType. Returns a value of the grObjectType enumerated datatype if the user clicks anywhere in the graph (including an empty area) and a NULL value if the user clicks outside the graph. If any arguments value is NULL, ObjectAtPointer also returns NULL. Values of grObjectType and the parts of the graph associated with them are: TypeCategory! A label for a category TypeCategoryAxis! The category axis or between the category labels TypeCategoryLabel! The label of the category axis TypeData! A data point or other data marker TypeGraph! Any place within the graph control that is not another grObjectType TypeLegend! Within the legend box, but not on a series label TypeSeries! The line that connects the data points of a series when the graphs type is line or on the series label in the legend box TypeSeriesAxis! The series axis of a 3D graph TypeSeriesLabel! The label of the series axis of a 3D graph TypeTitle! The title of the graph
770
PowerBuilder
CHAPTER 10
PowerScript Functions
Usage
TypeValueAxis! The value axis, including on the value labels TypeValueLabel! The user clicked the label of the value axis
The ObjectAtPointer function allows you to find out how the user is interacting with the graph. The function returns a value of the grObjectType enumerated datatype identifying the part of the graph. When the user clicks in a series, data point, or category, ObjectAtPointer stores the series and/or data point numbers in designated variables. When the user clicks a data point (or other data mark, such as line or bar), or on the series labels in the legend, ObjectAtPointer stores the series number in the designated variable. When the user clicks on a data point or category tickmark label, ObjectAtPointer stores the data point number in the designated variable. When the user clicks in a series, but not on the actual data point,
ObjectAtPointer stores 0 in datapoint and when the user clicks in a category, ObjectAtPointer stores 0 in seriesnumber. When the user clicks other parts of the graph, ObjectAtPointer stores 0 in both variables.
Call ObjectAtPointer first ObjectAtPointer is most effective as the first function call in the script for the
Clicked event for the graph control. Make sure you enable the graph control (the default is disabled). Otherwise, the Clicked event script is never run.
Examples
These statements store the series number and data point number at the pointer location in the graph named gr_product in SeriesNbr and ItemNbr. If the object type is TypeSeries! they obtain the series name, and if it is TypeData! they get the data value:
integer SeriesNbr, ItemNbr double data_value grObjectTypeobject_type string SeriesName object_type = & gr_product.ObjectAtPointer(SeriesNbr, ItemNbr) IF object_type = TypeSeries! THEN SeriesName = & gr_product.SeriesName(SeriesNbr) ELSEIF object_type = TypeData! THEN data_value = & gr_product.GetData(SeriesNbr, ItemNbr) END IF
771
ObjectAtPointer
These statements store the series number and data point number at the pointer location in the graph named gr_computers in the DataWindow control dw_equipment in SeriesNbr and ItemNbr:
integer SeriesNbr, ItemNbr dw_equipment.ObjectAtPointer("gr_computers", & SeriesNbr, ItemNbr) See also
AddData AddSeries
772
PowerBuilder
CHAPTER 10
PowerScript Functions
Object_To_String
Description
Gets the string form of an object. This function is used by PowerBuilder clients connecting to EAServer.
Applies to Syntax
JaguarORB objects
jaguarorb.Object_To_String ( object ) Argument jaguarorb object Description An instance of JaguarORB. The CORBA object that will be converted to a string. The string representation of a CORBA object is an Interoperable Object Reference (IOR) that describes how to connect to the server hosting the object. EAServer supports both standard format IORs (which are hex-encoded) and a URL format that is human-readable.
The Object_To_String function can be used to serialize a proxy object reference. By serializing an object reference, you can save the state of the object so that it persists after the client terminates processing.
Object_To_String is typically used in conjunction with String_To_Object, which
The following example shows the use of the Object_To_String function to serialize a proxy object reference:
Payroll payroll JaguarORB my_orb ... my_orb = CREATE JaguarORB my_orb.init("ORBRetryCount=3,ORBRetryDelay=1000") ... String payroll_ior = my_orb.Object_To_String(payroll)
See also
Init String_To_Object
773
OffsetPos
OffsetPos
Description Applies to Syntax
Sets the offset for progress bar controls. Progress bar controls
control.OffsetPos (increment ) Argument control increment Description The name of the progress bar control An integer that is added to the start position of the progress bar control
This statement offsets the start position of a horizontal progress bar by 10:
HProgressBar.OffsetPos ( 10 )
See also
774
PowerBuilder
CHAPTER 10
PowerScript Functions
Open
Opens a window or an OLE object.
For windows
Open displays a window and makes all its properties and controls available to scripts.
To Open an instance of a particular window datatype Allow the application to select the windows datatype when the script is executed
For OLE objects Open loads an OLE object contained in a file or storage into an OLE control or storage object variable. The source and the target are then connected for the purposes of saving work. To open An OLE object in a file and load it into an OLE control An OLE object in a storage object in memory and load it into an OLE control An OLE object in an OLE storage file and load it into a storage object in memory An OLE object that is a member of an open OLE storage and load it into a storage object in memory A stream in an OLE storage object in memory and load it into a stream object Use Syntax 3 Syntax 4 Syntax 5 Syntax 6 Syntax 7
For trace files Open opens the specified trace file for reading. To Open a trace file Use Syntax 8
Syntax 1
Description Applies to Syntax
775
Open
Argument windowvar
Description The name of the window you want to display. You can specify a window object defined in the Window painter (which is a window datatype) or a variable of the desired window datatype. Open places a reference to the opened window in windowvar. The window you want make the parent of the child or pop-up window you are opening. If you open a child or pop-up window and omit parent, PowerBuilder associates the window being opened with the currently active window.
parent (child and pop-up windows only) (optional) Return value Usage
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, Open returns NULL.
You must open a window before you can access the properties of the window. If you access the windows properties before you open it, an execution error will occur. To reference an open window in scripts, use windowvar.
Calling Open twice
If you call Syntax 1 of the Open function twice for the same window, PowerBuilder activates the window twice; it does not open two instances of the window. To open an array of windows where each window has different datatype, use Syntax 2 of Open.
Parent windows for the opened window Generally, if you are opening a child or a pop-up window and specify parent, the window identified by parent is the parent of the opened window (windowname or windowvar). When a parent window is closed, all its child and pop-up windows are closed too.
Not all types of windows can be parent windows. Only a window whose borders are not confined within another window can be a parent. A child window or a window opened as a sheet cannot be a parent. If you specify a confined window as a parent, PowerBuilder checks its parent, and that windows parent, until it finds a window that it can use as a parent. Therefore if you open a pop-up window and specify a sheet as its parent, PowerBuilder makes the MDI frame that contains the sheet its parent. If you do not specify a parent for a child or pop-up window, the active window becomes the parent. Therefore, if one pop-up is active and you open another pop-up, the first pop-up is the parent, not the main window. When the first pop-up is closed, PowerBuilder closes the second pop-up too. 776
PowerBuilder
CHAPTER 10
PowerScript Functions
However, in an MDI application, the active sheet is not the active window and cannot be the parent. In Windows, it is clear that the MDI frame, not the active sheet, is the active windowits title bar is the active color and it displays the menu.
Mouse behavior and response windows
Controls capture the mouse in order to perform certain operations. For instance, CommandButtons capture during mouse clicks, edit controls capture for text selection, and scrollbars capture during scrolling. If a response window is opened while the mouse is captured, unexpected results can occur. Because a response window grabs focus, you should not open it when focus is changing, such as in a LoseFocus event.
Examples
The following code opens an instance of a window of the type child named cw_data and makes w_employee the parent:
child cw_data Open(cw_data, w_employee)
777
Open
Syntax 2
Description
Applies to Syntax
parent (child and pop-up windows only) (optional) Return value Usage
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, Open returns NULL.
You must open a window before you can access the properties of the window. If you access the windows properties before you open it, an execution error will occur. To reference an open window in scripts, use windowvar. The window object specified in windowtype must be the same datatype as windowvar (the datatype includes datatypes inherited from it). The datatype of windowvar is usually window, from which all windows are inherited, but it can be any ancestor of windowtype. If it is not the same type, an execution error will occur. Use this syntax to open an array of windows when each window in the array will have a different datatype. See the last example, in which the window datatypes are stored in one array and are used for the windowtype argument when each window in another array is opened.
778
PowerBuilder
CHAPTER 10
PowerScript Functions
When you use Syntax 2, PowerBuilder opens an instance of a window of the datatype specified in windowtype and places a reference to this instance in the variable windowvar. If windowtype is a descendent window, you can only reference properties, events, functions, or structures that are part of the definition of windowvar. For example, if a user event is declared for windowtype, you cannot reference it. The object specified in windowtype is not automatically included in your executable application. To include it, you must save it in a PBD file (PowerBuilder dynamic library) that you deliver with your application. For information about the parent of an opened window, see Syntax 1.
Examples
This example opens a window of the type specified in the string s_w_name and stores the reference to the window in the variable w_to_open. The SELECT statement retrieves data specifying the window type from the database and stores it in s_w_name:
window w_to_open string s_w_name SELECT next_window INTO WHERE... ; Open(w_to_open, s_w_name) : s_w_name FROM routing_table
This example opens an array of ten windows of the type specified in the string is_w_emp1 and assigns a title to each window in the array. The string is_w_emp1 is an instance variable whose value is a window type:
integer n window win_array[10] FOR n = 1 to 10 Open(win_array[n], is_w_emp1) win_array[n].title = "Window " + string(n) NEXT
The following statements open four windows. The type of each window is stored in the array w_stock_type. The window reference from the Open function is assigned to elements in the array w_stock_win:
window w_stock_win[ ] string w_stock_type[4]
779
Open
= = = =
Syntax 3
Description Applies to Syntax
Return value
error occurs: -1 The file is not found or its data has an invalid format -9 Other error If any arguments value is NULL, Open returns NULL.
Examples
This example opens the object in the file MYSTUFF.OLE and loads it into in the control ole_1:
integer result result = ole_1.Open("c:\ole2\mystuff.ole")
See also
780
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 4
Description Applies to Syntax
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-2 -9
This example opens the object in the substorage excel_obj within the storage variable stg_stuff and loads it into the control ole_1. Olest_stuff is already open:
integer result result = ole_1.Open(stg_stuff, "excel_obj")
This example opens a substorage in the storage variable stg_stuff and loads it into the control ole_1. The substorage name is specified in the variable stuff_1. Olest_stuff is already open:
integer result string stuff_1 = "excel_obj" result = ole_1.Open(stg_stuff, stuff_1) See also
781
Open
Syntax 5
Description Applies to Syntax
readmode (optional)
sharemode (optional)
Return value
error occurs: -1 The file is not an OLE storage file -3 The file is not found -9 Other error
782
PowerBuilder
CHAPTER 10
PowerScript Functions
An OLE storage file is structured like a directory. Each OLE object can contain other OLE objects (substorages) and other data (streams). You can open the members of an OLE storage belonging to a server application if you know the structure of the storage. However, the PowerBuilder functions for manipulating storages are provided so that you can build your own storage files for organizing the OLE objects used in your applications. The whole file can be an OLE object and substorages within the file can also be OLE objects. More frequently, the structure for a storage file you create is a root level that is not an OLE object but contains independent OLE objects as substorages. Any level in the storage hierarchy can contain OLE objects or be simply a repository for another level of substorages.
Opening nested objects
Because you can specify path information within an OLE storage with a backslash as the separator, you can open a deeply nested object with a single call to Open. However, there is no error checking for the path you specify and if the Open fails, you wo not know why. It is strongly recommended that you open each object in the path until you get to the one you want.
Examples
This example opens the object in the file MYSTUFF.OLE and loads it into the OLEStorage variable stg_stuff:
integer result OLEStorage stg_stuff stg_stuff = CREATE OLEStorage result = stg_stuff.Open("c:\ole2\mystuff.ole")
783
Open
This example opens the object in the file MYSTUFF.OLE and loads it into the OLEStorage variable stg_stuff, as in the previous example. Then it opens the substorage drawing_1 into a second storage variable, using Syntax 6 of Open. This example does not include code to close and destroy any of the objects that were opened.
integer result OLEStorage stg_stuff, stg_drawing stg_stuff = CREATE OLEStorage result = stg_stuff.Open("c:\ole2\mystuff.ole") IF result >= 0 THEN stg_drawing = CREATE OLEStorage result = opest_drawing.Open("drawing_1", & stgRead!, stgDenyNone!, stg_stuff) END IF
This example opens the object in the file MYSTUFF.OLE and loads it into the OLEStorage variable stg_stuff. Then it checks whether a stream called info exists in the OLE object, and if so, opens it with read access using Syntax 7 of Open. This example does not include code to close and destroy any of the objects that were opened.
integer result boolean str_found OLEStorage stg_stuff OLEStream mystream stg_stuff = CREATE OLEStorage result = stg_stuff.Open("c:\ole2\mystuff.ole") IF result < 0 THEN RETURN result = stg_stuff.MemberExists("info", str_found) IF result < 0 THEN RETURN IF str_found THEN mystream = CREATE OLEStream result = mystream.Open(stg_stuff, "info", & stgRead!, stgDenyNone!) IF result < 0 THEN RETURN END IF See also
784
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 6
Description Applies to Syntax
readmode
sharemode
sourcestorage
785
Open
Return value
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an
error occurs: -2 -3 -9 The parent storage is not open The member is not found (when opened for reading) Other error
An OLE storage file is structured like a directory. Each OLE object can contain other OLE objects (substorages) and other data (streams). You can open the members of an OLE storage belonging to a server application if you know the structure of the storage. However, PowerBuilders functions for manipulating storages are provided so that you can build your own storage files for organizing the OLE objects used in your applications. The whole file can be an OLE object and substorages within the file can also be OLE objects. More frequently, the structure for a storage file you create is a root level that is not an OLE object but contains independent OLE objects as substorages. Any level in the storage hierarchy can contain OLE objects or be simply a repository for another level of substorages.
Opening nested objects
Because you can specify path information within an OLE storage with a backslash as the separator, you can open a deeply nested object with a single call to Open. However, there is no error checking for the path you specify and if the Open fails, you will not know why. It is strongly recommended that you open each object in the path until you get to the one you want.
Examples
This example opens the object in the file MYSTUFF.OLE and loads it into the OLEStorage variable stg_stuff, as in the previous example. Then it opens the substorage drawing_1 into a second storage variable. This example does not include code to close and destroy any of the objects that were opened.
integer result OLEStorage stg_stuff, stg_drawing stg_stuff = CREATE OLEStorage result = stg_stuff.Open("c:\ole2\mystuff.ole") IF result >= 0 THEN stg_drawing = CREATE OLEStorage result = opest_drawing.Open("drawing_1", & stgRead!, stgDenyNone!, stg_stuff) END IF
786
PowerBuilder
CHAPTER 10
PowerScript Functions
See also
Syntax 7
Description Applies to Syntax
sharemode (optional)
787
Open
Return value
error occurs: -1 -2 -3 -4 -5 -6 -9 Stream not found Stream already exists Stream is already open Storage not open Access denied Invalid name Other error
This example opens the object in the file MYSTUFF.OLE and loads it into the OLEStorage variable stg_stuff. Then it checks whether a stream called info exists in the OLE object, and if so, opens it with read access. This example does not include code to close and destroy any of the objects that were opened.
integer result boolean str_found OLEStorage stg_stuff OLEStream mystream stg_stuff = CREATE OLEStorage result = stg_stuff.Open("c:\ole2\mystuff.ole") IF result < 0 THEN RETURN result = stg_stuff.MemberExists("info", str_found) IF result < 0 THEN RETURN IF str_found THEN mystream = CREATE OLEStream result = mystream.Open(stg_stuff, "info", & stgRead!, stgDenyNone!) IF result < 0 THEN RETURN END IF
See also
Close
788
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 8
Description Applies to Syntax
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded FileAlreadyOpenError!The specified trace file has already been opened FileOpenError!The trace file can not be opened for reading FileInvalidFormatError!The file does not have the correct format EnterpriseOnlyFeature!This function is supported only in the Enterprise edition of PowerBuilder SourcePBLError!The source libraries cannot be found
Usage
You use this syntax to access the contents of a specified trace file created from a running PowerBuilder application. You can then use the properties and functions provided by the TraceFile object to perform your own analysis of tracing data instead of using the available modeling objects. This example opens a trace file:
TraceFile ltf_file String ls_filename ltf_file = CREATE TraceFile ltf_file.Open(ls_filename) ...
Examples
See also
789
OpenChannel
OpenChannel
Description Syntax
windowhandle (optional)
Return value
Long. Returns the handle to the channel (a positive integer) if it succeeds. If an error occurs, OpenChannel returns a negative integer. Values are:
-1 -9
Usage
Use OpenChannel to open a channel to a DDE server application and leave it open so you can efficiently execute more than one DDE request. This type of DDE conversation is called a warm link. Because you open a channel, the operating system does not have to poll all open applications every time you send or ask for data. The following is an outline of a warm-link conversation: Open a DDE channel with OpenChannel and check that it returns a valid channel handle (a positive value). Execute several DDE functions. You can use the following functions:
ExecRemote ( command, handle, <windowhandle> ) GetRemote ( location, target, handle, <windowhandle> ) SetRemote ( location, value, handle, <windowhandle> )
If you only need to use a remote DDE function once, you can call ExecRemote, GetRemote, or SetRemote without opening a channel. This is called a cold link. Without an open channel, the operating system polls all running applications to find the specified server application each time you call a DDE function. Your PowerBuilder application can also be a DDE server.
790
PowerBuilder
CHAPTER 10
PowerScript Functions
Each application decides how it supports DDE. You must check each potential server applications documentation to find out its DDE name, what its valid topics are, and how it expects locations to be specified.
Examples
These statements open a channel to the active spreadsheet REGION.XLS in Microsoft Excel and set handle to the handle to the channel:
long handle handle = OpenChannel("Excel", "REGION.XLS")
The following example opens a DDE channel to Excel and requests data from three spreadsheet cells. In the PowerBuilder application, the data is stored in the string array s_regiondata. The client window for the DDE conversation is w_ddewin:
long handle string s_regiondata[3] handle = OpenChannel("Excel", "REGION.XLS", & Handle(w_ddewin)) GetRemote("R1C2", s_regiondata[1], handle, & Handle(w_ddewin)) GetRemote("R1C3", s_regiondata[2], handle, & Handle(w_ddewin)) GetRemote("R1C4", s_regiondata[3], handle, & Handle(w_ddewin)) CloseChannel(handle, Handle(w_ddewin)) See also
791
OpenSheet
OpenSheet
Description Applies to Syntax
Opens a sheet within an MDI (multiple document interface) frame window and creates a menu item for selecting the sheet on the specified menu. Window objects
OpenSheet ( sheetrefvar {, windowtype }, mdiframe {, position {, arrangeopen } } ) Argument sheetrefvar Description The name of any window variable that is not an MDI frame window. OpenSheet places a reference to the open sheet in sheetrefvar. A string whose value is the datatype of the window you want to open. The datatype of windowtype must be the same or a descendant of sheetrefvar. The name of an MDI frame window. The number of the menu item (in the menu associated with the sheet) to which you want to append the names of the open sheets. Menu bar menu items are numbered from the left, beginning with 1. The default value of 0 lists the open sheets under the next-to-last menu item. A value of the ArrangeOpen enumerated datatype specifying how you want the sheet arranged in the MDI frame in relation to other sheets when it is opened: Cascaded! (Default) Cascade the sheet relative to other open sheets, so that its title bar is below the previously opened sheet. Layered! Layer the sheet so that it fills the frame and covers previously opened sheets. Original! Open the sheet in its original size and cascade it.
arrangeopen (optional)
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, OpenSheet returns NULL.
A sheet is a document window that is contained within an MDI frame window. MDI applications allow several sheets to be open at the same time. The newly opened sheet becomes the active sheet. If the opened sheet has an associated menu, that menu becomes the menu at the top of the frame. When you specify windowtype, the window object specified in windowtype must be the same datatype as sheetrefvar (a datatype includes datatypes inherited from it). The datatype of sheetrefvar is usually window, from which all windows are inherited, but it can be any ancestor of windowtype. If it is not the same type, an execution error occurs.
792
PowerBuilder
CHAPTER 10
PowerScript Functions
PowerBuilder does not automatically copy objects that are dynamically referenced (through string variables) into your executable. To include the window object specified in windowtype in your application, list it in the resource (PBR) file that you use when you build the executable. For more information about PBR files for an executable, see the PowerBuilder Users Guide.
OpenSheet opens a sheet and appends its name to the item on the menu bar specified in position. If position is 0 or greater than the number of items on the menu bar, PowerBuilder appends the name of the sheet to the next-to-last menu item in the menu bar. In most MDI applications, the next-to-last menu item on the menu bar is the Window menu, which contains options for arranging sheets, as well as the list of open sheets.
PowerBuilder cannot append the sheets to a menu that does not have any other menu selections. Make sure that the menu you specify or, if you leave out position, the next-to-last menu, has at least one other item. If more than nine sheets are open in the frame, the first nine are listed on the menu specified by position and a final item More Windows is added. Sheets in a frame cannot be made invisible. When you open a sheet, the value of the Visible property is ignored. Changing the Visible property when the window is already open has no effect.
Opening response windows Do not use the OpenSheet function to open a response window. Examples
This statement opens the sheet child_1 in the MDI frame MDI_User in its original size. It appends the name of the opened sheet to the second menu item in the menu bar, which is now the menu associated with child_1, not the menu associated with the frame:
OpenSheet(child_1, MDI_User, 2, Original!)
This example opens an instance of the window object child_1 as an MDI sheet and stores a reference to the opened window in child. The name of the sheet is appended to the fourth menu associated with child_1 and is layered:
window child OpenSheet(child, "child_1", MDI_User, 4, Layered!) See also
793
OpenSheetWithParm
OpenSheetWithParm
Description
Opens a sheet within an MDI (multiple document interface) frame window and creates a menu item for selecting the sheet on the specified menu, as OpenSheet does. OpenSheetWithParm also stores a parameter in the systems Message object so that it is accessible to the opened sheet. Window objects
OpenSheetWithParm ( sheetrefvar, parameter {, windowtype }, mdiframe {, position {, arrangeopen } } ) Argument sheetrefvar Description The name of any window variable that is not an MDI frame window. OpenSheetWithParm places a reference to the open sheet in sheetrefvar. The parameter you want to store in the Message object when the sheet is opened. Parameter must have one of these datatypes: String Numeric windowtype (optional) mdiframe position (optional) PowerObject A string whose value is the datatype of the window you want to open. The datatype of windowtype must be the same or a descendant of sheetrefvar. The name of the MDI frame window in which you want to open this sheet. The number of the menu item (in the menu associated with the sheet) to which you want to append the names of the open sheets. Menu bar menu items are numbered from the left, beginning with 1. The default is to list the open sheets under the next-to-last menu item. A value of the ArrangeOpen enumerated datatype specifying how you want the sheets arranged in the MDI frame when they are opened: Cascaded! (Default) Cascade the sheet relative to other open sheets so that its title bar is below the previously opened sheet. Layered! Layer the sheet so that it fills the frame and covers previously opened sheets. Original! Open the sheet in its original size and cascade it.
Applies to Syntax
parameter
arrangeopen (optional)
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, OpenSheetWithParm returns NULL.
794
PowerBuilder
CHAPTER 10
PowerScript Functions
Usage
The system Message object has three properties for storing data. Depending on the datatype of the parameter specified for OpenSheetWithParm, scripts for the opened sheet would check one of the following properties.
Message object property Message.DoubleParm Message.PowerObjectParm Message.StringParm Argument datatype Numeric PowerObject (PowerBuilder objects, including user-defined structures) String
In the opened window, it is a good idea to access the value passed in the Message object immediately (because some other script may use the Message object for another purpose).
Avoiding null object references
When you pass a PowerObject as a parameter, you are passing a reference to the object. The object must exist when you refer to it later or you get a null object reference, which causes an error. For example, if you pass the name of a control on a window that is being closed, that control will not exist when a script accesses the parameter.
Opening response windows Do not use the OpenSheetWithParm function to open a response window.
See the usage notes for OpenSheet, which also apply to OpenSheetWithParm.
Examples
This statement opens the sheet w_child_1 in the MDI frame MDI_User in its original size and stores MA in message.StringParm. It appends the names of the open sheet to the second menu item in the menu bar of MDI_User (the menu associated with w_child_1):
OpenSheetWithParm(w_child_1, "MA", & MDI_User, 2, Original!)
The next example illustrates how to access parameters passed in the Message object. These statements are in the scripts for two different windows. The script for the first window declares child as a window and opens an instance of w_child_1 as an MDI sheet. The name of the sheet is appended to the fourth menu item associated with w_child_1 and is layered.
795
OpenSheetWithParm
The script also passes a reference to the SingleLineEdit control sle_state as a PowerObject parameter of the Message object. The script for the Open event of w_child_1 uses the text in the edit control to determine what type of calculations to perform. Note that this would fail if sle_state no longer existed when the second script refers to it. As an alternative, you could pass the text itself, which would be stored in the String parameter of Message. The second script determines the text in the SingleLineEdit and performs processing based on that text. The script for the first window is:
window child OpenSheetWithParm(child, sle_state, & "w_child_1", MDI_User, 4, Layered!)
ArrangeSheets OpenSheet
796
PowerBuilder
CHAPTER 10
PowerScript Functions
OpenTab
Opens a visual user object and makes it a tab page in the specified Tab control and makes all its properties and controls available to scripts.
To open A user object as a tab page A user object as a tab page, allowing the application to select the user objects type during execution Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
index
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, OpenTab returns NULL.
Use Syntax 1 when you know what user object you want to open. Use Syntax 2 when the application will determine what type of user object to open when the script runs. The tab page for the user object does not become selected. Scripts for constructor events of the controls on the user object do not run until the tab page is selected.
797
OpenTab
You must open a user object before you can access the properties of the user object. If you access the user objects properties before you open it, an execution error will occur. A user object that is part of a Tab controls definition (that is, it was added to the Tab control in the Window painter) does not have to be opened in a script. PowerBuilder opens it when it opens the window containing the Tab control.
OpenTab adds the newly opened user object to the Tab controls Control array, which is a property that lists the tab pages within the Tab control.
If you call Syntax 1 twice to open the same user object, PowerBuilder does open the user object again as another tab page, in contrast to the behavior of Open and OpenUserObject.
Examples
This statement opens an instance of a user object named u_Employee as a tab page in the Tab control tab_1:
tab_1.OpenTab(u_Employee, 0)
The following statements open an instance of a user object u_to_open as a tab page in the Tab control tab_1. It becomes the first tab in the control:
u_employee u_to_open tab_1.OpenTab(u_to_open, 1) See also
OpenTabWithParm
Syntax 2
Description Applies to Syntax
798
PowerBuilder
CHAPTER 10
PowerScript Functions
Argument userobjecttype
Description A string whose value is the name of the user object you want to open. The datatype of userobjecttype must be a descendant of userobjectvar. The number of the tab before which you want to insert the new tab. If index is 0 or greater than the number of tabs, the tab page is inserted at the end
index
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, OpenTab returns NULL.
Use Syntax 1 when you know what user object you want to open. Use Syntax 2 when the application will determine what type of user object to open when the script runs. The tab page for the user object does not become selected. Scripts for Constructor events of the controls on the user object do not run until the tab page is selected. You must open a user object before you can access the properties of the user object. If you access the user objects properties before you open it, an execution error will occur. A user object that is part of a Tab controls definition (that is, it was added to the Tab control in the Window painter) does not have to be opened in a script. PowerBuilder opens it when it opens the window containing the Tab control.
OpenTab adds the newly opened user object to the Tab controls Control array, which is a property that lists the tab pages within the Tab control.
When you use Syntax 2, PowerBuilder opens an instance of a user object of the datatype specified in userobjecttype and places a reference to this instance in the variable userobjectvar. To refer to the instance in scripts, use userobjectvar. If userobjecttype is a descendent user object, you can only refer to properties, events, functions, or structures that are part of the definition of userobjectvar. For example, if a user event is declared for userobjecttype, you cannot reference it. The object specified in userobjecttype is not automatically included in your executable application. To include it, you must save it in a PBD file (PowerBuilder dynamic library) that you deliver with you application.
799
OpenTab
Examples
The following example opens a user object as the last tab page in the Tab control tab_1. The user object is of the type specified in the string s_u_name and stores the reference to the user object in the variable u_to_open:
UserObject u_to_open string s_u_name s_u_name = sle_user.Text tab_1.OpenTab(u_to_open, s_u_name, 0)
See also
OpenTabWithParm
800
PowerBuilder
CHAPTER 10
PowerScript Functions
OpenTabWithParm
Adds a visual user object to the specified window and makes all its properties and controls available to scripts, as OpenTab does. OpenTabWithParm also stores a parameter in the systems Message object so that it is accessible to the opened object.
To open A user object as a tab page A user object as a tab page, allowing the application to select the user objects type during execution Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
parameter
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, OpenTabWithParm returns NULL.
801
OpenTabWithParm
Usage
The system Message object has three properties for storing data. Depending on the datatype of the parameter specified for OpenTabWithParm, scripts for the opened user object would check one of the following properties.
Message object property message.DoubleParm message.PowerObjectParm message.StringParm Argument datatype Numeric PowerObject (PowerBuilder objects, including user-defined structures) String
In the opened user object, it is a good idea to access the value passed in the Message object immediately because some other script may use the Message object for another purpose.
Avoiding null object references
When you pass a PowerObject as a parameter, you are passing a reference to the object. The object must exist when you refer to it later or you get a null object reference, which causes an error. For example, if you pass the name of a control on a window that is being closed, that control will not exist when a script accesses the parameter. See also the usage notes for OpenTab, all of which apply to OpenTabWithParm.
Examples
This statement opens an instance of a user object named u_Employee as a tab page in the Tab control tab_empsettings. It also stores the string James Newton in Message.StringParm. The Constructor event script for the user object uses the string parameter as the text of a StaticText control st_empname in the object. The script that opens the tab page has the following statement:
tab_empsettings.OpenTabWithParm(u_Employee, & "James Newton", 0)
The user objects Constructor event script has the following statement:
st_empname.Text = Message.StringParm
The following statements open an instance of a user object u_to_open as the first tab page in the Tab control tab_empsettings and store a number in message.DoubleParm. The last statement selects the tab page:
u_employee u_to_open integer age = 50 tab_1.OpenTabWithParm(u_to_open, age, 1) tab_1.SelectTab(u_to_open) See also
OpenTab
802
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 2
Description
Applies to Syntax
index
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, OpenTabWithParm returns NULL.
The system Message object has three properties for storing data. Depending on the datatype of the parameter specified for OpenTabWithParm, scripts for the opened user object would check one of the following properties.
Message object property message.DoubleParm message.PowerObjectParm message.StringParm Argument datatype Numeric PowerObject (PowerBuilder objects, including user-defined structures) String
803
OpenTabWithParm
In the opened user object, it is a good idea to access the value passed in the Message object immediately because some other script may use the Message object for another purpose.
Avoiding null object references
When you pass a PowerObject as a parameter, you are passing a reference to the object. The object must exist when you refer to it later or you will get a null object reference, which causes an error. For example, if you pass the name of a control on a window that is being closed, that control will not exist when a script accesses the parameter. See also the usage notes for OpenTab, all of which apply to OpenTabWithParm.
Examples
The following statement opens an instance of a user object u_data of type u_benefit_plan as the last tab page in the Tab control tab_1. The parameter "Benefits" is stored in message.StringParm:
UserObject u_data tab_1.OpenTabWithParm(u_data, & "Benefits", "u_benefit_plan", 0)
These statements open a user object of the type specified in the string s_u_name and store the reference to the user object in the variable u_to_open. The script gets the value of s_u_name, the type of user object to open, from the database. The parameter is the text of the SingleLineEdit sle_loc, so it is stored in Message.StringParm. The user object becomes the third tab page in the Tab control tab_1:
UserObject u_to_open string s_u_name, e_location e_location = sle_location.Text SELECT next_userobj INTO FROM routing_table WHERE ... ; : s_u_name
804
PowerBuilder
CHAPTER 10
PowerScript Functions
The following statements open a user object of the type specified in the string s_u_name and store the reference to the user object in the variable u_to_open. The parameter is numeric so it is stored in message.DoubleParm. The user object becomes the first tab page in the Tab control tab_1:
UserObject u_to_open integer age = 60 string s_u_name s_u_name = sle_user.Text tab_1.OpenTabWithParm(u_to_open, age, & s_u_name, 1) See also
OpenTab
805
OpenUserObject
OpenUserObject
Adds a user object to the specified window and makes all its properties and controls available to scripts.
To Open an instance of a particular user object Open a user object, allowing the application to select the user objects type during execution Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, OpenUserObject returns NULL.
Use Syntax 1 when you know what user object you want to open. Use Syntax 2 when the application will determine what type of user object to open when the script runs. You must open a user object before you can access the properties of the user object. If you access the user objects properties before you open it, an execution error will occur. A user object that is part of a windows definition (that is, it was added to the window in the Window painter) does not have to opened in a script. PowerBuilder opens it when it opens the window.
806
PowerBuilder
CHAPTER 10
PowerScript Functions
OpenUserObject adds the newly opened user object to the windows Control
array, which is a property that lists the windows controls. When you open a user object during execution, the window does not destroy the user object automatically when you close the window. You need to call CloseUserObject to destroy the user object, usually when the window closes. If you do not destroy the user object, it holds on to its allocated memory, resulting in a memory leak. PowerBuilder displays the user object when it next updates the display or at the end of the script, whichever comes first. For example, if you open several user objects in a script, they will all display at once when the script is complete, unless some other statements cause a change in the screens appearance (for example, the MessageBox function displays a message or the script changes a visual property of a control).
Calling OpenUserObject twice
If you call Syntax 1 twice to open the same user object, PowerBuilder activates the user object twice; it does not open two instances of the user object.
Examples
This statement displays an instance of a user object named u_Employee in the upper left corner of the window w_emp (coordinates 0,0):
w_emp.OpenUserObject(u_Employee)
The following statements display an instance of a user object u_to_open at 200,100 in the window w_empstatus:
u_employee u_to_open w_empstatus.OpenUserObject(u_to_open, 200, 100)
The following statement displays an instance of a user object u_data at location 20,100 in w_info:
w_info.OpenUserObject(u_data, 20, 100) See also
OpenUserObjectWithParm
807
OpenUserObject
Syntax 2
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, OpenUserObject returns NULL.
Use Syntax 1 when you know what user object you want to open. Use Syntax 2 when the application will determine what type of user object to open when the script runs. You must open a user object before you can access the properties of the user object. If you access the user objects properties before you open it, an execution error will occur. A user object that is part of a windows definition (that is, it was added to the window in the Window painter) does not have to opened in a script. PowerBuilder opens it when it opens the window.
OpenUserObject adds the newly opened user object to the windows Control
array, which is a property that lists the windows controls. When you open a user object during execution, the window does not destroy the user object automatically when you close the window. You need to call CloseUserObject to destroy the user object, usually when the window closes. If you do not destroy the user object, it holds on to its allocated memory, resulting in a memory leak.
808
PowerBuilder
CHAPTER 10
PowerScript Functions
PowerBuilder displays the user object when it next updates the display or at the end of the script, whichever comes first. For example, if you open several user objects in a script, they will all display at once when the script is complete, unless some other statements cause a change in the screens appearance (for example, the MessageBox function displays a message or the script changes a visual property of a control).
The userobjecttype argument
When you use Syntax 2, PowerBuilder opens an instance of a user object of the datatype specified in userobjecttype and places a reference to this instance in the variable userobjectvar. To refer to the instance in scripts, use userobjectvar. If userobjecttype is a descendent user object, you can only refer to properties, events, functions, or structures that are part of the definition of userobjectvar. For example, if a user event is declared for userobjecttype, you cannot reference it. The object specified in userobjecttype is not automatically included in your executable application. To include it, you must save it in a PBD file (PowerBuilder dynamic library) that you deliver with your application.
Examples
The following example displays a user object of the type specified in the string s_u_name and stores the reference to the user object in the variable u_to_open. The user object is located at 100,200 in the window w_info:
DragObject u_to_open string s_u_name s_u_name = sle_user.Text w_info.OpenUserObject(u_to_open, s_u_name, 100, 200)
See also
OpenUserObjectWithParm
809
OpenUserObjectWithParm
OpenUserObjectWithParm
Adds a user object to the specified window and makes all its properties and controls available to scripts, as OpenUserObject does. OpenUserObjectWithParm also stores a parameter in the systems Message object so that it is accessible to the opened object.
To Open an instance of a particular user object Open a user object, allowing the application to select the user objects type during execution Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
parameter
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, OpenUserObjectWithParm returns NULL.
810
PowerBuilder
CHAPTER 10
PowerScript Functions
Usage
The system Message object has three properties for storing data. Depending on the datatype of the parameter specified for OpenUserObjectWithParm, scripts for the opened user object would check one of the following properties:
Message object property message.DoubleParm message.PowerObjectParm message.StringParm Argument datatype Numeric PowerObject (PowerBuilder objects, including user-defined structures) String
In the opened user object, it is a good idea to access the value passed in the Message object immediately because some other script may use the Message object for another purpose.
Avoiding null object references
When you pass a PowerObject as a parameter, you are passing a reference to the object. The object must exist when you refer to it later or you get a null object reference, which causes an error. For example, if you pass the name of a control on a window that is being closed, that control will not exist when a script accesses the parameter. See also the usage notes for OpenUserObject, all of which apply to OpenUserObjectWithParm.
Examples
This statement displays an instance of a user object named u_Employee in the window w_emp and stores the string James Newton in Message.StringParm. The Constructor event script for the user object uses the string parameter as the text of a StaticText control st_empname in the object. The script that opens the user object has the following statement:
w_emp.OpenUserObjectWithParm(u_Employee, "Jim Newton")
The user objects Constructor event script has the following statement:
st_empname.Text = Message.StringParm
The following statements display an instance of a user object u_to_open in the window w_emp and store a number in message.DoubleParm:
u_employee u_to_open integer age = 50 w_emp.OpenUserObjectWithParm(u_to_open, age) See also
811
OpenUserObjectWithParm
Syntax 2
Description
Applies to Syntax
parameter
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, OpenUserObjectWithParm returns NULL.
The system Message object has three properties for storing data. Depending on the datatype of the parameter specified for OpenUserObjectWithParm, scripts for the opened user object would check one of the following properties.
Message object property message.DoubleParm message.PowerObjectParm message.StringParm Argument datatype Numeric PowerObject (PowerBuilder objects, including user-defined structures) String
812
PowerBuilder
CHAPTER 10
PowerScript Functions
In the opened user object, it is a good idea to access the value passed in the Message object immediately because some other script may use the Message object for another purpose.
Avoiding null object references
When you pass a PowerObject as a parameter, you are passing a reference to the object. The object must exist when you refer to it later or you will get a null object reference, which causes an error. For example, if you pass the name of a control on a window that is being closed, that control will not exist when a script accesses the parameter. See also the usage notes for OpenUserObject, all of which apply to OpenUserObjectWithParm.
Examples
The following statement displays an instance of a user object u_data of type u_benefit_plan at location 20,100 in the window w_hresource. The parameter "Benefits" is stored in message.StringParm:
DragObject u_data w_hresource.OpenUserObjectWithParm(u_data, & "Benefits", "u_benefit_plan", 20, 100)
These statements open a user object of the type specified in the string s_u_name and store the reference to the user object in the variable u_to_open. The script gets the value of s_u_name, the type of user object to open, from the database. The parameter is the text of the SingleLineEdit sle_loc, so it is stored in Message.StringParm. The user object is at the default coordinates 0,0 in the window w_info:
DragObject u_to_open string s_u_name, e_location e_location = sle_location.Text SELECT next_userobj INTO FROM routing_table WHERE ... ; : s_u_name
813
OpenUserObjectWithParm
The following statements display a user object of the type specified in the string s_u_name and store the reference to the user object in the variable u_to_open. The parameter is numeric so it is stored in message.DoubleParm. The user object is at the coordinates 100,200 in the window w_emp:
userobject u_to_open integer age = 60 string s_u_name s_u_name = sle_user.Text w_emp.OpenUserObjectWithParm(u_to_open, age, & s_u_name, 100, 200) See also
814
PowerBuilder
CHAPTER 10
PowerScript Functions
OpenWithParm
Displays a window and makes all its properties and controls available to scripts, as Open does. OpenWithParm also stores a parameter in the systems Message object so that it is accessible to the opened window.
To Open an instance of a particular window datatype Allow the application to select the windows datatype when the script is executed Use Syntax 1 Syntax 2
Syntax 1
Description
Applies to Syntax
parameter
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, OpenWithParm returns NULL.
The system Message object has three properties for storing data. Depending on the datatype of the parameter specified for OpenWithParm, your scripts for the opened window would check one of the following properties.
815
OpenWithParm
Argument datatype
Numeric PowerObject (PowerBuilder objects, including user-defined structures) String
In the opened window, it is a good idea to access the value passed in the Message object immediately because some other script may use the Message object for another purpose.
Avoiding null object references When you pass a PowerObject as a
parameter, you are passing a reference to the object. The object must exist when you refer to it later or you will get a null object reference, which causes an error. For example, if you pass the name of a control on a window that is being closed, that control will not exist when a script accesses the parameter. To pass several values, create a user-defined structure to hold the values and access the PowerObjectParm property of the Message object in the opened window. The structure is passed by value, not by reference, so you can access the information even if the original structure has been destroyed.
Passing several values as a structure
See also the usage notes for Open, all of which apply to OpenWithParm.
Examples
This statement opens an instance of a window named w_employee and stores the string parameter in Message.StringParm. The script for the windows Open event uses the string parameter as the text of a StaticText control st_empname. The script that opens the window has the following statement:
OpenWithParm(w_employee, "James Newton")
The following statements open an instance of a window of the type w_employee. Since the parameter is a number it is stored in Message.DoubleParm:
w_employee w_to_open integer age = 50 OpenWithParm(w_to_open, age)
816
PowerBuilder
CHAPTER 10
PowerScript Functions
The following statement opens an instance of a child window named cw_data and makes w_employee the parent. The window w_employee must already be open. The parameter benefit_plan is a string and is stored in Message.StringParm:
OpenWithParm(cw_data, "benefit_plan", w_employee) See also
CloseWithReturn Open
Syntax 2
Description
Applies to Syntax
parameter
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, OpenWithParm returns NULL.
817
OpenWithParm
Usage
The system Message object has three properties for storing data. Depending on the datatype of the parameter specified for OpenWithParm, your scripts for the opened window would check one of the following properties.
Message object property Message.DoubleParm Message.PowerObjectParm Message.StringParm Argument datatype
Numeric PowerObject (PowerBuilder objects, including user-defined structures) String
In the opened window, it is a good idea to access the value passed in the Message object immediately because some other script may use the Message object for another purpose.
Avoiding null object references When you pass a PowerObject as a
parameter, you are passing a reference to the object. The object must exist when you refer to it later or you will get a null object reference, which causes an error. For example, if you pass the name of a control on a window that is being closed, that control will not exist when a script accesses the parameter. To pass several values, create a user-defined structure to hold the values and access the PowerObjectParm property of the Message object in the opened window. The structure is passed by value, not by reference, so you can access the information even if the original structure has been destroyed.
Passing several values as a structure
See also the usage notes for Open, all of which apply to OpenWithParm.
Examples
These statements open a window of the type specified in the string s_w_name and store the reference to the window in the variable w_to_open. The script gets the value of s_w_name, the type of window to open, from the database. The parameter in e_location is text, so it is stored in Message.StringParm:
window w_to_open string s_w_name, e_location e_location = sle_location.Text SELECT next_window INTO :s_w_name FROM routing_table WHERE ... ; OpenWithParm(w_to_open, e_location, s_w_name)
818
PowerBuilder
CHAPTER 10
PowerScript Functions
The following statements open a window of the type specified in the string c_w_name, store the reference to the window in the variable wc_to_open, and make w_emp the parent window of wc_to_open. The parameter is numeric, so it is stored in Message.DoubleParm:
window wc_to_open string c_w_name integer age = 60 c_w_name = "w_c_emp1" OpenWithParm(wc_to_open, age, c_w_name, w_emp) See also
CloseWithReturn Open
819
OutgoingCallList
OutgoingCallList
Description Applies to Syntax
Provides a list of the calls to other routines included in a performance analysis model. ProfileLine and ProfileRoutine objects
instancename.OutgoingCallList ( list, aggregate ) Argument instancename list Description Instance name of the ProfileLine or ProfileRoutine object. An unbounded array variable of datatype ProfileCall in which OutgoingCallList stores a ProfileCall object for each call to other routines from within this routine. This argument is passed by reference. A boolean indicating whether duplicate routine calls will result in the creation of a single or of multiple ProfileCall objects.
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded ModelNotExistsError!The model does not exist
Usage
You use the OutgoingCallList function to extract a list of the calls from a line and/or routine to other routines in a performance analysis model. You must have previously created the performance analysis model from a trace file using the BuildModel function. Each caller is defined as a ProfileCall object and provides the called routine and the calling routine, the number of times the call was made, and the elapsed time. The routines are listed in no particular order. The aggregate argument indicates whether duplicate routine calls result in the creation of a single or of multiple ProfileCall objects. This argument has no effect unless line tracing is enabled and a calling routine calls the current routine from more than one line. If aggregate is TRUE, a new ProfileCall object is created that aggregates all calls from the calling routine to the current routine. If aggregate is FALSE, multiple ProfileCall objects are returned, one for each line from which the calling routine called the called routine.
Examples
This example gets a list of the routines included in a performance analysis model and then gets a list of the routines called by each routine:
Long ll_cnt ProfileCall lproc_call[]
820
PowerBuilder
CHAPTER 10
PowerScript Functions
lpro_model.BuildModel() lpro_model.RoutineList(iprort_list) FOR ll_cnt = 1 TO UpperBound(iprort_list) iprort_list[ll_cnt].OutgoingCallList(lproc_call, & TRUE) ... NEXT See also
BuildModel IncomingCallList
821
PageCount
PageCount
Description Applies to Syntax
Returns the total number of pages in the document in a RichTextEdit control. RichTextEdit controls
rtename.PageCount ( ) Argument rtename Description The name of the RichTextEdit control in which you want the page count
the control contains no text and -1 if an error occurs. The number of pages in the document is determined by the amount of text and the layout specifications, such as page size, margins, font size, and so on. When the RichTextEdit control shares data with a DataWindow, there is an instance of the document for each row of the DataWindow. PageCount reports the page count of a single instance. Multiply the value of the DataWindows RowCount function by the page count to get the total number of pages.
Examples
This example displays the number of pages in the document in the RichTextEdit rte_1 as the text of the StaticText st_status:
st_status.Text = String(rte_1.PageCount())
See also
LineCount LineLength RowCount method for DataWindows in the DataWindow Reference or the online Help
822
PowerBuilder
CHAPTER 10
PowerScript Functions
PageCreated
Description Applies to Syntax
Reports whether a tab page has been created. User objects used as tab pages
userobject.PageCreated ( ) Argument userobject Description The name of the tab page whose existence you want to test
Boolean. Returns TRUE if the user object is a tab page and has been created and FALSE if the user object is not a tab page or has not been created.
A window will open more quickly if the creation of graphical representations is delayed for tab pages with many controls. However, scripts cannot refer to a control on a tab page until the tab pages Constructor event has run and a graphical representation of the control has been created. When the CreateOnDemand property of the Tab control is selected, scripts cannot reference controls on tab pages that the user has not viewed. PageCreated allows you to test whether a particular tab page has already been created. This example tests whether tabpage_2 has been created and, if not, creates it:
IF tab_1.CreateOnDemand = True THEN IF tab_1.tabpage_2.PageCreated() = False THEN tab_1.tabpage_2.CreatePage() END IF END IF
Examples
See also
CreatePage
823
ParentWindow
ParentWindow
Description Applies to Syntax
Window. Returns the parent of windowname. Returns a null object reference if an error occurs or if windowname is NULL. The ParentWindow function, along with the pronoun Parent, allows you to write more general scripts by avoiding the coding of actual window names. Parent refers to the window that contains the current object or controlthe local environment. ParentWindow returns the parent window of a specified window. Whether a window has a parent depends on its type and how it was opened. You can specify the parent when you open the window. For windows that always have parents, PowerBuilder chooses the parent if you do not specify it. Response windows and child windows always have a parent window. The parent of a sheet in an MDI application is the MDI frame window. Pop-up windows have a parent window when they are opened from another window but when used in an MDI application, the parent of the pop-up is the MDI frame. A pop-up window opened from the applications Open event does not have a parent. The ParentWindow property of the Menu object can be used like a pronoun in Menu scripts. It identifies the window with which the menu is associated when your program is running. For more information, see the PowerBuilder Users Guide.
Examples
These statements return the parent of child_1. The parent is a window of the datatype Win1:
Win1 w_parent w_parent = child_1.ParentWindow()
The following script for a Cancel button in a pop-up window triggers an event for the parent window of the buttons parent window (the window that contains the button). Then it closes the buttons window. The parent window of that window will have a script for the cancelrequested event:
Parent.ParentWindow().TriggerEvent("cancelrequested") Close(Parent)
824
PowerBuilder
CHAPTER 10
PowerScript Functions
Paste
Description
Inserts (pastes) the contents of the clipboard into the specified control. For editable controls, text on the clipboard is pasted at the insertion point. For OLE controls, the OLE object on the clipboard replaces any object already in the control. EditMask, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox, DropDownPictureListBox, DataWindow, OLE controls
controlname.Paste ( ) Argument controlname Description The name of the DataWindow control, EditMask, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox, DropDownPictureListBox, or OLE control into which you want to insert the contents of the clipboard. If controlname is a DataWindow, text is pasted into the edit control over the current row and column. If controlname is a DropDownListBox or DropDownPictureListBox, the AllowEdit property must be TRUE
Applies to Syntax
Return value
For edit controls, returns the number of characters that were pasted into controlname. If nothing has been cut or copied (the clipboard is empty), the Paste function does not change the contents of the edit control and returns 0. If the clipboard contains nontext data (for example, a bitmap or OLE object) and the control cannot accept that data, Paste does not change the contents and returns 0. For OLE controls, returns 0 if it succeeds and one of the following negative values if an error occurs: -1 -9
Usage
For editable controls, if text is selected in controlname, Paste replaces the text with the contents of the clipboard. If the clipboard contains more lines than fit in the edit control, only the number of lines that fit are pasted. In a DataWindow control, the text is pasted into the edit control over the current row and column. If the clipboard contains more text that is allowed for that column, the text is truncated. If the clipboard text does not match the columns datatype, all the text is truncated, so that any selected text is replaced with an empty string. You can paste bitmaps, as well as text, into a RichTextEdit control.
825
Paste
To insert a specific string in controlname or to replace selected text with a specific string, use the ReplaceText function. When you use Paste to put an OLE object in an OLE control, the data is embedded in the PowerBuilder application, not linked.
Examples
If the clipboard contains Proposal good for 90 days and no text is selected, this statement pastes Proposal good for 90 days in mle_Comment1 at the insertion point and returns 25:
mle_Comment1.Paste()
If the clipboard contains the string Final Edition, mle_Comment2 contains This is a Preliminary Draft, and the text in mle_Comment2 is selected, this statement deletes This is a Preliminary Draft, replaces it with Final Edition, and returns 13:
mle_Comment2.Paste()
If the clipboard contains an OLE object, this statement makes it the contents of the control ole_1 and returns 0:
ole_1.Paste() See also
826
PowerBuilder
CHAPTER 10
PowerScript Functions
PasteLink
Description Applies to Syntax
Pastes a link to the contents of the clipboard into the control. The server application for the object on the clipboard must be running. OLE controls
olecontrol.PasteLink ( ) Argument olecontrol Description The name of the OLE control into which you want to paste the object on the clipboard
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -9
When you copy data to the clipboard from an application that supports OLE (the server application), you can paste the object into PowerBuilders OLE control with a link to the original data. Object information about the source of the data is only available if the server application is running. You do not need to worry about running the server application if you are working with an OLE object that PowerBuilder knows about, such as an object in a PowerBuilder library or an object that is part of a controls definition in a window. For these objects, PowerBuilder runs the server application in the background to enable the link.
PasteLink fails, however, if the user switches to a server application, copies the data, quits the application, and then tries to paste and link the object in their PowerBuilder application.
Examples
If the clipboard contains an OLE object and the objects server application is running, then the following example pastes the object in the control ole_1 and sets li_result to 0:
integer li_result li_result = ole_1.PasteLink()
See also
827
PasteRTF
PasteRTF
Description Applies to Syntax
Pastes rich text data from a string into a DataWindow control, DataStore object, or RichTextEdit control. DataWindow controls, DataStore objects, and RichTextEdit controls
rtename.PasteRTF ( richtextstring, { band } ) Argument rtename Description The name of the DataWindow control, DataStore object, or RichTextEdit control into which you want to paste data in rich text format. The DataWindow object in the DataWindow control or DataStore must be a RichTextEdit DataWindow. A string whose value is data with rich text formatting. A value of the Band enumerated datatype specifying the band into which the rich text data is pasted. Values are: Detail! The data is pasted into the detail band Header! The data is pasted into the header band Footer! The data is pasted into the footer band The default is the band that contains the insertion point.
Long. Returns the number of characters pasted if it succeeds and -1 if an error occurs. If richtextstring is NULL, PasteRTF returns NULL.
A DataWindow in the RichText presentation style has only three bands. There are no summary or trailer bands and there are no group headers and footers. This statement pastes rich text in the string ls_richtext into the header of the RichTextEdit rte_message:
string ls_richtext rte_message.PasteRTF(ls_richtext, Header!)
See also
CopyRTF
828
PowerBuilder
CHAPTER 10
PowerScript Functions
PasteSpecial
Description
Displays a standard OLE dialog allowing the user to choose whether to embed or link the OLE object on the clipboard when pasting it in the specified control. Embedding is the equivalent of calling the Paste function, and linking is the same as calling PasteLink. OLE controls
olecontrol.PasteSpecial ( ) Argument olecontrol Description The name of the OLE control into which you want to paste the object on the clipboard
Applies to Syntax
Return value
Integer. Returns 0 if it succeeds and one of the following values if an error occurs:
1 User canceled without selecting a paste option -1 No data found -9 Other error If ole2control is NULL, PasteSpecial returns NULL.
Usage Examples
For information about when an object on the clipboard is linkable, see PasteLink. If the clipboard contains an OLE object and the objects server application is running, then the following example lets the user choose to embed or link the object in the control ole_1:
integer li_result li_result = ole_1.PasteSpecial()
See also
829
Pi
Pi
Description Syntax
Double. Returns the result of multiplying n by pi if it succeeds and -1 if an error occurs. If n is NULL, Pi returns NULL.
Use Pi to convert angles to and from radians. This statement returns pi:
Pi(1)
Both these statements return the area of a circle with the radius id_Rad, an instance variable of type double:
Pi(1) * id_Rad^2 Pi(id_Rad^2)
Cos Sin Tan Pi method for DataWindows in the DataWindow Reference or the online Help
830
PowerBuilder
CHAPTER 10
PowerScript Functions
PixelsToUnits
Description
Converts pixels to PowerBuilder units. Because pixels are not usually square, you also specify whether you are converting the pixels horizontal or vertical measurement.
PixelsToUnits ( pixels, type ) Argument pixels type Description An integer whose value is the number of pixels you want to convert to PowerBuilder units. A value of the ConvertType enumerated datatype value indicating how to convert the value: XPixelsToUnits! Convert the pixels in the horizontal direction. YPixelsToUnits! Convert the pixels in the vertical direction.
Syntax
Integer. Returns the converted value if it succeeds and -1 if an error occurs. If any arguments value is NULL, PixelsToUnits returns NULL.
These statements convert 35 horizontal pixels to PowerBuilder units and set the variable Value equal to the converted value:
integer Value Value = PixelsToUnits(35, XPixelsToUnits!)
See also
UnitsToPixels
831
PointerX
PointerX
Description Applies to Syntax
Determines the distance of the pointer from the left edge of the specified object. Any object or control
objectname.PointerX ( ) Argument objectname Description The name of the control or window for which you want the pointers distance from the left edge. If you do not specify objectname, PointerX reports the distance from the left edge of the current sheet or window.
Return value
Integer. Returns the pointers distance from the left edge of objectname in
Examples
In a script for a control in a window, the following example stores the distance of the pointer from the edge of the window in the variable li_dist. If the pointer is 5 units from the left edge of the window, li_dist equals 5:
integer li_dist li_dist = Parent.PointerX()
This statement in a controls RButtonDown script displays a pop-up menu m_Appl.M_Help at the cursor position:
m_Appl.m_Help.PopMenu(Parent.PointerX(), & Parent.PointerY())
If the previous example was part of the windows RButtonDown script, instead of a control in the window, the following statement displays the pop-up menu at the cursor position:
m_Appl.m_Help.PopMenu(This.PointerX(), & This.PointerY()) See also
832
PowerBuilder
CHAPTER 10
PowerScript Functions
PointerY
Description Applies to Syntax
Determines the distance of the pointer from the top of the specified object. Any object or control
objectname.PointerY ( ) Argument objectname Description The name of the control or window for which you want the pointers distance from the top. If you do not specify objectname, PointerY reports the distance from the top of the current sheet or window.
Return value
Examples
In a script for a control in a window, the following example stores the distance of the pointer from the top of the window in the variable li_dist. If the pointer is 10 units from the top of the window, li_dist equals 10:
integer li_Dist li_Dist = Parent.PointerY()
This statement in a controls RButtonDown script displays a pop-up menu m_Appl.M_Help at the cursor position:
m_Appl.M_Help.PopMenu(Parent.PointerX(), & Parent.PointerY()) See also
833
PopMenu
PopMenu
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, PopMenu returns NULL.
If the menu object is not associated with the window so that it was opened when the window was opened, you must use CREATE to allocated memory for the menu (see the last example). If the Visible property of the menu is FALSE, you must make the menu visible before you can display it as a pop-up menu. The coordinates you specify for PopMenu are relative to the active window. In an MDI application, the coordinates are relative to the frame window, which is the active window. To display a menu at the cursor position, call PointerX and PointerY for the active window (the frame window in an MDI application) to get the coordinates of the cursor. (See the examples.)
Calling PopMenu in an object script
PopMenu must be called in an object script. It should not be called in a global function.
Examples
These statements display the menu m_Emp.M_Procedures at location 100, 200 in the active window. M_Emp is the menu associated with the window:
m_Emp.M_Procedures.PopMenu(100, 200)
This statement displays the menu m_Appl.M_File at the cursor position, where m_Appl is the menu associated with the window.
m_Appl.M_file.PopMenu(PointerX(), PointerY())
834
PowerBuilder
CHAPTER 10
PowerScript Functions
These statements display a pop-up menu at the cursor position. Menu4 was created in the Menu painter and includes a menu called m_language. Menu4 is not the menu for the active window. NewMenu is an instance of Menu4 (datatype Menu4):
Menu4 NewMenu NewMenu = CREATE Menu4 NewMenu.m_language.PopMenu(PointerX(), PointerY())
In an MDI application, the last line would include the MDI frame as the object for the pointer functions:
NewMenu.m_language.PopMenu( & w_frame.PointerX(), w_frame.PointerY())
835
PopulateError
PopulateError
Description Syntax
usually not used. If the values you want to populate the Error object with depend on the current value of a variable in your script, you can use PopulateError to assign values to the number and text fields in the Error object (the remaining fields of the Error object will be populated automatically, including the line number of the error). Then you can call SignalError without arguments to trigger a SystemError. You will need to include code in the SystemError event script to recognize and handle the error you have created. If there is no script for the SystemError event, the SignalError function does nothing. The gf_DoSomething function takes a table name and a record and returns 0 for success and a negative number for an error. The following statements set the number and text values in the Error object according to a script variable, then trigger a SystemError event once the processing is complete:
li_result = gf_DoSomething("Company", record_id) IF (li_result < 0) THEN CHOOSE CASE li_result CASE -1 PopulateError(1, "No company record exists & record id: " + record_id) CASE -2 PopulateError(2, "That company record is & currently locked. Please try again later.") CASE -3 PopulateError(3, "The company record could & not be updated.") CASE else PopulateError(999, "Update failed.") END CHOOSE SignalError() END IF See also
Examples
SignalError
836
PowerBuilder
CHAPTER 10
PowerScript Functions
Pos
Description
Long. Returns a long whose value is the starting position of the first occurrence
of string2 in string1 after the position specified in start. If string2 is not found in string1 or if start is not within string1, Pos returns 0. If any arguments value is NULL, Pos returns NULL.
Usage
The Pos function is case sensitive. In SBCS environments, the Pos and PosW functions return the same result. Although you can use the Pos function in DBCS environments, the value returned by this function is based exclusively on single-byte computation. Since characters in DBCS environments can be single byte, double byte, or mixed, you must use the PosW function to evaluate the position of a string within a string containing double-byte or mixed single-byte and double-byte characters.
Examples
This statement starts searching at position 4 and returns 0, because position 4 is after the occurrence of BE:
Pos("BABE RUTH", "BE", 4 )
837
PosW
These statements change the text NY in the SingleLineEdit sle_group to North East:
long place_nbr place_nbr = Pos(sle_group.Text, "NY") sle_group.SelectText(place_nbr, 2) sle_group.ReplaceText("North East")
These statements separate the return value of GetBandAtPointer into the band name and row number. The Pos function finds the position of the tab in the string and the Left and Mid functions extract the information to the left and right of the tab:
string s, ls_left, ls_right integer li_tab s = dw_groups.GetBandAtPointer() li_tab = Pos(s, "~t", 1) ls_left = Left(s, li_tab - 1) ls_right = Mid(s, li_tab + 1)
You could write similar code for a generic parsing function with three arguments. The string s would be an argument passed by value and ls_left and ls_right would be strings passed by reference. Other functions that return a pair of tab-separated values for which you could use the parsing function are GetObjectAtPointer and GetValue.
See also
GetValue method for DataWindows in the DataWindow Reference or the online
Help
GetObjectAtPointer method for DataWindows in the DataWindow Reference or
the online Help LastPos Left Mid Right Pos method for DataWindows in the DataWindow Reference or the online Help
PosW
Description Syntax
Finds one string within another string. For more information, see Pos.
PosW ( string1, string2 {, start } )
838
PowerBuilder
CHAPTER 10
PowerScript Functions
Position
Reports the position of the insertion point in an editable control.
To report The position of the insertion point in any editable control (except RichTextEdit) The position of the insertion point or the start and end of selected text in a RichTextEdit control or a DataWindow whose object has the RichTextEdit presentation style Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
Long. Returns the location of the insertion point in editname if it succeeds and -1 if an error occurs. If editname is NULL, Position returns NULL. Position reports the position number of the character immediately following the insertion point. For example, Position returns 1 if the cursor is at the beginning of editname. If text is selected in editname, Position reports the number of the
first character of the selected text. In a DataWindow control, Position reports the insertion points position in the edit control over the current row and column.
Examples
If mle_EmpAddress contains Boston Street, the cursor is immediately after the n in Boston, and no text is selected, this statement returns 7:
mle_EmpAddress.Position()
If mle_EmpAddress contains Boston Street and Street is selected, this statement returns 8 (the position of the S in Street):
mle_EmpAddress.Position()
839
Position
See also
SelectedLine SelectedStart
Syntax 2
Description Applies to Syntax
Band enumerated datatype. Returns the band (Detail!, Header!, or Footer!) containing the selection or insertion point. Position reports the position of the insertion point if you omit the toline and tochar arguments. If text is selected, the insertion point can be at the beginning or the end of the selection. For example, if the user dragged down to select text, the insertion point is at the end. If there is a selection, a character argument can be set to 0 to indicate that the selection begins or ends at the start of a line, with nothing else selected on that line. When the user drags up, the selection can begin at the start of a line and fromchar is set to 0. When the user drags down, the selection can end at the beginning of a line and tochar is set to 0.
Selection or insertion point
To find out whether there is a selection or just an insertion point, specify all four arguments. If toline and tochar are set to 0, then there is no selection, only an insertion point. If there is a selection and you want the position of the insertion point, you will have to call Position again with only two arguments. This difference is described next.
840
PowerBuilder
CHAPTER 10
PowerScript Functions
The position of the insertion point and end of selection can differ When reporting the position of selected text, the positions are inclusivePosition
reports the first line and character and the last line and character that are selected. When reporting the position of the insertion point, Position identifies the character just after the insertion point. Therefore, if text is selected and the insertion point is at the end, the values for the insertion point and the end of the selection differ. To illustrate, suppose the first four characters in line 1 are selected and the insertion point is at the end. If you request the position of the insertion point:
rte_1.Position(ll_line, ll_char)
Then: ll_line is set to 1 ll_char is set to 5, the character following the insertion point
ll_startline and ll_startchar are both set to 1 ll_endline is 1 and ll_endchar is set to 4, the last character in the selection
Because values obtained with Position provide more information that simply a selection range, you cannot pass the values directly to SelectText. In particular, 0 is not a valid character position when selecting text, although it is meaningful in describing the selection.
Examples
This example calls Position to get the band and the line and column values for the beginning and end of the selection. The values are converted to strings and displayed in the StaticText st_status:
integer li_rtn long ll_startline, ll_startchar long ll_endline, ll_endchar string ls_s, ls_band band l_band // Get the band and start and end of the selection l_band = rte_1.Position(ll_startline, ll_startchar,& ll_endline, ll_endchar)
841
Position
// Convert position values to strings ls_s = "Start line/char: " + String(ll_startline) & + ", " + String(ll_startchar) ls_s = ls_s + " End line/char: " & + String(ll_endline) + ", " + String(ll_endchar) // Convert Band datatype to string CHOOSE CASE l_band CASE Detail! ls_band = " Detail" CASE Header! ls_band = " Header" CASE Footer! ls_band = " Footer" CASE ELSE ls_band = " No band" END CHOOSE ls_s = ls_s + ls_band // Display the information st_status.Text = ls_s
This example extends the current selection down 1 line. It takes into account whether there is an insertion point or a selection, whether the insertion point is at the beginning or end of the selection, and whether the selection ends at the beginning of a line:
integer rtn long l1, c1, l2, c2, linsert, cinsert long l1select, c1select, l2select, c2select // Get selectio start and end rte_1.Position(l1, c1, l2, c2)
// Get insertion point rte_1.Position(linsert, cinsert) IF l2 = 0 and l1select = c1select = l2select = c2select = c2 = 0 THEN //insertion point linsert cinsert l1select + 1 // Add 1 to end line c1select
ELSEIF l2 > l1 THEN // Selection, ins pt at end IF c2 = 0 THEN // End of selection (ins pt) // at beginning of a line (char 0)
842
PowerBuilder
CHAPTER 10
PowerScript Functions
c2 = 999 // Change to end of prev line l2 = l2 - 1 END IF l1select c1select l2select c2select = = = = l1 c1 l2 + 1 // Add 1 to end line c2
ELSEIF l2 < l1 THEN // selection, ins pt at start IF c1 = 0 THEN // End of selection (not ins pt) // at beginning of a line c1 = 999 // Change to end of prev line l1 = l1 - 1 END IF l1select = l2 c1select = c2 l2select = l1 + 1 // Add 1 to end line // (start of selection) c2select = c1 ELSE // l1 = l2, selection on one line l1select = l1 l2select = l2 + 1 // Add 1 to line IF c1 < c2 THEN // ins pt at end c1select = c1 c2select = c2 ELSE // c1 > c2, ins pt at start c1select = c2 c2select = c1 END IF END IF // Select the extended selection rtn = rte_1.SelectText( l1select, c1select, & l2select, c2select )
843
Post
Post
Description Syntax
Adds a message to the message queue for a window, either a PowerBuilder window or window of another application.
Post ( handle, message#, word, long ) Argument handle Description A long whose value is the system handle of a window (that you have created in PowerBuilder or another application) to which you want to post a message. An UnsignedInteger whose value is the system message number of the message you want to post. A long whose value is the integer value of the message. If this argument is not used by the message, enter 0. The long value of the message or a string.
Use Post or Send when you want to trigger system events that are not PowerBuilder-defined events. Post is asynchronous; it adds a message to the end of the windows message queue. Send is synchronous; its message triggers an event immediately. To obtain the handle of a PowerBuilder window, use the Handle function. To trigger PowerBuilder events, use TriggerEvent or PostEvent. These functions run the script associated with the event. They are easier to code and bypass the messaging queue. When you specify a string for long, Post stores a copy of the string and passes a pointer to it.
Examples
This statement scrolls the window w_date down one page after all the previous messages in the message queue for the window have been processed:
Post(Handle(w_date), 277, 3, 0)
See also
844
PowerBuilder
CHAPTER 10
PowerScript Functions
PostEvent
Description Applies to Syntax
Adds an event to the end of the event queue of an object. Any object, except the application object
objectname.PostEvent ( event, { word, long } ) Argument objectname event Description The name of any PowerBuilder object or control (except an application) that has events associated with it. A value of the TrigEvent enumerated datatype that identifies a PowerBuilder event (for example, Clicked!, Modified!, or DoubleClicked!) or a string whose value is the name of an event. The event must be a valid event for objectname and a script must exist for the event in objectname. A long value to be stored in the WordParm property of the systems Message object. If you want to specify a value for long, but not word, enter 0. (For cross-platform compatibility, WordParm and LongParm are both longs). A long value or a string that you want to store in the LongParm property of the systems Message object. When you specify a string, a pointer to the string is stored in the LongParm property, which you can access with the String function (see Usage).
word (optional)
long (optional)
Return value
Boolean. Returns TRUE if it is successful and FALSE if the event is not a valid event for objectname or no script exists for the event in objectname. If any arguments value is NULL, PostEvent returns NULL.
Usage
You cannot post events to the event queue for an application object. Use TriggerEvent instead. You cannot post or trigger events for objects that do not have events, such as drawing objects. You cannot post or trigger events in a batch application that has no user interface because the application has no event queue. After you call PostEvent, check the return code to determine whether PostEvent succeeded. You can pass information to the event script with the word and long arguments. The information is stored in the Message object. In your script, you can reference the WordParm and LongParm fields of the Message object to access the information. Note that the Message object is saved and restored just before the posted event script runs so that the information you passed is available even if other code has used the Message object too.
845
PostEvent
If you have specified a string for long, you can access it in the triggered event by using the String function with the keyword "address" as the format parameter. (Note that PowerBuilder has stored the string at an arbitrary memory location and you are relying on nothing else having altered the pointer or the stored string.) Your event script might begin as follows:
string PassedString PassedString = String(Message.LongParm, "address")
TriggerEvent and PostEvent are useful for preventing duplication of code. If two controls perform the same task, you can use PostEvent in one controls event
script to execute the others script, instead of repeating the code in two places. For example, if both a button and a menu delete data, the buttons Clicked script can perform the deletion and the menus Clicked event script can post an event that runs the buttons Clicked event script. Choosing PostEvent or TriggerEvent Both PostEvent and TriggerEvent cause event scripts to be executed. PostEvent is asynchronous; it adds the event to the end of an objects event queue. TriggerEvent is synchronous; the event is triggered immediately. Use PostEvent when you want the current event script to complete before the posted event script runs. TriggerEvent interrupts the current script to run the triggered events script. Use it when you need to interrupt a process, such as canceling printing. If the function is the last line in an event script and there are no other events pending, PostEvent and TriggerEvent have the same effect. Events and messages in Windows Both PostEvent and TriggerEvent cause a script associated with an event to be executed. However, these functions do not send the actual event message. This is important when you are choosing the target object and event. The following background information explains this concept. Many PowerBuilder functions send Windows messages, which in turn trigger events and run scripts. For example, the Close function sends a Windows close message (WM_CLOSE). PowerBuilder maps the message to its internal close message (PBM_CLOSE), then runs the Close events script and closes the window. If you use TriggerEvent or PostEvent with Close! as the argument, PowerBuilder runs the Close events script but it does not close the window because it did not receive the close message. Therefore, the choice of which event to trigger is important. If you trigger the Clicked! event for a button whose script calls the Close function, PowerBuilder runs the Close events script and closes the window.
846
PowerBuilder
CHAPTER 10
PowerScript Functions
Use Post or Send when you want to trigger system events that are not PowerBuilder-defined events.
Examples
This statement adds the Clicked event to the event queue for CommandButton cb_OK. The event script will be executed after any other pending event scripts are run:
cb_OK.PostEvent(Clicked!)
This statement adds the user-defined event cb_exit_request to the event queue in the parent window:
Parent.PostEvent("cb_exit_request")
This example posts an event for cb_exit_request with an argument and then retrieves that value from the Message object in the events script. The first part of the example is code for a button in a window. It adds the user-defined event cb_exit_request to the event queue in the parent window. The value 455 is stored in the Message object for the use of the events script:
Parent.PostEvent("cb_exit_request", 455, 0)
The second part of the example is the beginning of the cb_exit_request event script, which assigns the value passed in the Message object to a local variable. The script can use the value in whatever way is appropriate to the situation:
integer numarg numarg = Message.WordParm See also
847
PostURL
PostURL
Description Applies to Syntax
Performs an HTTP Post, allowing a PowerBuilder application to send a request through CGI, NSAPI, or ISAPI. Inet objects
servicereference.PostURL ( urlname, urldata, headers, {serverport, } data ) Argument servicereference urlname urldata headers Description Reference to the Internet service instance. String specifying the URL to post. Blob specifying arguments to the URL specified by urlname. String specifying HTML headers. In Netscape, a newline (~n) is required after each HTTP header and a final newline after all headers. Specifies the server port number for the request. The default value for this argument is 0, which means that the port number is determined by the system (port 80 for HTTP requests). InternetResult instance into which the function returns HTML.
1 Success -1 General error -2 Invalid URL -4 Cannot connect to the Internet -5 Unsupported secure (HTTPS) connection attempted -6 Internet request failed
Usage
Call this function to invoke a CGI, NSAPI, or ISAPI function. Data references a standard class user object that descends from InternetResult and that has an overridden InternetData function. This overridden function then performs the required processing with the returned HTML. Because the Internet returns data asynchronously, data must reference a variable that remains in scope after the function executes (such as a window-level instance variable). To simulate a form submission, you need to send a header that indicates the proper Content-Type. For forms, the proper Content-Type header is:
Content-Type: application/x-www-form-urlencoded
For more information on the InternetResult standard class user object and the InternetData function, use the PowerBuilder Browser.
848
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This example calls the PostURL function using server port 8080. Iinet is an instance variable of type inet:
Blob lblb_args String ls_headers String ls_url Long ll_length iir_msgbox = CREATE n_ir_msgbox ls_url = "http://coltrane.sybase.com/" ls_url += "cgi-bin/pbcgi60.exe/" ls_url += "myapp/n_cst_html/f_test?" lblb_args = blob("") ll_length = Len(lblb_args) ls_headers = "Content-Length: " & + String(ll_length) + "~n~n" iinet.PostURL & (ls_url, lblb_args, ls_headers, 8080, iir_msgbox)
This example shows the use of a header with the correct content-type for a form:
Blob lblb_args String ls_headers String ls_url String ls_args long ll_length integer li_rc li_rc = GetContextService( "Internet", iinet_base ) IF li_rc = 1 THEN ir = CREATE n_ir ls_url = "http://localhost/Site/testurl.stm?" ls_args = "user=MyName&pwd=MyPasswd" lblb_args = Blob( ls_args ) ll_length = Len( lblb_args ) ls_header = "Content-Type: " + & "application/x-www-form-urlencoded~n" + & "Content-Length: " + String( ll_length ) + "~n~n" li_rc = iinet.PostURL( ls_url, lblb_args, & ls_header, ir ) END IF See also
849
Preview
Preview
Description Applies to Syntax
Displays the contents of a RichTextEdit control as either a preview of the document as it would print or in an editing view. RichTextEdit controls
rtename.Preview ( previewsetting ) Argument rtename previewsetting Description The name of the RichTextEdit control which you want to preview or edit. A boolean value indicating whether to put the RichTextEdit into preview or edit mode. Values are: True Preview the contents of the RichTextEdit as it would look when printed False Displays the contents in editable form
A RichTextEdit control has two ways of viewing the content: edit mode and preview mode. The Preview function switches between the two.
Edit mode Edit mode displays the text in readable form. The user can enter, select, and change text. There are properties for controlling the display of nonprinting characters in the text, such as carriage returns, spaces, tabs, and input fields. In edit mode, the toolbar, ruler bar, and tab bar, if visible, display above the editing area of the control. Preview mode Preview mode displays a miniature page within the control. The page is sized to fit within the control. Preview mode provides edit boxes for specifying paper dimensions and margins. Any selection is canceled when the control switches to preview mode. The user cannot edit text in preview mode, but scripts can call functions for selecting and changing text, including inserting documents.
If you call ShowHeadFoot when the control is in preview mode, you return to edit mode with the header and footer editing panels displayed. Make sure the RichTextEdit control is big enough to display the page formatting and scrolling controls available in preview mode.
Examples
See also
IsPreview
850
PowerBuilder
CHAPTER 10
PowerScript Functions
Print
Sends data to the current printer (or spooler, if the user has a spooler set up). There are several syntaxes. For syntax for DataWindows or DataStores, see the Print method for DataWindows in the DataWindow Reference or the online Help.
To Include a visual object, such as a window or a graph control in a print job Send one or more lines of text as part of a print job Print the contents of an RTE control Use Syntax 1 Syntax 2 Syntax 3
Syntax 1
Description Applies to Syntax
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, Print returns NULL.
851
Usage
PowerBuilder manages print jobs by opening the job, sending data, and closing the job. When you use Syntax 2 or 3, you must call the PrintOpen function and the PrintClose or PrintCancel functions yourself to manage the process. Print area and margins The print area is the physical page size minus any margins in the printer itself.
Examples
This example prints the CommandButton cb_close in its original size at location 500, 1000:
long Job Job = PrintOpen( ) cb_close.Print(Job, 500,1000) PrintClose(Job)
This example opens a print job, which defines a new page, then prints a title using the third syntax of Print. Then it uses this syntax of Print to print a graph on the first page and a window on the second page:
long Job Job = PrintOpen( ) Print(Job, "Report of Year-to-Date Sales") gr_sales1.Print(Job, 1000,PrintY(Job)+500, & 6000,4500) PrintPage(Job) w_sales.Print(Job, 1000,500, 6000,4500) PrintClose(Job) See also
Syntax 2
Description
Applies to Syntax
852
PowerBuilder
CHAPTER 10
PowerScript Functions
Description The position, measured from the left edge of the print area in thousandths of a inch, to which the print cursor should move before string is printed. If the print cursor is already at or beyond the position or if you omit tab1, Print starts printing at the current position of the print cursor. The string you want to print. If the string includes carriage return-newline character pairs (~r~n), the string will print on multiple lines. However, the initial tab position is ignored on subsequent lines. The new position, measured from the left edge of the print area in thousandths of a inch, of the print cursor after string printed. If the print cursor is already at or beyond the specified position, Print ignores tab2 and the print cursor remains at the end of the text. If you omit tab2, Print moves the print cursor to the beginning of a new line.
string
tab2 (optional)
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, Print returns NULL.
PowerBuilder manages print jobs by opening the job, sending data, and closing the job. When you use Syntax 2 or 3, you must call the PrintOpen function and the PrintClose or PrintCancel functions yourself to manage the process. Print cursor In a print job, PowerBuilder uses a print cursor to keep track of the print location. The print cursor stores the coordinates of the upper-left corner of the location at which print will being. PowerBuilder updates the print cursor after printing text with Print. Line spacing when printing text Line spacing in PowerBuilder is proportional to character height. The default line spacing is 1.2 times the character height. When Print starts a new line, it sets the x coordinate of the cursor to 0 and increases the y coordinate by the current line spacing. You can change the line spacing with the PrintSetSpacing function, which lets you specify a new factor to be multiplied by the character height. Because Syntax 3 of Print increments the y coordinate each time it creates a new line, it also handles page breaks automatically. When the y coordinate exceeds the page size, PowerBuilder automatically creates a new page in the print job. You do not need to call the PrintPage function, as you would if you were using the printing functions that control the cursor position (for example, PrintText or PrintLine). Print area and margins The print area is the physical page size minus any margins in the printer itself.
853
Using fonts You can use PrintDefineFont and PrintSetFont to specify the font used by the Print function when you are printing a string.
Examples
This example opens a print job, prints the string Sybase Corporation in the default font, and then starts a new line:
long Job // Define a blank page and assign the job an ID Job = PrintOpen( ) // Print the string and then start a new line Print(Job, "Sybase Corporation") ... PrintClose(Job)
This example opens a print job, prints the string Sybase Corporation in the default font, tabs 5 inches from the left edge of the print area but does not start a new line:
long Job // Define a blank page and assign the job an ID Job = PrintOpen( ) // Print the string but do not start a new line Print(Job, "Sybase Corporation", 5000) ... PrintClose(Job)
The first Print statement below tabs half an inch from the left edge of the print area, prints the string Sybase Corporation, and then starts a new line. The second Print statement tabs one inch from the left edge of the print area, prints the string Directors:, and then starts a new line:
long Job // Define a blank page and assign the job an ID Job = PrintOpen( ) // Print the string and start a new line Print(Job, 500, "Sybase Corporation") // Tab 1 inch from the left edge and print Print(Job, 1000, "Directors:") ... PrintClose(Job)
854
PowerBuilder
CHAPTER 10
PowerScript Functions
The first Print statement below tabs half an inch from the left edge of the print area prints the string Sybase Corporation, and then tabs 6 inches from the left edge of the print area but does not start a new line. The second Print statement prints the current date and then starts a new line:
long Job // Define a blank page and assign the job an ID Job = PrintOpen( ) // Print string and tab 6 inches from the left edge Print(Job, 500, "Sybase Corporation", 6000) // Print the current date on the same line Print(Job, String(Today())) ... PrintClose(Job)
In a window that displays a database error message in a MultiLineEdit mle_message, the following script for a Print button prints a title with the date and time and the message:
long li_prt li_prt = PrintOpen("Database Error") Print(li_prt, "Database error - " & + String(Today(), "mm/dd/yyyy") & + " - " & + String(Now(), "HH:MM:SS")) Print(li_prt, " ") Print(li_prt, mle_message.text) PrintClose(li_prt) See also
855
Syntax 3
Description Applies to Syntax
canceldialog
A boolean value indicating whether you want to display a nonmodal dialog box that allows the user to cancel printing. Values are:
TRUE Display the dialog box FALSE Do not display the dialog box
When the RichTextEdit control shares data with a DataWindow, the total number of pages contained in the control is the page count of the document multiplied by the row count of the DataWindow. You can specify printed page numbers by including an input field in the header or footer of your document. By calling InputFieldChangeData in the PrintHeader or PrintFooter event, you can specify the current value of that input field. Print might trigger the PrintHeader and PrintFooter events.
Examples
This statement prints one copy of pages 1 to 5 of the document in the RichTextEdit control rte_1. The output is not collated and a dialog box displays to allow the user to cancel the printing:
rte_1.Print(1, "1-5", FALSE, TRUE)
See also
Preview
856
PowerBuilder
CHAPTER 10
PowerScript Functions
PrintBitmap
Description Syntax
height
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintBitmap returns NULL. PrintBitmap does not change the position of the print cursor, which remains where it was before the function was called. In general, print functions in which you specify coordinates do not affect the print cursor (see the functions listed in See also).
Examples
These statements define a new blank page and then print the bitmap in file d:\PB\BITMAP1.BMP in its original size at location 50,100:
long Job // Define a new blank page. Job = PrintOpen( ) // Print the bitmap in its original size. PrintBitmap(Job, "d:\PB\BITMAP1.BMP", 50,100, 0,0) // Send the page to the printer and close Job. PrintClose(Job)
See also
PrintCancel
PrintCancel
Description
Cancels printing and deletes the spool file, if any. Cancels printing of a print job that you opened with the PrintOpen function. The print job is identified by the number returned by PrintOpen. For syntax for DataWindows and DataStores, see the PrintCancel method for DataWindows in the DataWindow Reference or the online Help.
Syntax
PrintCancel ( printjobnumber ) Argument printjobnumber Description The number the PrintOpen function assigned to the print job
Integer. Returns 1 if it succeeds and -1 if an error occurs. If printjobnumber is NULL, PrintCancel returns NULL. PrintCancel cancels the specified print job by deleting the spool file, if any, and closing the job. Because PrintCancel closes the print job, do not call the PrintClose function after you call PrintCancel.
Examples
In this example, a script for a Print button opens a print job and then opens a window with a cancel button. If the user clicks on the cancel button, its script sets a global variable that indicates that the user wants to cancel the job. After each printing command in the Print buttons script, the code checks the global variable and cancels the job if its value is TRUE. The definition of the global variable is:
boolean gb_printcancel
858
PowerBuilder
CHAPTER 10
PowerScript Functions
... // Additional printing commands, ... // including checking gb_printcancel PrintClose(job) Close(w_printcancel)
The script for the cancel button in the second window is:
gb_printcancel = TRUE Close(w_printcancel) See also
859
PrintClose
PrintClose
Description
Sends the current page to the printer (or spooler) and closes the job. Call PrintClose as the last command of a print job unless PrintCancel function has closed the job.
PrintClose ( printjobnumber ) Argument printjobnumber Description The number the PrintOpen function assigned to the print job
Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If printjobnumber is NULL, PrintClose returns NULL.
When you open a print job, you must close (or cancel) it. To avoid hung print jobs, process and close a print job in the same event in which you open it. This example opens a print job, which creates a blank page, prints a bitmap on the page, then sends the current page to the printer or spooler and closes the job:
ulong Job // Begin a new job and a new page. Job = PrintOpen( ) // Print the bitmap in its original size. PrintBitmap(Job, d:\PB\BITMAP1, 5,10, 0,0) // Send the page to the printer and close Job. PrintClose(Job)
See also
PrintCancel PrintOpen
860
PowerBuilder
CHAPTER 10
PowerScript Functions
PrintDataWindow
Description Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintDataWindow returns NULL.
Do not use PrintDataWindow with any Print functions except PrintOpen and PrintClose. When you use PrintDataWindow with PrintOpen and PrintClose, you can print several DataWindows in one print job. The information in each DataWindow control starts printing on a new page. When you print a DataWindow using PrintDataWindow, PowerBuilder uses the fonts and layout specified in the computers printer setup, not the fonts and layout specified in the DataWindow. PrintDefineFont and PrintSetFont also have no effect. When the DataWindows presentation style is RichTextEdit, each row begins a new page in the printed output. For information on skipping individual pages with return codes in the PrintPage event, see the Print function.
Examples
These statements send the contents of three DataWindow controls to the current printer in a single print job:
long job job = PrintOpen( ) // Each DataWindow starts printing on a new page. PrintDataWindow(job, dw_EmpHeader) PrintDataWindow(job, dw_EmpDetail) PrintDataWindow(job, dw_EmpDptSum) PrintClose(job)
See also
861
PrintDefineFont
PrintDefineFont
Description
Creates a numbered font definition that consists of a font supported by your printer and a set of font properties. You can use the font number in the PrintSetFont or PrintText functions. You can define up to eight fonts at a time.
PrintDefineFont ( printjobnumber, fontnumber, facename, height, weight, fontpitch, fontfamily, italic, underline ) Argument printjobnumber fontnumber facename height Description The number the PrintOpen function assigned to the print job. The number (1 to 8) you want to assign to the font. A string whose value is the name of a typeface supported by your printer (for example, Courier 10Cpi). An integer whose value is the height of the type in thousandths of an inch (for example, 250 for 18-point 10Cpi) or a negative number representing the point size (for example, -18 for 18point). Specifying the point size is more exact; the height in thousandths of an inch only approximates the point size. The stroke weight of the type. Normal weight is 400 and bold is 700. A value of the FontPitch enumerated datatype indicating the pitch of the font: Default! Fixed! Variable! A value of the FontFamily enumerated datatype indicating the family of the font: AnyFont! Decorative! Modern! Roman! Script! Swiss! italic underline A boolean value indicating whether the font is italic. The default is FALSE (not italic). A boolean value indicating whether the font is underlined. The default is FALSE (not underlined).
Syntax
weight fontpitch
fontfamily
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintDefineFont returns NULL.
You can use as many as eight fonts in one print job. If you require more than eight fonts in one job, you can call PrintDefineFont again to change the settings for a font number.
862
PowerBuilder
CHAPTER 10
PowerScript Functions
Use PrintSetFont to make a font number the current font for the open print job.
Fonts in Microsoft Windows
Although the fontfamily argument seems to duplicate information in the font name, Windows uses it along with the font name to identify the correct font or substitute a similar font if the named font is unavailable.
Some font names include a size, especially monospaced fonts which include characters per inch. This is the recommended size for the font and does not affect the printed size, which you specify with the height argument.
Examples
These statements define a new blank page, and then define print font 1 for Job as Courier 10Cpi, 18 point, normal weight, default pitch, Decorative font, with no italic or underline:
long Job Job = PrintOpen() PrintDefineFont(Job, 1, "Courier 10Cpi", & -18, 400, Default!, Decorative!, FALSE, FALSE)
See also
863
PrintGetPrinter
PrintGetPrinter
Description Syntax Return value Usage
The current printer is the default printer unless you change it with the PrintSetPrinter method. A PowerBuilder application calling the PrintGetPrinter method does not get an externally reset default after the application initializes. This example places the current printer name, driver, and port in separate SingleLineEdit textboxes:
String ls_fullstring=PrintGetPrinter() String ls_name, ls_driver, ls_port, ls_temp Long ll_place ll_place=pos (ls_fullstring, "~t") ls_name=left(ls_fullstring, ll_place -1) ls_temp=mid(ls_fullstring, ll_place +1) ll_place=pos (ls_temp, "~t") ls_driver=left(ls_temp, ll_place -1) ls_port=mid(ls_temp, ll_place +1) sle_1.text=ls_name sle_2.text=ls_driver sle_3.text=ls_port
Examples
See also
PrintGetPrinters PrintSetPrinter
864
PowerBuilder
CHAPTER 10
PowerScript Functions
PrintGetPrinters
Description Syntax Return value Usage Examples
drivername ~t port ~n. The return string can be loaded into a DataWindow using ImportString or separated using the ~n as shown in the example. This example parses printer names from the return string on the PrintGetPrinters call, then places each printer name in an existing SingleLineEdit control. If you have more printers than SingleLineEdit boxes, the last SingleLineEdit contains a string for all the printers that are not listed in the other SingleLineEdits:
singlelineedit sle long ll_place, i, k string ls_left, ls_prntrs ls_prntrs = PrintGetPrinters ( ) k = upperbound(control) FOR i= k to 1 STEP -1 IF parent.control[i].typeof()=singlelineedit! then sle=parent.control[i] ll_place=pos (ls_prntrs, "~n" ) ls_left = Left (ls_prntrs, ll_place - 1) sle.text = ls_left ls_prntrs = Mid (ls_prntrs, ll_place + 1) END IF NEXT sle.text = ls_prntrs See also
ImportString method for DataWindows in the DataWindow Reference or the online Help PrintGetPrinter PrintSetPrinter
865
PrintLine
PrintLine
Description Syntax
Draws a line of a specified thickness between the specified endpoints on the current print page.
PrintLine ( printjobnumber, x1, y1, x2, y2, thickness ) Argument printjobnumber x1 y1 x2 y2 thickness Description The number the PrintOpen function assigned to the print job An integer specifying the x coordinate in thousandths of an inch of the start of the line An integer specifying the y coordinate in thousandths of an inch of the start of the line An integer specifying the x coordinate in thousandths of an inch of the end of the line An integer specifying the y coordinate in thousandths of an inch of the end of the line An integer specifying the thickness of the line in thousandths of an inch
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintLine returns NULL. PrintLine does not change the position of the print cursor, which remains where it was before the function was called.
These statements start a new page in a print job and then print a line starting at 0,5 and ending at 7500,5 with a thickness of 10/1000 of an inch:
long Job Job = PrintOpen( ) ... // various print commands // Start a new page. PrintPage(Job) // Print a line at the top of the page PrintLine(Job,0,5,7500,5,10) ... // Other printing PrintClose(Job)
See also
866
PowerBuilder
CHAPTER 10
PowerScript Functions
PrintOpen
Description Syntax
Opens a print job and assigns it a number, which you use in other printing statements.
PrintOpen ( { jobname } ) Argument jobname (optional) Description A string specifying a name for the print job. The name is displayed in the Windows Print Manager dialog box and in the Spooler dialog box.
Long. Returns the job number if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintOpen returns NULL.
A new print job begins on a new page and the font is set to the default font for the printer. The print cursor is at the upper left corner of the print area. Use the job number that PrintOpen returns to identify this print job in all subsequent print functions. Calling MessageBox after PrintOpen can cause undesirable behavior that is confusing to a user. Calling PrintOpen causes the currently active window in PowerBuilder to be disabled to allow Windows to handle printing. If you display a MessageBox after calling PrintOpen, Windows assigns the active window to be its parent, which is often another application, causing that application to become active.
Balancing PrintOpen and PrintClose
When you open a print job, you must close (or cancel) it. To avoid hung print jobs, process and close a print job in the same event in which you open it.
Examples
867
PrintOpen
See also
Print PrintBitmap PrintCancel PrintClose PrintDataWindow PrintDefineFont PrintLine PrintOval PrintPage PrintRect PrintRoundRect PrintSend PrintSetFont PrintSetup PrintText PrintWidth PrintX PrintY
868
PowerBuilder
CHAPTER 10
PowerScript Functions
PrintOval
Description Syntax
Draws a white oval outlined in a line of the specified thickness on the print page.
PrintOval ( printjobnumber, x, y, width, height, thickness ) Argument printjobnumber x y width height thickness Description The number the PrintOpen function assigned to the print job An integer specifying the x coordinate in thousandths of an inch of the upper-left corner of the ovals bounding box An integer specifying the y coordinate in thousandths of an inch of the upper-left corner of the ovals bounding box An integer specifying the width in thousandths of an inch of the ovals bounding box An integer specifying the height in thousandths of an inch of the ovals bounding box An integer specifying the thickness of the line that outlines the oval in thousandths of an inch
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintOval returns NULL.
The PrintOval, PrintRect, and PrintRoundRect functions draw filled shapes. To print other shapes or text inside the shapes, draw the filled shape first and then add text and other shapes or lines inside it. If you draw the filled shape after other printing functions, it will cover anything inside it. For example, to draw a border around text and lines, draw the oval or rectangular border first and then use PrintLine and PrintText to position the lines and text inside.
PrintOval does not change the position of the print cursor, which remains where it was before the function was called. In general, print functions in which you specify coordinates do not affect the print cursor (see the functions listed in See also).
Examples
This example starts a print job with a new blank page, and then prints an oval that fits in a 1-inch square. The upper-left corner of the ovals bounding box is four inches from the top and three inches from the left edge of the print area. Because its height and width are equal, the oval is actually a circle:
long Job
869
PrintOval
870
PowerBuilder
CHAPTER 10
PowerScript Functions
PrintPage
Description Syntax
Sends the current page to the printer or spooler and begins a new blank page in the current print job.
PrintPage ( printjobnumber ) Argument printjobnumber Description The number the PrintOpen function assigned to the print job
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintPage returns NULL.
This example opens a print job with a new blank page, prints a bitmap on the page, and then sends the page to the printer and sets up a new blank page. Finally, the last Print statement prints the company name on the new page:
long Job // Open a job with new blank page. Job = PrintOpen() // Print a bitmap on the page. PrintBitmap(Job, "d:\PB\BITMAP1.BMP", 100,250, 0,0) // Begin a new page. PrintPage(Job) // Print the company name on the new page. Print(Job, "Sybase Corporation")
See also
PrintClose PrintOpen
871
PrintRect
PrintRect
Description Syntax
Draws a white rectangle with a border of the specified thickness on the print page.
PrintRect ( printjobnumber, x, y, width, height, thickness ) Argument printjobnumber x y width height thickness Description The number the PrintOpen function assigned to the print job An integer specifying the x coordinate in thousandths of an inch of the upper-left corner of the rectangle An integer specifying the y coordinate in thousandths of an inch of the upper-left corner of the rectangle An integer specifying the rectangles width in thousandths of an inch An integer specifying the rectangles height in thousandths of an inch An integer specifying the thickness of the rectangles border line in thousandths of an inch
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintRect returns NULL.
The PrintOval, PrintRect, and PrintRoundRect functions draw filled shapes. To print other shapes or text inside the shapes, draw the filled shape first and then add text and other shapes or lines inside it. If you draw the filled shape after other printing functions, it will cover anything inside it. For example, to draw a border around text and lines, draw the oval or rectangular border first and then use PrintLine and PrintText to position the lines and text inside. PrintRect does not change the position of the print cursor, which remains where it was before the function was called. In general, print functions in which you specify coordinates do not affect the print cursor (see the functions listed in See also).
Examples
These statements open a print job with a new page and draw a 1-inch square with a line thickness of 1/8 of an inch. The squares upper left corner is four inches from the left and three inches from the top of the print area:
long Job // Define a new blank page. Job = PrintOpen() // Print the rectangle on the page. PrintRect(Job, 4000,3000, 1000,1000, 125) ... // Other printing PrintClose(Job)
872
PowerBuilder
CHAPTER 10
PowerScript Functions
See also
873
PrintRoundRect
PrintRoundRect
Description Syntax
Draws a white rectangle with rounded corners and a border of the specified thickness on the print page.
PrintRoundRect ( printjobnumber, x, y, width, height, xradius, yradius, thickness ) Argument printjobnumber x y width height xradius yradius thickness Description The number the PrintOpen function assigned to the print job An integer specifying the x coordinate in thousandths of an inch of the upper-left corner of the rectangle An integer specifying the y coordinate in thousandths of an inch of the upper-left corner of the rectangle An integer specifying the rectangles width in thousandths of an inch An integer specifying the rectangles height in thousandths of an inch An integer specifying the x radius of the corner rounding An integer specifying the y radius of the corner rounding An integer specifying the thickness of the rectangles border line in thousandths of an inch
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintRoundRect returns NULL.
The PrintOval, PrintRect, and PrintRoundRect functions draw filled shapes. To print other shapes or text inside the shapes, draw the filled shape first and then add text and other shapes or lines inside it. If you draw the filled shape after other printing functions, it will cover anything inside it. For example, to draw a border around text and lines, draw the oval or rectangular border first and then use PrintLine and PrintText to position the lines and text inside.
PrintRoundRect does not change the position of the print cursor, which remains
where it was before the function was called. In general, print functions in which you specify coordinates do not affect the print cursor (see the functions listed in See also).
Examples
This example starts a new print job, which begins a new page, and prints a rectangle with rounded corners as a page border. Then it closes the print job, which sends the page to the printer.
874
PowerBuilder
CHAPTER 10
PowerScript Functions
The rectangle is 6 1/4 inches wide by 9 inches high and its upper corner is one inch from the top and one inch from the left edge of the print area. The border has a line thickness of 1/8 of an inch and the corner radius is 300:
long Job // Define a new blank page. Job = PrintOpen() // Print a RoundRectangle on the page. PrintRoundRect(Job, 1000,1000, 6250,9000, & 300,300, 125) // Send the page to the printer. PrintClose(Job) See also
875
PrintScreen
PrintScreen
Description Syntax
width (optional)
height (optional)
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintScreen returns NULL.
This statement prints the current screen image in its original size at location 500, 1000:
long Job Job = PrintOpen() PrintScreen(Job, 500,1000) PrintClose(Job)
See also
876
PowerBuilder
CHAPTER 10
PowerScript Functions
PrintSend
Description
Sends an arbitrary string of characters to the printer. PrintSend is usually used for sending escape sequences that change the printers setup.
Obsolete function PrintSend is an obsolete function and is provided for backward compatibility
only. The ability to use this function is dependent upon the printer driver.
Syntax PrintSend ( printjobnumber, string {, zerochar } ) Argument printjobnumber string zerochar (optional) Return value Usage Description The number the PrintOpen function assigned to the print job. A string you want to send to the printer. In the string, use ASCII values for nonprinting characters. An ASCII value (1 to 255) that you want to use to represent the number zero in string.
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintSend returns NULL.
Use PrintSend to send escape sequences to specific printers (for example, to set condensed mode or to set margins). Escape sequences are printer specific. As with any string, the number zero terminates the string argument. If the printer code you want to send includes a zero, you can use another character for zero in string and specify the character that represents zero in zerochar. The character you select should be a character you do not usually use. When PowerBuilder sends the string to the printer it converts the substitute character to a zero. A typical print job, in which you want to make printer-specific settings, might consist of the following function calls: 1 2 3 4 5
PrintOpen PrintSend, to change the printer orientation, select a tray, and so on PrintDefineFont and PrintSetFont to specify fonts for the job Print to output job text PrintClose
877
PrintSend
Examples
This example opens a print job and sends an escape sequence to a printer in IBM Proprinter mode to change the margins. There is no need to designate a character to represent zero:
long Job // Open a print job. Job = PrintOpen() /* Send the escape sequence. 1B is the escape character in hexadecimal. X indicates that you are changing the margins. 030 sets the left margin to 30 character spaces. 040 sets the right margin to 40 character spaces. */ PrintSend(Job," ~ h1BX ~ 030 ~ 040") ... // Print text or DataWindow // Send the job to the printer or spooler. PrintClose(Job)
This example opens a print job and sends an escape sequence to a printer in IBM Proprinter mode to change the margins. The decimal ASCII code 255 represents zero:
long Job // Open a print job. Job = PrintOpen() /* Send the escape sequence. 1B is the escape character, in hexadecimal. X indicates that you are changing the margins. 255 sets the left margin to 0. 040 sets the right margin to 40 character spaces. */ PrintSend(Job, "~h1BX~255~040", 255) PrintDataWindow(Job, dw_1) // Send the job to the printer or spooler. PrintClose(Job) See also
PrintClose PrintOpen
878
PowerBuilder
CHAPTER 10
PowerScript Functions
PrintSetFont
Description
Designates a font to be used for text printed with the Print function. You specify the font by number. Use PrintDefineFont to associate a font number with the desired font, a size, and a set of properties.
PrintSetFont ( printjobnumber, fontnumber ) Argument printjobnumber fontnumber Description The number the PrintOpen function assigned to the print job The number (1 to 8) of a font defined for the job in PrintDefineFont or 0 (the default font for the printer)
Syntax
Integer. Returns the character height of the current font if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintSetFont returns NULL.
This example starts a new print job and specifies that font number 2 is Courier, 18 point, bold, default pitch, in modern font, with no italic or underline. The PrintSetFont statement sets the current font to font 2. Then the Print statement prints the company name:
long Job // Start a new print job and a new page. Job = PrintOpen() // Define the font for Job. PrintDefineFont(Job, 2, "Courier 10Cps", & 250, 700, Default!, Modern!, FALSE, FALSE) // Set the font for Job. PrintSetFont(Job, 2) // Print the company name in the specified font. Print(Job,"Sybase Corporation")
See also
PrintDefineFont PrintOpen
879
PrintSetPrinter
PrintSetPrinter
Description Syntax
Sets the printer to use for the next print function call. This function does not affect open jobs.
PrintSetPrinter ( printername ) Argument printername Description String for the name of the printer you want to use
The printername argument must use the same format as returned by the PrintGetPrinter function. This example sets the printer to the first printer in the list retrieved by the PrintGetPrinters function:
long ll_place string ls_setprn string ls_prntrs = PrintGetPrinters ( ) ll_place=pos (ls_prntrs, "~n") mle_1.text = PrintGetPrinters ( ) ls_setprn = Left (ls_prntrs, ll_place - 1) PrintSetPrinter (ls_setprn)
See also
PrintGetPrinter PrintGetPrinters
880
PowerBuilder
CHAPTER 10
PowerScript Functions
PrintSetSpacing
Description Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintSetSpacing returns NULL.
Line spacing in PowerBuilder is proportional to character height. The default line spacing is 1.2 times the character height. When Print starts a new line, it sets the x coordinate of the cursor to 0 and increases the y coordinate by the current line spacing. The PrintSetSpacing function lets you specify a new factor to be multiplied by the character height for an open print job. These statements start a new print job and set the vertical spacing factor to 1.5 (one and a half spacing):
long Job // Define a new blank page. Job = PrintOpen() // Set the spacing factor. PrintSetSpacing(Job, 1.5)
Examples
See also
PrintOpen
881
PrintSetup
PrintSetup
Description Syntax Return value Usage Examples
Calls the Printer Setup dialog box provided by the system printer driver and lets the user specify settings for the printer.
PrintSetup ( )
Integer. Returns 1 if it succeeds and -1 if an error occurs.
The users settings have effect for the duration of the application only. After the application exits, printer settings revert to their previous values. These statements call the Printer Setup dialog box for the current system printer and then start a new print job:
long Job // Call the printer setup program. PrintSetup() // Start a job and a new page. Job = PrintOpen()
See also
PrintOpen
882
PowerBuilder
CHAPTER 10
PowerScript Functions
PrintSetupPrinter
Description Syntax Return value Usage
You can display the printer setup dialog box for different printers by first calling the PrintSetPrinter function. You cannot change the printer by calling PrintSetupPrinter as you can with the PrintSetup function. This example displays the printer setup dialog box for the last printer in the list retrieved by the PrintGetPrinters function.
long ll_place string ls_setptr string ls_prntrs = PrintGetPrinters ( ) ll_place=lastpos (ls_prntrs, "~n") ls_setptr = Mid (ls_prntrs, ll_place + 1) PrintSetPrinter (ls_setptr) PrintSetupPrinter ()
Examples
See also
883
PrintText
PrintText
Description Syntax
you omit fontnumber, the text prints in the current font for the print job. Return value
Integer. Returns the x coordinate of the new cursor location (that is, the value of the parameter x plus the width of the text) if it succeeds. PrintText returns -1 if an error occurs. If any arguments value is NULL, PrintText returns NULL. PrintText does change the position of the print cursor, unlike the other print functions for which you specify coordinates. The print cursor moves to the end of the printed text. PrintText also returns the x coordinate of the print cursor. You can use the return value to determine where to begin printing additional text. PrintText does not change the print cursors y coordinate, which is its vertical position on the page.
Usage
Examples
These statements start a new print job and then print PowerBuilder in the current font 3.7 inches from the left edge at the top of the page (location 3700,10):
long Job // Define a new blank page. Job = PrintOpen() // Print the text. PrintText(Job,"PowerBuilder", 3700, 10) ... // Other printing PrintClose(Job)
884
PowerBuilder
CHAPTER 10
PowerScript Functions
The following statements define a new blank page and then print Confidential in bold (as defined for font number 3), centered at the top of the page:
long Job // Start a new job and a new page. Job = PrintOpen() // Define the font. PrintDefineFont(Job, 3, & "Courier 10Cps", 250,700, & Default!, AnyFont!, FALSE, FALSE) // Print the text. PrintText(Job, "Confidential", 3700, 10, 3) ... // Other printing PrintClose(Job)
This example prints four lines of text in the middle of the page. The coordinates for PrintText establish a new vertical position for the print cursor, which the subsequent Print functions use and increment. The first Print function uses the x coordinate returned by PrintText to continue the first line. The rest of the Print functions print additional lines of text, after tabbing to the x coordinate used initially by PrintText. In this example, each Print function increments the y coordinate so that the following Print function starts a new line:
long Job // Start a new job and a new page. Job = PrintOpen() // Print the text. x = PrintText(Job,"The material ", 2000, 4000) Print(Job, x, " in this report") Print(Job, 2000, "is confidential and should not") Print(Job, 2000, "be disclosed to anyone who") Print(Job, 2000, "is not at this meeting.") ... // Other printing PrintClose(Job) See also
885
PrintWidth
PrintWidth
Description Syntax
Determines the width of a string using the current font of the specified print job.
PrintWidth ( printjobnumber, string ) Argument printjobnumber string Description The number the PrintOpen function assigned to the print job A string whose value is the text for which you want to determine the width
Return value
Integer. Returns the width of string in thousandths of an inch using the current font of printjobnumber if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintWidth returns NULL. If the returned width exceeds the maximum integer limit (+32767), PrintWidth returns -1.
Examples
These statements define a new blank page and then set W to the length of the string PowerBuilder in the current font and then use the length to position the next text line:
long Job int W // Start a new print job. Job = PrintOpen() // Determine the width of the text. W = PrintWidth(Job,"PowerBuilder") // Use the width to get the next print position. Print(Job, W - 500, "Features List")
See also
PrintClose PrintOpen
886
PowerBuilder
CHAPTER 10
PowerScript Functions
PrintX
Description Syntax
Integer. Returns the x coordinate of the print cursor if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintX returns NULL.
These statements set LocX to the x coordinate of the cursor and print End of
Report an inch beyond that location: integer LocX long Job Job = PrintOpen() ... //Print statements LocX = PrintX(Job) Print(LocX+1000, "End of Report")
See also
PrintY
887
PrintY
PrintY
Description Syntax
Integer. Returns the y coordinate of the cursor if it succeeds and -1 if an error occurs. If any arguments value is NULL, PrintY returns NULL.
These statements print a bitmap one inch below the location of the print cursor:
integer LocX, LocY long Job
Job = PrintOpen() ... //Print statements LocX = PrintX(Job) LocY = PrintY(Job) + 1000 PrintBitmap(Job, "CORP.BMP", LocX, LocY, 1000,1000) See also
PrintX
888
PowerBuilder
CHAPTER 10
PowerScript Functions
ProfileInt
Description Syntax
Obtains the integer value of a setting in the profile file for your application.
ProfileInt ( filename, section, key, default ) Argument filename Description A string whose value is the name of the profile file. If you do not specify a full path, ProfileInt uses the operating systems standard file search order to find the file. A string whose value is the name of a group of related values in the profile file. In the file, section names are in square brackets. Do not include the brackets in section. Section is not case sensitive. A string specifying the setting name in section whose value you want. The setting name is followed by an equal sign in the file. Do not include the equal sign in key. Key is not case sensitive. An integer value that ProfileInt will return if filename is not found, if section or key does not exist in filename, or if the value of key cannot be converted to an integer.
section
key
default
Return value
Integer. Returns default if filename is not found, section is not found in filename, or key is not found in section, or the value of key is not an integer. Returns -1 if an error occurs. If any arguments value is NULL, ProfileInt returns NULL.
Usage
Use ProfileInt or ProfileString to get configuration settings from a profile file that you have designed for your application. You can use SetProfileString to change values in the profile file to customize your applications configuration during execution. Before you make changes, you can use ProfileInt and ProfileString to obtain the original settings so you can restore them when the user exits the application.
Windows registry ProfileInt can also be used to obtain configuration settings from the Windows
system registry. For information on how to use the system registry, see the discussion of initialization files and the Windows registry in Application Techniques.
Examples
These examples use a file called PROFILE.INI, which contains the following:
[Pb] Maximized=1 [security] Class=7
889
ProfileInt
This statement returns the integer value for the keyword Maximized in section PB of file PROFILE.INI. If there were no PB section or no Maximized keyword in the PB section, it would return 3:
ProfileInt("C:\PROFILE.INI", "PB", "maximized", 3)
The following statements display a MessageBox if the integer value for the Class setting in section Security of file C:\PROFILE.INI is less than 10. The default security setting is 6 if the profile file is not found or does not contain a Class setting:
IF ProfileInt("C:\PROFILE.INI", "Security", & "Class", 6) < 10 THEN // Class is < 10 MessageBox("Warning", "Access Denied") ELSE ... // Some processing END IF See also
ProfileString SetProfileString ProfileInt method for DataWindows in the DataWindow Reference or the online Help
890
PowerBuilder
CHAPTER 10
PowerScript Functions
ProfileString
Description Syntax
Obtains the string value of a setting in the profile file for your application.
ProfileString ( filename, section, key, default ) Argument filename Description A string whose value is the name of the profile file. If you do not specify a full path, ProfileString uses the operating systems standard file search order to find the file. A string whose value is the name of a group of related values in the profile file. In the file, section names are in square brackets. Do not include the brackets in section. Section is not case sensitive. A string specifying the setting name in section whose value you want. The setting name is followed by an equal sign in the file. Do not include the equal sign in key. Key is not case sensitive. A string value that ProfileString will return if filename is not found, if section or key does not exist in filename, or if the value of key cannot be converted to an integer.
section
key
default
Return value
String, with a maximum length of 4096 characters. Returns the string from key within section within filename. If filename is not found, section is not found in filename, or key is not found in section, ProfileString returns default. If an error occurs, it returns the empty string (""). If any arguments value is NULL, ProfileString returns NULL.
Usage
Use ProfileInt or ProfileString to get configuration settings from a profile file that you have designed for your application. You can use SetProfileString to change values in the profile file to customize your applications configuration during execution. Before you make changes, you can use ProfileInt and ProfileString to obtain the original settings so you can restore them when the user exits the application.
Windows registry
ProfileString can also be used to obtain configuration settings from the Windows system registry. For information on how to use the system registry, see the discussion of initialization files and the Windows registry in Application Techniques.
891
ProfileString
Examples
These examples use a file called PROFILE.INI, which contains the following lines. Quotes around string values in the INI file are optional:
[Employee] Name=Smith [Dept] Name=Marketing
This statement returns the string contained in keyword Name in section Employee in file C:\PROFILE.INI and returns None if there is an error. In the example, the return value is Smith:
ProfileString("C:\PROFILE.INI", "Employee", & "Name", "None")
The following statements open w_marketing if the string in the keyword Name in section Department of file C:\PROFILE.INI is Marketing:
IF ProfileString("C:\PROFILE.INI", "Department", & "Name", "None") = "Marketing" THEN Open(w_marketing) END IF See also
ProfileInt SetProfileString ProfileString method for DataWindows in the DataWindow Reference or the online Help
892
PowerBuilder
CHAPTER 10
PowerScript Functions
Rand
Description Syntax
A numeric datatype, the datatype of n. Returns a random whole number between 1 and n inclusive. If n is NULL, Rand returns NULL. The sequence of numbers generated by repeated calls to the Rand function is a pseudorandom sequence. You can control whether the sequence is different each time your application runs by calling the Randomize function to initialize the random number generator. This statement returns a random whole number between 1 and 10:
Rand(10)
Examples
See also
Randomize
893
Randomize
Randomize
Description Syntax
Initializes the random number generator so that the Rand function begins a new series of pseudorandom numbers.
Randomize ( n ) Argument n Description The starting value (seed) for the random number generator. When n is 0, PowerBuilder takes the seed from the system clock and begins a nonrepeatable sequence. A nonzero number generates a different but repeatable sequence for each seed value. n cannot exceed 32,767.
Integer. If n is NULL, Randomize returns NULL. The return value is never used.
The sequence of numbers generated by repeated calls to the Rand function is a computer-generated pseudorandom sequence. You can use the Randomize function to initialize the random number generator with a value from the system clock, or some other changing value, so that the sequence is always different. For testing purposes, you can select a specific seed value, which you can reuse to make the pseudorandom sequence repeatable each time you run the application. Include Randomize in the script for the Open event in the application.
Examples
This statement sets the seed for the random number generator to 0 so that calls to Rand generate a new sequence each time the script is run:
Randomize(0)
This statement sets the seed for the random number generator to 4 so that calls to Rand repeat a specific sequence each time the random number generator is initialized:
Randomize(4) See also
Rand
894
PowerBuilder
CHAPTER 10
PowerScript Functions
Read
Reads data from an opened OLE stream object.
To Read data into a string Read data into a character array or blob Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
Return value
Integer. Returns the number of characters or bytes read. If an end-of-file mark (EOF) is encountered before any characters are read, Read returns -100. Read returns one of the following negative values if an error occurs:
-1 -2 -9
This example opens an OLE object in the file MYSTUFF.OLE and assigns it to the OLEStorage object stg_stuff. Then it opens the stream called info in stg_stuff and assigns it to the stream object olestr_info. Finally, it reads the contents of olestr_info into the string ls_info.
895
Read
The example does not check the functions return values for success, but you should be sure to check the return values in your code:
boolean lb_memexists OLEStorage stg_stuff OLEStream olestr_info blob ls_info stg_stuff = CREATE OLEStorage stg_stuff.Open("c:\ole2\mystuff.ole") olestr_info.Open(stg_stuff, "info", & stgRead!, stgExclusive!) olestr_info.Read(ls_info) See also
Syntax 2
Description Applies to Syntax
Return value
896
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This example opens an OLE object in the file MYSTUFF.OLE and assigns it to the OLEStorage object stg_stuff. Then it opens the stream called info in stg_stuff and assigns it to the stream object olestr_info. Finally, it reads the contents of olestr_info into the blob lb_info. The example does not check the functions return values for success, but you should be sure to check the return values in your code:
boolean lb_memexists OLEStorage stg_stuff OLEStream olestr_info blob lb_info stg_stuff = CREATE OLEStorage stg_stuff.Open("c:\ole2\mystuff.ole") olestr_info.Open(stg_stuff, "info", & stgRead!, stgExclusive!) olestr_info.Read(lb_info)
See also
897
Real
Real
Description Syntax
Converts a string value to a real datatype or obtains a real value that is stored in a blob.
Real ( stringorblob ) Argument stringorblob Description The string whose value you want returned as a real value or a blob in which the first value is the real value. The rest of the contents of the blob is ignored. Stringorblob can also be an Any variable containing a string or blob.
Return value
Real. Returns the value of stringorblob as a real. If stringorblob is not a valid PowerScript number or is an incompatible datatype, Real returns 0. If stringorblob is NULL, Real returns NULL.
Examples
The following example, although of no practical value, illustrates how to assign real values to a blob and how to use Real to extract those values. The two BlobEdit statements store two real values in the blob, one after the other. In the statements that use Real to extract the values, you have to know where the beginning of each real value is. Specifying the correct length in BlobMid is not important because the Real function knows how many bytes to evaluate:
blob{20} lb_blob real r1, r2 integer len1, len2 len1 = BlobEdit(lb_blob, 1, 32750E0) len2 = BlobEdit(lb_blob, len1, 43750E0) // // r1 // r2 See also
Double
Extract the real value at the beginning and ignore the rest of the blob = Real(lb_blob) Extract the second real value stored in the blob = Real(BlobMid(lb_blob, len1, len2 - len1))
Integer Long Real method for DataWindows in the DataWindow Reference or online Help
898
PowerBuilder
CHAPTER 10
PowerScript Functions
RegistryDelete
Description Syntax
For more information about entries in the system registry, see RegistrySet. This statement deletes the value name Title and its associated value from the registry. The key is not deleted:
RegistryDelete( & "HKEY_LOCAL_MACHINE\Software\MyApp.Settings\Fonts", & "Title")
See also
899
RegistryGet
RegistryGet
Description Syntax
valuetype
Return value
if the datatype of valuevariable does not correspond to the datatype specified in valuetype.
Usage
Long string values (more than 2048 bytes) should be stored as files and the file name stored in the registry. For more information about keys and value names in the system registry, see RegistrySet.
900
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This statement obtains the value for the name Title and stores it in the string ls_titlefont:
string ls_titlefont RegistryGet( & "HKEY_LOCAL_MACHINE\Software\MyApp.Settings\Fonts", & "Title", RegString!, ls_titlefont)
This statement obtains the value for the name NameOfEntryNum and stores it in the long ul_num:
ulong ul_num RegistryGet( & "HKEY_USERS\MyApp.Settings\Fonts", & "NameOfEntryNum", RegULong!, ul_num) See also
901
RegistryKeys
RegistryKeys
Description Syntax
Obtains a list of the keys that are child items (subkeys) one level below a key in the Windows system registry.
RegistryKeys ( key, subkeys ) Argument key Description A string whose value names the key in the system registry whose subkeys you want. To uniquely identify a key, specify the list of parent keys above it in the hierarchy, starting with the root key. The keys in the list are separated by backslashes. subkeys An array variable of strings in which you want to store the subkeys. If the array is variable size, its upper bound will reflect the number of subkeys found. If the array is fixed size, it must be large enough to hold all the subkeys. However, there will be no way to know how many subkeys were actually found.
For more information about entries in the system registry, see RegistrySet. This example obtains the subkeys associated with the key HKEY_CLASSES_ROOT\MyApp. The subkeys are stored in the variable-size array ls_subkeylist:
string ls_subkeylist[] integer li_rtn li_rtn = RegistryKeys("HKEY_CLASSES_ROOT\MyApp", & ls_subkeylist) IF li_rtn = -1 THEN ... // Error processing END IF
See also
902
PowerBuilder
CHAPTER 10
PowerScript Functions
RegistrySet
Description
Sets the value for a key and value name in the system registry. If the key or value name does not exist, RegistrySet creates a new key or name and sets its value.
RegistrySet ( key, valuename, valuetype, value ) Argument key Description A string whose value names the key in the system registry whose value you want to set. To uniquely identify a key, specify the list of parent keys above it in the hierarchy, starting with the root key. The keys in the list are separated by backslashes. If key does not exist in the registry, RegistrySet creates a new key. To create a key without a named value, specify an empty string for valuename. valuename A string containing the name of a value in the registry. Each key may have several named values. To specify the unnamed value, specify an empty string. If valuename does not exist in the registry, RegistrySet causes a new name to be created for key. valuetype A value of the RegistryValueType enumerated datatype identifying the datatype of a value in the registry. Values are: RegString!A null-terminated string RegExpandString!A null-terminated string that contains unexpanded references to environment variables RegBinary!Binary data ReguLong!A 32-bit number ReguLongBigEndian!A 32-bit number RegLink!A Unicode symbolic link value RegMultiString!An unbounded array of strings A variable corresponding to the datatype of valuetype containing a value to be set in the registry.
Syntax
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. An error is returned if the datatype of valuevariable does not correspond to the datatype specified in valuetype.
Usage
Long string values (more than 2048 bytes) should be stored as files and the file name stored in the registry.
903
RegistrySet
Item Key
Description An element in the registry. A key is part of a tree of keys, descending from one of the predefined root keys. Each key is a subkey or child of the parent key above it in the hierarchy. There are four root strings: HKEY_CLASSES_ROOT HKEY_LOCAL_MACHINE HKEY_USERS HKEY_CURRENT_USER A key is uniquely identified by the list of parent keys above it. The keys in the list are separated by slashes, as shown in these examples:
HKEY_CLASSES_ROOT\Sybase.Application HKEY_USERS\MyApp\Display\Fonts
The name of a value belonging to the key. A key can have one unnamed value and one or more named values. A value identifying the datatype of a value in the registry. A value associated with a value name or an unnamed value. Several string, numeric, and binary datatypes are supported by the registry.
Examples
This example sets a value for the key Fonts and the value name Title:
RegistrySet( & "HKEY_LOCAL_MACHINE\Software\MyApp\Fonts", & "Title", RegString!, sle_font.Text)
This statement sets a value for the key Fonts and the value name NameOfEntryNum:
ulong ul_num RegistrySet( & "HKEY_USERS\MyApp.Settings\Fonts", & "NameOfEntryNum", RegULong!, ul_num) See also
904
PowerBuilder
CHAPTER 10
PowerScript Functions
RegistryValues
Description Syntax
For more information about entries in the system registry, see RegistrySet. This example gets the value names associated with the key Fonts and stores them in the array ls_valuearray:
string ls_valuearray[] RegistryValues( & "HKEY_LOCAL_MACHINE\Software\MyApp.Settings\Fonts",& ls_valuearray)
See also
905
RelativeDate
RelativeDate
Description Syntax
Obtains the date that occurs a specified number of days after or before another date.
RelativeDate ( date, n ) Argument date n Description A value of type date An integer indicating a number of days
Return value
Date. Returns the date that occurs n days after date if n is greater than 0. Returns the date that occurs n days before date if n is less than 0. If any arguments value is NULL, RelativeDate returns NULL.
Examples
DaysAfter
RelativeDate method for DataWindows in the DataWindow Reference or the
online Help
906
PowerBuilder
CHAPTER 10
PowerScript Functions
RelativeTime
Description Syntax
Obtains a time that occurs a specified number of seconds after or before another time within a 24-hour period.
RelativeTime ( time, n ) Argument time n Description A value of type time A long number of seconds
Return value
Time. Returns the time that occurs n seconds after time if n is greater than 0. Returns the time that occurs n seconds before time if n is less than 0. The maximum return value is 23:59:59. If any arguments value is NULL, RelativeTime returns NULL.
Examples
SecondsAfter RelativeTime method for DataWindows in the DataWindow Reference or the online Help
907
ReleaseAutomationNativePointer
ReleaseAutomationNativePointer
Description Applies to Syntax
Releases the pointer to an OLE object that you got with GetAutomationNativePointer. OLEObject
oleobject.ReleaseAutomationNativePointer ( pointer ) Argument oleobject pointer Description The name of an OLEObject variable containing the object for which you want to release the native pointer. A UnsignedLong variable that holds the pointer you want to release. ReleaseAutomationNativePointer sets pointer to 0 so that it is clearly no longer a valid pointer.
Pointer is a pointer to OLEs IUnknown interface. You can use IUnknown::QueryInterface to get other interface pointers. When you call GetAutomationNativePointer, PowerBuilder calls OLEs AddRef function, which locks the pointer. You can release the pointer in your DLL function or in a PowerBuilder script with the ReleaseAutomationNativePointer function.
908
PowerBuilder
CHAPTER 10
PowerScript Functions
ReleaseNativePointer
Description Applies to Syntax
Releases the pointer to an OLE object that you got with GetNativePointer. OLE controls and OLE custom controls
olename.ReleaseNativePointer ( pointer ) Argument olename pointer Description The name of the OLE control containing the object for which you want the native pointer. A UnsignedLong variable that holds the pointer you want to release. ReleaseNativePointer sets pointer to 0 so that it is clearly no longer a valid pointer.
Pointer is a pointer to OLEs IUnknown interface. You can use IUnknown::QueryInterface to get other interface pointers. When you call GetNativePointer, PowerBuilder calls OLEs AddRef function, which locks the pointer. You can release the pointer in your DLL function or in a PowerBuilder script with the ReleaseNativePointer function.
909
RemoveDirectory
RemoveDirectory
Description Syntax
Removes a directory.
RemoveDirectory ( directoryname ) Argument directoryname Description String for the name of the directory you want to remove. If you do not specify an absolute path, this function deletes relative to the current working directory.
The directory must be empty and must not be the current directory for this function to succeed. This example removes a subdirectory from the current directory:
string ls_path="my targets" integer li_filenum li_filenum = RemoveDirectory ( ls_path ) If li_filename <> 1 then MessageBox("Remove directory failed", & + "Check that the directory exists, is empty, and " & + "is not the current directory") else MessageBox("Success", "Directory " + ls_path + & " deleted") end if
See also
DirectoryExists GetCurrentDirectory
910
PowerBuilder
CHAPTER 10
PowerScript Functions
Repair
Description Applies to Syntax
Updates the target database with corrections that have been made in the pipeline user objects Error DataWindow. Pipeline objects
pipelineobject.Repair ( destinationtrans ) Argument pipelineobject destinationtrans Description The name of a pipeline user object that contains the pipeline object being executed The name of a transaction object with which to connect to the target database
Return value
Integer. Returns 1 if it succeeds and a negative number if an error occurs. Error values are:
-5 Missing connection -9 Fatal SQL error in destination -10 Maximum number of errors exceeded -11 Invalid window handle -12 Bad table syntax -15 Pipe already in progress -17 Error in destination database -18 Destination database is read-only If any arguments value is NULL, Repair returns NULL.
Usage
When errors have occurred during a pipeline data transfer, Start populates its pipeline-error DataWindow control with the rows that caused the errors. The user or a script can then make corrections to the data. The Repair function is usually associated with a CommandButton that the user can click after correcting data in the pipeline-error DataWindow. If errors occur again, the rows that are in error remain in the pipeline-error DataWindow. The user can correct the data again and click the button that calls Repair.
Examples
This statement connects to the destination database using the transaction instance variable i_dst. It then updates the database with the corrections made in the Error DataWindow for pipeline i_pipe:
i_pipe.Repair(i_dst)
See also
911
Replace
Replace
Description
String. Returns the string with the characters replaced if it succeeds and the empty string if it fails. If any arguments value is NULL, Replace returns NULL.
If the start position is beyond the end of the string, Replace appends string2 to string1. If there are fewer characters after the start position than specified in n, Replace replaces all the characters to the right of character start. If n is zero, then, in effect, Replace inserts string2 into string1.
Examples
912
PowerBuilder
CHAPTER 10
PowerScript Functions
These statements replace all occurrences of red within the string mystring with green. The original string is taken from the SingleLineEdit sle_1 and the result becomes the new text of sle_1:
long start_pos=1 string old_str, new_str, mystring mystring = sle_1.Text old_str = "red" new_str = "green" // Find the first occurrence of old_str. start_pos = Pos(mystring, old_str, start_pos) // Only enter the loop if you find old_str. DO WHILE start_pos > 0 // Replace old_str with new_str. mystring = Replace(mystring, start_pos, & Len(old_str), new_str) // Find the next occurrence of old_str. start_pos = Pos(mystring, old_str, & start_pos+Len(new_str)) LOOP sle_1.Text = mystring See also
Replace method for DataWindows in the DataWindow Reference or the online
Help
ReplaceW
Description Syntax
Replaces a portion of one string with another. For more information, see Replace.
ReplaceW ( string1, start, n, string2 )
913
ReplaceText
ReplaceText
Description Applies to Syntax
Replaces selected text in an edit control with a specified string. DataWindow, EditMask, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox, and DropDownPictureListBox controls
editname.ReplaceText (string ) Argument editname Description The name of the DataWindow, EditMask, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox, or DropDownPictureListBox control in which you want to replace the selected string. In a DataWindow control, the text is replaced in the edit control over the current row and column. string The string that replaces the selected text.
Long. Returns the number of characters in string and -1 if an error occurs. If any arguments value is NULL, ReplaceText returns NULL.
If there is no selection, ReplaceText inserts the replacement text at the cursor position. In a RichTextEdit control, the selection can include pictures.
Other ways to replace text
To use the contents of the clipboard as the replacement text, call the Paste function, instead of ReplaceText. To replace text in a string, rather than a control, use the Replace function.
Examples
If the MultiLineEdit mle_Comment contains Offer Good for 3 Months and the selected text is 3 Months, this statement replaces 3 Months with 60 Days and returns 7. The resulting value of mle_Comment is Offer Good for 60 Days:
mle_Comment.ReplaceText("60 Days")
If there is no selected text, this statement inserts "Draft" at the cursor position in the SingleLineEdit sle_Comment3:
sle_Comment3.ReplaceText("Draft") See also
914
PowerBuilder
CHAPTER 10
PowerScript Functions
Reset
Clears data from a control or object. The syntax you choose depends on the target object. For syntax for DataWindows and DataStores see the Reset method for DataWindows in the DataWindow Reference or the online Help.
To Delete all items from a list Delete all the data (and optionally the series and categories) from a graph Return to the beginning of a trace file Use Syntax 1 Syntax 2 Syntax 3
Syntax 1
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If listboxname is NULL, Reset returns NULL. The return value is usually not used.
See also
DeleteItem
Syntax 2
Description Applies to
For graphs
Deletes the data, the categories, or the series from a graph. Graph controls in windows and user objects and graphs within a DataWindow object with an external data source. Does not apply to other graphs within DataWindow objects because their data comes directly from the DataWindow.
Syntax
controlname.Reset ( graphresettype )
915
Reset
Description The name of the graph object in which you want to delete all the data values or all series and all data values A value of the grResetType enumerated datatype specifying whether you want to delete only data values or all series and all data values: All! Delete all series, categories, and data in controlname Category! Delete categories and data in controlname Data! Delete data in controlname Series! Delete the series and data in controlname
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, Reset returns NULL. The return value is usually not used.
Use Reset to clear the data in a graph before you add new data. This statement deletes the series and data, but leaves the categories, in the graph gr_product_data:
gr_product_data.Reset(Series!)
See also
AddData AddSeries
Syntax 3
Description Applies to Syntax
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded FileNotOpenError!The specified trace file has not been opened
916
PowerBuilder
CHAPTER 10
PowerScript Functions
Usage
Use this function to return to the start of the open trace file and begin rereading the contents of the file. To use the Reset function, you must have previously opened the trace file with the Open function. You use the Reset and Open functions as well as the other properties and functions provided by the TraceFile object to access the contents of a trace file directly. You use these functions if you want to perform your own analysis of the tracing data instead of using the available modeling objects. This example returns execution to the start of the open trace file ltf_file so that the files contents can be reread:
TraceFile ltf_file string ls_filename ltf_file = CREATE TraceFile ltf_file.Open(ls_filename) ... ltf_file.Reset(ls_filename) ...
Examples
See also
917
ResetArgElements
ResetArgElements
Description Applies to Syntax
Call this function after calling InvokePBFunction or TriggerPBEvent to clear the argument list. If you populate the argument list with SetArgElement, you should call this function to clear the argument list after using InvokePBFunction or TriggerPBEvent to call an event or function with arguments.
Examples
918
PowerBuilder
CHAPTER 10
PowerScript Functions
ResetDataColors
Description Applies to Syntax
Restores the color of a data point to the default color for its series. Graph controls in windows and user objects, and graphs in DataWindow controls
controlname.ResetDataColors ( { graphcontrol, } seriesnumber, datapointnumber ) Argument controlname Description The name of the graph in which you want to reset the color of a data point, or the name of the DataWindow containing the graph (Optional) A string whose value is the name of the graph in the DataWindow control in which you want to reset the color The number of the series in which you want to reset the color of a data point The number of the data point for which you want to reset the color
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, ResetDataColors returns NULL.
To set the color for a series, use SetSeriesStyle. The color you set for the series is the default color for all data points in the series.
Examples
These statements change the color of data point 10 in the series named Costs in the graph gr_product_data to the color for the series:
SeriesNbr = gr_product_data.FinSeries("Costs") gr_product_data.ResetDataColors(SeriesNbr, 10)
These statements change the color of data point 10 in the series named Costs in the graph gr_comps in the DataWindow control dw_equip to the color for the series:
SeriesNbr = dw_equipment.FindSeries("Costs") dw_equip.ResetDataColors("gr_comps", SeriesNbr, 10) See also
Resize
Resize
Description Applies to Syntax
Resizes an object or control by setting its Width and Height properties and then redraws the object. Any object, except a child DataWindow
objectname.Resize ( width, height ) Argument objectname width height Description The name of the object or control you want to resize The new width in PowerBuilder units The new height in PowerBuilder units
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs or if objectname is a minimized or maximized window. If any arguments value is NULL, Resize returns NULL.
Usage
Equivalent syntax You can set objects Width and Height properties instead of calling the Resize function. However, the two statements cause PowerBuilder to redraw objectname twice; first with the new width, and then with the new width and height. objectname.Width = width objectname.Height = height
The first two statements, although they redraw gb_box1 twice, achieve the same result as the third statement:
gb_box1.Width = 100 // These lines resize gb_box1.Height = 150 // gb_box1 to 100 x 150 gb_box1.Resize(100, 150)// So does this line Examples
This statement changes the Width and Height properties of gb_box1 and redraws gb_box1 with the new properties:
gb_box1.Resize(100, 150)
This statement doubles the width and height of the picture control p_1:
p_1.Resize(p_1.Width*2, p_1.Height*2)
920
PowerBuilder
CHAPTER 10
PowerScript Functions
Resolve_Initial_References
Description
Uses the CORBA naming service API to obtain the initial naming context for an EAServer component. This function is used by PowerBuilder clients connecting to EAServer.
Applies to Syntax
JaguarORB objects
jaguarorb.Resolve_Initial_References ( objstring, object ) Argument jaguarorb objstring object Description An instance of JaguarORB A string that has the value "NameService" A reference variable of type CORBAobject that will contain a reference to the COS naming service
If you want to use the Jaguar naming service API, you can use the Resolve_Initial_References function to obtain the initial naming context. However, this technique is not recommended because it requires use of a deprecated SessionManager::Factory create method. Most PowerBuilder clients do not need to use the CORBA naming service explicitly. Instead, they can rely on the name resolution that is performed automatically when they create EAServer component instances using the CreateInstance and Lookup functions of the Connection object. You can also use the JaguarORB objects String_To_Object function to instantiate a proxy instance without using the CORBA naming service explicitly. For more information about connecting to EAServer using the JaguarORB object, see Application Techniques. When you use the CORBA naming service, you need to generate proxies for the naming service interface and include these proxies in the library list for the client.
Examples
The following example shows the use of the Resolve_Initial_References function to obtain an initial naming context. After obtaining the naming context, it uses the naming contexts resolve method to obtain a reference to a Factory object for the component and then narrows that reference to the SessionManagers Factory interface.
921
Resolve_Initial_References
The resolve method takes a name parameter, which is a sequence of NameComponent structures. Each NameComponent structure has an id attribute that identifies the component and a kind attribute that can be used to describe the component. In the example below, the name has only one component. The create method of the Factory object obtains proxies for the component. It returns a CORBA object reference that you can convert into a reference to the components interface using the _Narrow function. The NamingContext and NameComponent types used in the example are proxies imported from the CosNaming package in EAServer, and the Factory type is imported from the SessionManager package:
CORBAObject my_corbaobj JaguarORB my_orb NamingContext my_nc NameComponent the_name[] Factory my_Factory n_jagcomp my_jagcomp my_orb = CREATE JaguarORB // Enclose the name of the URL in single quotes my_orb.init("ORBNameServiceURL=iiop://server1:9000") my_orb.Resolve_Initial_References("NameService", & my_corbaobj) my_corbaobj._narrow(my_nc, & "omg.org/CosNaming/NamingContext") the_name[1].id = "mypackage/n_jagcomp" the_name[1].kind = "" TRY my_corbaobj = my_nc.resolve(the_name) my_corbaobj._narrow(my_Factory, & "SessionManager/Factory") my_corbaobj = my_Factory.create("jagadmin","") my_corbaobj._narrow(my_jagcomp, & "mypackage/n_jagcomp") CATCH (Exception e) MessageBox("Exception Raised!", e.getMessage()) END TRY my_jagcomp.getdata() See also
922
PowerBuilder
CHAPTER 10
PowerScript Functions
RespondRemote
Description Syntax
Sends a DDE message indicating whether the command or data received from a remote DDE application was acceptable.
RespondRemote ( boolean ) Argument boolean Description A boolean expression. TRUE indicates that the previously received command or data was acceptable. FALSE indicates that it was not.
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs (for example, the function was called in wrong context). If boolean is NULL, RespondRemote returns NULL.
Usage
You can use RespondRemote when the PowerBuilder application is the DDE server or DDE client application. You usually call RespondRemote after these functions:
GetCommandDDE GetCommandDDEOrigin GetDataDDE GetDataDDEOrigin
For more information about PowerBuilder as a client, see OpenChannel and ExecRemote. For more information about PowerBuilder as a server, see StartServerDDE.
Examples
In a script for the HotLinkAlarm event, these statements tell a remote application named Gateway that its data was successfully received:
String Applname, Topic, Item, Value GetDataDDEOrigin(Applname, Topic, Item) IF Applname = "Gateway" THEN IF GetDataDDE(Value) = 1 THEN RespondRemote(TRUE) END IF END IF
See also
923
Restart
Restart
Description
Stops the execution of all scripts, closes all windows (without executing the scripts for the Close events), commits and disconnects from the database, restarts the application, and executes the application-level script for the Open event.
Restart ( )
Integer. Returns 1 if it succeeds and -1 if it fails. The return value is usually not
used. You can use Restart in the application-level script for the Idle event to restart the application after a period of user inactivity, a typical behavior of kiosk applications. In the application-level script for the Idle event, this statement restarts the application:
Restart() See also
Examples
924
PowerBuilder
CHAPTER 10
PowerScript Functions
ResumeTransaction
Description Applies to Syntax
Associates the EAServer transaction passed as an argument with the calling thread. CORBACurrent objects
CORBACurrent.ResumeTransaction ( handletrans ) Argument CORBACurrent handletrans Description Reference to the CORBACurrent service instance An unsignedlong containing the handle of a suspended transaction
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -2 Usage
The ResumeTransaction function associates the transaction referred to by the handletrans argument with the calling thread. The argument is obtained from a call to SuspendTransaction and may refer to a transaction that was previously associated with the current thread or with a different thread in the same execution environment.
Caution
The handletrans argument must be obtained from the SuspendTransaction function. Using any other value as the argument to ResumeTransaction may have unpredictable results.
ResumeTransaction can be called by a client or a component that is marked as
OTS style. EAServer must be using the two-phase commit transaction coordinator (OTS/XA).
Examples
This example shows the use of the ResumeTransaction function to associate the calling thread with the transaction referred to by the ll_handle argument returned by SuspendTransaction:
// Instance variable: // CORBACurrent corbcurr integer li_rc unsignedlong ll_handle li_rc = this.GetContextService("CORBACurrent", & corbcurr)
925
ResumeTransaction
li_rc = corbcurr.Init() li_rc = corbcurr.BeginTransaction() // do some transactional work ll_handle = corbcurr.SuspendTransaction() //do some non-transactional work li_rc = corbcurr.ResumeTransaction(ll_handle) // do some more transactional work li_rc = corbcurr.CommitTransaction() See also
BeginTransaction CommitTransaction GetContextService GetStatus GetTransactionName Init RollbackOnly RollbackTransaction SetTimeout SuspendTransaction
926
PowerBuilder
CHAPTER 10
PowerScript Functions
Reverse
Description Syntax
String. Returns a string with the characters of string in reversed order. Returns the empty string if it fails. Reverse is useful with the IsArabic and IsHebrew functions, which help you
implement right-to-left character display when you are using a version of Windows that supports right-to-left languages.
Examples
Under a a version of Windows that supports right-to-left languages, this statement returns a string with the characters in reverse order from the characters entered in sle_name:
string ls_name ls_name = Reverse(sle_name.Text)
See also
IsArabic IsHebrew
927
RevertToSelf
RevertToSelf
Description Applies to Syntax
Restores the security attributes for a COM object that is running on MTS and impersonating the client. TransactionServer objects
transactionserver.RevertToSelf ( ) Argument transactionserver Description Reference to the TransactionServer service instance
COM objects running on MTS can use the ImpersonateClient function to run in the clients security context so that the object has access to the same resources as the client. Use RevertToSelf to restore the objects security context. The following example creates an instance of the TransactionServer service and checks whether the COM object is currently running in the clients security context. If it is, it reverts to the objects security context:
TransactionServer txninfo_test integer li_rc li_rc = GetContextService( "TransactionServer", txninfo_test ) IF txninfo_test.IsImpersonating() THEN & txninfo_test.RevertToSelf() &
Examples
See also
928
PowerBuilder
CHAPTER 10
PowerScript Functions
RGB
Description Syntax
Calculates the long value that represents the color specified by numeric values for the red, green, and blue components of the color.
RGB ( red, green, blue ) Argument red green blue Description The integer value of the red component of the desired color The integer value of the green component of the desired color The integer value of the blue component of the desired color
Return value
Long. Returns the long that represents the color created by combining the values specified in red, green, and blue. If an error occurs, RGB returns -1. If any arguments value is NULL, RGB returns NULL.
Usage
Use RGB to obtain the long value required to set the color for text and drawing objects. You can also set an objects color to the long value that represents the color. The RGB function provides an easy way to calculate that value.
About color values
The value of a component of a color is an integer between 0 and 255 that represents the amount of the color that is required to create the color you want. The lower the value, the darker the color; the higher the value, the lighter the color. To determine the values for the components of a color (known as the RGB values), use the Edit Color Entry window. To access the Edit Color Entry window, select a color in the color bar at the bottom of the workspace and then double-click the selected color when it displays in the first box of the color bar. The following table lists red, green, and blue values for the 16 standard colors.
Table 10-7: Red, green, and blue color values for use with RGB Color Black White Light Gray Dark Gray Red Dark Red Red value 0 255 192 128 255 128 Green value 0 255 192 128 0 0 Blue value 0 255 192 128 0 0
929
RGB
Color Green Dark Green Blue Dark Blue Magenta Dark Magenta Cyan Dark Cyan Yellow Brown Examples
These statements set the color properties of the StaticText st_title to be green letters on a dark magenta background:
st_title.TextColor = RGB(0, 255, 0) st_title.BackColor = RGB(128, 0, 128) See also
RGB method for DataWindows in the DataWindow Reference or the online
Help
930
PowerBuilder
CHAPTER 10
PowerScript Functions
Right
Description
Return value
String. Returns the rightmost n characters in string if it succeeds and the empty string ("") if an error occurs. If any arguments value is NULL, Right returns NULL. If n is greater than or equal to the length of the string, Right returns the entire string. It does not add spaces to make the return values length equal to n.
Usage
In SBCS environments, the Right and RightW functions return the same results. Although you can use the Right function in DBCS environments, the string returned by this function is based exclusively on single-byte computation. Since characters in DBCS environments can be single byte, double byte, or mixed, you must use the RightW function to return a string with double-byte or mixed single-byte and double-byte characters. This statement returns RUTH:
Right("BABE RUTH", 4)
Examples
RightW
Description Syntax
Obtains a specified number of characters from the end of a string. For more information, see Right.
RightW ( string, n )
931
RightTrim
RightTrim
Description
String. Returns a copy of string with trailing blanks deleted if it succeeds and the empty string ("") if an error occurs. If any arguments value is NULL, RightTrim returns NULL.
Usage
In SBCS environments, the RightTrim and RightTrimW functiones return the same results. Although you can use the RightTrim function in DBCS environments, it cannot remove double-byte spaces. You must use the RightTrimW function to remove double-byte or mixed single-byte and double-byte spaces. This statement returns RUTH:
RightTrim("RUTH ")
Examples
See also
LeftTrim Trim
RightTrim method for DataWindows in the DataWindow Reference or the online Help
RightTrimW
Description Syntax
Removes spaces from the end of a string. For more information, see RightTrim.
RightTrimW ( string )
932
PowerBuilder
CHAPTER 10
PowerScript Functions
RollbackOnly
Description Applies to Syntax
Modifies an EAServer transaction associated with a calling thread so that the only possible outcome is to roll back the transaction. CORBACurrent objects
CORBACurrent.RollbackOnly ( ) Argument CORBACurrent Description Reference to the CORBACurrent service instance
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -2 Usage
Failed for unknown reason No transaction is associated with the calling thread
RollbackTransaction is typically called by the originator of the transaction. Another participant in a client- or OTS style transaction can call RollbackOnly
Examples
In this example, a participant in a transaction has determined that it should be rolled back. It creates and initializes an instance of the CORBACurrent service object and votes to roll back the transaction:
// Instance variable: // CORBACurrent corbcurr int li_rc li_rc = this.GetContextService("CORBACurrent", & corbcurr) IF li_rc <> 1 THEN // handle the error END IF li_rc = corbcurr.Init() IF li_rc <> 0 THEN // handle the error ELSE corbcurr.RollbackOnly() END IF
933
RollbackOnly
See also
BeginTransaction CommitTransaction GetContextService GetStatus GetTransactionName Init ResumeTransaction RollbackTransaction SetTimeout SuspendTransaction
934
PowerBuilder
CHAPTER 10
PowerScript Functions
RollbackTransaction
Description Applies to Syntax
Rolls back the EAServer transaction associated with the calling thread. CORBACurrent objects
CORBACurrent.RollbackTransaction ( ) Argument CORBACurrent Description Reference to the CORBACurrent service instance
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -2 -3 -4 Usage
Failed for unknown reason No transaction is associated with the calling thread The calling thread does not have permission to commit the transaction The HeuristicCommit exception was raised
The RollbackTransaction function rolls back the transaction associated with the calling thread. The call fails if the HeuristicCommit exception is raised. Heuristic decisions are usually made when normal processing cannot continue, such as when a communications failure occurs. The HeuristicCommit exception is raised when all relevant updates have been committed.
RollbackTransaction can be called by a client or a component that is marked as
OTS style. EAServer must be using the two-phase commit transaction coordinator (OTS/XA).
Examples
This example shows the use of RollbackTransaction to roll back a transaction when an update does not succeed:
// Instance variables: // CORBACurrent corbcurr int li_rc1, li_rc2 long ll_rc this.GetContextService("CORBACurrent", corbcurr) li_rc1 = corbcurr.Init() IF li_rc1 <> 1 THEN // handle the error ELSE ll_rc = CreateInstance(mycomp) // invoke methods on the instantiated component // test return values and roll back // if unsatisfactory
935
RollbackTransaction
BeginTransaction CommitTransaction GetContextService GetStatus GetTransactionName Init ResumeTransaction RollbackOnly SetTimeout SuspendTransaction
936
PowerBuilder
CHAPTER 10
PowerScript Functions
Round
Description Syntax
Decimal. Returns x rounded to the specified number of decimal places if it succeeds, and null if it fails or if any arguments value is NULL.
Ceiling Int Truncate Round method for DataWindows in the DataWindow Reference or the online Help
937
RoutineList
RoutineList
Description Applies to Syntax
Provides a list of the routines included in a performance analysis model. ProfileClass and Profiling objects
instancename.RoutineList ( list ) Argument instancename list Description Instance name of the ProfileClass or Profiling object. An unbounded array variable of datatype ProfileRoutine in which RoutineList stores a ProfileRoutine object for each routine that exists in the model within a class. This argument is passed by reference.
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded ModelNotExistsError! No model exists
Usage
Use this function to extract a list of the routines included in the performance analysis model in a particular class. You must have previously created the performance analysis model from a trace file using the BuildModel function. Each routine is defined as a ProfileRoutine object and provides the time spent in the routine, any called routines, the number of times each routine was called, and the class to which the routine belongs. The routines are listed in no particular order. Object creation and destruction for a class are each indicated by a routine in this list as well as by embedded SQL statements.
Examples
This example lists the routines included in each class found in a performance analysis model:
Long ll_cnt ProfileCall lproc_call[] lpro_model.BuildModel() lpro_model.RoutineList(iprort_list) ...
See also
ClassList
938
PowerBuilder
CHAPTER 10
PowerScript Functions
Run
Description Syntax
windowstate (optional)
Integer. Returns 1 if it is successful and -1 if an error occurs. If any arguments value is NULL, Run returns NULL.
You can use Run for any program that you can run from the operating system. If you do not specify parameters, Run opens the application and displays the first application window. If you specify windowstate, the application window is displayed in the specified state. If you specify parameters, the application determines the meaning of those parameters. A typical use is to identify a data file to be opened when the program is executed. If you are running another PowerBuilder application, that application can call the CommandParm function to retrieve the parameters and process them as it sees fit. If the file extension is omitted from the file name, PowerBuilder assumes the extension is .EXE. To run a program with another extension (for example, .BAT, .COM, or .PIF), you must specify the extension.
Examples
This statement runs the Microsoft Windows Clock accessory application in its normal size:
Run("Clock")
This statement runs the Microsoft Windows Clock accessory application minimized:
Run("Clock", Minimized!)
939
Run
This statement runs the program WINNER.COM on the C drive in a maximized state. The parameter passed to WINNER.COM opens the file EMPLOYEE.INF:
Run("C:\WINNER.COM EMPLOYEE.INF", Maximized!)
This example runs the DOS batch file MYBATCH.BAT and passes the parameter TEST to the batch file. In the batch file, you include percent substitution characters in the commands to indicate where the parameter is used:
Run("MYBATCH.BAT TEST")
940
PowerBuilder
CHAPTER 10
PowerScript Functions
Save
Description Syntax
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -9
When you save an OLE object, PowerBuilder saves it according to the current connection between it and an open storage or file. You establish an initial connection when you call the Open function. When you call SaveAs, the old connection is ended and a new connection is established with another storage or file. When you call Save for an OLE control, PowerBuilder saves the object in the OLE control to the storage to which it is currently connected. The storage can be a storage object variable or a OLE storage file. If the data has never been saved in the server application, so that there is no file on disk, the Save function in PowerBuilder returns an error. When you call Save for a storage object variable, PowerBuilder saves the storage to the file, or substorage within the file, to which it is currently connected. You must have previously established a connection to an OLE storage file on disk, or a substorage within the file, either with Open or SaveAs.
When do you have to save twice?
If you create a storage object variable and then open that object in an OLE control, you need to call Save twice to write changed OLE information to disk: once to save from the object in the control to the storage, and again to save the storage to its associated file.
Examples
This example saves the object in the control ole_1 back to the storage from which it was loaded, either a storage object variable or a file on disk:
integer result result = ole_1.Save()
941
Save
This example saves a storage object to its file. Olestor_1 is an instance variable of type olestorage:
integer result result = olestor_1.Save()
In a windows Open script, this code creates a storage variable ole_stor, which is declared as an instance variable, and associates it with a storage file that contains several Visio drawings. The script then opens one of the drawings into the control ole_draw. After the user activates and edits the object, the script for a Save button saves the object to the storage and then to the storages file. The script for the windows Open event includes:
OLEStorage stg_stor stg_stor = CREATE OLEStorage stg_stor.Open("myvisio.ole") ole_draw.Open(ole_stor, "visio_drawing1")
Close SaveAs
942
PowerBuilder
CHAPTER 10
PowerScript Functions
SaveAs
Saves the contents of a DataWindow, DataStore, graph, OLE control, or OLE storage in a file. The syntax you use depends on the type of object you want to save. For DataWindow and DataStore syntax, see the SaveAs method for DataWindows in the DataWindow Reference or the online Help.
To Save the data in a graph Save the OLE object in an OLE control to a storage file Save the OLE object in an OLE control to a storage object in memory Save an OLE storage and any controls that have opened that storage in a file Save an OLE storage object in another OLE storage object Use Syntax 1 Syntax 2 Syntax 3 Syntax 4 Syntax 5
Syntax 1
Description Applies to Syntax
filename (optional)
943
SaveAs
Description A value of the SaveAsType enumerated datatype specifying the format in which to save the data represented in the graph. Values are: Clipboard! Save an image of the graph to the clipboard CSV! Comma-separated values dBASE2! dBASE-II format dBASE3! dBASE-III format DIF! Data Interchange Format Excel! Microsoft Excel format PSReport! Powersoft Report (PSR) format SQLInsert! SQL syntax SYLK! Microsoft Multiplan format Text! (Default) Tab-separated columns with a return at the end of each row WKS! Lotus 1-2-3 format WK1! Lotus 1-2-3 format WMF! Windows Metafile format XML! Extensible Markup Language
colheading (optional)
A boolean value indicating whether you want column headings with the saved data. The default value is TRUE. Colheading is ignored for dBASE files; column headings are always saved.
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SaveAs returns NULL.
You must use zero or three arguments. If you do not specify any arguments for SaveAs, PowerBuilder displays the Save As dialog box, letting the user specify the format of the saved data.
Regional settings
If you use date formats in your graph, you must verify that yyyy is the Short Date Style for year in the Regional Settings of the users Control Panel. Your program can check this with the RegistryGet function. If the setting is not correct, you can ask the user to change it manually or to have the application change it (by calling the RegistrySet function). The user may need to reboot after the setting is changed.
944
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This statement saves the contents of the graph gr_History. The file and format information are not specified, so PowerBuilder prompts for the file name and save the graph as tab-delimited text:
gr_History.SaveAs()
This statement saves the contents of gr_History to the file G:\HR\EMPLOYEE.HIS. The format is CSV without column headings:
gr_History.SaveAs("G:\HR\EMPLOYEE.HIS" ,CSV!, FALSE)
This statement saves the contents of gr_computers in the DataWindow control dw_equipmt to the file G:\INVENTORY\SALES.XLS. The format is Excel with column headings:
dw_equipmt.SaveAs("gr_computers", & "G:\INVENTORY\SALES.XLS", Excel!, TRUE) See also
Syntax 2
Description Applies to Syntax
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 The control is empty -2 The storage is not open -3 The storage name is invalid -9 Other error If any arguments value is NULL, SaveAs returns NULL.
945
SaveAs
Usage
The Open function establishes a connection between a storage file and a storage object, or a storage file or object and an OLE control. The Save function uses this connection to save the OLE data. When you call SaveAs for an OLE control, it closes the current connection between the OLE object and its storage, either file or storage object. It establishes a new connection with the new storage, which will be the target of subsequent calls to the Save function.
Examples
See also
Open Save
Syntax 3
Description Applies to Syntax
Return value
error occurs: -1 The control is empty -2 The storage is not open -3 The storage name is invalid -9 Other error If any arguments value is NULL, SaveAs returns NULL.
Usage
The Open function establishes a connection between a storage file and a storage object, or a storage file or object and an OLE control. The Save function uses this connection to save the OLE data.
946
PowerBuilder
CHAPTER 10
PowerScript Functions
When you call SaveAs for an OLE control, it closes the current connection between the OLE object and its storage, either file or storage object. It establishes a new connection with the new storage, which will be the target of subsequent calls to the Save function.
Examples
This example saves the object in the control ole_1 in the storage variable stg_stuff:
integer result result = ole_1.SaveAs(stg_stuff)
See also
Open Save
Syntax 4
Description Applies to Syntax
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 The storage is not open -2 The storage name is invalid -3 The parent storage is not open -4 The file already exists -5 Insufficient memory -6 Too many files open -7 Access denied -9 Other error If any arguments value is NULL, SaveAs returns NULL.
Usage
The Open function establishes a connection between a storage file and a storage object, or a storage file or object and an OLE control. The Save function uses this connection to save the OLE data.
947
SaveAs
When you call SaveAs for a storage object, it closes the current connection between the storage object and a file and creates a new file for the storage objects data. For information about the structure of storage files, see the Open function.
Examples
This example saves the storage object stg_stuff to the file MYSTUFF.OLE. Olest_stuff is an instance variable:
integer result result = stg_stuff.SaveAs("c:\ole\mystuff.ole")
This example opens a substorage in one file and saves it in another file. An OLE storage file called MYROOT.OLE contains several substorages; one is called sub1. To open sub1 and save it in another file, the example defines two storage objects: stg1 and stg2. First MYROOT.OLE is opened into stg1. Next, sub1 is opened into stg2. Finally, stg2 is saved to the new file MYSUB.OLE. Just as when you open a word processing document and save it to a new name, the open object in stg2 is no longer associated with MYROOT.OLE; it is now connected to MYSUB.OLE:
olestorage stg1, stg2 stg1 = CREATE OLEStorage stg2 = CREATE OLEStorage stg1.Open("myroot.ole") stg2.Open("sub1", stg1) stg2.SaveAs("mysub.ole") See also
Syntax 5
Description Applies to Syntax
948
PowerBuilder
CHAPTER 10
PowerScript Functions
Description A string whose value is the name of a substorage within targetstorage. If substorage does not exist, SaveAs creates it. The name of an object variable of OLEStorage in which to store the object in olestorage. Note the reversed order of the substoragename and targetstorage arguments from Syntax 4.
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 The storage is not open -2 The storage name is invalid -3 The parent storage is not open -4 The file already exists -5 Insufficient memory -6 Too many files open -7 Access denied -9 Other error If any arguments value is NULL, SaveAs returns NULL.
Usage
The Open function establishes a connection between a storage file and a storage object, or a storage file or object and an OLE control. The Save function uses this connection to save the OLE data. When you call SaveAs for a storage object, it closes the current connection between the storage object and a file and creates a new file for the storage objects data. For information about the structure of storage files, see the Open function.
Examples
This example saves the object in the OLEStorage variable stg_stuff in a second storage variable stg_clone as the substorage copy1:
integer result result = stg_stuff.SaveAs("copy1", stg_clone)
See also
949
SaveDocument
SaveDocument
Description Applies to Syntax
Saves the contents of a RichTextEdit control in a file. You can specify either rich-text format (RTF) or ASCII text format for the file. RichTextEdit controls
rtename.SaveDocument ( filename {, filetype } ) Argument rtename filename filetype (optional) Description The name of the RichTextEdit control whose contents you want to save. A string whose value is the name of the file to be saved. If the file already exists, the FileExists event is triggered. A value of the FileType enumerated datatype specifying the format of the saved file. Values are: FileTypeRichText! Save the file in rich text format (RTF) FileTypeText! Save the file as ASCII text
Integer. Returns 1 if it succeeds and -1 if an error occurs. SaveDocument triggers a FileExists event when the file you name already
exists. This code for a CommandButton saves the document in the RichTextEdit rte_1:
integer li_rtn li_rtn = rte_1.SaveDocument("c:\test.rtf", & FileTypeRichText!)
If the file TEST.RTF already exists, PowerBuilder triggers the FileExists event with the following script. OpenWithParm displays a response window that asks the user if it is OK to overwrite the file. The return value from FileExists determines whether the file is saved:
OpenWithParm( w_question, & "The specified file already exists. " + & "Do you want to overwrite it?" ) IF Message.StringParm = "Yes" THEN RETURN 0 // File is saved ELSE RETURN -1 // Saving is canceled END IF See also
InsertDocument
950
PowerBuilder
CHAPTER 10
PowerScript Functions
Scroll
Description Applies to Syntax
Scrolls a multiline edit control or the edit control of a DataWindow a specified number of lines up or down. DataWindow, MultiLineEdit, and RichTextEdit controls
editname.Scroll ( number ) Argument editname Description The name of the DataWindow, RichTextEdit, or MultiLineEdit in which you want to scroll up or down. If editname is a DataWindow, then Scroll affects its edit control. A long specifying the direction and number of lines you want to scroll. To scroll down, use a positive long value. To scroll up, use a negative long value.
number
Return value
Long. For RichTextEdit controls, Scroll returns 1 if it succeeds. For other controls, Scroll returns the line number of the first visible line in editname if it succeeds. Scroll returns -1 if an error occurs. If any arguments value is NULL, Scroll returns NULL.
Usage
If the number of lines left in the list is less than the number of lines that you want to scroll, then Scroll scrolls to the beginning or end, depending on the direction specified. This statement scrolls mle_Employee down 4 lines:
mle_Employee.Scroll(4)
Examples
The following functions implement scrolling in a DataWindow or a RichTextEdit: ScrollNextPage ScrollNextRow ScrollPriorPage ScrollPriorRow ScrollToRow
951
ScrollNextPage
ScrollNextPage
Description
Scrolls to the next page of the document in a RichTextEdit control or RichTextEdit DataWindow. For DataWindow syntax, see the ScrollNextPage method for DataWindows in the DataWindow Reference or the online Help.
Applies to Syntax
RichTextEdit controls
rtename.ScrollNextPage ( ) Argument rtename Description The name of the RichTextEdit or DataWindow control in which you want to scroll to the next page. The DataWindow object in the DataWindow control must be a RichTextEdit DataWindow.
When the RichTextEdit control shares data with a DataWindow, the RichTextEdit contains multiple instances of the document, one instance for each row. When the last page of the document for one row is visible, calling ScrollNextPage advances to the first page for the next row.
Examples
This statement scrolls to the next page of the document in the RichTextEdit control rte_1. If there are multiple instances of the document, it can scroll to the next instance:
rte_1.ScrollNextPage()
See also
952
PowerBuilder
CHAPTER 10
PowerScript Functions
ScrollNextRow
Description
Scrolls to the next instance of the document in a RichTextEdit control or RichTextEdit DataWindow. A RichTextEdit control has multiple instances of its document when it shares data with a DataWindow. The next instance of the document is associated with the next row in the DataWindow. For syntax specific to DataWindow controls and child DataWindows, see the ScrollNextRow method for DataWindows in the DataWindow Reference or the online Help.
Applies to Syntax
When the RichTextEdit shares data with a DataWindow, the RichTextEdit contains multiple instances of the document, one instance for each row.
ScrollNextRow advances to the next instance of the RichTextEdit document. In contrast, repeated calls to ScrollNextPage advance through all the pages of the
document instance and then on to the pages for the next row.
Examples
This statement scrolls to the next instance of the document in the RichTextEdit control rte_1. Each document instance is associated with a row of data.
rte_1.ScrollNextRow()
See also
953
ScrollPriorPage
ScrollPriorPage
Description
Scrolls to the prior page of the document in a RichTextEdit control or RichTextEdit DataWindow. For syntax specific to DataWindow controls and child DataWindows, see the ScrollPriorPage method for DataWindows in the DataWindow Reference or the online Help.
Applies to Syntax
When the RichTextEdit shares data with a DataWindow, the RichTextEdit contains multiple instances of the document, one instance for each row. When the first page of the document for one row is visible, calling ScrollPriorPage goes to the last page for the prior row.
Examples
This statement scrolls to the prior page of the document in the RichTextEdit control rte_1. If there are multiple instances of the document, it can scroll to the prior instance:
rte_1.ScrollPriorPage()
See also
954
PowerBuilder
CHAPTER 10
PowerScript Functions
ScrollPriorRow
Description
Scrolls to the prior instance of the document in a RichTextEdit control or RichTextEdit DataWindow. A RichTextEdit control has multiple instances of its document when it shares data with a DataWindow. The next instance of the document is associated with the next row in the DataWindow. For syntax specific to DataWindow controls and child DataWindows, see the ScrollPriorRow method for DataWindows in the DataWindow Reference or the online Help.
Applies to Syntax
When the RichTextEdit shares data with a DataWindow, the RichTextEdit contains multiple instances of the document, one instance for each row.
ScrollPriorRow goes to the prior instance of the RichTextEdit document. In contrast, repeated calls to ScrollPriorPage pages back through all the pages of the document instance and then back to the pages for the prior row.
Examples
This statement scrolls to the prior instance of the document in the RichTextEdit control rte_1. Each document instance is associated with a row of data.
rte_1.ScrollPriorRow()
See also
955
ScrollToRow
ScrollToRow
Description
Scrolls to the document instance associated with the specified row when the RichTextEdit controls shares data with a DataWindow. For syntax specific to DataWindow controls and child DataWindows, see the ScrollToRow method for DataWindows in the DataWindow Reference or the online Help.
Applies to Syntax
RichTextEdit controls
rtename.ScrollToRow ( row ) Argument rtename row Description The name of the RichTextEdit control in which you want to scroll to a document instance associated with the specified row. A long identifying the row to which you want to scroll. If row, is 0, ScrollToRow scrolls to the first row. If row is greater than the number of rows in the associated DataWindow, it scrolls to the last row.
When the RichTextEdit shares data with a DataWindow, the RichTextEdit contains multiple instances of the document, one instance for each row. ScrollToRow goes to the instance associated with the specified row. In this example, dw_1 has retrieved at least 25 rows of data. After calling DataSource, the RichTextEdit control contains at least 25 instances of its document. ScrollToRow scrolls to the 25th instance:
rte_1.DataSource(dw_1) rte_1.ScrollToRow(25)
Examples
See also
956
PowerBuilder
CHAPTER 10
PowerScript Functions
Second
Description Syntax
Integer. Returns the seconds portion of time (00 to 59). If time is NULL, Second returns NULL.
See also
Hour Minute
Second method for DataWindows in the DataWindow Reference or the online
Help
957
SecondsAfter
SecondsAfter
Description Syntax
Return value
Long. Returns the number of seconds time2 occurs after time1. If time2 occurs before time1, SecondsAfter returns a negative number. If any arguments value is NULL, SecondsAfter returns NULL.
Examples
If you declare start_time and end_time time variables and assign 19:02:16 to start_time and 19:02:28 to end_time as shown below:
time start_time, end_time start_time = 19:02:16 end_time = 19:02:28
online Help
958
PowerBuilder
CHAPTER 10
PowerScript Functions
Seek
Description Applies to Syntax
Moves the read/write pointer to the specified position in an OLE stream object. The pointer is the position in the stream at which the next read or write begins. OLEStream objects
olestream.Seek ( position {, origin } ) Argument olestream position origin (optional) Description The name of an OLE stream variable that has been opened. A long whose value is the position relative to origin to which you want to move the read/write pointer. The value of the SeekType enumerated datatype specifying where you want to start the seek. Values are: FromBeginning! (Default) At the beginning of the file FromCurrent! At the current position FromEnd! At the end of the file
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -2 -9
This example writes additional data to an OLE stream. First, it opens an OLE object in the file MYSTUFF.OLE and assigns it to the OLEStorage object stg_stuff. Then it opens the stream called info in stg_stuff and assigns it to the stream object olestr_info. Seek positions the read/write pointer at the end of the stream so that the contents of the instance blob variable lb_info is written at the end. The example does not check the functions return values for success, but you should be sure to check the return values in your code:
boolean lb_memexists OLEStorage stg_stuff OLEStream olestr_info stg_stuff = CREATE OLEStorage stg_stuff.Open("c:\ole\mystuff.ole") olestr_info.Open(stg_stuff, "info", & stgReadWrite!, stgExclusive!)
959
Seek
960
PowerBuilder
CHAPTER 10
PowerScript Functions
SelectedColumn
Description Applies to Syntax
Obtains the number of the character column just after the insertion point in a RichTextEdit control. RichTextEdit controls
rtename.SelectedColumn ( ) Argument rtename Description The name of the RichTextEdit in which you want the number of the character after the insertion point
Integer. Returns the number of the character before the insertion point in rtename. If an error occurs, SelectedColumn returns -1.
The insertion point can be at the beginning or end of the selection. Therefore, SelectedColumn can return the first character of the selection or the character just after the selection, depending on the position of the insertion point. If the insertion point is positioned before the fifth character on line 8 of the RichTextEdit rte_Contact, the following example sets li_SL to 5 and li_line to 8:
integer li_SL, li_line li_SL = rte_Contact.SelectedColumn()
Examples
See also
961
SelectedIndex
SelectedIndex
Description Applies to Syntax
Obtains the number of the selected item in a ListBox or ListView control. ListBox and ListView controls
listcontrolname.SelectedIndex ( ) Argument listcontrolname Description The name of the ListBox or ListView control in which you want to locate the selected item
Return value
Integer. Returns the index of the selected item in listcontrolname. If more than one item is selected, SelectedIndex returns the index of the first selected item. If there are no selected items or an error occurs, SelectedIndex returns -1. If listcontrolname is NULL, SelectedIndex returns NULL. SelectedIndex and SelectedItem are meant for lists that allow a single selection only (when the MultiSelect property for the control is FALSE).
Usage
When the MultiSelect property is TRUE, SelectedIndex gets the index of the first selected item only. Use the State function, instead of SelectedIndex, to check each item in the list and find out if it is selected. Use the Text function to get the text of any item in the list.
Examples
SelectedItem
962
PowerBuilder
CHAPTER 10
PowerScript Functions
SelectedItem
Description Applies to Syntax
Obtains the text of the selected item in a ListBox control. ListBox and PictureListBox controls
listboxname.SelectedItem ( ) Argument listboxname Description The name of the ListBox or PictureListBox in which you want the text of the currently selected item
Return value
String. Returns the text of the selected item in listboxname. Returns the empty string ("") if no items are selected. If listboxname is NULL, SelectedItem returns NULL. SelectedIndex and SelectedItem are meant for lists that allow a single selection only (when the MultiSelect property for the control is FALSE).
Usage
When the MultiSelect property is TRUE, SelectedItem gets the text of the first selected item only. Use the State function, instead of SelectedItem, to check each item in the list and find out if it is selected. Use the Text function to get the text of any item in the list.
Examples
If the text of the selected item in the ListBox lb_shortcuts is F1, then this example sets ls_item to F1:
string ls_Item ls_Item = lb_Shortcuts.SelectedItem()
See also
SelectedIndex State
963
SelectedLength
SelectedLength
Description Applies to Syntax
Determines the total number of characters in the selected text in an editable control, including spaces and line endings. DataWindow, EditMask, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox, and DropDownPictureListBox controls
editname.SelectedLength ( ) Argument editname Description The name of the DataWindow, EditMask, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox, or DropDownPictureListBox control in which you want the length of the selected text. For a DataWindow, it reports the length of the selected text in the edit control over the current row and column.
Return value
Long. Returns the length of the selected text in editname. If no text is selected, SelectedLength returns 0. If an error occurs, it returns -1. If editname is NULL, SelectedLength returns NULL.
Usage
The characters that make up a line ending, produced by typing Ctrl+Enter or Enter, is different on different platforms. On Windows, it is a carriage return plus a line feed and equals two characters when calculating the length. On other platforms, a line ending is a single character. A line that has wrapped has no line-ending character. For DropDownListBox and DropDownPictureListBox controls, SelectedLength returns -1 if the controls AllowEdit property is set to FALSE.
Focus and the selection in a drop-down list
When a DropDownListBox or DropDownPictureListBox loses focus, the selected text is no longer selected.
Examples
If the selected text in the MultiLineEdit mle_Contact is John Smith, then this example sets li_length to 10:
integer li_length li_length = mle_Contact.SelectedLength()
See also
964
PowerBuilder
CHAPTER 10
PowerScript Functions
SelectedLine
Description Applies to Syntax
Obtains the number of the line that contains the insertion point in an editable control. DataWindow, MultiLineEdit, and RichTextEdit controls
editname.SelectedLine ( ) Argument editname Description The name of the DataWindow, MultiLineEdit, or RichTextEdit in which you want the number of the line containing the insertion point. For a DataWindow, it reports the line number in the edit control over the current row and column.
Return value
Long. Returns the number of the line containing the insertion point in editname. If an error occurs, SelectedLine returns -1. If editname is NULL, SelectedLine returns NULL.
Usage
For EditMask controls, SelectedLine compiles but always returns 1. The insertion point can be at the beginning or end of the selection. Therefore, SelectedLine can return the first or last selected line, depending on the position of the insertion point.
Examples
If the insertion point is positioned anywhere in line 5 of the MultiLineEdit mle_Contact, the following example sets li_SL to 5:
integer li_SL li_SL = mle_Contact.SelectedLine()
In this example, the line the user selects in the MultiLineEdit mle_winselect determines which window to open:
integer li_SL li_SL = mle_winselect.SelectedLine() IF li_SL = 1 THEN Open(w_emp_data) ELSEIF li_SL = 2 THEN Open(w_dept_data) END IF See also
965
SelectedPage
SelectedPage
Description Applies to Syntax
Obtains the number of the current page in a RichTextEdit control. RichTextEdit controls
rtename.SelectedPage ( ) Argument rtename Description The name of the RichTextEdit control in which you want the number of the current page
Integer. Returns the number of the current page in rtename. If an error occurs, SelectedPage returns -1.
The current page in a RichTextEdit control is the page that contains the insertion point in text entry mode or the page currently being displayed in preview mode. When the RichTextEdit shares data with a DataWindow, SelectedPage returns the page number within the document instance for the current row. For more information about document instances, see DataSource.
Examples
See also
966
PowerBuilder
CHAPTER 10
PowerScript Functions
SelectedStart
Description Applies to Syntax
Reports the position of the first selected character in an editable control. DataWindow, EditMask, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox, and DropDownPictureListBox controls
editname.SelectedStart ( ) Argument editname Description The name of the DataWindow, EditMask, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox, or DropDownPictureListBox control in which you want to determine the starting position of selected text. For a DataWindow, it reports the starting position in the edit control over the current row and column.
Return value
Long. Returns the starting position of the selected text in editname. If no text is selected, SelectedStart returns the position of the character immediately following the insertion point. If an error occurs, SelectedStart returns -1. If editname is NULL, SelectedStart returns NULL.
Usage
For all controls except RichTextEdit, SelectedStart counts from the start of the text and includes spaces and line endings. For RichTextEdit controls, SelectedStart counts from the start of the line on which the selection begins. The start is at the opposite end of the selection from the insertion point. For example, if the user dragged back to make the selection, the start of the selection is at the end of the highlighted text and the insertion point is before the start. Use the Position function to get information about the start and end of the selection.
Focus and the selection in a drop-down list
When a DropDownListBox or DropDownPictureListBox loses focus, the selected text is no longer selected.
Examples
If the MultiLineEdit mle_Comment contains Closed for Vacation July 3 to July 10, and Vacation is selected, then this example sets li_Start to 12 (the position of the first character in Vacation):
integer li_Start li_Start = mle_Comment.SelectedStart()
See also
967
SelectedText
SelectedText
Description Applies to Syntax
Obtains the selected text in an editable control. DataWindow, EditMask, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox, and DropDownPictureListBox controls
editname.SelectedText ( ) Argument editname Description The name of the DataWindow, EditMask, MultiLineEdit, SingleLineEdit, RichTextEdit, DropDownListBox, or DropDownPictureListBox control from which you want the selected text. For a DropDownListBox or DropDownPictureListBox, the AllowEdit property must be TRUE. For a DataWindow, it reports the selected text in the edit control over the current row and column.
Return value
String. Returns the selected text in editname. If there is no selected text or if an error occurs, SelectedText returns the empty string (""). If editname is NULL, SelectedText returns NULL.
Usage
In a RichTextEdit control, any pictures in the selection are ignored. If the selection contains input fields, the names of the input fields, enclosed in brackets, become part of the string SelectedText returns. The contents of the input fields are not returned. For example, when the salutation of a letter is selected, SelectedText might return:
Dear {title} {lastname}: Focus and the selection in a drop-down list
When a DropDownListBox or DropDownPictureListBox loses focus, the selected text is no longer selected.
Examples
If the text in the MultiLineEdit mle_Contact is James B. Smith and James B. is selected, these statements set the value of emp_fname to James B:
string ls_emp_fname ls_emp_fname = mle_Contact.SelectedText()
968
PowerBuilder
CHAPTER 10
PowerScript Functions
If the selected text in the edit portion of the DropDownListBox ddlb_Location is Maine, these statements display the ListBox lb_LBMaine:
string ls_Loc ls_Loc = ddlb_Location.SelectedText() IF ls_Loc = "Maine" THEN lb_LBMaine.Show() ELSE ... END IF See also
SelectText
969
SelectionRange
SelectionRange
Description
Highlights a range of contiguous values in a trackbar control. The range you select is highlighted in the trackbar channel, with an arrow at each end of the range. Trackbar controls
control.SelectionRange ( startpos, endpos ) Argument control startpos endpos Description The name of the trackbar control An integer that specifies the starting position of the range An integer that specifies the ending position of the range
Applies to Syntax
Use this function to indicate a range of preferred values. In a scheduling application, the selection range could indicate a block of time that is unavailable. Setting a selection range does not prevent the user from selecting a value either inside or outside the range.
Examples
See also
HTrackBar in PowerBuilder Objects and Controls VTrackBar in PowerBuilder Objects and Controls
970
PowerBuilder
CHAPTER 10
PowerScript Functions
SelectItem
Finds and highlights an item in a ListBox, DropDownListBox, or TreeView control.
To select an item In a ListBox control when you know the text of the item, but not its position In a ListBox control when you know the position of the item in the controls list, or to clear the current selection In a TreeView control Use Syntax 1 Syntax 2 Syntax 3
Syntax 1
Description Applies to Syntax
Return value
Integer. Returns the index number of the selected item. If no match is found, SelectItem returns 0; it returns -1 if an error occurs. If any arguments value is NULL, SelectItem returns NULL. SelectItem begins searching for the desired item after the item identified by
Usage
index. To match, the item must start with the specified text; however, the text in the item can be longer than the specified text. To find an item but not select it, use the FindItem function.
MultiSelect ListBoxes SelectItem has no effect on a ListBox or PictureListBox whose MultiSelect property is TRUE. Instead, use SetState to select items without affecting the
971
SelectItem
To clear the edit box of a DropDownListBox or DropDownPictureListBox that the user cannot edit, use Syntax 2 of SelectItem.
Examples
If item 5 in lb_Actions is Delete Files, this example starts searching after item 2, finds and highlights Delete Files, and sets li_Index to 5:
integer li_Index li_Index = lb_Actions.SelectItem("Delete Files", 2)
If item 4 in lb_Actions is Select Objects, this example starts searching after item 2, finds and highlights Select Objects, and sets li_Index to 4:
integer li_Index li_Index = lb_Actions.SelectItem("Sel", 2) See also
Syntax 2
Description
Applies to Syntax
972
PowerBuilder
CHAPTER 10
PowerScript Functions
Return value
Integer. Returns the index number of the selected item. SelectItem returns 0 if
itemnumber is not valid or if you specified 0 in order to clear the selected item. It returns -1 if an error occurs. If any arguments value is NULL, SelectItem returns NULL.
Usage
To find an item but not select it, use the FindItem function.
MultiSelect ListBoxes SelectItem has no effect on a ListBox or PictureListBox whose MultiSelect property is TRUE. Instead, use SetState to select items without affecting the
To clear the text box of a DropDownListBox or DropDownPictureListBox that the user cannot edit, set itemnumber to 0. Setting the controls text to the empty string does not work if the controls AllowEdit property is FALSE.
Examples
This example clears the selection from the text box of the DropDownListBox ddlb_choices and sets li_Index to 0:
integer li_Index li_Index = ddlb_choices.SelectItem(0) See also
973
SelectItem
Syntax 3
Description Applies to Syntax
Use the FindItem function to get handles for items at specific positions in the TreeView control. This example selects the parent of the current TreeView item:
long ll_tvi, ll_tvparent int li_tvret ll_tvi = tv_list.FindItem(CurrentTreeItem! , 0) ll_tvparent = tv_list.FindItem(ParentTreeItem! , & ll_tvi) li_tvret = tv_list.SelectItem(ll_tvparent)
See also
FindItem
974
PowerBuilder
CHAPTER 10
PowerScript Functions
SelectObject
Description
Selects or clears the object in an OLE control but does not activate the server application. The servers menus are added to the PowerBuilder applications menus. OLE controls
olecontrol.SelectObject ( selectstate ) Argument olecontrol selectstate Description The name of the OLE control containing the object you want to select A boolean value indicating whether you want to select or deselect the object
Applies to Syntax
Return value
Integer. Returns 0 if it succeeds and one of the following negative values if an error occurs:
-1 -9
975
SelectTab
SelectTab
Description Applies to Syntax
Selects the specified tab, displaying its tab page in the Tab control. Tab controls
tabcontrolname.SelectTab ( tabidentifier ) Argument tabcontrolname tabidentifier Description The name of the Tab control in which you want to select a tab The tab you want to select. You can specify: The tab page index (an integer) The name of the user object (datatype DragObject or UserObject) A string holding the name of the user object
Equivalent syntax You can select a tab by setting the SelectedTab property to the tabs index number: tab_1.SelectedTab = 3
Examples
These three examples select the third tab in tab_1. They could be in the script for a CommandButton on the window containing the Tab control tab_1:
tab_1.SelectTab(3) tab_1.SelectTab(tab_1.uo_3) string ls_tabpage ls_tabpage = "uo_3" tab_1.SelectTab(ls_tabpage)
This example opens an instance of the user object uo_fontsettings as a tab page and selects it:
userobject uo_tabpage string ls_tabpage ls_tabpage = "uo_fontsettings" tab_1.OpenTab(uo_tabpage, ls_tabpage, 0) tab_1.SelectTab(uo_tabpage) See also
OpenTab
976
PowerBuilder
CHAPTER 10
PowerScript Functions
SelectText
Selects text in an editable control.
To select text in Any editable control, other than a RichTextEdit A RichTextEdit control or a DataWindow whose object has the RichTextEdit presentation style Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
start length
Long. Returns the number of characters selected. If an error occurs, SelectText returns -1. If any arguments value is NULL, SelectText returns NULL.
If the control does not have the focus when you call SelectText, then the text is not highlighted until the control has focus. To set focus on the control so that the selected text is highlighted, call the SetFocus function.
How much to select
When you want to select all the text of a line edit or select the contents from a specified position to the end of the edit, use the Len function to obtain the length of the controls text. To select text in a DataWindow with the RichTextEdit presentation style, use Syntax 2.
977
SelectText
Examples
This statement sets the insertion point at the end of the text in the SingleLineEdit sle_name:
sle_name.SelectText(Len(sle_name.Text), 0)
The rest of these examples assume the MultiLineEdit mle_EmpAddress contains Boston Street. The following statement selects the string ost and returns 3:
mle_EmpAddress.SelectText(2, 3)
The next statement selects the string oston Street and returns 12:
mle_EmpAddress.SelectText(2, & Len(mle_EmpAddress.Text))
These statements select the string Bos, returns 3, and sets the focus to mle_EmpAddress so that Bos is highlighted:
mle_EmpAddress.SelectText(1, 3) mle_EmpAddress.SetFocus() See also
Syntax 2
Description Applies to Syntax
fromline
978
PowerBuilder
CHAPTER 10
PowerScript Functions
Description A long specifying the number in the line of the first character in the selection. A long specifying the line number where the selection ends. To specify an insertion point, set toline and tochar to 0. A long specifying the number in the line of the character before which the selection ends. A value of the Band enumerated datatype specifying the band in which to make the selection. Values are: Detail! Header! Footer! The default is the band that contains the insertion point.
Long. Returns the number of characters selected. If an error occurs it returns -1. If any arguments value is NULL, SelectText returns NULL.
The insertion point is at the "to" end of the selection, that is, the position specified by toline and tochar. If toline and tochar are before fromline and fromchar, then the insertion point is at the beginning of the selection. You cannot specify 0 for a character position when making a selection. You cannot always use the values returned by Position to make a selection. Position can return a character position of 0 when the insertion point is at the beginning of a line. To select an entire line, set the insertion point and call SelectTextLine. To select the rest of a line, set the insertion point and call SelectText with a character position greater than the line length.
Examples
This statement selects text from the first character in the RichTextEdit control to the fourth character on the third line:
rte_1.SelectText(1,1, 3,4)
This example sets the insertion point at the end of line 2 by specifying a large number of characters. The selection highlight extends past the end of the line:
rte_1.SelectText(2,999, 0,0)
979
SelectText
This example sets the insertion point at the end of line 2 by finding out how long the line really is. The code moves the insertion point to the beginning of the line, gets the length, and then sets the insertion point at the end:
long ll_length //Make line 2 the current line rte_1.SelectText(2,1, 0,0) // Specify a position after the last character ll_length = rte_1.LineLength() + 1 // Set the insertion point at the end rte_1.SelectText(2,ll_length, 0,0) rte_1.SetFocus()
This example selects the text from the insertion point to the end of the current line. If the current line is the last line, the reported line length is 1 greater than the number of character you can select, so the code adjusts for it:
long ll_insertline, ll_insertchar long ll_line, ll_count // Get the insertion point rte_1.Position(ll_insertline, ll_insertchar) // Get the line number and line length ll_line = rte_1.SelectedLine() ll_count = rte_1.LineLength() // Line length includes the eof file character, // which cant be selected IF ll_line = rte_1.LineCount() THEN ll_count -= 1 // Select from the insertion point to the end of // line rte_1.SelectText(ll_insertline, ll_insertchar, & ll_line, ll_count) See also
980
PowerBuilder
CHAPTER 10
PowerScript Functions
SelectTextAll
Description Applies to Syntax
Selects all the contents of a RichTextEdit control including any special characters such as a carriage return (CR), line feel (LF), and end-of-file (EOF). RichTextEdit and DataWindow controls
rtename.SelectTextAll ( { band } ) Argument rtename Description The name of the RichTextEdit or DataWindow control in which you want to select all the contents. The DataWindow object in the DataWindow control must be a RichTextEdit DataWindow. A value of the Band enumerated datatype specifying the band in which you want to select all the text. Values are: Detail! Header! Footer! The default is the band that contains the insertion point.
band (optional)
Integer. Returns the number of characters selected. If an error occurs, SelectTextAll returns -1.
981
SelectTextLine
SelectTextLine
Description Applies to Syntax
Selects the line containing the insertion point in a RichTextEdit control. RichTextEdit and DataWindow controls
rtename.SelectTextLine ( ) Argument rtename Description The name of the RichTextEdit or DataWindow control in which you want select a line. The DataWindow object in the DataWindow control must be a RichTextEdit DataWindow.
error occurs. If the RichTextEdit control contains a selection, the insertion point is either at the beginning or end of the selection. The way the text was selected determines which. If the user made the selection by dragging toward the end, then calling SelectTextLine selects the line at the end of the selection. If the user dragged back, then SelectTextLine selects the line at the beginning of the selection.
SelectTextLine does not select the line-ending characters (carriage return and linefeed in Windows).
Examples
See also
982
PowerBuilder
CHAPTER 10
PowerScript Functions
SelectTextWord
Description Applies to Syntax
Selects the word containing the insertion point in a RichTextEdit control. RichTextEdit and DataWindow controls
rtename.SelectTextWord ( ) Argument rtename Description The name of the RichTextEdit or DataWindow control in which you want to select a word. The DataWindow object in the DataWindow control must be a RichTextEdit DataWindow.
Integer. Returns the number of characters selected if it succeeds and -1 if a word cannot be selected or an error occurs.
A word is any group of alphanumeric characters. A word can include underscores and single quotes but does not include punctuation and special characters such as $ or #. If punctuation or special characters follow the selected word, they are not selected. If the character after the insertion point is a space, punctuation, special character, or end-of-line mark, SelectTextWord does not select anything and returns -1.
Examples
The following statement selects the word containing the insertion point:
rte_1.SelectTextWord()
This example selects the word at the insertion point. If there is no word, it increments the position until it finds a word. It checks when it reaches the end of a line and wraps to the next line as it looks for a word. If this script is assigned to a command button and the button is clicked repeatedly, you step through the text word by word:
integer li_rtn long llstart, lcstart, ll_lines, ll_chars ll_lines = rte_1.LineCount() ll_chars = rte_1.LineLength() li_rtn = rte_1.SelectTextWord() // -1 if a word is not found at the insertion point DO WHILE li_rtn = -1 // Get the position of the cursor rte_1.Position(llstart, lcstart)
983
SelectTextWord
// Increment by 1 to look for next word lcstart += 1 // If at end of line move to next line IF lcstart >= ll_chars THEN lcstart = 1 // First character llstart += 1 // next line // If beyond last line, return IF llstart > ll_lines THEN RETURN 0 END IF END IF // Set insertion point rte_1.SelectText(llstart, lcstart, 0, 0) // In case its a new line, get new line length // Cant do this until the ins pt is in the line ll_chars = rte_1.LineLength( ) // Select word, if any li_rtn = rte_1.SelectTextWord() LOOP // Add code here to process the word (for example, // passing the word to a spelling checker) See also
984
PowerBuilder
CHAPTER 10
PowerScript Functions
Send
Description Syntax
Long. Returns the value returned by SendMessage in Windows if it succeeds and -1 if an error occurs. If any arguments value is NULL, Send returns NULL.
PowerBuilders Send function sends the message identified by message# and optionally, lowword and long, to the window identified by handle to the Windows function SendMessage. The message is sent directly to the object, bypassing the objects message queue. Send waits until the message is processed and obtains the value returned by SendMessage.
Messages in Windows Use the Handle function to get the Windows handle of a PowerBuilder object.
You specify Windows messages by number. They are documented in the file WINDOWS.H that is part of the Microsoft Windows Software Development Kit (SDK) and other Windows development tools.
Posting a message Messages sent with Send are executed immediately. To post a message to the end of an objects message queue, use the Post function. Examples
985
Send
You can send messages to maximize or minimize a DataWindow, and return it to normal. To use these messages, enable the TitleBar, Minimize, and Maximize properties of your DataWindow control. Also, you should give your DataWindow control an icon for its minimized state. This statement minimizes the DataWindow:
Send(Handle(dw_whatever), 274, 61472, 0)
You can send a Windows message to determine the last item clicked in a multiselect ListBox. The following script for the SelectionChanged event of a ListBox control gets the return value of the LB_GETCURSEL message which is the item number in the list (where the first item is 0, not 1). To get PowerBuilders index for the list item, the example adds 1 to the return value from Send. In this example, idx is an integer instance variable for the window:
// Send the Windows message for LB_GETCURSEL // to the list box idx = Send(Handle(This), 1033, 0, 0) idx = idx + 1 See also
Handle Post
986
PowerBuilder
CHAPTER 10
PowerScript Functions
SeriesCount
Description Applies to Syntax
Counts the number of series in a graph. Graph controls in windows and user objects, and graphs in DataWindow controls
controlname.SeriesCount ( { graphcontrol } ) Argument controlname Description The name of the graph for which you want the number of series, or the name of the DataWindow control containing the graph A string whose value is the name of the graph in the DataWindow control for which you want the number of series
Integer. Returns the number of series in the graph if it succeeds and -1 if an error occurs. If any arguments value is NULL, SeriesCount returns NULL.
These statements store in the variable li_series_count the number of series in the graph gr_product_data:
integer li_series_count li_series_count = gr_product_data.SeriesCount()
These statements store in the variable li_series_count the number of series in the graph gr_computers in the DataWindow control dw_equipment:
integer li_series_count li_series_count = & dw_equipment.SeriesCount("gr_computers") See also
CategoryCount DataCount
987
SeriesName
SeriesName
Description Applies to Syntax
Obtains the series name associated with the specified series number. Graph controls in windows and user objects, and graphs in DataWindow controls
controlname.SeriesName ( { graphcontrol, } seriesnumber ) Argument controlname graphcontrol (DataWindow control only) (optional) seriesnumber Description The name of the graph in which you want the name of a series, or the name of the DataWindow containing the graph A string whose value is the name of the graph in the DataWindow control for which you want the name of a series
The number of the series for which you want to obtain the name
String. Returns the name assigned to the series. If an error occurs, it returns the empty string (""). If any arguments value is NULL, SeriesName returns NULL.
Series are numbered consecutively, from 1 to the value returned by SeriesCount. When you delete a series, the series are renumbered to keep the numbering consecutive. You can use SeriesName to find out the name of the series associated with a series number. These statements store in the variable ls_SeriesName the name of series 5 in the graph gr_product_data:
string ls_SeriesName ls_SeriesName = gr_product_data.SeriesName(5)
Examples
These statements store in the variable ls_SeriesName the name of series 5 in the graph gr_computers in the DataWindow control dw_equipment:
string ls_SeriesName ls_SeriesName = & dw_equipment.SeriesName("gr_computers", 5) See also
988
PowerBuilder
CHAPTER 10
PowerScript Functions
SetAbort
Declares that a transaction on a transaction server should be rolled back.
To roll back a transaction For OLETxnObject objects For TransactionServer objects Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
Call the SetAbort function from the client to force an MTS transaction to be rolled back. The default is to complete the transaction if all participants in the transaction on the MTS server have called SetComplete or EnableCommit. The following example shows the use of SetAbort in a component method that performs database updates:
integer li_rc OleTxnObject lotxn_obj lotxn_obj = CREATE OleTxnObject li_rc = lotxn_obj.ConnectToNewObject("pb70com.n_test") IF li_rc <> 0 THEN Messagebox( "Connect Error", string(li_rc) ) // handle error END IF lotxn_obj.f_dowork() lotxn_obj.f_domorework() IF /* test for client satisfaction */ THEN lotxn_obj.SetComplete()
Examples
989
SetAbort
SetComplete
Syntax 2
Description
Applies to Syntax
The SetAbort function corresponds to the rollbackWork transaction primitive in EAServer. Any component that participates in a transaction can roll back the transaction by calling the rollbackWork primitive. Only the action of the root component (the component instance that began the transaction) determines when EAServer commits the transaction.
Examples
The following example shows the use of SetAbort in a component method that performs database updates:
// Instance variables: // DataStore ids_datastore // TransactionServer ts Integer li_rc long ll_rv li_rc = this.GetContextService("TransactionServer", & ts) IF li_rc <> 1 THEN // handle the error END IF ... ...
990
PowerBuilder
CHAPTER 10
PowerScript Functions
ll_rv = ids_datastore.Update() IF ll_rv = 1 THEN ts.SetComplete() ELSE ts.SetAbort() END IF See also
991
SetAlignment
SetAlignment
Description Applies to Syntax
Sets the alignment of the selected paragraphs in a RichTextEdit control. RichTextEdit controls
rtename.SetAlignment ( align ) Argument rtename align Description The name of the RichTextEdit control in which you want to set the alignment of selected paragraphs. A value of the Alignment enumerated datatype specifying how to align the paragraphs. Values are: Left! Align each line at the left margin Right! Align each line at the right margin Center! Center the text between the left and right margins Justify! Justify the paragraphs
This example sets the alignment of the selected paragraphs in the RichTextEdit control rte_1:
integer li_success li_success = rte_1.SetAlignment(Right!)
See also
992
PowerBuilder
CHAPTER 10
PowerScript Functions
SetArgElement
Description Applies to Syntax
Sets the value in the specified argument element. Window ActiveX controls
activexcontrol.SetArgElement ( index, argument ) Argument activexcontrol Description Identifier for the instance of the PowerBuilder window ActiveX control. When used in HTML, this is the NAME attribute of the object element. When used in other environments, this references the control that contains the PowerBuilder window ActiveX. Integer specifying argument placement. Any specifying the argument value.
Call this function before calling InvokePBFunction or TriggerPBEvent to specify an argument for the passed function. JavaScript scripts must use this function to specify function and event arguments. VBScript scripts can either use this function or specify the arguments array directly.
Examples
See also
993
SetAutomationLocale
SetAutomationLocale
Description
Sets the language to be used in automation programming for an OLE object. Call SetAutomationLocale if you have programmed automation commands in a language other than the users locale. OLE objects
olename.SetAutomationLocale ( language, sortorder ) Argument olename language Description The name of the object for which you want to set the automation locale. A value of the LanguageID enumerated datatype specifying the language you have used for automation commands. The OLE server must have function and property names defined in the language you specify. Some values of LanguageID are: LanguageNeutral! No language is assumed. Automation commands match the servers default command set. LanguageUserDefault! The language locale is taken from the users settings in the International control panel. LanguageSystemDefault! The language locale is taken from the version of Windows that is installed on the users machine. You can also specify a language or dialect, such as LanguagePolish! or LanguagePortuguese_Brazilian! For the list of language-specific values for LanguageID, use the PowerBuilder Browser. sortorder A value of the LanguageSortID enumerated datatype specifying the sort order for the language. Values are: LanguageSortNative! Use the traditional sort order of the selected language. LanguageSortUnicode! Use the sort order defined for Unicode
Applies to Syntax
For most situations, you do not need to call SetAutomationLocale. If an automation command fails, PowerBuilder makes additional attempts to execute it in other languages before it triggers the Error event. It attempts to execute the command using these languages: 1 2 The command as is (the command is in a language the server understands) The current locale (if it is different from the users default locale)
994
PowerBuilder
CHAPTER 10
PowerScript Functions
3 4 5
The users default locale (LanguageUserDefault!) The systems default locale (LanguageSystemDefault!) English (LanguageEnglish!)
If PowerBuilder is successful in validating the name in any of the languages above, it resets the locale to the value that succeeded. While this may result in the wrong locale in ambiguous cases, it will probably simplify access to standard Microsoft Office products that ship with both localized and English function and property names. If you specify a language with SetAutomationLocale, but the OLE server does not have function and property names in that language, your OLE automation commands will fail unless the above procedure finds a language that works. If you have called SetAutomationLocale, PowerBuilders procedure for finding the correct language can reset it, as described in the previous paragraph.
Examples
This example sets the language to German for an OLEObject called oleobj_report:
oleobj_report.SetAutomationLocale(LanguageGerman!)
This example sets the language to German for an OLE control ole_1:
ole_1.Object.SetAutomationLocale(LanguageGerman!)
995
SetAutomationPointer
SetAutomationPointer
Description Applies to Syntax
Sets the automation pointer of an OLEObject object to the value of the automation pointer of another object. OLEObject
oleobject.SetAutomationPointer ( object ) Argument oleobject Description The name of an OLEObject variable whose automation pointer you want to set. You cannot specify an OLEObject that is the Object property of an OLE control. The name of an OLEObject variable that contains the automation pointer you want to use to set the pointer value in oleobject.
object
Integer. Returns 0 if it succeeds and -1 if the object does not contain a valid
This example creates an OLEObject variable and calls ConnectToNewObject to create a new Excel object and connect to it. It also creates an object of type oleobjectchild (which is a descendant of OLEObject) and sets the automation pointer of the descendant object to the value of the automation pointer in the OLEObject object. Then it sets a value in the worksheet using the descendent object, saves it to a different file, and destroys both objects:
OLEObject ole1 oleobjectchild oleChild integer rs ole1= CREATE OLEObject rs = ole1.ConnectToNewObject("Excel.Application") oleChild = CREATE oleobjectchild rs = oleChild.SetAutomationPointer(ole1 ) IF ( rs = 0 ) THEN oleChild.workbooks.open("d:\temp\expenses.xls") oleChild.cells(1,1).value = 11111 oleChild.activeworkbook.saveas( & "d:\temp\newexp.xls") oleChild.activeworkbook.close() oleChild.quit() END IF ole1.disconnectobject() DESTROY oleChild DESTROY ole1
996
PowerBuilder
CHAPTER 10
PowerScript Functions
SetAutomationTimeout
Description Applies to Syntax
Sets the number of milliseconds that a PowerBuilder client waits before canceling an OLE procedure call to the server. OLEObject objects
oleobject.SetAutomationTimeout ( interval ) Argument oleobject interval Description The name of an OLEObject variable containing the object for which you want to set the timeout period. A 32-bit signed long integer value (in milliseconds) specifying how long a PowerBuilder client waits before canceling a procedure call. The default value is 300,000 milliseconds (5 minutes). Specifying 0 or a negative value resets interval to the default value.
This function passes the value of interval to PowerBuilders implementation of the IMessageFilter interface and determines how long PowerBuilder tries to complete an OLE procedure call. The value applies only when PowerBuilder is the OLE client, not when PowerBuilder is the OLE server.
Default timeout period
For most situations, you do not need to call SetAutomationTimeout. The default timeout period of five minutes is usually appropriate. Use SetAutomationTimeout to change the default timeout period if you expect a specific OLE request to take longer than five minutes. If the timeout period is too short, you may get a PowerBuilder application execution error, R0035. In this case, use SetAutomationTimeout to lengthen the timeout period. If the timeout period expires, runtime error 1037 occurs. You may want to add code to handle this error, which is often the only indication of a hung server. Note that canceling a transaction often causes memory leaks on both the server and the operating system. The value that you specify with SetAutomationTimeout applies to all OLE transactions in the current session, including calls that relate to other objects.
997
SetAutomationTimeout
998
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This example calls the ConnectToObject function to connect to an Excel worksheet and sets a timeout period of 900,000 milliseconds (15 minutes):
OLEObject ole1 integer rs long interval interval = 900000 ole1 = create OLEObject rs = ole1.ConnectToObject("Excel.Application") rs = ole1.SetAutomationTimeOut(interval)
999
SetColumn
SetColumn
Description
Sets column information for a DataWindow, child DataWindow, or ListView control. For syntax for a DataWindow or child DataWindow, see the SetColumn method for DataWindows in the DataWindow Reference or the online Help.
Applies to Syntax
ListView controls
listviewname.SetColumn ( index, label, alignment, width ) Argument listviewname index label alignment Description The name of the ListView control for which you want to set column properties. The number of the column for which you want to set column properties. The label of the column for which you want to set column properties. A value of the Alignment enumerated datatype specifying how to align the column. Values are: Left! Align the column at the left margin Right! Align the column at the right margin Center! Center the column between the left and right margins width Justify! Not valid for the SetColumn function The width of the column for which you want to set column properties.
Integer. Returns 1 if it succeeds and -1 if an error occurs. SetColumn is used only in report views.
See also
1000
PowerBuilder
CHAPTER 10
PowerScript Functions
SetComplete
Declares that a transaction on a transaction server should be committed.
To commit a transaction For OLETxnObject objects For TransactionServer objects Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
Call the SetComplete function from a client to allow an MTS transaction to be completed if all participants in the transaction on the MTS server have called SetComplete or EnableCommit. If any participant in the transaction has called DisableCommit or SetAbort, the transaction is not completed. The following example shows the use of SetComplete in a component method that performs database updates:
integer li_rc OleTxnObject lotxn_obj lotxn_obj = CREATE OleTxnObject li_rc = lotxn_obj.ConnectToNewObject("pb70com.n_test") IF li_rc <> 0 THEN Messagebox( "Connect Error", string(li_rc) ) // handle error END IF lotxn_obj.f_dowork() lotxn_obj.f_domorework() lotxn_obj.SetComplete() lotxn_obj.DisconnectObject()
Examples
See also
SetAbort
1001
SetComplete
Syntax 2
Description Applies to Syntax
The SetComplete function corresponds to the completeWork transaction primitive in EAServer. Any component that participates in a transaction can roll back the transaction by calling the rollbackWork primitive. Only the action of the root component (the component instance that began the transaction) determines when EAServer commits the transaction. The transaction is committed if either of the following occurs: The root component returns with a state of completeWork and no participating component has set a state of disallowCommit. The root component is deactivated due to an explicit destroy from the client and no participating component has set a state of disallowCommit. (A client disconnect that is not preceded by an explicit destroy request always causes a rollback.)
You can use the transaction state primitives in any component; the component does not have to be declared transactional. Calling completeWork or rollbackWork from methods causes early deactivation.
Examples
The following example shows the use of SetComplete in a component method that performs database updates:
// Instance variables: // DataStore ids_datastore // TransactionServer ts Integer li_rc long ll_rv li_rc = this.GetContextService("TransactionServer", & ts)
1002
PowerBuilder
CHAPTER 10
PowerScript Functions
IF li_rc <> 1 THEN // handle the error END IF ... ... ll_rv = ids_datastore.Update() IF ll_rv = 1 THEN ts.SetComplete() ELSE ts.SetAbort() END IF See also
1003
SetData
SetData
Description Applies to Syntax
Sets data in the OLE server associated with an OLE control using Uniform Data Transfer. OLE controls and OLE custom controls
olename.SetData ( clipboardformat, data ) Argument olename clipboardformat Description The name of the OLE or custom control associated with the OLE server to which you want to transfer data. The format of the data. You can specify a standard format with a value of the ClipboardFormat enumerated datatype. You can specify a nonstandard format as a string.Values for ClipboardFormat are: ClipFormatBitmap! ClipFormatDIB! ClipFormatDIF! ClipFormatEnhMetafile! ClipFormatHdrop! ClipFormatLocale! ClipFormatMetafilePict! ClipFormatOEMText! ClipFormatPalette! ClipFormatPenData! ClipFormatRIFF! ClipFormatSYLK! ClipFormatText! ClipFormatTIFF! ClipFormatUnicodeText! ClipFormatWave! If clipboardformat is an empty string or a NULL value, SetData transfers the data with the format ClipFormatText!. data A string or blob whose value is the data you want to transfer.
Integer. Returns 0 if it succeeds and -1 if an error occurs. SetData returns an error if you specify a clipboard format that the OLE server
does not support. See the documentation for the OLE server to find out what formats it supports.
1004
PowerBuilder
CHAPTER 10
PowerScript Functions
SetData operates via Uniform Data Transfer, a mechanism defined by Microsoft for exchanging data with container applications. PowerBuilder enables data transfer via a global handle. The OLE server must also support data transfer via a global handle. If it does not, you cannot transfer data to or from that server.
For an example of moving data between two OLE controls (a Microsoft Word table and a Microsoft Graph), see GetData. GetData
1005
SetDataDDE
SetDataDDE
Description
Sends data to a DDE client application when PowerBuilder is acting as a DDE server. You would usually call SetDataDDE in the script for the RemoteRequest event, which is triggered by a DDE request for data from the client application.
SetDataDDE ( string {, applname, topic, item } ) Argument string applname (optional) topic (optional) item (optional) Description The data you want to send to a DDE client application The DDE name for the client application A string whose value is the basic data grouping the DDE client application referenced A string (data within topic)
Syntax
Return value
negative integer. Values are: -1 -2 Function called in the wrong context Data not accepted
To enable DDE server mode in your PowerBuilder application, call the StartServerDDE function. Then DDE messages from a DDE client trigger events in the PowerBuilder window. It is up to you to decide how your application responds by writing code for those events. When an application requests data of the DDE server, it triggers a RemoteRequest event. You typically call SetDataDDE in the script for a windows RemoteRequest event. If a client application has established a hot link with a location in your PowerBuilder application, you can call SetDataDDE in an event for the object associated with the location. As a server application, you decide how location names map to the controls in your application. For example, your application can decide that the DDE name loc1 refers to the SingleLineEdit sle_name and a client application can establish a hot link with "loc1." Then in the Modified event for sle_name, you can call SetDataDDE so that the client application receives changes each time sle_name is changed. Likewise, if loc1 referred to a DataWindow, you can call SetDataDDE in the ItemChanged event for the DataWindow.
1006
PowerBuilder
CHAPTER 10
PowerScript Functions
The applname argument refers to the client application that has established a channel or a hot link with your application. Topic and item refer to a topic and location recognized by your server application. You only need to specify these arguments to make it clear to the client application who should receive the message and what is being sent.
Examples
This statement illustrates how SetDataDDE is used in a script for a RemoteRequest event when another DDE application requests data. The data sent is the text of the SingleLineEdit sle_Address:
SetDataDDE(sle_Address.Text)
GetDataDDE StartServerDDE
1007
SetDataPieExplode
SetDataPieExplode
Description
Explodes a pie slice in a pie graph. The exploded slice is moved away from the center of the pie, which draws attention to the data. You can explode any number of slices of the pie. Graph controls in windows and user objects, and graphs in DataWindow controls
controlname.SetDataPieExplode ( { graphcontrol, } seriesnumber, datapoint, percentage ) Argument controlname graphcontrol (DataWindow control only) (optional) seriesnumber datapoint percentage Description The name of the graph in which you want to explode a pie slice, or the name of the DataWindow containing the graph. A string whose value is the name of the graph in the DataWindow control in which you want to explode a pie slice.
Applies to Syntax
The number that identifies the series. The number of the data point (that is, the pie slice) to be exploded. A number between 0 and 100 which is the percentage of the radius that the pie slice is moved away from the center. When percentage is 100, the tip of the slice is even with the circumference of the pies circle.
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetDataPieExplode returns NULL.
If the graph is not a pie graph, the function has no effect. This example explodes the pie slice under the pointer to 50% when the user double-clicks within the graph. The code checks the property GraphType to make sure the graph is a pie graph. It then finds out whether the user clicked on a pie slice by checking the series and data point values set by ObjectAtPointer. The script is for the DoubleClicked event of a graph object:
integer series, datapoint grObjectType clickedtype integer percentage percentage = 50 IF (This.GraphType <> PieGraph! AND & This.GraphType <> Pie3D!) THEN RETURN clickedtype = This.ObjectAtPointer( & series, datapoint)
1008
PowerBuilder
CHAPTER 10
PowerScript Functions
IF (series > 0 and datapoint > 0) THEN This.SetDataPieExplode(series, datapoint, & percentage) END IF See also
GetDataPieExplode
1009
SetDataStyle
SetDataStyle
Specifies the appearance of a data point in a graph. The data points series has appearance settings that you can override with SetDataStyle.
To Set the data points colors Set the line style and width for the data point Set the fill pattern or symbol for the data point Use Syntax 1 Syntax 2 Syntax 3
Syntax 1
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetDataStyle returns NULL.
1010
PowerBuilder
CHAPTER 10
PowerScript Functions
Usage
To change the appearance of a series, use SetSeriesStyle. The settings you make for the series are the defaults for all data points in the series. To reset the color of individual points back to the series color, call ResetDataColors. For a graph in a DataWindow, you can specify the appearance of a data point in the graph before PowerBuilder draws the graph. To do so, define a user event for pbm_dwngraphcreate and call SetDataStyle in the script for that event. The event pbm_dwngraphcreate is triggered just before a graph is created in a DataWindow object.
Examples
This example checks the background color for data point 6 in the series named Salary in the graph gr_emp_data. If it is red, SetDataStyle sets it to black:
long color_nbr integer SeriesNbr // Get the number of the series SeriesNbr = gr_emp_data.FindSeries("Salary") // Get the background color gr_emp_data.GetDataStyle(SeriesNbr, 6, & Background!, color_nbr) // If color is red, change it to black IF color_nbr = 255 THEN & gr_emp_data.SetDataStyle(SeriesNbr, 6, & Background!, 0)
These statements set the text (foreground) color to black for data point 6 in the series named Salary in the graph gr_depts in the DataWindow control dw_employees:
integer SeriesNbr // Get the number of the series SeriesNbr = & dw_employees.FindSeries("gr_depts" , "Salary") // Set the background color dw_employees.SetDataStyle("gr_depts" , SeriesNbr, & 6, Background!, 0) See also
1011
SetDataStyle
Syntax 2
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetDataStyle returns NULL.
To change the appearance of a series, use SetSeriesStyle. The settings you make for the series are the defaults for all data points in the series. For a graph in a DataWindow, you can specify the appearance of a data point in the graph before PowerBuilder draws the graph. To do so, define a user event for pbm_dwngraphcreate and call SetDataStyle in the script for that event. The event pbm_dwngraphcreate is triggered just before a graph is created in a DataWindow object.
1012
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This example checks the line style used for data point 10 in the series named Costs in the graph gr_computers in the DataWindow control dw_equipment. If it is dash-dot, the SetDataStyle sets it to continuous. The line width stays the same:
integer SeriesNbr, line_width LineStyle line_style // Get the number of the series SeriesNbr = dw_equipment.FindSeries( & "gr_computers", "Costs") // Get the current line style dw_equipment.GetDataStyle("gr_computers", & SeriesNbr, 10, line_style, line_width) // If the pattern is dash-dot, change to continuous IF line_style = DashDot! THEN & dw_equipment.SetDataStyle("gr_computers", & SeriesNbr, 10, Continuous!, line_width)
See also
Syntax 3
Description Applies to Syntax
1013
SetDataStyle
Description The number of the series in which you want to set the appearance of a data point. The number of the data point for which you want to set the appearance. An enumerated datatype specifying the appearance setting for the data point. You can specify a FillPattern or grSymbolType value. To change the fill pattern, use a FillPattern value: Bdiagonal! Lines from lower left to upper right Diamond! Fdiagonal! Lines from upper left to lower right Horizontal! Solid! Square! Vertical! To change the symbol type, use a grSymbolType value: NoSymbol! SymbolHollowBox! SymbolX! SymbolStar! SymbolHollowUpArrow! SymbolHollowCircle! SymbolHollowDiamond! SymbolSolidDownArrow! SymbolSolidUpArrow! SymbolSolidCircle! SymbolSolidDiamond! SymbolPlus! SymbolHollowDownArrow! SymbolSolidBox!
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetDataStyle returns NULL.
To change the appearance of a series, use SetSeriesStyle. The settings you make for the series are the defaults for all data points in the series. For a graph in a DataWindow, you can specify the appearance of a data point in the graph before PowerBuilder draws the graph. To do so, define a user event for pbm_dwngraphcreate and call SetDataStyle in the script for that event. The event pbm_dwngraphcreate is triggered just before a graph is created in a DataWindow object.
1014
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This example checks the fill pattern used for data point 10 in the series named Costs in the graph gr_product_data. If it is diamond, then SetDataStyle changes it to solid:
integer SeriesNbr FillPattern data_pattern // Get the number of the series SeriesNbr = gr_product_data.FindSeries("Costs") // Get the current fill pattern gr_product_data.GetDataStyle(SeriesNbr, 10, & data_pattern) // If the pattern is diamond, change it to solid IF data_pattern = Diamond! THEN & gr_product_data.SetDataStyle(SeriesNbr, & 10, Solid!)
See also
1015
SetDropHighlight
SetDropHighlight
Description Applies to Syntax
Use in a drag operation to specify a drop target. This example uses the TreeView Clicked event to set the current TreeView item as the drop target:
handle = tv_list.FindItem(CurrentTreeItem!,0) tv_list.SetDropHighlight(handle)
See also
FindItem SetItem
1016
PowerBuilder
CHAPTER 10
PowerScript Functions
SetDynamicParm
Description
Specifies a value for an input parameter in the DynamicDescriptionArea that is used in an SQL OPEN or EXECUTE statement.
Only for Format 4 dynamic SQL
Use this function only in conjunction with Format 4 dynamic SQL statements.
Syntax DynamicDescriptionArea.SetDynamicParm ( index, value ) Argument DynamicDescriptionArea index Description The name of the DynamicDescriptionArea, usually SQLDA. An integer identifying the input parameter descriptor in which you want to set the data. Index must be less than or equal to the value in NumInputs in DynamicDescriptionArea. The value you want to use to fill the input parameter descriptor identified by index.
value
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetDynamicParm returns NULL. SetDynamicParm specifies a value for the parameter identified by index in the
array of input parameter descriptors in DynamicDescriptionArea. Use SetDynamicParm to fill the parameters in the input parameter descriptor array in the DynamicDescriptionArea before executing an OPEN or EXECUTE statement.
Examples
This statement fills the first input parameter descriptor in SQLDA with the string MA:
SQLDA.SetDynamicParm(1, "MA")
This statement fills the fourth input parameter descriptor in SQLDA with the number 01742:
SQLDA.SetDynamicParm(4, "01742")
This statement fills the third input parameter descriptor in SQLDA with the date 12-31-1992:
SQLDA.SetDynamicParm(3, "12-31-1992")
1017
SetDynamicParm
See also
GetDynamicDate GetDynamicDateTime GetDynamicNumber GetDynamicString GetDynamicTime Using dynamic SQL OPEN Cursor
1018
PowerBuilder
CHAPTER 10
PowerScript Functions
SetFirstVisible
Description Applies to Syntax
Sets the specified item as the first visible item in a TreeView control. TreeView controls
treeviewname.SetFirstVisible ( itemhandle ) Argument treeviewname itemhandle Description The TreeView control in which you want to identify an item as the first visible item The handle of the item you are identifying as the first visible item in the TreeView control
Use to give focus to the TreeView item specified by the itemhandle and scroll it to the top of the TreeView control (or as close to the top as the item list allows; if the item is the last item in a TreeView control, for example, it cannot scroll to the top of the control). This example sets the current TreeView item as the first item visible in a TreeView control:
long ll_tvi int li_tvret ll_tvi = tv_list.FindItem(CurrentTreeItem! , 0) li_tvret = tv_list.SetFirstVisible(ll_tvi) IF li_tvret = -1 THEN MessageBox("Warning!" , "Didnt Work") END IF
Examples
See also
FindItem SetItem
1019
SetFocus
SetFocus
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If objectname is NULL, SetFocus returns NULL.
If objectname is a ListBox, SetFocus displays the focus rectangle around the first item. If objectname is a DropDownListBox, SetFocus highlights the edit box. To select an item in a ListBox or DropDownListBox, use SelectItem. Drawing objects cannot have focus. Therefore, you cannot use SetFocus to set focus to in a Line, Oval, Rectangle, or RoundRectangle.
Examples
This statement in the script for the Open event in a window moves the focus to the first item in lb_Actions:
lb_Actions.SetFocus()
See also
1020
PowerBuilder
CHAPTER 10
PowerScript Functions
SetGlobalProperty
Description Applies to Syntax
0 -1 -2 -3 -10 -11
Usage
Success Unknown property Property is read only Invalid value for property An EAServer or SSL failure has occurred Bad argument list
The SetGlobalProperty function allows PowerBuilder clients that connect to EAServer through SSL to set global SSL properties. Any properties set using the SSLServiceProvider interface are global to all connections made by the client to all EAServer servers. You can override any of the global settings at the connection level by specifying them as options to the Connection object or JaguarORB object. Only clients can get and set SSL properties. Server components do not have permission to use the SSLServiceProvider service.
Examples
The following example shows the use of the SetGlobalProperty function to set the value of the cacheSize property to 300:
SSLServiceProvider ssl long rc ... this.GetContextService("SSLServiceProvider", ssl) rc = ssl.SetGlobalProperty("cacheSize", "300") ...
See also
GetGlobalProperty
1021
SetItem
SetItem
Sets the value of an item in a list. For use with DataWindows and DataStores, see the SetItem method for DataWindows in the DataWindow Reference or the online Help.
To set the values of A ListView control item A ListView control item and column A TreeView control item Use Syntax 1 Syntax 2 Syntax 3
Syntax 1
Description Applies to Syntax
You can set properties for any ListView item with this syntax. If you do not specify a column, SetItem sets properties for the first column of an item. Only report views display multiple columns. To add items to a ListView control, use the AddItem function. To add columns to a ListView control, use AddColumn. To set display values for the columns of a ListView item, use Syntax 2. If you want to set column properties, such as alignment or width, use
SetColumn. These column properties are independent of the ListViewItem
objects.
1022
PowerBuilder
CHAPTER 10
PowerScript Functions
To change pictures and other property values associated with a ListView item, use GetItem, change the property values, and use SetItem to apply the changes back to the ListView.
Examples
This example uses SetItem to change the state picture index for the selected lv_list ListView item:
listviewitem lvi_1 lv_list.GetItem(lv_list.SelectedIndex( ), lvi_1) lvi_1.StatePictureIndex = 2 lv_list.SetItem(lv_list.SelectedIndex () , lvi_1)
See also
Syntax 2
Description Applies to Syntax
You must include the column number as an argument, even if you are only assigning values to a single-column ListView control. To specify the properties for a ListView item, use Syntax 1.
1023
SetItem
Examples
This example assigns display values to three columns in a report view for three lv_list ListView items:
listviewitem l_lvi integer li_count, li_index FOR li_index = 1 to 3 li_count=li_count+1 lv_1ist.AddItem("Category " + String(li_index), 1) NEXT lv_list.AddColumn("Composition", Left! , 860) lv_list.AddColumn(" Album", Left! , 610) lv_list.AddColumn(" Artist", Left! , 710) lv_list.SetItem(1 , 1 , "St. Thomas") lv_list.SetItem(1 , 2 , "The Bridge") lv_list.SetItem(1 , 3 , "Sonny Rollins") lv_list.SetItem(2 , 1 , "So What") lv_list.SetItem(2 , 2 , "Kind of Blue") lv_list.SetItem(2 , 3 , "Miles Davis") lv_list.SetItem(3 , 1 , "Goodbye, Porkpie Hat") lv_list.SetItem(3 , 2 , "Mingus-Ah-Um") lv_list.SetItem(3 , 3 , "Charles Mingus")
See also
GetItem
Syntax 3
Description Applies to Syntax
Return value
1024
PowerBuilder
CHAPTER 10
PowerScript Functions
Usage Examples
Typically, you would call GetItem first, edit the data, and then call SetItem to reflect your changes in the TreeView control. This example uses the ItemExpanding event to change the picture index and selected picture index of the current TreeView item:
treeviewitem l_tvi long ll_tvi ll_tvi = tv_list.FindItem(CurrentTreeItem! , 0) tv_list.GetItem(ll_tvi , l_tvi) l_tvi.PictureIndex = 5 l_tvi.SelectedPictureIndex = 5 tv_list.SetItem( ll_tvi, l_tvi )
See also
GetItem
1025
SetLevelPictures
SetLevelPictures
Description Applies to Syntax
Sets the picture indexes for all items at a particular level. TreeView controls
treeviewname.SetLevelPictures ( level, pictureindex, selectedpictureindex, statepictureindex, overlaypictureindex) Argument treeviewname level pictureindex selectedpictureindex statepictureindex overlaypictureindex Description The TreeView control in which you want to set the pictures for a given TreeView level The TreeView level for which you are setting the picture indexes An index from the regular picture list specifying the picture to be displayed when the item is not selected An index from the regular picture list specifying the picture to be displayed when the item is selected An index from the state picture list specifying the picture to be displayed to the left of the regular picture An index from the overlay picture list specifying the picture to be displayed on top of the regular picture
To set pictures for individual items, call GetItem, set the picture properties, and call SetItem to copy the changes to the TreeView. You must specify a value for all four indexes. To display nothing, specify 0. This example sets the pictures for TreeView level 3, then inserts two new TreeView items:
long ll_tvi, ll_child, ll_child2 int li_pict, li_level treeviewitem l_tvi li_level = 6 tv_list.SetLevelPictures( 3, li_level, li_level, & li_level, li_level) ll_tvi = tv_list.FindItem(RootTreeItem! , 0) ll_child = tv_list.InsertItemLast(ll_tvi, "Walton",2) ll_child2 = tv_list.InsertItemLast(ll_child, & "Spitfire Suite", li_level) tv_list.ExpandItem(ll_child) tv_list.SetFirstVisible(ll_child)
Examples
See also
AddPicture
1026
PowerBuilder
CHAPTER 10
PowerScript Functions
SetLibraryList
Description
Changes the files in the library search path of the application at runtime.
Obsolete syntax
You can still use the old syntax with the name of the application object before the function call: applicationname.SetLibraryList ( filelist).
Syntax SetLibraryList ( filelist ) Argument filelist Description A comma-separated list of file names. Specify the full file name with its extension. If you do not specify a path, PowerBuilder uses the systems search path to find the file.
Return value
-1 -2 Usage
The application is being run from PowerBuilder, rather than from a standalone executable. A currently instantiated object is in a library that is not on the new list. If any arguments value is NULL, SetLibraryList returns NULL.
When your application needs to load an object, PowerBuilder searches for the object first in the executable file and then in the dynamic libraries specified for the application. You can specify a different list of library files from those specified in the executable with SetLibraryList. To avoid problems that can occur when components share resources, you should use AddToLibraryList instead of SetLibraryList to add additional PBD files to the search list of a component deployed to EAServer. Calling SetLibraryList replaces the list of library files specified in the executable with a new list of files. For example, you might use SetLibraryList to configure the library list for an application containing many subsystems. You should always use GetLibraryList to return the current library search path and then append any files you want to add to this list. You can then pass the complete list in the filelist argument. PowerBuilder cannot check whether the libraries you specify are appropriate for the application. It is up to you to make sure the libraries contain the objects that the application needs. The executable file is always first in the library search path. If you include it in filelist, it is ignored.
1027
SetLibraryList
If you are running your application in the PowerBuilder development environment, this function has no effect.
Examples
This example specifies different files in the library search path based on the selected application subsystem:
string ls_list ls_list = getlibrarylist () CHOOSE CASE configuration CASE "Config1" SetLibraryList(ls_list + ",lib1.pbd, lib2.pbd, & lib5.pbd") CASE "Config2" SetLibraryList(ls_list + ",lib1.pbd, lib3.pbd, & lib4.pbd") END CHOOSE
See also
AddToLibraryList GetLibraryList
1028
PowerBuilder
CHAPTER 10
PowerScript Functions
SetMask
Description Applies to Syntax
Sets the edit mask and edit mask datatype for an EditMask control. EditMask controls
editmaskname.SetMask ( maskdatatype, mask ) Argument editmaskname maskdatatype Description The name of the EditMask for which you want to specify the edit mask. A MaskDataType enumerated datatype indicating the datatype of the mask. Values are: DateMask! DateTimeMask! DecimalMask! NumericMask! StringMask! mask TimeMask! A string whose value is the edit mask.
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetMask returns NULL.
In an edit mask, a fixed set of characters represent a type of character that the user can enter. In addition, punctuation controls the format of the entered value. Each mask datatype has its own set of valid characters. For example, the following is a mask of type string for a telephone number. The EditMask control displays the punctuation (the parentheses and dash). The pound signs represent the digits that the user enters. The user cannot enter any characters other than digits.
(###) ###-####
For help in specifying a valid mask, see the Edit Mask Style dialog box for an EditMask control in the Window painter. A ListBox in the dialog box shows the meaning of the special mask characters for each datatype, as well as masks that have already been defined. If you are specifying the mask for a number, the format must use U.S. notation. That is, comma represents the thousands delimiter and a period represents the decimal place. During execution, the locally correct symbols are displayed. You cannot use color for edit masks as you can for display formats.
1029
SetMask
Examples
These statements set the mask for the EditMask password_mask to the mask in pword_code. The mask requires the user to enter a digit followed by four characters of any type:
string pword_code pword_code = "#xxxx" password_mask.SetMask(StringMask!, pword_code)
This statement sets the mask for the EditMask password_mask to a 5-digit numeric mask:
password_mask.SetMask(NumericMask!, "#####")
1030
PowerBuilder
CHAPTER 10
PowerScript Functions
SetMessage
Description Syntax
None Use to set a customized message on a user-defined exception object. Although it is possible to use SetMessage to modify the preset error messages for RuntimeError objects, this is not recommended. This statement is an example of a message set on a user object of type Throwable:
MyException.SetMessage ("MyException thrown")
Examples
This example uses SetMessage in the try-catch block for a user-defined function that takes an input value from one text box and outputs the arccosine for that value into another text box:
uo_exception lu_error Double ld_num ld_num = Double (sle_1.text) TRY sle_2.text = string (acos (ld_num)) CATCH (runtimeerror er) lu_error = Create uo_exception lu_error.SetMessage("Value must be between -1" +& "and 1") Throw lu_error END TRY See also
GetMessage
1031
SetMicroHelp
SetMicroHelp
Description Applies to Syntax
Specifies the text to be displayed in the MicroHelp box in an MDI frame window. MDI frame windows
windowname.SetMicroHelp ( string ) Argument windowname string Description The name of the MDI frame window with MicroHelp for which you want to set the MicroHelp text A string whose value is the new MicroHelp text
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetMicroHelp returns NULL.
The Tag property of a control is a useful place to store MicroHelp text. When the control gets the focus, you can use SetMicroHelp in the GetFocus event script to display the Tag propertys text in the MicroHelp box on the window frame. For menus, PowerBuilder automatically displays the MicroHelp text you have specified in the Menu painter when the user selects the menu item. You can use SetMicroHelp in the script for a menu items Selected event to override the predefined MicroHelp and display some other text in the MicroHelp box. SetMicroHelp does not change the predefined MicroHelp text.
Examples
This statement changes the MicroHelp displayed in the frame of W_New to Delete selected text:
W_New.SetMicroHelp("Delete selected text")
In this example, the string Close the Window is a tag value associated with the CommandButton cb_done in W_New. In the script for the GetFocus event in cb_done, this statement displays Close the Window as MicroHelp in W_New when cb_done gets focus:
W_New.SetMicroHelp(This.Tag)
1032
PowerBuilder
CHAPTER 10
PowerScript Functions
SetNull
Description Syntax
Sets a variable to NULL. The variable can be any datatype except for an array, structure, or autoinstantiated object.
SetNull ( anyvariable ) Argument anyvariable Description The variable you want to set to NULL
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetNull returns NULL.
Use SetNull to set a variable to NULL before writing it to the database. Note that PowerBuilder does not initialize variables to NULL; it initializes variables to the default initial value for the datatype unless you specify a value when you declare the variable. If you assign a value to a variable whose datatype is Any and then set the variable to NULL, the datatype of the NULL value is still the datatype of the assigned value. You cannot untype an Any variable with the SetNull function.
Examples
See also
IsNull
1033
SetOverlayPicture
SetOverlayPicture
Description Applies to Syntax
Puts an image in the controls image list into an overlay image list. ListView and TreeView controls
controlname.SetOverlayPicture ( overlayindex, imageindex ) Argument controlname overlayindex Description The name of the ListView or TreeView control to which you want to add an overlay image. The index number of the overlay picture in the overlay image list. The overlay image list is a 1-based array. Overlayindex must be 1 (for the first image), a previously designated index (replacing an image), or 1 greater than the current largest index (adding another image). SetOverlayPicture fails if you specify an index that creates gaps in the array. The index number of an image in the controls main image list. For ListViews, both the large and small pictures at that index become overlay images. The image is still available for use as an items main image.
imageindex
An overlay picture must have the same height and width as the picture it is used to overlay. The color specified in the SetPictureMask property when the picture is inserted becomes transparent when the picture is used as an overlay, allowing part of the original image to be visible beneath the overlay. The overlay list acts as a pointer back to the source image in the regular picture lists. If you delete an image that is also used in the overlay list, the displayed overlay pictures are affected too.
Examples
This example designates overlay images in a ListView control. The same picture is used for large and small images:
// Set up the overlay images integer index index = lv_1.AddLargePicture("shortcut.ico") index = lv_1.AddSmallPicture("shortcut.ico") lv_1.SetOverlayPicture(1, index) index = lv_1.AddLargePicture("not.ico") index = lv_1.AddSmallPicture("not.ico") lv_1.SetOverlayPicture(2, index)
1034
PowerBuilder
CHAPTER 10
PowerScript Functions
// Assign the second overlay image to the first item listviewitem lvi integer i i = lv_1.GetItem(1, lvi) lvi.OverlayPictureIndex = 2 i = lv_1.SetItem(1, lvi)
This example designates the first picture in the TreeViews main image list as the first overlay picture. The picture was added to the main image list on the TreeViews property sheet:
tv_list.SetOverlayPicture(1, 1)
This code in the TreeViews Clicked event assigns the overlay image to the clicked item:
treeviewitem tvi tv_list.GetItem(handle, tvi) tvi.OverlayPictureIndex = 1 tv_list.SetItem(handle, tvi)
1035
SetParagraphSetting
SetParagraphSetting
Description Applies to Syntax
Sets the size of the indentation, left margin, or right margin of the paragraph containing the insertion point in a RichTextEdit control. RichTextEdit controls
rtecontrol.SetParagraphSetting ( whichsetting, value ) Argument rtecontrol whichsetting Description The name of the control for which you want paragraph information. A value of the ParagraphSetting enumerated datatype specifying the setting you want to change. Values are: Indent! Returns the indentation of the paragraph LeftMargin! Returns the left margin of the paragraph RightMargin! Returns the right margin of the paragraph value A long whose value is the width of the margin or indent in units of 1000ths of an inch. For example, a value of 500 specifies a width of half an inch.
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any argument is NULL, it returns NULL.
Each paragraph has indentation, left margin, and right margin settings. To set all three for the current paragraph, call SetParagraphSetting three times. This example sets the indentation setting for the current paragraph to a quarter inch:
ll_indent = rte_1.SetParagraphSetting(Indent!, 250)
This example sets the left margin for the current paragraph to an inch:
rte_1.SetParagraphSetting(LeftMargin!, 1000) See also
1036
PowerBuilder
CHAPTER 10
PowerScript Functions
SetPicture
Description Applies to Syntax
Assigns an image stored in a blob to be the image in a Picture control. Picture controls
picturecontrol.SetPicture ( bimage ) Argument picturecontrol bimage Description The name of a Picture control in which you want to set the bitmap. A blob containing the new bitmap. bimage must be a valid picture in bitmap (BMP), Compuserve Graphics Interchange Format (GIF), Joint Photographic Experts Group (JPEG), run-length encoded (RLE), or Windows Metafile (WMF).
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetPicture returns NULL.
If you use FileRead to get the bitmap image from a file, remember that the FileRead function can read a maximum of 32765 characters at a time. To check the length of a file, call FileLength. If the file is over 32765 characters, you can call FileRead more than once and concatenate the return values. These statements allow the user to select a file and then open the file and set the Picture control p_1 to the bitmap in the selected file:
integer fh, ret blob Emp_pic string txtname, named string defext = "BMP" string Filter = "bitmap Files (*.bmp), *.bmp" ret = GetFileOpenName("Open Bitmap", txtname, & named, defext, filter) IF ret = 1 THEN fh = FileOpen(txtname, StreamMode!) IF fh <> -1 THEN FileRead(fh, Emp_pic) FileClose(fh) p_1.SetPicture(Emp_pic) END IF END IF
Examples
1037
SetPointer
SetPointer
Description Syntax
Pointer. Returns the enumerated type of the pointer it replaced so the script can restore it, if necessary. If type is NULL, SetPointer returns NULL. Use SetPointer to display an hourglass at the beginning of a script when the script will take a long time to execute. The pointer remains set until you change it again in the script or the script terminates.
Restoring the arrow pointer
The pointer automatically changes back to an arrow when the script finishes executing. You do not have to change it back to an arrow. In PowerBuilders painters, you can specify the pointer shape that PowerBuilder displays when the user moves the pointer over a window, a control, or specific parts of a DataWindow object. The available shapes include the stock pointers listed above, as well as any custom cursor files you have.
Examples
This example saves the old pointer and restores it when a long activity is completed:
pointer oldpointer // Declares a pointer variable oldpointer = SetPointer(HourGlass!) ... // Performs some long activity SetPointer(oldpointer)
1038
PowerBuilder
CHAPTER 10
PowerScript Functions
SetPosition
Specifies the front-to-back position of a control in a window, a window, or an object within a DataWindow.
To Specify the front-to-back position of a control in a window, or specify that a window should always display on top of other windows Move an object in a DataWindow to another band or to specify its frontto-back position within a band Use Syntax 1 Syntax 2
Syntax 1
Description
Applies to Syntax
position
1039
SetPosition
Integer. Returns 1 when it succeeds and -1 if an error occurs. If any arguments value is NULL, SetPosition returns NULL.
The front-to-back order for controls determines which control covers another when they overlap. If a control completely covers another control, the control that is in back becomes inaccessible to the user. When you specify TopMost! for more than one window, the most recently executed SetPosition function controls which window displays on top.
Examples
This statement makes the window w_signon no longer necessarily the topmost window:
w_signon.SetPosition(NoTopMost!)
Syntax 2
Description Applies to Syntax
1040
PowerBuilder
CHAPTER 10
PowerScript Functions
Argument band
Description The name of the band or layer in which you want to position objectname. Layer names are background and foreground. Band names are detail, header, footer, summary, header.#, and trailer.#. # is the group level number. Enter the empty string ("") if you do not want to change the band A boolean indicating whether you want to bring objectname to the front within the band: TRUE Bring it to the front FALSE Do not bring it to the front
bringtofront
Integer. Returns 1 when it succeeds and -1 if an error occurs. If any arguments value is NULL, SetPosition returns NULL.
This statement moves oval_red in dw_rpt to the header and brings it to the front:
dw_rpt.SetPosition("oval_red", "header", TRUE)
This statement does not change the position of oval_red , but does bring it to the front:
dw_rpt.SetPosition("oval_red", "", TRUE)
This statement moves oval_red to the footer but does not bring it to the front:
dw_rpt.SetPosition("oval_red", "footer", FALSE)
1041
SetProfileString
SetProfileString
Description Syntax
section
key
Integer. Returns 1 when it succeeds and -1 if it fails because filename is not found or cannot be accessed. If any arguments value is NULL, SetProfileString returns NULL.
Usage
A profile file consists of section labels, which are enclosed in square brackets, and keys, which are followed by an equal sign and a value. By changing the values assigned to the keys, you can specify custom settings for each installation of your application. When you are planning your own profile file, you select the section and key names and determine how the values are used. For example, a profile file might contain information about the user. In the sample below, User Info is the section name and the other values are the keys. There is no space before and after the equal sign used in the keys or in the section label (if you use a section name such as Section=1):
[User Info] Name="James Smith" JobTitle="Window Washer" SecurityClearance=9 Password=
Call SetProfileString to store configuration information, supplied by you or the user, in a profile file. You can call the functions ProfileInt and ProfileString to use that information to customize your PowerBuilder application during execution.
1042
PowerBuilder
CHAPTER 10
PowerScript Functions
Accessing the profile file SetProfileString uses profile calls to write data to the profile file. Consequently it does not control when the profile file is written and closed. If you try to read data from the profile file immediately after calling SetProfileString, the file may still be open and you will receive incomplete or incorrect data. To avoid this problem, you can use the PowerScript FileOpen, FileWrite, and FileClose functions to write data to the profile file instead of using SetProfileString. Or you can add some additional processing after the SetProfileString call so that the profile calls have time to complete before you try to read from the profile file.
Windows registry SetProfileString can also be used to obtain configuration settings from the
Windows system registry. For information on how to use the system registry, see the discussion of initialization files and the Windows registry in Application Techniques.
Examples
This statement sets the keyword Title in section Position of file C:\PROFILE.INI to the string MGR:
SetProfileString("C:\PROFILE.INI", & "Position", "Title", "MGR")
See also
ProfileInt ProfileString
1043
SetRange
SetRange
Description Applies to Syntax
Sets a duration for a progress bar control or sets the start and end position for a trackbar control. Progress bar and trackbar controls
controlname.SetRange ( startpos, endpos ) Argument controlname startpos endpos Description The name of the progress bar or trackbar Integer indicating the initial position of the range Integer indicating the terminal position of the range
The default range for the progress bar controls is 0 to 100. This statement sets a range of 1 to 10 for a progress bar control:
HProgressBar.SetRange ( 1, 10 )
See also
1044
PowerBuilder
CHAPTER 10
PowerScript Functions
SetRecordSet
Description Applies to Syntax
Sets an ADOResultSet object to obtain its data and metadata from a passed ADO Recordset. ADOResultSet objects
adoresultset.SetRecordSet ( adorecordsetobject ) Argument adoresultset adorecordsetobject Description An ADOResultSet object into which the function places the passed ADO Recordset. An OLEObject object that contains an ADO Recordset. Passing an OLEObject that does not contain an ADO Recordset generates an error.
Use the SetRecordSet function to populate an ADOResultSet object with data passed in an OLEObject that contains an ADO Recordset. Record sets are returned from MTS components as ADO Recordsets. The following example connects to an MTS component and calls a method on the component that returns an ADO Recordset to an OLEObject object. Then it creates an ADOResultSet object and populates it with data from the OLEObject using SetRecordSet:
OLEObject loo_mycomponent OLEObject loo_ADOrecordset ADOresultset lrs_ADOresultset integer li_rc loo_mycomponent = CREATE OLEObject li_rc = loo_mycomponent.ConnectToNewObject("PB.Test") IF li_rc <> 0 THEN MessageBox("Connect Failed", string(li_rc) ) RETURN END IF // Use an OLEObject to hold ADO Recordset // returned from method on MTS component loo_ADOrecordset = loo_mycomponent.GetTestResult() // Create an ADOResultSet and get its data // from OLEObject holding passed ADO Recordset lrs_ADOresultset = CREATE ADOResultSet lrs_ADOresultset.SetRecordSet(loo_ADOrecordset)
Examples
1045
SetRecordSet
See also
online Help
GenerateResultSet method for DataWindows in the DataWindow Reference or
1046
PowerBuilder
CHAPTER 10
PowerScript Functions
SetRedraw
Description Applies to Syntax
Controls the automatic redrawing of an object or control after each change to its properties. Any object except a Menu
objectname.SetRedraw ( boolean ) Argument objectname Description The name of the object or control for which you want to change the redraw setting. Objectname can be a child DataWindow, but cannot be a menu. A boolean value that controls whether PowerBuilder redraws an object automatically after a change. Values are: TRUE Automatically redraw the object or control after each change to its properties FALSE Do not redraw after each change
boolean
Integer. Returns 1 if it succeeds and -1 if an error occurs. If boolean is NULL, SetRedraw returns NULL.
By default, PowerBuilder redraws a control after each change to properties that affect appearance. Use SetRedraw to turn off redrawing temporarily in order to avoid flicker and reduce redrawing time when you are making several changes to the properties of an object or control. If the window is not visible, SetRedraw fails.
Caution
If you turn redraw off, you must turn it on again. Otherwise, problems may result. In addition, if redraw is off and you change the Visible or Enabled property of an object in the window, the tabbing order may be affected.
Examples
If lb_Location is sorted (lb_Location.Sorted = TRUE), these statements use SetRedraw to avoid sorting and redrawing the list of lb_Location until all the new items have been added:
lb_Location.SetRedraw(FALSE) lb_Location.AddItem("Atlanta") lb_Location.AddItem("Boston") lb_Location.AddItem("Washington") lb_Location.SetRedraw(TRUE)
1047
SetRemote
SetRemote
Asks a DDE server application to accept data and store it in the specified location. There are two ways of calling SetRemote, depending on the type of DDE connection you have established.
To Make a single DDE request of a server application (a cold link) Make a DDE request of a server application when you have established a warm link by opening a channel Use Syntax 1 Syntax 2
Syntax 1
Description
Syntax
Return value
When using DDE, your PowerBuilder application must have an open window, which will be the client window. For this syntax, the active window is the DDE client window. For more information about DDE channels and warm and cold links, see the ExecRemote function.
1048
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This statement asks Microsoft Excel to set the value of the data in row 5, column 7 of a worksheet called SALES.XLS to 4500:
SetRemote("R5C7", "4500", "Excel", "SALES.XLS")
See also
Syntax 2
Description
Syntax
value handle
are: -1 -2 -9
Usage
When using DDE, your PowerBuilder application must have an open window, which will be the client window. For this syntax, you can specify a client window other than the active window with the windowhandle argument. Before using this syntax of SetRemote, call OpenChannel to establish a DDE channel. For more information about DDE channels and warm and cold links, see the ExecRemote function.
1049
SetRemote
Examples
This example opens a channel to a Microsoft Excel worksheet and asks it to set the value of the data in row 5 column 7 to 4500:
long handle handle = OpenChannel("Excel", "REGION.XLS") SetRemote("R5C7", "4500", handle)
See also
1050
PowerBuilder
CHAPTER 10
PowerScript Functions
SetResultSet
Description Applies to Syntax
Populates a new ADOResultSet object with data passed in a ResultSet object. ADOResultSet objects
adoresultset.SetResultSet ( resultsetobject ) Argument adoresultset resultsetobject Description An ADOResultSet object into which the function places the passed result set as an ADO Recordset A ResultSet object that contains result set data
Use SetResultSet when you want to create an ADOResultSet object and populate it with data from a ResultSet object. The ResultSet object can be generated from a DataStore object using the GenerateResultSet function. After you create the ADOResultSet object using SetResultSet, you can use the GetRecordSet function to return the ADO result set in an ADO Recordset object of type OLEObject that you can use as a native ADO Recordset object in PowerScript.
See GetRecordSet.
GenerateResultSet method for DataWindows in the DataWindow Reference or
1051
SetSeriesStyle
SetSeriesStyle
Specifies the appearance of a series in a graph. There are several syntaxes, depending on what settings you want to change.
To Set the series colors Set the line style and width Set the fill pattern or symbol for the series Specify that the series is an overlay Use Syntax 1 Syntax 2 Syntax 3 Syntax 4
Syntax 1
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetSeriesStyle returns NULL.
1052
PowerBuilder
CHAPTER 10
PowerScript Functions
Usage
Data points in a series can have their own style settings. Settings made with SetDataStyle set the style of individual data points and override series settings. The graph stores style information for properties that do not apply to the current graph type. For example, you can set the fill pattern in a two-dimensional line graph or the line style in a bar graph, but that fill pattern or line style will not be visible. For a graph in a DataWindow, you can specify the appearance of a series in the graph before PowerBuilder draws the graph. To do so, define a user event for pbm_dwngraphcreate and call SetSeriesStyle in the script for that event. The event pbm_dwngraphcreate is triggered just before a graph is created in a DataWindow object.
Examples
This statement sets the text (foreground) color of the series named Salary in the graph gr_emp_data to black:
gr_emp_data.SetSeriesStyle("Salary", & Foreground!, 0)
This statement sets the background color of the series named Salary in the graph gr_depts in the DataWindow control dw_employees to black:
dw_employees.SetSeriesStyle("gr_depts", & "Salary", Background!, 0)
These statements in the Clicked event of the graph control gr_product_data coordinate line color between it and the graph gr_sales_data. The script stores the line color for the series under the mouse pointer in the graph gr_product_data in the variable line_color. Then it sets the line color for the series northeast in the graph gr_sales_data to that color:
string SeriesName integer SeriesNbr, Series_Point long line_color grObjectType MouseHit MouseHit = ObjectAtPointer(SeriesNbr,Series_Point) IF MouseHit = TypeSeries! THEN SeriesName = & gr_product_data.SeriesName(SeriesNbr) gr_product_data.GetSeriesStyle(SeriesName, & LineColor!, line_color)
1053
SetSeriesStyle
Syntax 2
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetSeriesStyle returns NULL.
Data points in a series can have their own style settings. Settings made with SetDataStyle set the style of individual data points and override series settings.
1054
PowerBuilder
CHAPTER 10
PowerScript Functions
The graph stores style information for properties that do not apply to the current graph type. For example, you can set the fill pattern in a two-dimensional line graph or the line style in a bar graph, but that fill pattern or line style will not be visible. For a graph in a DataWindow, you can specify the appearance of a series in the graph before PowerBuilder draws the graph. To do so, define a user event for pbm_dwngraphcreate and call SetSeriesStyle in the script for that event. The event pbm_dwngraphcreate is triggered just before a graph is created in a DataWindow object.
Examples
This statement sets the line style and width for the series named Costs in the graph gr_product_data:
gr_product_data.SetSeriesStyle("Costs", & Dot!, 5)
See also
Syntax 3
Description Applies to Syntax
A string whose value is the name of the series in which you want to set the appearance. A value of an enumerated datatype specifying an appearance setting for the series. Values for the FillPattern or grSymbolType enumerated datatypes follow.
1055
SetSeriesStyle
Argument
Description To change the fill pattern, use a FillPattern value: Bdiagonal! (Lines from lower left to upper right) Diamond! Fdiagonal! (Lines from upper left to lower right) Horizontal! Solid! Square! Vertical! To change the symbol type, use a grSymbolType value: NoSymbol! SymbolHollowBox! SymbolX! SymbolStar! SymbolHollowUpArrow! SymbolHollowCircle! SymbolHollowDiamond! SymbolSolidDownArrow! SymbolSolidUpArrow! SymbolSolidCircle! SymbolSolidDiamond! SymbolPlus! SymbolHollowDownArrow! SymbolSolidBox!
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetSeriesStyle returns NULL.
Data points in a series can have their own style settings. Settings made with SetDataStyle set the style of individual data points and override series settings. The graph stores style information for properties that do not apply to the current graph type. For example, you can set the fill pattern in a two-dimensional line graph or the line style in a bar graph, but that fill pattern or line style will not be visible. For a graph in a DataWindow, you can specify the appearance of a series in the graph before PowerBuilder draws the graph. To do so, define a user event for pbm_dwngraphcreate and call SetSeriesStyle in the script for that event. The event pbm_dwngraphcreate is triggered just before a graph is created in a DataWindow object.
1056
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This statement sets the symbol used for the series named Costs in the graph gr_product_data to a plus sign:
gr_product_data.SetSeriesStyle("Costs", & SymbolPlus!)
This statement sets the symbol used for the series named Costs in the graph gr_computers in the DataWindow control dw_equipment to X:
dw_equipment.SetSeriesStyle("gr_computers", & "Costs", SymbolX!) See also
Syntax 4
Description Applies to Syntax
Return value
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetSeriesStyle returns NULL.
1057
SetSeriesStyle
Usage
For a graph in a DataWindow, you can specify the appearance of a series in the graph before PowerBuilder draws the graph. To do so, define a user event for pbm_dwngraphcreate and call SetSeriesStyle in the script for that event. The event pbm_dwngraphcreate is triggered just before a graph is created in a DataWindow object. This statement sets the style of the series named Costs in the graph gr_product_data to overlay:
gr_product_data.SetSeriesStyle("Costs", TRUE)
Examples
These statements in the Clicked event of the DataWindow control dw_employees store the style of the series under the pointer in the graph gr_depts in the variable style_type. If the style of the series is overlay (TRUE), the script changes the style to normal (FALSE):
string SeriesName integer SeriesNbr, Data_Point boolean overlay_style grObjectType MouseHit MouseHit = dw_employees.ObjectAtPointer( & "gr_depts", SeriesNbr, Data_Point) IF MouseHit = TypeSeries! THEN SeriesName = & dw_employees.SeriesName("gr_depts",SeriesNbr) dw_employees.GetSeriesStyle("gr_depts", & SeriesName, overlay_style) IF overlay_style THEN & dw_employees.SetSeriesStyle("gr_depts", & SeriesName, FALSE) END IF See also
1058
PowerBuilder
CHAPTER 10
PowerScript Functions
SetSpacing
Description Applies to Syntax
Sets the line spacing for the selected paragraphs or the paragraph containing the insertion point in a RichTextEdit control. RichTextEdit controls
rtename.SetSpacing ( spacing ) Argument rtename spacing Description The name of the RichTextEdit control in which you want to set the line spacing. A value of the Spacing enumerated datatype specifying the line spacing for the text. Values are: Spacing1! Single spacing Spacing15! One and a half line spacing Spacing2! Double spacing
Because spacing is a setting for paragraphs, not individual lines, then if lines have wrapped, spacing will change for all the lines in all the paragraphs that are selected. When you expand the line spacing, the extra space is added before the affected lines.
Examples
This example specifies double spacing for the selected paragraphs in the RichTextEdit rte_1:
rte_1.SetSpacing(Spacing2!)
SetTextColor SetTextStyle
1059
SetState
SetState
Description Applies to Syntax
Sets the highlighted state of an item in a list box. SetState is only applicable to a list box control whose MultiSelect property is set to TRUE. ListBox and PictureListBox controls
listboxname.SetState ( index, state ) Argument listboxname Description The name of the ListBox or PictureListBox in which you want to set the state (highlighted or not highlighted) for an item. The MultiSelect property for the control must be set to TRUE. The number of the item for which you want to set the state. Specify 0 to set the state of all the items in the ListBox. A boolean value that determines the state of the item: TRUE Selected FALSE Not selected
index state
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetState returns NULL.
When the MultiSelect property for the control is FALSE, use SelectItem, instead of SetState, to select one item at a time. This statement turns on the highlight for item 6 in lb_Actions:
lb_Actions.SetState(6, TRUE)
This statement turns off the highlight for item 6 in lb_Actions if it is selected and turns it on again if it is not selected:
IF lb_Actions.State(6) = 1 THEN lb_Actions.SetState(6, FALSE) ELSE lb_Actions.SetState(6, TRUE) END IF See also
1060
PowerBuilder
CHAPTER 10
PowerScript Functions
SetTextColor
Description Applies to Syntax
For more information about calculating color values, see RGB. This example sets the selected text in RichTextEdit rte_1 to dark red:
rte_1.SetTextColor(RGB(100, 0, 0))
See also
1061
SetTextStyle
SetTextStyle
Description
Specifies the text formatting for selected text in a RichTextEdit control. You can make the text bold, underlined, italic, and struck out. You can also make it either a subscript or superscript. RichTextEdit controls
rtename.SetTextStyle ( bold, underline, subscript, superscript, italic, strikeout ) Argument rtename bold underline subscript superscript Description The name of the RichTextEdit control in which you want to specify formatting for selected text. A boolean value specifying whether the selected text is bold. A boolean value specifying whether the selected text is underlined. A boolean value specifying whether the selected text is a subscript. A boolean value specifying whether the selected text is a superscript. If both subscript and superscript are TRUE, subscript takes precedence and the text is subscripted A boolean value specifying whether the selected text is italic. A boolean value specifying whether the selected text is has a line drawn through it.
Applies to Syntax
italic strikeout
This example makes selected text in the RichTextEdit rte_1 bold and italic:
rte_1.SetTextStyle(TRUE, FALSE, FALSE, FALSE, & TRUE, FALSE)
This example makes the selected text a subscript. It keeps other text formatting as it was:
rte_1.SetTextStyle(rte_1.GetTextStyle(Bold!), & rte_1.GetTextStyle(Underlined!), & TRUE, FALSE, & rte_1.GetTextStyle(Italic!), & rte_1.GetTextStyle(Strikeout!)) See also
1062
PowerBuilder
CHAPTER 10
PowerScript Functions
SetTimeout
Description Applies to Syntax
Sets the timeout value for subsequent EAServer transactions. The transaction is rolled back if it does not complete before the timeout expires. CORBACurrent objects
CORBACurrent.SetTimeout ( seconds ) Argument CORBACurrent seconds Description Reference to the CORBACurrent service instance An unsignedlong that specifies the number of seconds that elapse before a transaction is rolled back
The SetTimeout function specifies the number of seconds that can elapse before a transaction is rolled back. The timeout period applies to transactions created by subsequent invocations of BeginTransaction. If seconds is 0, no timeout period is in effect.
SetTimeout can be called by a client or a component that is marked as OTS
style. EAServer must be using the two-phase commit transaction coordinator (OTS/XA).
Examples
This example shows the use of SetTimeout to set the timeout period to five minutes:
// Instance variables: // CORBACurrent corbcurr boolean lb_timeout integer li_rc li_rc = this.GetContextService("CORBACurrent", & corbcurr) IF li_rc <> 1 THEN // handle the error END IF li_rc = corbcurr.Init( "iiop://server1:9003") IF li_rc <> 1 THEN // handle the error ELSE lb_timeout = corbcurr.SetTimeout(300) li_rc = corbcurr.BeginTransaction() END IF
1063
SetTimeout
See also
BeginTransaction CommitTransaction GetContextService GetStatus GetTransactionName Init ResumeTransaction RollbackOnly RollbackTransaction SuspendTransaction
1064
PowerBuilder
CHAPTER 10
PowerScript Functions
SetToolbar
Description Applies to Syntax
Specifies the alignment, visibility, and title for the specified toolbar. MDI frame and sheet windows
window.SetToolbar ( toolbarindex, visible {, alignment {, floatingtitle } } ) Argument window toolbarindex visible Description The MDI frame or sheet to which the toolbar belongs. An integer whose value is the index of the toolbar whose settings you want to change. A boolean value specifying whether to make the toolbar visible. Values are: TRUE Make the toolbar visible alignment (optional) FALSE Hide the toolbar A value of the ToolbarAlignment enumerated datatype specifying the alignment for the toolbar. Values are: AlignAtTop! Dock the toolbar at the top of the frame. AlignAtLeft! Dock the toolbar on the left side of the frame. AlignAtRight! Dock the toolbar on the right side of the frame. AlignAtBottom! Dock the toolbar at the bottom of the frame. Floating! Float the toolbar. The floating toolbar has its own frame and miniature title bar A string whose value is the title for the toolbar when its alignment is Floating!.
Integer. Returns 1 if it succeeds. SetToolbar returns -1 if there is no toolbar for the index you specify or if an error occurs. If any arguments value is NULL, returns NULL.
Usage
When you use SetToolbar to change the toolbar alignment from a docked position to Floating!, PowerBuilder uses the last known position information unless you also call SetToolbarPos to adjust the position. The toolbars are not redrawn until the script ends, so setting the alignment with SetToolbar and the position with SetToolbarPos looks like a single change to the user.
1065
SetToolbar
Examples
This example allows the user to choose an alignment in a ListBox lb_position. The selected string is converted to a ToolbarAlignment enumerated value, which is used to change the alignment of toolbar index 1:
toolbaralignment tba_align CHOOSE CASE lb_position.SelectedItem() CASE "Top" tba_align CASE "Left" tba_align CASE "Right" tba_align CASE "Bottom" tba_align CASE "Floating" tba_align END CHOOSE
In this example, the user clicks a radio button to choose an alignment. The radio buttons Clicked event sets an instance variable of type ToolbarAlignment. Here the radio buttons are packaged as a custom visual user object. I_toolbaralign is an instance variable of the user object. This is the script for the Top radio button:
Parent.i_toolbaralign = AlignAtTop!
1066
PowerBuilder
CHAPTER 10
PowerScript Functions
SetToolbarPos
Sets the position of the specified toolbar.
To set Docking position of a docked toolbar Coordinates and size of a floating toolbar Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
offset
1067
SetToolbarPos
Return value
Integer. Returns 1 if it succeeds. SetToolbarPos returns -1 if there is no toolbar for the index you specify or if an error occurs. If any arguments value is NULL, returns NULL.
Usage
To find out whether the docked toolbar is at the top, bottom, left, or right edge of the window, call GetToolbar. If the toolbars alignment is floating, instead of docked, then values you specify with Syntax 1 of SetToolbarPos take effect when you change the alignment to a docked position with SetToolbar. When insert is FALSE, to move the toolbar before other toolbars in dockrow, specify a value that is less than the offset for the existing toolbars. If there is already a toolbar at offset 1, then you can move the toolbar to the beginning of the row by setting offset to 0. If offset is equal to or greater than the offset of existing toolbars, but less than their end, the newly positioned toolbar will begin just after the existing one. Otherwise, the toolbar will be positioned at offset. If the user drags the toolbar to a docked position, the new row and offset replace values set with SetToolbarPos.
Examples
This example docks toolbar 2 at the left, adding it to docking row 1. If the toolbars already in the dock extend past offset 250, then the offset of toolbar 2 is increased to accommodate them. Otherwise, it is positioned at offset 250:
w_frame.SetToolbar(2, TRUE, AlignAtLeft!) w_frame.SetToolbarPos(2, 1, 250, FALSE)
This example docks toolbar 2 at the left in docking row 2. Any toolbar docked on the left in row 2 or higher is moved over a row:
w_frame.SetToolbar(1, TRUE, AlignAtLeft!) w_frame.SetToolbarPos(1, 2, 1, TRUE) See also
1068
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 2
Description Applies to Syntax
Return value
Integer. Returns 1 if it succeeds. SetToolbarPos returns -1 if there is no toolbar for the index you specify or if an error occurs. If any arguments value is NULL, SetToolbarPos returns NULL.
Usage
If the toolbars alignment is a docked position, instead of floating, then values you specify with Syntax 2 of SetToolbarPos take effect when you change the alignment to floating in a script with SetToolbar. If the user drags the toolbar to a floating position, the new position values replace values set with SetToolbarPos. The floating toolbar is never too large or too small for the buttons. If you specify width and height values that are too small to accommodate the buttons, the width and height are adjusted to make room for the buttons. If both width and height are larger than needed, the height is reduced. If you specify x and y coordinates that are outside the frame, the toolbar becomes inaccessible to the user.
Examples
This example displays toolbar 1 near the upper-left corner of the frame. An arbitrary width and height lets PowerBuilder size the toolbar as needed:
w_frame.SetToolbarPos(1, 10, 10, 400, 1) w_frame.SetToolbar(1, TRUE, Floating!)
This example displays toolbar 2 close to the lower-right corner of the frame. GetToolbarPos gets the current width and height of the toolbar so that the toolbar stays the same size:
integer ix, iy, iw, ih w_frame.GetToolbarPos(2, ix, iy, iw, ih)
1069
SetToolbarPos
w_frame.SetToolbarPos(2, & w_frame.WorkspaceWidth()-400, & w_frame.WorkspaceHeight()-400, & iw, ih) w_frame.SetToolbar(2, TRUE, Floating!)
This example positions floating toolbar 2 just inside the lower-right corner of the MDI frame. GetToolbarPos gets the current width and height of the toolbar. These values and the height of the MicroHelp are used to calculate the x and y coordinates for the floating toolbar:
integer ix, iy, iw, ih // Find out toolbar size w_frame.GetToolbarPos(2, ix, iy, iw, ih) // Set the position, taking the size into account w_frame.SetToolbarPos(2, & w_frame.WorkspaceWidth( ) - iw, & w_frame.WorkspaceHeight( ) & - ih - w_frame.MDI_1.MicroHelpHeight, & iw, ih) // Set the alignment to floating w_frame.SetToolbar(2, TRUE, Floating!) See also
1070
PowerBuilder
CHAPTER 10
PowerScript Functions
SetTop
Description Applies to Syntax
Scrolls a list box control so that the specified item is the first visible item. ListBox and PictureListBox controls
listboxname.SetTop ( index ) Argument listboxname index Description The name of the ListBox or PictureListBox that you want to scroll The number of the item you want to become the first visible item
Integer. Returns 1 if it succeeds and -1 if an error occurs. If any arguments value is NULL, SetTop returns NULL.
This statement scrolls item 6 in lb_Actions to the top of the ListBox so that it is the first visible item:
lb_Actions.SetTop(6)
The following statement scrolls the currently selected item in lb_Actions to the top of the list of items:
lb_Actions.SetTop(lb_Actions.SelectedIndex()) See also
SetFocus SetState
1071
SetTraceFileName
SetTraceFileName
Description Applies to Syntax
Specifies the name of the trace file PowerBuilder will analyze when the BuildModel function is called. Profiling and TraceTree objects
instancename.SetTraceFileName ( tracefilename ) Argument instancename tracefilename Description Instance name of the Profiling or TraceTree object A string that identifies the name of the trace file PowerBuilder will analyze
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded FileOpenError!The file could not be opened FileInvalidFormatError!The trace file is not in the correct format ModelExistsError!A model has already been built
Use this function to specify the trace file PowerBuilder should analyze with the BuildModel function. You call the SetTraceFileName function before calling the BuildModel function. This example provides the name of the trace file for which a performance analysis model is to be built:
Profiling lpro_model String ls_line lpro_model = CREATE Profiling lpro_model.SetTraceFileName (filename) ls_line = "CollectionTime = " + & String(lpro_model.CollectionTime ) + "~r~n" & + "Num Activities = " & + String(lpro_model.NumberOfActivities) + "~r~n" lpro_model.BuildModel() ...
Examples
See also
BuildModel
1072
PowerBuilder
CHAPTER 10
PowerScript Functions
SetTransPool
Description
Sets up a pool of database transactions for an application. SetTransPool allows you to minimize the overhead associated with database connections and also limit the total number of database connections permitted. Application object
applicationname.SetTransPool ( minimum, maximum, timeout ) Argument applicationname minimum maximum timeout Description The name of the application object for which you want to establish a transaction pool The minimum number of transactions to be kept open in the pool The maximum number of transactions that can be open in the pool The number of seconds to allow a request to wait for a connection in the transaction pool
Applies to Syntax
Transaction pooling maximizes database throughput while also controlling the number of database connections that can be open at one time. By establishing a transaction pool before connecting to the database, an application can reuse connections made to the same data source. When an application connects to a database without using transaction pooling, PowerBuilder physically terminates each database transaction for which a DISCONNECT statement is issued. When transaction pooling is in effect, PowerBuilder logically terminates the database connections and commits any database changes, but does not physically remove them. Instead, the database connections are kept open in the transaction pool so that they can be reused for other database operations. Before reusing a connection in the transaction pool, PowerBuilder checks to see that the database parameters specified in the incoming connection request match those specified by one of the connections in the pool. A match occurs when both transaction objects specify the same DBMS, ServerName, LogID, LogPass, Database, and DBParm values. The minimum value specified in the SetTransPool function must be less than or equal to the maximum value. When the minimum value is less than the maximum and the number of transactions in the pool is greater than the minimum, PowerBuilder physically terminates connections for which a DISCONNECT statement is issued until the minimum number is reached.
1073
SetTransPool
The maximum value specified for a transaction pool limits the total number of database connections made by the application. When the transaction pool is full, each attempt to connect will fail after the timeout interval has been exceeded. To set up transaction pooling for an application, you need to issue SetTransPool before establishing any connections to the database.
Examples
A distributed PowerBuilder server application that services a high volume of short database transactions to the same data source could issue the following statement in its application Open event:
server_app.SetTransPool(12,16,10)
This statement specifies that up to 16 database connections will be supported through this server, and that 12 connections will be kept open once successfully connected. When the maximum number of connections has been reached, each subsequent connection request will wait for up to 10 seconds for a connection in the pool to become available. After 10 seconds, the server will return an error to the client. The following statement specifies that up to 8 database connections will be allowed through this server, and that all 8 will be kept open once successfully connected. When the transaction pool is full, each subsequent connection request will immediately result in an error:
server_app.SetTransPool(8,8,0) See also
SetTrans method for DataWindows in the DataWindow Reference or the online
Help
SetTransObject method for DataWindows in the DataWindow Reference or the
online Help
1074
PowerBuilder
CHAPTER 10
PowerScript Functions
SharedObjectDirectory
Description
Retrieves the list of objects that have been registered for sharing. This function was used primarily for distributed PowerBuilder applications.
Syntax
SharedObjectDirectory ( instancenames {, classnames } ) Argument instancenames classnames (optional) Description An unbounded array of type string in which you want to store the names of objects that have been registered for sharing An unbounded array of type string in which you want to store the class names of objects registered for sharing
Return value
ErrorReturn. Returns one of the following values: Success! The function succeeded FeatureNotSupportedError! This function is not supported on Windows 3.x
Usage Examples
Use this function to obtain a list of objects that have been registered for sharing. In this example, the application retrieves the list of shared objects and their class names:
integer status string InstanceNames[] string ClassNames[] status = SharedObjectDirectory(InstanceNames, & ClassNames)
See also
SharedObjectGet SharedObjectRegister
1075
SharedObjectGet
SharedObjectGet
Description
Gets a reference to a shared object instance. This function was used primarily in distributed PowerBuilder applications.
Syntax
SharedObjectGet ( instancename , objectinstance ) Argument instancename Description The name of a shared object instance to which you want to obtain references. The name you specify must match the name given to the object instance when it was first registered with the SharedObjectRegister function. An object variable of type PowerObject in which you want to store an instance of a shared object.
objectinstance
Return value
ErrorReturn. Returns one of the following values: Success! The function succeeded SharedObjectCreateInstanceError! The local reference to the shared object could not be created SharedObjectNotExistsError! The instance name has not been registered
Usage
You can use a shared object on a PowerBuilder client to simulate an asynchronous call to EAServer. The main thread on the client makes an asynchronous call to a function on the shared object, passing it a callback object that is notified when processing has finished on the server. The method on the shared object makes a synchronous call to the EAServer component method that performs processing. Since the shared object is running in a separate thread on the client, the main thread on the client can proceed with other work while the process runs on the server.
Examples
This example shows how you might use a shared object to make an asynchronous request against an EAServer component method and return data back to a client application window. The client has a Retrieve button on a window, a SetDW function, a shared object, and a callback handler. The component deployed to EAServer retrieves employee information from a database.
1076
PowerBuilder
CHAPTER 10
PowerScript Functions
The Retrieve button on the window creates a shared object that communicates with EAServer as well as an instance of a callback handler: // instance variables // uo_sharedobject iuo_sharedobject // uo_callback iuo_callback long ll_rv SharedObjectRegister("uo_sharedobject","myshare") SharedObjectGet("myshare",iuo_sharedobject) iuo_callback = CREATE uo_callback // Pass a reference to the window to // the callback object iuo_callback.passobject (parent) iuo_sharedobject.post retrievedata(iuo_callback) The SetDW function applies the contents of the DataWindow blob returned from the EAServer component to a DataWindow control in the window:
long ll_rv ll_rv = dw_employee.SetFullState(ablb_data) if ll_rv = -1 then MessageBox("Error", "SetFullState call failed!") end if return ll_rv
The Constructor event of the shared object uses a custom Connection object called n_jagclnt_connect to connect to the server. Then it creates an instance of the EAServer component:
// Instance variables // uo_employee iuo_employee // n_jagclnt_connect myconnect Constructor event long ll_rc myconnect = create n_jagclnt_connect ll_rc = myconnect.ConnectToServer() ll_rv = myconnect.CreateInstance(iuo_employee, & "uo_employee")
The shared object has a single function called RetrieveData that makes a synchronous call to the RetrieveData function on the EAServer component.
1077
SharedObjectGet
When the function completes processing, it calls the Notify function on the callback object, passing it the DataWindow blob returned from the server component:
blob lblb_data long ll_rv ll_rv = iuo_employee.retrievedata(lblb_data) auo_callback.notify(lblb_data) return ll_rv
When the EAServer component has finished processing, the shared object notifies a user object called uo_callback, which in turns notifies the w_employee window. The uo_callback object has two functions, Notify and PassObject.The Notify function calls a function called SetDW on the w_employee window, passing it the DataWindow blob returned from the server component:
long ll_rv ll_rv = iw_employee.setdw(ablb_data) if ll_rv = -1 then MessageBox("Error", "SetDW call failed!") end if return ll_rv
The callback handlers PassObject function caches a reference to the w_employee window in the iw_employee instance variable. The function takes the argument aw_employee, which is of type w_employee, and returns a long value:
iw_employee = aw_employee return 1
The EAServer component is a PowerBuilder user object called uo_employee. The uo_employee object has a function called RetrieveData that uses a DataStore to retrieve employee rows from the database:
// instance variables // protected TransactionServer txnsrv // protected DataStore ids_datastore long ll_rv ll_rv = ids_datastore.Retrieve() ll_rv = ids_datastore.GetFullState(ablb_data) txnsrv.SetComplete() return ll_rv See also
SharedObjectRegister SharedObjectUnregister GetFullState and SetFullState methods for DataWindows in the DataWindow Reference or the online Help
1078
PowerBuilder
CHAPTER 10
PowerScript Functions
SharedObjectRegister
Description
Registers a user object so that it can be shared. This function was used primarily in distributed PowerBuilder applications.
Syntax
SharedObjectRegister ( classname , instancename ) Argument classname instancename Description The name of the user object that you want to share A string whose value is the name you want to assign to the shared object instance
Return value
ErrorReturn. Returns one of the following values: Success! The function succeeded SharedObjectExistsError! The instance name has already been used SharedObjectCreateInstanceError! The object could not be created SharedObjectCreatePBSessionError! The shared object session could not be created
Usage
When you call the SharedObjectRegister function, PowerBuilder opens a separate runtime session for the shared object and creates the shared object. The name you specify for the object instance provides a way for you to access the object instance with the SharedObjectGet function. You can use a shared object on a PowerBuilder client to simulate an asynchronous call to EAServer. For more information, see the description of the SharedObjectGet function.
Examples
In this example, the user object uo_customers is registered so that it can be shared. The name assigned to the shared object instance is share1. After registering the object, the application uses the SharedObjectGet function to store an instance of the object in an object variable:
SharedObjectRegister("uo_customers", "share1") SharedObjectGet("share1",shared_object)
See also
SharedObjectGet SharedObjectUnregister
1079
SharedObjectUnregister
SharedObjectUnregister
Description
Unregisters a user object that was previously registered. This function was used primarily in distributed PowerBuilder applications.
Syntax
SharedObjectUnregister ( instancename ) Argument instancename Description The name assigned to the shared object instance when it was first registered
Return value
ErrorReturn. Returns one of the following values: Success! The function succeeded SharedObjectNotExistsError! The instance name has not been registered
Usage
This function marks a shared object for destruction. But the object is not actually destroyed until there are no more references to the object. You can use a shared object on a PowerBuilder client to simulate an asynchronous call to EAServer. For more information, see the description of the SharedObjectGet function.
Examples
In this example the application unregisters the object instance called share1:
SharedObjectUnregister("share1")
See also
SharedObjectRegister
1080
PowerBuilder
CHAPTER 10
PowerScript Functions
Show
Description Applies to Syntax
Makes an object or control visible, if it is hidden. If the object is already visible, Show brings it to the top. Any object
objectname.Show ( ) Argument objectname Description The name of the object or control you want to make visible (show)
Integer. Returns 1 if it succeeds and -1 if an error occurs. If objectname is NULL, Show returns NULL.
If the specified object is a window that is not open, an execution error occurs. You cannot use Show to show a drop-down or cascading menu, or any menu that has an MDI frame window as its parent window.
Equivalent syntax calling Show:
objectname.Visible = TRUE
This statement:
m_status.m_options.Visible = TRUE
is equivalent to:
m_status.m_options.Show() Examples
This statement makes visible the menu selection called m_options on the menu m_status:
m_status.m_options.Show()
Hide
1081
ShowHeadFoot
ShowHeadFoot
Description Applies to Syntax
Displays the panels for editing the header and footer in a RichTextEdit control or hides the panels and returns to editing the main text. RichTextEdit controls and DataWindow controls with the RichTextEdit presentation style
rtename.ShowHeadFoot ( editheadfoot ) Argument rtename editheadfoot Description The name of the RichTextEdit or DataWindow control for which you want to edit header and footer information. A boolean value specifying the editing panel to display. Values are: TRUE Display the header and footer editing panels FALSE Display the detail editing panel for the document body
Integer. Returns 1 if it succeeds and -1 if an error occurs. ShowHeadFoot takes effect when the control is in preview mode or when it is
in edit mode for the main text. If the control is in preview mode, calling
ShowHeadFoot returns to edit mode. The value of editheadfoot determines
whether the main text or the header and footer panels display. The header and footer can include input fields for page numbers and dates. Scripts for the PrintHeader and PrintFooter events can provide values for these fields. For a DataWindow control, ShowHeadFoot has no effect if the DataWindow object does not have the RichTextEdit presentation style.
Examples
This example displays the header and footer editing panels, allowing the user to specify their contents:
rte_1.ShowHeadFoot(TRUE)
See also
Preview
1082
PowerBuilder
CHAPTER 10
PowerScript Functions
ShowHelp
Description
Provides access to a Microsoft Windows-based Help system or to compiled HTML Help files that you have created for your PowerBuilder application. When you call ShowHelp, PowerBuilder starts the Help executable and displays the Help file you specify.
ShowHelp ( helpfile, helpcommand {, typeid } ) Argument helpfile helpcommand Description A string whose value is the name of the compiled HLP file or the CHM (HTML Help) file. A value of the HelpCommand enumerated type. Values are: Finder!Displays the Help file in its most recently used state (the Help Topics dialog box in WinHelp or the Navigator pane in the HTML Help viewer open to the lastused tab or the default tab for the Help file). Index! Displays the top-level contents topic in the Help file. Keyword! Goes to the topic identified by the keyword in typeid. Topic! Displays the topic identified by the number in typeid. typeid (optional) A number identifying the topic if helpcommand is Topic! or a string whose value is a keyword of a help topic if helpcommand is Keyword!. Do not specify typeid when helpcommand is Finder! or Index!.
Syntax
Return value
if you specify typeid when helpcommand is Finder! or Index!. If any arguments value is NULL, ShowHelp returns NULL.
Usage
To provide context-sensitive Help, use ShowHelp in appropriate scripts throughout your application with specific topic IDs or keywords. If you specify Keyword! for helpcommand and the string in typeid is not unique, the Help Search window displays. For information on how to create online Help files for your PowerBuilder application, see the chapter on providing online Help in PowerBuilder Application Techniques.
1083
ShowHelp
Examples
This statement displays Help topic 143 in the file EMP.HLP file:
ShowHelp("EMP.HLP", Topic!, 143)
This statement displays the Help topic associated with the keyword Part# in the file EMP.HLP:
ShowHelp("EMP.HLP", Keyword!, "Part#")
This statement displays the Help search window. The word in the box above the keyword list is the first keyword that begins with M:
ShowHelp("EMP.HLP", Keyword!, "M") See also
Help ShowPopupHelp
1084
PowerBuilder
CHAPTER 10
PowerScript Functions
ShowPopupHelp
Description Applies to Syntax
A typical location for the ShowPopupHelp call is in the Help event of a response window with the Context Help property enabled. Events relating to movement of the cursor over a control or to the dragging of a control or object are also logical places for a ShowPopupHelp call. You must type a correct context ID number for the contextid argument or you get a message that a Help topic does not exist for the item calling the ShowPopupHelp function.
Examples
See also
Help ShowHelp
1085
Sign
Sign
Description Syntax
Integer. Returns a number (-1, 0, or 1) indicating the sign of n. If n is NULL, Sign returns NULL.
1086
PowerBuilder
CHAPTER 10
PowerScript Functions
SignalError
Description Syntax
Integer. Returns 1 if it succeeds and -1 if an error occurs. The return value is usually not used.
During development you can use SignalError to test error-processing scripts.You can call PopulateError to populate the Error object and call SignalError without arguments. You can examine how the SystemError event script handles the forced error. If you pass the optional number and text arguments to SignalError, it populates all the fields in the Error object and then triggers a SystemError event. In an application, SignalError can also be useful. For example, if a user error is so severe that you do not want the application to continue, you can set values in the Error object, including your own error number, and call SignalError. You need to include code in the SystemError event script to recognize and handle the error you have created.If there is no script for the SystemError event, the SignalError function does nothing. For the execution-time error numbers assigned to the Number property of the Error object when an application error occurs, see the PowerBuilder Users Guide.
Examples
These statements set values in the Error object and then trigger a SystemError event so the error processing for these values can be tested:
int error_number string error_text Error.Number = 1010 Error.Text = "Salary must be a positive number." Error.Windowmenu = "w_emp" error_number = Error.Number error_text = Error.Text SignalError(error_number, error_text)
See also
PopulateError
1087
Sin
Sin
Description Syntax
ASin Cos Pi Tan Sin method for DataWindows in the DataWindow Reference or the online Help
Sleep
Description Syntax
1088
PowerBuilder
CHAPTER 10
PowerScript Functions
Sort
Sorts rows in a DataWindow control, DataStore, or child DataWindow, or items in a TreeView or ListView control. For syntax for DataWindows and DataStores, see the Sort method for DataWindows in the DataWindow Reference or the online Help.
To sort Items in a TreeView Items in a ListView Use Syntax 1 Syntax 2
Syntax 1
Description Applies to Syntax
The Sort function only sorts the immediate level beneath the specified item. If you want to sort multiple levels, use SortAll. If you specify UserDefinedSort! as your sorttype, define your sort criteria in the Sort event of the TreeView control. The Sort function cannot sort level 1 of a TreeView. However, level 1 is sorted automatically when the TreeViews SortType property calls for sorting. This example sorts the children of the current TreeView item:
long ll_tvi ll_tvi = tv_foo.FindItem(CurrentTreeItem! , 0) tv_foo.SetRedraw(false) tv_foo.Sort(ll_tvi , Ascending!) tv_foo.SetRedraw(true)
Examples
See also
SortAll
1089
Sort
Syntax 2
Description Applies to Syntax
The default sort is alphanumeric. If you do not specify a column to sort, the first column is sorted.
Examples
See also
SortAll
1090
PowerBuilder
CHAPTER 10
PowerScript Functions
SortAll
Description Applies to Syntax
Sorts all the levels below an item in the TreeView item hierarchy. TreeView controls
treeviewname.SortAll ( itemhandle, sorttype ) Argument treeviewname itemhandle sorttype Description The TreeView control in which you want to sort the subsequent levels in an items hierarchy. The item for which you want to sort all the levels below it. The sort method you want to use. Values are: Ascending! Descending! Unsorted! UserDefinedSort!
If you specify UserDefinedSort! as your sorttype, define your sort criteria in the Sort event of the TreeView control. The SortAll function cannot sort level 1 of a TreeView. However, level 1 is sorted automatically when the TreeViews SortType property calls for sorting.
Examples
This example sorts the subsequent levels recursively under the current TreeView item:
long ll_tvi //Find the current treeitem ll_tvi = tv_list.FindItem(CurrentTreeItem! , 0) //Sort all children tv_list.SortAll(ll_tvi , Ascending!)
Sort
1091
Space
Space
Description Syntax
String. Returns a string filled with n spaces if it succeeds and the empty string ("") if an error occurs. If n is NULL, Space returns NULL.
Fill
Space method for DataWindows in the DataWindow Reference or online Help
1092
PowerBuilder
CHAPTER 10
PowerScript Functions
Sqrt
Description Syntax
Double. Returns the square root of n. If n is NULL, Sqrt returns NULL. Sqrt(n) is the same as n^.5.
1093
Start
Start
Start has two basic syntaxes.
To Execute a pipeline object Activate a timing object Use Syntax 1 Syntax 2
Syntax 1
Description
Applies to Syntax
Return value
values are: -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 Pipe open failed Too many columns Table already exists Table does not exist Missing connection Wrong arguments Column mismatch Fatal SQL error in source Fatal SQL error in destination Maximum number of errors exceeded
1094
PowerBuilder
CHAPTER 10
PowerScript Functions
Bad table syntax Key required but not supplied Pipe already in progress Error in source database Error in destination database Destination database is read-only
A pipeline transfer involves several PowerBuilder objects. You need: A pipeline object, which you define in the Data Pipeline painter. It contains the SQL statements that specify what data is transferred and how that data is mapped from the tables in the source database to those in the target database. A user object inherited from the pipeline system object. It inherits properties that let you check the progress of the pipeline transfer. In the painter, you define instance variables and write scripts for pipeline events. A window that contains a DataWindow control or a Data Store for the pipeline-error DataWindow. Do not put a DataWindow object in the DataWindow control. The control displays PowerBuilders pipeline-error DataWindow object if errors occur when the pipeline executes.
The window can also include buttons, menus, or some other means to execute the pipeline, repair errors, and cancel the execution. The scripts for these actions use the functions Start, Repair, and Cancel. Before the application executes the pipeline, it needs to connect to the source and destination databases, create an instance of the user object, and assign the pipeline object to the user objects DataObject property. Then it can call Start to execute the pipeline. This code may be in one or several scripts. When you execute the pipeline, the piped data is committed according to the settings you make in the Data Pipeline painter. You can specify that: The data is committed when the pipeline finishes. If the maximum error limit is exceeded, all data is rolled back. Data is committed at regular intervals, after a specified number of rows have been transferred. When the maximum error limit is exceeded, all rows already transferred are committed.
For information about specifying the pipeline object in the Data Pipeline painter and how the settings affect committing, see the PowerBuilder Users Guide. For more information on using a pipeline in an application, see Application Techniques.
1095
Start
When you dynamically assign the pipeline object to the user objects DataObject property, you must remember to include the pipeline object in a dynamic library when you build your applications executable.
Examples
The following script creates an instance of the pipeline user object, assigns a pipeline object to the pipeline user objects DataObject property, and executes the pipeline. I_src and i_dst are transaction objects that have been previously declared and created. Another script has established the database connections.
U_pipe is the user object inherited from the pipeline system object. I_upipe is an instance variable of type u_pipe. P_pipe is a pipeline object created in the Data Pipeline painter:
i_upipe = CREATE u_pipe i_upipe.DataObject = "p_pipe" i_upipe.Start(i_src, i_dst, dw_1) See also
Cancel Repair
Syntax 2
Description Applies to Syntax
interval specified is invalid, or there are no system timers available. This syntax of the Start function is used to activate a nonvisual timing object. Timing objects can be used to trigger a Timer event that is not associated with a PowerBuilder window, and they are therefore useful for distributed PowerBuilder servers or shared objects that do not have a window for each client connection.
1096
PowerBuilder
CHAPTER 10
PowerScript Functions
A timing object is a standard class user object inherited from the Timing system object. Once you have created a timing object and coded its timer event, you can create any number of instances of the object within the constraints of your operating system. An operating system supports a fixed number of timers. Some of those timers will already be in use by PowerBuilder and other applications and by the operating system itself. To activate an instance of the timing object, call the Start function, specifying the interval that you want between Timer events. The Timer event of that instance is triggered as soon as possible after the specified interval, and will continue to be triggered until you call the Stop function on that instance of the timing object or the object is destroyed.
When the Timer event occurs The interval specified for the Start function is the minimum interval between
Timer events. All other posted events occur before the Timer event. The resolution of the interval depends on your operating system. You can determine what the timing interval is and whether a timer is running by accessing the timing objects Interval and Running properties. These properties are read-only. You must stop and restart a timer in order to change the value of the timing interval.
Garbage collection
If a timing object is running, it is not subject to garbage collection. Garbage collection can occur only if the timing object is not running and there are no references to it.
Examples Example 1 Suppose you have a distributed application in which the local client performs some processing, such as calculating the value of a stock portfolio, based on values in a database. The client requests a user object on a remote server to retrieve the data values from the database.
Create a standard class user object on the server called uo_timer, inherited from the Timing system object, and code its Timer event to refresh the data. Then the following code creates an instance, MyTimer, of the timing object uo_timer. The Start function activates the timer with an interval of 60 seconds so that the request to the server is issued at 60-second intervals:
uo_timer MyTimer MyTimer = CREATE uo_timer MyTimer.Start(60)
1097
Start
Example 2
The following example uses a timing object as a shared object in a window that has buttons for starting a timer, getting a hit count, stopping the timer, and closing the window. Status is shown in a single line edit called sle_state. The timing object, uo_timing, is a standard class user object inherited from the Timing system object. It has one instance variable that holds the number of times a connection is made:
long il_hits
RETURN il_hits
il_hits = 0
When the main window (w_timer) opens, its Open event script registers the uo_timing user object as a shared object:
ErrorReturn result string ls_result SharedObjectRegister("uo_timing","Timing") result = SharedObjectGet("Timing", iuo_timing) // convert enumerated type to string ls_result = of_converterror(result) IF result = Success! THEN sle_stat.text = "Object Registered"
1098
PowerBuilder
CHAPTER 10
PowerScript Functions
ELSE MessageBox("Failed", "SharedObjectGet failed, " & + "Status code: "+ls_result) END IF
The Start Timer button starts the timer with an interval of five seconds:
double ld_interval integer li_err IF (isvalid(iuo_timing)) THEN li_err = iuo_timing.Start(5) ld_interval = iuo_timing.interval sle_2.text = "Timer started. Interval is " & + string(ld_interval) + " seconds" // disable Start Timer button THIS.enabled = FALSE ELSE sle_2.text = "No timing object" END IF
The Get Hits button calls the of_hitcount function and writes the result in a single line edit:
long ll_hits IF (isvalid(iuo_timing)) THEN ll_hits = iuo_timing.of_hitcount() sle_hits.text = string(ll_hits) ELSE sle_hits.text = "" sle_stat.text = "Invalid timing object..." END IF
The Stop Timer button stops the timer, reenables the Start Timer button, and resets the hit counter:
integer li_err IF (isvalid(iuo_timing)) THEN li_err = iuo_timing.Stop() IF li_err = 1 THEN sle_stat.text = "Timer stopped" cb_start.enabled = TRUE iuo_timing.of_resetcounter() ELSE sle_stat.text = "Error - timer could " &
1099
Start
The Close button checks that the timer has been stopped and closes the window if it has:
IF iuo_timing.running = TRUE THEN MessageBox("Error","Click the Stop Timer " & + "button to clean up before closing") ELSE close(parent) END IF
The Close event for the window unregisters the shared timing object:
SharedObjectUnregister("Timing")
The of_converterror window function converts the ErrorReturn enumerated type to a string. It takes an argument of type ErrorReturn:
string ls_result CHOOSE CASE a_error CASE Success! ls_result = "The function succeeded" CASE FeatureNotSupportedError! ls_result = "Not supported on this platform" CASE SharedObjectExistsError! ls_result = "Instance name already used" CASE MutexCreateError! ls_result = "Locking mechanism unobtainable" CASE SharedObjectCreateInstanceError! ls_result = "Object could not be created" CASE SharedObjectCreatePBSessionError! ls_result = "Could not create context session" CASE SharedObjectNotExistsError! ls_result = "Instance name not registered" CASE ELSE ls_result = "Unknown Error Code" END CHOOSE RETURN ls_result See also
Stop
1100
PowerBuilder
CHAPTER 10
PowerScript Functions
StartHotLink
Description
Establishes a hot link with a DDE server application so that PowerBuilder is notified immediately of any changes in the specified data. When the data changes in the server application, it triggers a HotLinkAlarm event in the current application.
StartHotLink ( location, applname, topic ) Argument location Description A string whose value is the location of the data in which a change of value triggers a HotLinkAlarm event. The format of the location depends on the application that contains the data. A string whose value is the DDE name of the server application. A string identifying the data or the instance of the application in which a change triggers a HotLinkAlarm event (for example, in Microsoft Excel, the topic name could be the name of an open spreadsheet).
Syntax
applname topic
Return value
After establishing a hot link, you can include the following functions in the HotLinkAlarm event:
GetDataDDEOrigin To determine what application sent the notification
of changed data
GetDataDDE To obtain the new data RespondRemote To acknowledge receipt of the data
Examples
In this example, another PowerBuilder application has called the StartServerDDE function and identified itself as MyPBApp. This statement in your application establishes a hot link to data in MyPBApp. The values you specify for location and topic depend on conventions established by MyPBApp:
StartHotLink("Any", "MyPBApp", "Any")
1101
StartHotLink
This statement establishes a hot link with Microsoft Excel, which notifies the PowerBuilder window when the data at row 1 column 2 of REGION.XLS changes:
StartHotLink("R1C2", "Excel", "Region.XLS") See also
StopHotLink
1102
PowerBuilder
CHAPTER 10
PowerScript Functions
StartServerDDE
Description Syntax
Establishes your application as a DDE server. You specify the DDE name, topic, and items that you support.
StartServerDDE ( { windowname, } applname, topic {, item } ) Argument windowname (optional) applname topic item (optional) Description The name of the server window. The default is the current window. The DDE name for your application. A string whose value is the basic data grouping the DDE client application references. A comma-separated list of one or more strings (data within topic) that specify what your DDE server application supports (for example, "Table1","Table2").
Return value
meaning the your application is already started as a server. If any arguments value is NULL, StartServerDDE returns NULL.
Usage
When a DDE client application sends a DDE request, the request includes one of the items you have declared that you support. You determine how your application responds to each of those items. A window must be open to provide a handle for the DDE conversation. You cannot call StartServerDDE and other DDE functions in an application objects events. When your application has established itself as a DDE server, other applications can send DDE requests that trigger these events in your application.
Table 10-8: Events triggered by DDE requests and DDE functions available to each event
Client action Sends a request for a hot link Sends a command to your application
Purpose of function Obtain the command Find out what client application sent the command Obtain the data Find out what client application sent the data
Sends data
RemoteSend
GetDataDDE GetDataDDEOrigin
1103
StartServerDDE
Client action Requests data from your server application Wants to terminate the hot link Examples
This statement causes your PowerBuilder application to begin acting as a server. It is known to other DDE applications as MyPBApp; its topic is System, and it supports items called Table1 and Table2:
StartServerDDE(w_emp, "MyPBApp","System", & "Table1", "Table2")
See also
StopServerDDE
1104
PowerBuilder
CHAPTER 10
PowerScript Functions
State
Description Applies to Syntax
Determines whether an item in a ListBox control is highlighted. ListBox and PictureListBox controls
listboxname.State ( index ) Argument listboxname Description The name of the ListBox or PictureListBox in which you want to obtain the state (highlighted or not highlighted) of the item identified by index The number of the item for which you want to obtain the state
Integer. Returns 1 if the item in listboxname identified by index is highlighted and 0 if it is not. If the index does not point to a valid item number, State returns -1. If any arguments value is NULL, State returns NULL.
Usage
The State and SetState functions are meant for a ListBox that allows multiple selections (its MultiSelect property is TRUE). To find all of a lists selected items, loop through the list, checking the state of each item. The SelectedItem and SelectItem functions are meant for single-selection ListBox controls. SelectedItem reports the selection directly with no need for looping. In a multiple-selection ListBox control, SelectedItem reports the first selected item only. When you know the index of an item, you can use the Text function to get the items text.
Examples
The following statements obtain the text of all the selected items in a ListBox that allows the user to select more than one item. The MessageBox function displays each item as it is found. You could include other processing that created an array or list of the selected values:
integer li_ItemTotal, li_ItemCount // Get the number of items in the ListBox. li_ItemTotal = lb_contact.TotalItems( )
1105
State
// Loop through all the items. FOR li_ItemCount = 1 to li_ItemTotal // Is the item selected? If so, display the text IF lb_Contact.State(li_ItemCount) = 1 THEN & MessageBox("Selected Item", & lb_Contact.text(li_ItemCount)) NEXT
This statement executes some statements if item 3 in the ListBox lb_Contact is highlighted:
IF lb_Contact.State(3) = 1 THEN ... See also
SelectedItem SetState
1106
PowerBuilder
CHAPTER 10
PowerScript Functions
StepIt
Description Applies to Syntax
Increments the current position in a progress bar control by the value specified in the SetStep property of the control. Progress bar controls
control.StepIt ( ) Argument control Description The name of the progress bar
Integer. Returns 1 if it succeeds and -1 if there is an error. StepIt causes the position in a progress bar to wrap if the value of the SetStep takes the current position out of range. For example, if the SetStep value is 40, the current position 80, and the range is set from 0 to 100, the position on the redrawn progress bar after you call StepIt is 20.
The SetStep property can have a negative value. The default value for SetStep is 10.
Examples
See also
SetRange
Stop
Description Applies to Syntax
Integer. Returns 1 if it succeeds and -1 if the timer is not running or could not be stopped.
Use this function to deactivate a timing object. A stopped timer can be reactivated with the Start function. This statement stops the timing object instance MyTimer:
MyTimer.Stop()
See also
Start
1107
StopHotLink
StopHotLink
Description
applname topic
Return value
Integer. Returns 1 if it succeeds. If an error occurs, StopHotLink returns a negative integer. Values are:
-1 -2 -3
Link was not started Request denied Could not terminate server
If another PowerBuilder application called StartServerDDE to establish itself as a server using the name MyPBApp, then your application can act as a DDE client and call StartHotLink to establish a hot link with MyPBApp. The following statement ends that hot link. The values you specify for location and topic depend on conventions established by MyPBApp:
StopHotLink("Any", "MyPBApp", "Any")
This statement stops the hot link with Microsoft Excel for row 1 column 2 in the spreadsheet REGION.XLS:
StopHotLink("R1C2", "Excel", "Region.XLS") See also
StartHotLink
1108
PowerBuilder
CHAPTER 10
PowerScript Functions
StopServerDDE
Description Syntax
Causes your application to stop acting as a DDE server application. Any subsequent requests from a DDE client application fail.
StopServerDDE ( { windowname, } applname, topic ) Argument windowname (optional) applname topic Description The name of the server window. The default is the current window. If you have more than one server window, windowname is required. The DDE name for your PowerBuilder application. A string whose value is the topic you declared when you called StartServerDDE.
Return value
Integer. Returns 1 if it succeeds. If an error occurs, StopServerDDE returns -1, meaning the DDE server was not started. If any arguments value is NULL, StopServerDDE returns NULL.
Caution
The arguments applname and topic must match the arguments in a prior StartServerDDE call.
Examples
This statement causes the PowerBuilder application MyPBApp to stop acting as a server:
StopServerDDE(w_emp, "MyPBApp", "System")
See also
StartServerDDE
1109
String
String
String has two syntaxes.
To Format data as a string according to a specified display format mask Convert a blob to a string
Syntax 1
Description
Syntax
format (optional)
Return value
String. Returns data in the specified format if it succeeds and the empty string ("") if the datatype of data does not match the type of display mask specified, format is not a valid mask, or data is an incompatible datatype.
Usage
For date, DateTime, numeric, and time data, PowerBuilder uses the systems default format for the returned string if you do not specify a format. For numeric data, the default format is the [General] format. For string data, a display format mask is required. (Otherwise, the function would have nothing to do.) The format can consist of one or more masks: Formats for date, DateTime, string, and time data can include one or two masks. The first mask is the format for the data; the second mask is the format for a null value.
1110
PowerBuilder
CHAPTER 10
PowerScript Functions
Formats for numeric data can have up to four masks. A format with a single mask handles both positive and negative data. If there are additional masks, the first mask is for positive values, and the additional masks are for negative, zero, and NULL values.
To display additional characters as part of the mask for a decimal value, you must precede each character with a backslash. For example, to display a decimal number with two digits of precision preceded by four asterisks, you must type a backslash before each asterisk:
dec{2} amount string = ls_result amount = 123456.32 ls_result = string(amount,"\*\*\*\*0.00")
The resulting string is ****123456.32. For more information on specifying display formats, see the PowerBuilder Users Guide. Note that, although a format can include color specifications, the colors are ignored when you use String in PowerScript. Colors appear only for display formats specified in the DataWindow painter. If the display format does not match the datatype, PowerBuilder tries to apply the mask, which can produce unpredictable results.
Times and dates from a DataWindow control When you call GetItemTime or GetItemString as an argument for the String
function and do not specify a display format, the value is formatted as a DateTime value. This statement returns a string like "2/26/03 00:00:00":
String(dw_1.GetItemTime(1, "start_date")) International deployment When you use String to format a date and the month is displayed as text (for example, the display format includes "mmm"), the month is in the language of the runtime DLLs available when the application is run. If you have installed localized runtime files in the development environment or on a users machine, then on that machine, the month in the resulting string is in the language of the localized files.
For information about the localized runtime files, which are available in French, German, Italian, Spanish, Dutch, Danish, Norwegian, and Swedish, see the chapter on internationalization in Application Techniques.
Message object You can also use String to extract a string from the Message object after calling TriggerEvent or PostEvent. For more information, see the TriggerEvent or PostEvent functions.
1111
String
Examples
This statement applies a display format to a date value and returns Jan 31,
2002: String(2002-01-31, "mmm dd, yyyy")
This example applies a format to the value in order_date and sets date1 to 6-11-02:
Date order_date = 2002-06-11 string date1 date1 = String(order_date,"m-d-yy")
This example includes a format for a NULL date value so that when order_date is NULL, date1 is set to none:
Date order_date = 2002-06-11 string date1 SetNull(order_date) date1 = String(order_date, "m-d-yy;none")
This statement applies a format to a DateTime value and returns Jan 31, 2001 6 hrs and 8 min:
String(DateTime(2001-01-31, 06:08:00), & mmm dd, yyyy h "hrs and" m "min")
This example builds a DateTime value from the system date and time using the Today and Now functions. The String function applies formatting and sets the text of sle_date to that value, for example, 6-11-02 8:06 pm:
DateTime sys_datetime string datetime1 sys_datetime = DateTime(Today(), Now()) sle_date.text = String(sys_datetime, & "m-d-yy h:mm am/pm;none")
1112
PowerBuilder
CHAPTER 10
PowerScript Functions
This statement formats string data and returns A-B-C. The display format assigns a character in the source string to each @ and inserts other characters in the format at the appropriate positions:
String("ABC", "@-@-@")
This statement applies a display format to time data and returns 6 hrs and 8 min:
String(06:08:02,h "hrs and" m "min")
Syntax 2
Description Syntax
For blobs
Converts data in a blob to a string value. If the blobs value is not text data, String attempts to interpret the data as characters.
String ( blob )
1113
String
Argument blob
Description The blob whose value you want returned as a string. Blob can also be an Any variable containing a blob.
Return value
String. Returns the value of blob as a string if it succeeds and the empty string ("") if it fails. It the blob does not contain string data, String interprets the data as characters, if possible, and returns a string. If blob is NULL, String returns NULL.
Usage
You can also use String to extract a string from the Message object after calling TriggerEvent or PostEvent. For more information, see the TriggerEvent or PostEvent functions. This example converts the blob instance variable ib_sblob, which contains string data, to a string and stores the result in sstr:
string sstr sstr = String(ib_sblob)
Examples
This example stores todays date and test status information in the blob bb. Pos1 and pos2 store the beginning and end of the status text in the blob. Finally, BlobMid extracts a "sub-blob" that String converts to a string. Sle_status displays the returned status text:
blob{100} bb long pos1, pos2 string test_status date test_date test_date = Today() IF DayName(test_date) = "Wednesday" THEN & test_status = "Coolant Test" IF DayName(test_date) = "Thursday" THEN & test_status = "Emissions Test" // Store data in the blob pos1 = BlobEdit( bb, 1, test_date) pos2 = BlobEdit( bb, pos1, test_status ) ... // Some processing // Extract the status stored in bb and display it sle_status.text = String( & BlobMid(bb, pos1, pos2 - pos1)) See also
String method for DataWindows in the DataWindow Reference or online Help
1114
PowerBuilder
CHAPTER 10
PowerScript Functions
String_To_Object
Description
Gets an object reference based on a passed string. This function is used by PowerBuilder clients connecting to EAServer.
Applies to Syntax
JaguarORB objects
jaguarorb.String_To_Object ( objstring , object) Argument jaguarorb objstring Description An instance of JaguarORB. A string that represents a CORBA object. The string representation of a CORBA object is an Interoperable Object Reference (IOR) that describes how to connect to the server hosting the object. EAServer supports both standard format IORs (which are hex-encoded) and a URL format that is human-readable. A variable of type CORBAobject that will contain the object reference.
object
The String_To_Object function allows you to instantiate a proxy instance without using the Jaguar naming service.
Connecting to EJB components
In PowerBuilder 7 and earlier releases, the JaguarORB String_To_Object function was used to access EJB components in EAServer. In PowerBuilder 8 and later, the Lookup function on the Connection object can be used to instantiate a proxy for the home interface of an EJB component in EAServer. In PowerBuilder 9, the Lookup function on the EJBConnection PowerBuilder extension object can be used to instantiate proxies for EJB components running in any J2EE-compliant server. When you use String_To_Object for proxy instantiation, you instantiate the object directly. The disadvantage of this approach is that you lose the benefits of server address abstraction that are provided by the naming service. To use the naming service API explicitly, you can use the Resolve_Initial_References function to obtain an initial naming context. However, this technique is not recommended because it requires use of deprecated SessionManager::Factory methods. For more information about connecting to EAServer using the JaguarORB object, see Application Techniques.
1115
String_To_Object
The String_To_Object can be used to obtain an EAServer authentication manager instance by using a URL format IOR. IOR strings in URL format must have the form:
protocol : // host : iiop_port
where: protocol is iiops if connecting to a secure port and iiop otherwise host is the EAServer host address or machine name iiop_port is the port number for IIOP requests
If the server is part of a cluster, the objstring argument can contain a list of IORs separated by semicolons. After calling String_To_Object, you can use the Manager interface to obtain an instance of the Session interface, which allows you to create component instances. When you use the Manager and Session interfaces, you need to generate proxies for these interfaces and include these proxies in the library list for the client. For information about methods on these interfaces, see the interface repository documentation at the URL http://yourhost:yourport/ir/, where yourhost is the server's host name and yourport is the HTTP port number. The String_To_Object function can also be used to deserialize a Proxy object reference. By serializing an object reference, you can save the state of the object so that it persists after the client terminates processing. Deserializing the object reference gets an object reference from a serialized string. String_To_Object is often used in conjunction with Object_To_String, which allows you to serialize an object reference.
Examples
The following example shows the use of the String_To_Object function to obtain an EAServer authentication manager instance. The function uses a URL format IOR:
JaguarORB my_orb CORBAObject my_corbaobj Manager my_manager Session my_session Factory my_Factory n_Bank_Account my_account my_orb = CREATE JaguarORB my_orb.init("ORBRetryCount=3,ORBRetryDelay=1000")
1116
PowerBuilder
CHAPTER 10
PowerScript Functions
my_orb.String_To_Object("iiop://myhost:9000", & my_corbaobj) my_corbaobj._narrow(my_manager, & "SessionManager/Manager") my_session = my_manager.createSession("jagadmin", "") my_corbaobj = my_session.lookup("Bank/n_Bank_Account") my_corbaobj._narrow(my_Factory, "SessionManager/Factory") my_corbaobj = my_Factory.create() my_corbaobj._narrow(my_account,"Bank/n_Bank_Account") my_account.withdraw(100.0)
In this example, the component is an EJB component. When the _Narrow function is called to convert the object reference returned from the Lookup call on the Session object, the second argument includes the domain name as well as the package name. This is necessary if the Java package name uses the domainname.packagename format:
JaguarORB my_orb CORBAObject my_corbaobj Manager my_mgr Session my_session CartHome my_cartHome Cart my_cart long ll_return my_orb = CREATE JaguarORB my_orb.init("ORBLogFile=c:\temp\orblog") my_orb.String_to_Object("iiop://svr1:9000", & my_corbaObj) my_corbaObj._narrow(my_mgr, "SessionManager/Manager" ) my_Session = my_mgr.createSession("jagadmin", "") my_corbaObj = my_session.lookup("Cart") ll_return = my_corbaObj._narrow(my_CartHome, "com/shopping/CartHome") my_corbaObj = my_CartHome.create() my_Cart.addItem() See also
1117
SuspendTransaction
SuspendTransaction
Description Applies to Syntax
Suspends the EAServer transaction associated with the calling thread. CORBACurrent objects
CORBACurrent.SuspendTransaction ( ) Argument CORBACurrent Description Reference to the CORBACurrent service instance
Unsigned long. Returns a handle that refers to the transaction associated with
the thread or 0 if an error occurs. The SuspendTransaction function returns a handle referring to the transaction associated with the calling thread. This handle can be passed to the ResumeTransaction function on the same or a different thread. When SuspendTransaction is called, the current thread is no longer associated with a transaction.
SuspendTransaction can be called by a client or a component that is marked as
OTS style. EAServer must be using the two-phase commit transaction coordinator (OTS/XA).
Examples
This example shows the use of the SuspendTransaction function to disassociate the calling thread from the current transaction:
// Instance variable: // CORBACurrent corbcurr integer li_rc unsignedlong ll_handle // Get and initialize an instance of CORBACurrent ... li_rc = corbcurr.BeginTransaction() // do some transactional work ll_handle = corbcurr.SuspendTransaction() // do some nontransactional work li_rc = corbcurr.ResumeTransaction(ll_handle) // do some more transactional work li_rc = corbcurr.CommitTransaction()
1118
PowerBuilder
CHAPTER 10
PowerScript Functions
See also
BeginTransaction CommitTransaction GetContextService GetStatus GetTransactionName Init ResumeTransaction RollbackOnly RollbackTransaction SetTimeout
1119
SyntaxFromSQL
SyntaxFromSQL
Description Applies to Syntax
Generates DataWindow source code based on a SQL SELECT statement. Transaction objects
transaction.SyntaxFromSQL ( sqlselect, presentation, err ) Argument transaction sqlselect presentation Description The name of a connected transaction object. A string whose value is a valid SQL SELECT statement. A string whose value is the default presentation style you want for the DataWindow. The simple format is:
Style(Type=presentationstyle)
Values for presentationstyle correspond to the styles in the New DataWindow dialog box in the DataWindow painter. Keywords are: (Default) Tabular
Grid Form (for freeform) Graph Group Label Nup
The Usage section lists the keywords you can use in presentation. err A string variable to which PowerBuilder will assign any error messages that occur.
Return value
String. Returns the empty string ("") if an error occurs. If SyntaxFromSQL fails, err may contain error messages if warnings or soft errors occur (for example, a syntax error). If any arguments value is NULL, SyntaxFromSQL returns NULL.
Usage
To create a DataWindow object, you can pass the source code returned by SyntaxFromSQL directly to the Create function. Table owner in the SQL statement If the value of the LogID property of the Transaction object is not the owner of the table being accessed in the SQL statement for the SyntaxFromSQL function, then the table name in the SQL SELECT statement must be qualified with the owner name.
1120
PowerBuilder
CHAPTER 10
PowerScript Functions
If your DBMS is Adaptive Server Enterprise and you call SyntaxFromSQL, PowerBuilder must determine whether the tables are updatable through a unique index. This is only possible if you set AutoCommit to TRUE before calling SyntaxFromSQL, as shown here:
sqlca.autocommit=TRUE ls_dws=sqlca.syntaxfromsql (sqlstmt, presentation, err) sqlca.autocommit=FALSE
The presentation string can also specify object keywords followed by properties and values to customize the DataWindow. You can specify the style of a column, the entire DataWindow, areas of the DataWindow, and text in the DataWindow. The object keywords are:
Column DataWindow Group Style Text Title
The checklists in the DataWindow object properties chapter in the DataWindow Reference identify the properties that you can use for each object keyword. If a database column has extended attributes with font information, then font information you specify in the SyntaxFromSQL presentation string is ignored.
Examples
The following statements display the DataWindow source for a tabular DataWindow object generated by the SyntaxFromSQL function in a MultiLineEdit. If errors occur, PowerBuilder fills the string ERRORS with any error messages that are generated:
string ERRORS, sql_syntax
1121
SyntaxFromSQL
sql_syntax = "SELECT emp_data.emp_id," & + "emp_data.emp_name FROM emp_data " & + "WHERE emp_data.emp_salary >45000" mle_sql.text = & SQLCA.SyntaxFromSQL(sql_syntax, "", ERRORS)
The following statements create a grid DataWindow dw_1 from the DataWindow source generated in the SyntaxFromSQL function. If errors occur, the string ERRORS contains any error messages that are generated, which are displayed to the user in a message box. Note that you need to call SetTransObject with SQLCA as its argument before you can call the Retrieve function:
string ERRORS, sql_syntax string presentation_str, dwsyntax_str sql_syntax = "SELECT emp_data.emp_id,"& + "emp_data.emp_name FROM emp_data "& + "WHERE emp_data.emp_salary > 45000" presentation_str = "style(type=grid)" dwsyntax_str = SQLCA.SyntaxFromSQL(sql_syntax, & presentation_str, ERRORS) IF Len(ERRORS) > 0 THEN MessageBox("Caution", & "SyntaxFromSQL caused these errors: " + ERRORS) RETURN END IF dw_1.Create( dwsyntax_str, ERRORS) IF Len(ERRORS) > 0 THEN MessageBox("Caution", & "Create cause these errors: " + ERRORS) RETURN END IF See also
Create method for DataWindows in the DataWindow Reference or online Help Information on DataWindow object properties in the DataWindow Reference
1122
PowerBuilder
CHAPTER 10
PowerScript Functions
SystemRoutine
Description Applies to Syntax
Provides the routine node representing the system root in a performance analysis model. Profiling object
instancename.SystemRoutine ( theroutine ) Argument instancename theroutine Description Instance name of the Profiling object. A value of type ProfileRoutine containing the routine node representing the system root. This argument is passed by reference.
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded ModelNotExistsError!The function failed because no model exists
Usage
Use this function to extract the routine node representing the system root in a performance analysis model. You must have previously created the performance analysis model from a trace file using the BuildModel function. The routine node is defined as a ProfileRoutine object and provides the time spent in the routine, any called routines, the number of times each routine was called, and the class to which the routine belongs. This example provides the routine that represents the system root in a performance analysis model:
Profiling lpro_model ProfileRoutine lprort_routine lpro_model.BuildModel() lpro_model.SystemRoutine(lprort_routine) ...
Examples
See also
BuildModel
1123
TabPostEvent
TabPostEvent
Description Applies to Syntax
Posts the specified event for each tab page in a Tab control, adding them to the end of the event queues for the tab page user objects. Tab controls
tabcontrolname.TabPostEvent ( event {, word, long } ) Argument tabcontrolname event Description The name of the Tab control for which you want to post events for its tab page user objects. A value of the TrigEvent enumerated datatype that identifies a PowerBuilder event (for example, Clicked!, Modified!, or DoubleClicked!) or a string whose value is the name of an event. The event must be a valid event for a tab page user object in tabcontrolname and a script must exist for the event in tabcontrolname. A long value to be stored in the WordParm property of the systems Message object. If you want to specify a value for long, but not word, enter 0. (For cross-platform compatibility, WordParm and LongParm are both longs). A long value or a string that you want to store in the LongParm property of the systems Message object. When you specify a string, a pointer to the string is stored in the LongParm property, which you can access with the String function (see Usage for PostEvent).
word (optional)
long (optional)
valid event for the tab page user object, or if a script does not exist for the event. Suppose tab_address contains several tab pages inherited from uo_list and uo_list has a user event called ue_display. This statement posts the event ue_display for each the tab pages in tab_address:
tab_address.TabPostEvent("ue_display") See also
TabTriggerEvent
1124
PowerBuilder
CHAPTER 10
PowerScript Functions
TabTriggerEvent
Description Applies to Syntax
Triggers the specified event for each tab page in a Tab control, which executes the scripts immediately in the index order of the tab pages. Tab controls
tabcontrolname.TabTriggerEvent ( event {, word, long } ) Argument tabcontrolname event Description The name of the Tab control for which you want to trigger events for its tab page user objects. A value of the TrigEvent enumerated datatype that identifies a PowerBuilder event (for example, Clicked!, Modified!, or DoubleClicked!) or a string whose value is the name of an event. The event must be a valid event for a tab page user object in tabcontrolname and a script must exist for the event in tabcontrolname. A long value to be stored in the WordParm property of the systems Message object. If you want to specify a value for long, but not word, enter 0. (For cross-platform compatibility, WordParm and LongParm are both longs). A long value or a string that you want to store in the LongParm property of the systems Message object. When you specify a string, a pointer to the string is stored in the LongParm property, which you can access with the String function (see Usage for TriggerEvent).
word (optional)
long (optional)
Integer. Returns 1 if it succeeds and -1 if an error occurs, if the event is not a valid event for the tab page user object, or if a script does not exist for the event.
Suppose tab_address contains several tab pages inherited from uo_list and uo_list has a user event called ue_display. This statement executes immediately the script for ue_display for each the tab pages in tab_address:
tab_address.TabTriggerEvent("ue_display")
See also
TabPostEvent
1125
Tan
Tan
Description Syntax
Double. Returns the tangent of n. An execution error occurs if n is not valid. If n is NULL, Tan returns NULL.
ATan Cos Pi Sin Tan method for DataWindows in the DataWindow Reference or online Help
1126
PowerBuilder
CHAPTER 10
PowerScript Functions
Text
Description Applies to Syntax
Obtains the text of an item in a ListBox control. ListBox, DropDownListBox, PictureListBox, and DropDownPictureListBox controls
listboxname.Text ( index ) Argument listboxname index Description The name of the ListBox control in which you want the text of an item The number of the item for which you want the text
Return value
String. Returns the text of the item in listboxname identified by index. If the index does not point to a valid item number, Text returns the empty string (""). If any arguments value is NULL, Text returns NULL.
Examples
Assume the ListBox lb_Cities contains: Atlanta Boston Chicago Denver Then these statements store the text of item 3, which is Chicago, in current_city:
string current_city current_city = lb_Cities.Text(3)
See also
1127
TextLine
TextLine
Description Applies to Syntax
Obtains the text of the line that contains the insertion point. TextLine works for controls that can contain multiple lines. DataWindow, EditMask, MultiLineEdit, and RichTextEdit controls
editname.TextLine ( ) Argument editname Description The name of the DataWindow control, EditMask, MultiLineEdit, or RichTextEdit control in which you want the text on the line that contains the insertion point
Return value
String. Returns the text on the line with the insertion point in editname. If an error occurs, TextLine returns the empty string (""). If editname is NULL, TextLine returns NULL.
Usage Examples
If editname is a DataWindow control, then TextLine reports information about the edit control over the current row and column. In the MultiLineEdit mle_state, if the insertion point is on line 4 and its text is North Carolina, then this example sets linetext to North Carolina:
string linetext linetext = mle_state.TextLine()
If the insertion point is on a line whose text is Y in the MultiLineEdit mle_contact, then some processing takes place:
IF mle_contact.TextLine() = "Y" THEN ... See also
SelectedItem SelectTextLine
1128
PowerBuilder
CHAPTER 10
PowerScript Functions
Time
Converts DateTime, string, or numeric data to data of type time. It also extracts a time value from a blob. You can use one of three syntaxes, depending on the datatype of the source data.
To Extract the time from DateTime data, or to extract a time stored in a blob Convert a string to a time Combine numbers for hours, minutes, and seconds into a time value Use Syntax 1 Syntax 2 Syntax 3
Syntax 1
Description Syntax
Return value
Time. Returns the time in datetime as a time. If datetime does not contain a valid time or is an incompatible datatype, Time returns 00:00:00.000000. If datetime is NULL, Time returns NULL.
Examples
After StartDateTime has been retrieved from the database, this example sets StartTime equal to the time in StartDateTime:
DateTime StartDateTime time StartTime ... StartTime = Time(StartDateTime)
Suppose that the value of a blob variable ib_blob contains a DateTime value beginning at byte 32. The following statement extracts the time from the value:
time lt_time lt_time = Time(BlobMid(ib_blob, 32)) See also
Time method for DataWindows in the DataWindow Reference or online Help
1129
Time
Syntax 2
Description Syntax
For strings
Converts a string containing a valid time into a time value.
Time ( string ) Argument string Description A string whose value is a valid time (such as 8am or 10:25) that you want returned as a time. Only the hour is required; you do not have to include the minutes, seconds, or microseconds of the time or am or pm. The default value is 00 for minutes and seconds and 000000 for microseconds. PowerBuilder determines whether the time is am or pm based on a 24-hour clock. String can also be an Any variable containing a string or blob.
Return value
Time. Returns the time in string as a time. If string does not contain a valid time or is an incompatible datatype, Time returns 00:00:00.000000. If string is NULL, Time returns NULL.
Usage Examples
Valid times can include any combination of hours (00 to 23), minutes (00 to 59), seconds (00 to 59), and microseconds (0 to 999999). These statements set What_Time to NULL:
Time What_Time string null_string SetNull(null_string) What_Time = Time(null_string)
This statement returns a time value for 45 seconds before midnight (23:59:15), which is specified as a string:
Time("23:59:15")
This statement converts the text in the SingleLineEdit sle_Time_Received to a time value:
Time(sle_Time_Received.Text) See also
Time method for DataWindows in the DataWindow Reference or online Help
1130
PowerBuilder
CHAPTER 10
PowerScript Functions
Syntax 3
Description Syntax
For integers
Combines integers representing hours, minutes, seconds, and microseconds into a time value.
Time ( hour, minute, second {, microsecond } ) Argument hour minute second microsecond (optional) Description The integer for the hour (00 to 23) of the time The integer for the minutes (00 to 59) of the time The integer for the seconds (0 to 59) of the time The integer for the microseconds (0 to 32767) of the time (note that the range of values supported for this argument is less than the total range of values possible for a microsecond)
Return value
Time. Returns the time as a time datatype and 00:00:00 if the value in any argument is not valid (out of the specified range of values). If any argument is NULL, Time returns NULL.
Examples
These statements set What_Time to a time value with microseconds, and display the resulting time as a string in st_1. The default display format does not include microseconds, so the String function specifies a display format with microseconds. Leading zeros are appended to the string value for microseconds:
Time What_Time What_Time = Time(10, 15, 45, 234) st_1.Text = String(What_Time, "hh:mm:ss:ffffff")
The time in the string variable is set to 10:15:45:000234. These statements set What_Time to 10:15:45:
Time What_Time What_Time = Time(10, 15, 45) See also
Time method for DataWindows in the DataWindow Reference or online Help
1131
Timer
Timer
Description
Causes a Timer event in a window to occur repeatedly at the specified interval. When you call Timer, it starts a timer. When the interval is over, PowerBuilder triggers the Timer event and resets the timer.
Timer ( interval {, windowname } ) Argument interval Description The number of seconds that you want between Timer events. interval can be a whole number or fraction greater than 0 and less than or equal to 4,294,967 seconds. If interval is 0, Timer turns off the timer so that it no longer triggers Timer events. The window in which you want the timer event to be triggered. The window must be an open window. If you do not specify a window, the Timer event occurs in the current window.
Syntax
windowname (optional)
Integer. Returns 1 if succeeds and -1 if an error occurs. If any arguments value is NULL, Timer returns NULL.
Do not call the Timer function in the Timer event. The timer gets reset automatically and the Timer event retrigger sat the interval that has already been established. Call the Timer function in another events script when you want to stop the timer or change the interval. This statement triggers a Timer event every two seconds in the active window:
Timer(2)
Examples
This statement stops the triggering of the Timer event in the active window:
Timer(0)
These statements trigger a Timer event every half second in the window w_Train:
Open(w_Train) Timer(0.5, w_Train)
This example causes the current time to be displayed in a StaticText control in a window. Calling Timer in the windows Open event script starts the timer. The script for the Timer event refreshes the displayed time. In the windows Open event script, the following code displays the time initially and starts the timer:
st_time.Text = String(Now(), "hh:mm") Timer(60)
1132
PowerBuilder
CHAPTER 10
PowerScript Functions
In the windows Timer event, which is triggered every minute, this code displays the current time in the StaticText st_time:
st_time.Text = String(Now(), "hh:mm") See also
Idle
1133
ToAnsi
ToAnsi
Description Syntax
The ToAnsi function converts an ANSI character string to a blob. ToAnsi has the same result as Blob(string).
Unicode file format
Unicode files have two extra bytes at the start of the file to indicate that they are Unicode files. If you are opening a Unicode file in stream mode, skip the first two bytes.
Examples
This example converts a string into an ANSI blob using the ToAnsi function and then writes the blob to a file.
integer li_filenum blob lblb_text string ls_native ls_native = "Sample text in native format" li_filenum = FileOpen("ansi_out.txt", StreamMode!, & Write!, LockWrite!, Replace!) lblb_text = ToAnsi(ls_native) FileWrite(li_filenum, lblb_text) FileClose(li_filenum)
See also
1134
PowerBuilder
CHAPTER 10
PowerScript Functions
Today
Description Syntax Return value Usage
Obtains the system date and, in some cases, the system time.
Today ( )
Date. Returns the current system date.
Although the datatype of the Today function is date, it can also return the current time. This occurs when Today is used as an argument for another function and that argument allows different datatypes. For example, if you call Today as an argument to the String function, String returns both the date and time when you use a date-plus-time display format. A second example: if you call Today as an argument for the SetItem function and the datatype of the target column is DateTime, both the date and time are assigned to the DataWindow.
Examples
This statement executes some statements when the current system date is before April 15, 2003:
IF Today() < 2003-04-15 THEN ...
This statement displays the current date in the StaticText st_date in the corner of a window:
st_date.Text = String(Today(), "m/d/yy")
This statement displays the current date and time in the StaticText st_date:
st_date.Text = String(Today(), "m/d/yy hh:mm") See also
Now
Today method for DataWindows in the DataWindow Reference or online Help
1135
Top
Top
Description Applies to Syntax
Obtains the index number of the first visible item in a ListBox control. Top lets you to find out how the user has scrolled the list. ListBox and PictureListBox controls
listboxname.Top ( ) Argument listboxname Description The name of the ListBox or PictureListBox in which you want the index of the first visible item in the list
Integer. Returns the index of the first visible item in listboxname. Top returns 1 if an error occurs. If listboxname is NULL, Top returns NULL.
The index of a list item is its position in the full list of items, regardless of how many are currently visible in the control. If item 15 has been scrolled to the top of the list in lb_Contacts, then this example sets Num to 15:
integer Num Num = lb_Contacts.Top()
If the user has not scrolled the list in lb_Contacts, then Num is set to 1:
integer Num Num = lb_Contacts.Top()
If the item at the top of the list in lb_Contacts is not the currently selected item, the following statements scroll the currently selected item to the top:
integer Num Num = lb_Contacts.SelectedIndex() IF lb_Contacts.Top() <> Num THEN & lb_contacts.SetTop(Num) See also
SelectedIndex SetTop
1136
PowerBuilder
CHAPTER 10
PowerScript Functions
TotalColumns
Description Applies to Syntax
Use when the ListView control is set to report view. This example displays the number of columns in a ListView report view in a SingleLineEdit:
int li_cols li_cols = lv_list.TotalColumns() sle_info.text = "Total columns = " + string(li_cols)
See also
TotalItems TotalSelected
1137
TotalItems
TotalItems
Description Applies to Syntax
Determines the total number of items in a ListBox control. ListBox, DropDownListBox, PictureListBox, DropDownPictureListBox, and ListView controls
listcontrolname.TotalItems ( ) Argument listcontrolname Description The name of the ListBox, DropDownListBox, PictureListBox, DropDownPictureListBox, or ListView in which you want the total number of items
Return value
Integer. Returns the total number of items in listcontrolname. If listcontrolname contains no items, TotalItems returns 0. If an error occurs, it returns -1. If listcontrolname is NULL, TotalItems returns NULL.
Examples
TotalSelected
1138
PowerBuilder
CHAPTER 10
PowerScript Functions
TotalSelected
Description Applies to Syntax
Determines the number of items in a ListBox control that are selected. ListBox, PictureListBox, and ListView controls
listcontrolname.TotalSelected ( ) Argument listcontrolname Description The name of the ListBox, PictureListBox, or ListView in which you want the number of items that are selected
Return value
Integer. Returns the number of items in listcontrolname that are selected. If no items in listcontrolname are selected, TotalSelected returns 0. If an error occurs, it returns -1. If listcontrolname is NULL, TotalSelected returns NULL. TotalSelected works only if the MultiSelect property of listcontrolname is TRUE.
Usage Examples
These statements in the SelectionChanged event of lb_Actions display a MessageBox if the user tries to select more than three items:
IF lb_Actions.TotalSelected() > 3 THEN MessageBox("Warning", & "You can only select 3 items!") ELSE ... // Some processing END IF See also
TotalItems
1139
ToUnicode
ToUnicode
Description Syntax
Unicode files have two extra bytes at the start of the file to indicate that they are Unicode files.
Examples
This example illustrates the use of the ToUnicode function to convert a string entered in a MultilineEdit control into a Unicode blob:
blob lblb_text string ls_native ls_native = mle_entry.Text lblb_text = ToUnicode(ls_native)
See also
1140
PowerBuilder
CHAPTER 10
PowerScript Functions
TraceBegin
Description
Inserts an activity type value in the trace file indicating that logging has begun and then starts logging all the enabled application trace activities. Before calling TraceBegin, you must have opened the trace file using the TraceOpen function.
TraceBegin ( identifier ) Argument identifier Description A read-only string, logged to the trace file, used to identify a tracing block. If identifier is NULL, an empty string is placed in the trace file.
Syntax
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded FileNotOpenError!TraceOpen has not been called yet TraceStartedError!TraceBegin has already been called
Usage
The TraceBegin call inserts an activity type value of ActBegin! in the trace file to indicate that logging has begun and then begins logging all the application activities you have selected for tracing.
TraceBegin can only be called following a TraceOpen call. And all activities to be logged must be enabled using the TraceEnableActivity function before calling TraceBegin.
If you want to generate a trace file for an entire application run, you typically include the TraceBegin function in your applications open script. If you want to generate a trace file for only a portion of the application run, you typically include the TraceBegin function in the script that initiates the functionality on which youre trying to collect data. You can use the identifier argument to identify the tracing blocks within a trace file. A tracing block represents the data logged between calls to TraceBegin and TraceEnd. There may be multiple tracing blocks within a single trace file if you are tracing more than one portion of the application run.
Examples
This example opens a trace file with the name you entered in a single line edit box and a timer kind selected from a drop-down list. It then begins logging the enabled activities for the first block of code to be traced:
TimerKind ltk_kind CHOOSE CASE ddlb_timestamp.text
1141
TraceBegin
CASE "None" ltk_kind CASE "Clock" ltk_kind CASE "Process" ltk_kind CASE "Thread" ltk_kind END CHOOSE
1142
PowerBuilder
CHAPTER 10
PowerScript Functions
TraceClose
Description Syntax Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded FileNotOpenError!TraceOpen has not been called yet FileCloseError!The log file is full
Usage
TraceClose closes the trace file. If you have not already called TraceEnd, TraceClose will call that function before proceeding with its processing.
You typically include the TraceClose function in your applications Close script.
Examples
This example stops logging of application trace activities and then closes the open trace file:
TraceEnd() TraceClose()
See also
1143
TraceDisableActivity
TraceDisableActivity
Description Syntax
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded FileNotOpenError!TraceOpen has not been called yet TraceStartedError!You have called TraceDisableActivity after TraceBegin and before TraceEnd
Usage
Use this function to disable the logging of the specified trace activities. You typically use this function if you are tracing only portions of an application run (and thus you are calling TraceBegin multiple times) and you want to log different activities during each portion of the application. Unless specifically disabled with TraceDisableActivity, activities that were previously enabled with a call to the TraceEnableActivity function remain enabled throughout the entire application run. You must always call the TraceEnd function before calling TraceDisableActivity.
1144
PowerBuilder
CHAPTER 10
PowerScript Functions
Examples
This example logs the enabled activities for the first block of code to be traced. Then it stops logging and disables two activity types for a second trace block. When logging is resumed for another portion of the application run, the activities that are not specifically disabled remain enabled until TraceClose is called:
TraceEnableActivity(ActESQL!) TraceEnableActivity(ActGarbageCollect) TraceEnableActivity(ActObjectCreate!) TraceEnableActivity(ActObjectDestroy!) TraceBegin("Trace_block_1") TraceEnd() TraceDisableActivity(ActESQL!) TraceDisableActivity(ActGarbageCollect!) TraceBegin("Trace_block_2")
See also
TraceEnd TraceEnableActivity
1145
TraceEnableActivity
TraceEnableActivity
Description Syntax
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded FileNotOpenError!TraceOpen has not been called yet TraceStartedError!You have called TraceEnableActivity after TraceBegin and before TraceEnd
Usage
Call the TraceEnableActivity function following the TraceOpen function. TraceEnableActivity allows you to specify the types of activities you want logged in the trace file. The default activity type logged is a user-defined activity type identified by the value ActUser!. This activity is enabled by the TraceOpen call. You must call TraceEnableActivity to specify the activities to be logged before you call TraceBegin. Each call to TraceOpen resets the activity types to be logged to the default (that is, only ActUser! activities are logged). Since the ActError! and ActUser! values require the passing of strings to the trace file, you must call the TraceError and TraceUser functions to log this information.
1146
PowerBuilder
CHAPTER 10
PowerScript Functions
Unless specifically disabled with a call to the TraceDisableActivity function, activities that are enabled with TraceEnableActivity remain enabled throughout the entire application run.
Examples
This example opens a trace file with the name you entered in a single line edit box and a timer kind selected from a drop-down list. Then it begins logging the enabled activities for the first block of code to be traced:
TimerKindltk_kind CHOOSE CASE ddlb_timestamp.text CASE "None" ltk_kind = TimerNone! CASE "Clock" ltk_kind = Clock! CASE "Process" ltk_kind = Process! CASE "Thread" ltk_kind = Thread! END CHOOSE TraceOpen(sle_filename.text,ltk_kind) TraceEnableActivity(ActRoutine!) TraceEnableActivity(ActESQL!) TraceEnableActivity(ActGarbageCollect!) TraceEnableActivity(ActError!) TraceEnableActivity(ActCreateObject!) TraceEnableActivity(ActDestroyObject!) TraceBegin("Trace_block_1")
See also
1147
TraceEnd
TraceEnd
Description Syntax Return value
Inserts an activity type value in the trace file indicating that logging has ended and then stops logging application trace activities.
TraceEnd ( )
ErrorReturn. Returns one of the following values: Success!The function succeeded FileNotOpenError!TraceOpen has not been called yet TraceNotStartedError!TraceBegin has not been called yet
Usage
The TraceEnd call inserts an activity type value of ActBegin! in the trace file to indicate that logging has ended and then stops logging all application activities that you selected for tracing. If you have not already called TraceEnd when you call TraceClose, TraceClose calls TraceEnd before proceeding. If you want to generate a trace file for an entire application run, you would typically include the TraceEnd function in your applications Close script. If you want to generate a trace file for only a portion of the application run, you typically include the TraceEnd function in the script that terminates the functionality on which youre trying to collect data.
Examples
This example stops logging of application trace activities and then closes the open trace file:
TraceEnd() TraceClose()
See also
1148
PowerBuilder
CHAPTER 10
PowerScript Functions
TraceError
Description Syntax
Logs your own error message and its severity level to the trace file if tracing of this activity type has been enabled.
TraceError ( severity, message ) Argument severity message Description A long whose value is a number you want to indicate the severity of the error A string whose value is the error message you want to add to the trace file
Return value
ErrorReturn. This function always returns Success!. If severity or message is NULL, TraceError returns NULL and no entry is made in the trace file.
Usage
TraceError logs an activity type value of ActError! to the trace file if you enabled the tracing of this type with the TraceEnableActivity function and then called the TraceBegin function. You use the TraceError function to record your own error message. It works just like the TraceUser function except that you use it to identify more severe problems. The severity and message values are passed without modification to the trace file.
Examples
This example logs an error message to the trace file when a database retrieval fails:
dw_1.SetTransObject(SQLCA) TraceUser(100, "Starting database retrieval") IF dw_1.Retrieve() = -1 THEN TraceError(999, "Retrieve for dw_1 failed") ELSE TraceUser(200, "Database retrieval complete") END IF
See also
TraceEnableActivity TraceUser
1149
TraceOpen
TraceOpen
Description Syntax
Opens a trace file with the specified name and enables logging of application trace activities.
TraceOpen ( filename, timer ) Argument filename timer Description A read-only string used to identify the trace file A value of the enumerated datatype TimerKind that identifies the timer. Values are: Clock!Use the wall clock timer Process!Use the process timer Thread!Use the thread timer TimeNone!Do not log timer values
Return value
ErrorReturn. Returns one of the following values: Success!The function succeeded FileAlreadyOpenError!TraceOpen has been called again without an intervening TraceClose FileOpenError!The file could not be opened for writing EnterpriseOnlyFeature!This function is only supported in the Enterprise edition of PowerBuilder.
application and library list to the trace file. It also enables logging of the default activity type, a user-defined activity type identified by the value ActUser!. After calling TraceOpen, you can select any additional activities to be logged in the trace file using the TraceEnableActivity function. Once you have called TraceOpen and TraceEnableActivity, you must then call TraceBegin for logging to begin. To stop logging of application trace activity, you must call the TraceEnd function followed by TraceClose to close the trace file. Each call to TraceOpen resets the logging of activity types to the default ActUser! You typically include the TraceOpen function in your applications Open script.
1150
PowerBuilder
CHAPTER 10
PowerScript Functions
Caution
If the trace file runs out of disk space, no error is generated, but logging is stopped, and the trace file cannot be used for analysis. By default, the time at which each activity begins and ends is recorded using the clock timer, which measures an absolute time with reference to an external activity, such as the machines startup time. The clock timer measures time in microseconds. Depending on the speed of your machines central processing unit, the clock timer can offer a resolution of less than one microsecond. A timers resolution is the smallest unit of time the timer can measure. You can also use process or thread timers, which measure time in microseconds with reference to when the process or thread being executed started. Use the thread timer for distributed applications. Both process and thread timers give you a more accurate measurement of how long the process or thread is taking to execute, but both have a lower resolution than the clock timer. If your analysis does not require timing information, you can omit timing information from the trace file. Collection time The timestamps in the trace file exclude the time taken to collect the trace data.
Examples
This example opens a trace file with the name you entered in a single line edit box and a timer kind selected from a drop-down list. Then it begins logging the enabled activities for the first block of code to be traced:
TimerKindltk_kind CHOOSE CASE ddlb_timestamp.text CASE "None" ltk_kind = TimerNone! CASE "Clock" ltk_kind = Clock! CASE "Process" ltk_kind = Process! CASE "Thread" ltk_kind = Thread! END CHOOSE TraceOpen(sle_filename.text,ltk_kind)
See also
1151
TraceUser
TraceUser
Description Syntax
Logs the activity type value you specify to the trace file.
TraceUser (info, message ) Argument info message Description A long whose value is a reference number you want to associate with the logged activity A string whose value is the activity type value you want to add to the trace file
Return value
ErrorReturn. This function always returns Success!. If info or message is NULL, TraceUser returns NULL and no entry is made in the log file.
Usage
TraceUser logs an activity type value of ActUser! to the trace file. This is the default activity type and is enabled when the TraceOpen function is called. You use the TraceUser function to record your own message identifying a specific
occurrence during an application run. For example, you may want to log the occurrences of a specific return value or the beginning and end of a body of code. TraceUser works just like the TraceError function except that you use TraceError to identify more severe problems. The info and message values are passed without modification to the trace file.
Examples
This example logs user messages to the trace file identifying when a database retrieval is started and when it is completed:
dw_1.SetTransObject(SQLCA) TraceUser(100, "Starting database retrieval") IF dw_1.Retrieve() = -1 THEN TraceError(999, "Retrieve for dw_1 failed") ELSE TraceUser(200, "Database retrieval complete") END IF
See also
TraceEnableActivity TraceError
1152
PowerBuilder
CHAPTER 10
PowerScript Functions
TriggerEvent
Description Applies to Syntax
Triggers an event associated with the specified object, which executes the script for that event immediately. Any object
objectname.TriggerEvent ( event {, word, long } ) Argument objectname event Description The name of any PowerBuilder object or control that has events associated with it. A value of the TrigEvent enumerated datatype that identifies a PowerBuilder event (for example, Clicked!, Modified!, or DoubleClicked!) or a string whose value is the name of an event. The event must be a valid event for objectname and a script must exist for the event in objectname. A long value to be stored in the WordParm property of the systems Message object. If you want to specify a value for long, but not word, enter 0. (For cross-platform compatibility, WordParm and LongParm are both longs.) A long value or a string that you want to store in the LongParm property of the systems Message object. When you specify a string, a pointer to the string is stored in the LongParm property, which you can access with the String function (see Usage).
word (optional)
long (optional)
Return value
Integer. Returns 1 if it is successful and the event script runs and -1 if the event is not a valid event for objectname, or no script exists for the event in objectname. If any arguments value is NULL, TriggerEvent returns NULL.
Usage
If you specify the name of an event instead of a value of the TrigEvent enumerated datatype, enclose the name in double quotation marks.
Check return code
It is a good idea to check the return code to determine whether TriggerEvent succeeded and, based on the result, perform the appropriate processing. You can pass information to the event script with the word and long arguments. The information is stored in the Message object. In your script, you can reference the WordParm and LongParm fields of the Message object to access the information.
1153
TriggerEvent
If you have specified a string for long, you can access it in the triggered event by using the String function with the keyword "address" as the format parameter. Your event script might begin as follows:
string PassedString PassedString = String(Message.LongParm, "address") Caution
Do not use this syntax unless you are certain the long argument contains a valid string value. For more information about events and when to use PostEvent and TriggerEvent, see PostEvent. To trigger system events that are not PowerBuilder-defined events, use Post or Send, instead of PostEvent and TriggerEvent. Although Send can send messages that trigger PowerBuilder events, as shown below, you have to know the codes for a particular message. It is easier to use the PowerBuilder functions that trigger the desired events.
Equivalent syntax Both of the following statements click the CheckBox cb_OK. The following call to the Send function: Send(Handle(Parent), 273, 0, Long(Handle(cb_OK), 0))
is equivalent to:
cb_OK.TriggerEvent(Clicked!) Examples
This statement executes the script for the Clicked event in the CommandButton cb_OK immediately:
cb_OK.TriggerEvent(Clicked!)
This statement executes the script for the user-defined event cb_exit_request in the parent window:
Parent.TriggerEvent("cb_exit_request")
This statement executes the script for the Clicked event in the menu selection m_File on the menu m_Appl:
m_Appl.m_File.TriggerEvent(Clicked!) See also
1154
PowerBuilder
CHAPTER 10
PowerScript Functions
TriggerPBEvent
Description Applies to Syntax
Triggers the specified user event in the child window contained in a PowerBuilder window ActiveX control. Window ActiveX controls
activexcontrol.TriggerPBEvent ( name {, numarguments {, arguments } } ) Argument activexcontrol Description Identifier for the instance of the PowerBuilder window ActiveX control. When used in HTML, this is the NAME attribute of the object element. When used in other environments, this references the control that contains the PowerBuilder window ActiveX. String specifying the name of the user event. This argument is passed by reference. Integer specifying the number of elements in the arguments array. The default is zero. Variant array containing event arguments. In PowerBuilder, Variant maps to the Any datatype. This argument is passed by reference. If you specify this argument, you must also specify numarguments. If you do not specify this argument and the function contains arguments, populate the argument list by calling the SetArgElement function once for each argument. JavaScript cannot use this argument.
Call this function to trigger a user event in the child window contained in a PowerBuilder window ActiveX control. To check the PowerBuilder functions return value, call the GetLastReturn function. JavaScript cannot use the arguments argument.
Examples
1155
TriggerPBEvent
theArg = f.textToPB.value; PBRX1.SetArgElement(1, theArg); theEvent = "ue_args"; retcd = PBRX1.TriggerPBEvent(theEvent, numargs); rc = parseInt(PBRX1.GetLastReturn()); if (rc != 1) { alert("Error. Empty string."); } PBRX1.ResetArgElements(); }
1156
PowerBuilder
CHAPTER 10
PowerScript Functions
Trim
Description
Return value
String. Returns a copy of string with all leading and trailing spaces deleted if it succeeds and the empty string ("") if an error occurs. If string is NULL, Trim returns NULL. Trim is useful for removing spaces that a user may have typed before or after newly entered data. In SBCS environments, the Trim and TrimW functions return the same results. Although you can use the Trim function in DBCS environments, it cannot remove double-byte spaces. You must use the TrimW function to remove double-byte or mixed single-byte and double-byte spaces.
Usage
Examples
This example removes the leading and trailing spaces from the user-entered value in the SingleLineEdit sle_emp_fname and saves the value in emp_fname:
string emp_fname emp_fname = Trim(sle_emp_fname.Text) See also
LeftTrim RightTrim Trim method for DataWindows in the DataWindow Reference or online Help
TrimW
Description Syntax
Removes leading and trailing spaces from a string. For more information, see Trim.
TrimW ( string )
1157
Truncate
Truncate
Description Syntax
Return value
Decimal. Returns the result of the truncation if it succeeds and NULL if it fails or if any argument is NULL.
A real number loaded into a floating point register (used for calculation) is represented as precisely as the binary storage will permit. For example, the real number displayed as 2.07 is actually stored as 2.0699999999999997. Truncating such a number may not give the expected result. To avoid this problem, you can change the initial real datatype to long, Integer, or decimal, or you can append a constant in the truncate argument: Truncate (x + 0.0000001, n )
Examples
Help
1158
PowerBuilder
CHAPTER 10
PowerScript Functions
TrustVerify
Description
Called by EAServer when an SSL certificate chain needs to be approved for use by a client. This function is used by PowerBuilder clients connecting to EAServer. SSLCallBack objects
sslcallback.TrustVerify ( thesessioninfo, reason ) Argument sslcallback thesessioninfo reason Description An instance of a customized SSLCallBack object A CORBAObject that contains information about the SSL session A long value indicating the reason for the call back. Values are: 1 REASON_CHAIN_INCOMPLETE 2 REASON_UNKNOWN_CA 3 REASON_CHAIN_EXPIRED 4 REASON_TRUSTDBPINNOTSET 5 REASON_TRUSTDBLOGINFAILED
Applies to Syntax
Return value
1 TRUST_ONCE (accept the current connection) 2 TRUST_FAIL (reject the current connection) 3 TRUST_ALWAYS (accept and mark as trusted in the database) 4 TRUST_NEVER (reject and mark as untrusted in the database) 5 TRUST_SESSION (accept now and throughout the current session) 6 TRUST_FAIL_SESSION (reject throughout the current session)
Usage
A PowerBuilder application does not usually call the TrustVerify function directly. TrustVerify is called by EAServer when the internal SSL trust verification check fails to verify the servers certificate chain or when the PIN to log in to the Sybase PKCS11 token was not supplied or incorrect. TrustVerify can be invoked when you are using any SSL protocol, because server authentication is a required step in the SSL handshake process. To override the behavior of any of the functions of the SSLCallBack object, create a standard class user object that descends from SSLCallBack and customize this object as necessary. To let EAServer know which object to use when a callback is required, specify the name of the object in the callbackImpl SSL property. You can set this property value by calling the SetGlobalProperty function. If you do not provide an implementation of TrustVerify, EAServer receives the CORBA::NO_IMPLEMENT exception and the connection is rejected.
1159
TrustVerify
To obtain a useful return value, provide the user with information about the reason for failure and ask the user to determine whether the server certificate chain can be trusted so that the session can continue. If the user specifies TRUST_FAIL or TRUST_ONCE, the function may be called again during the current session. You can enable the user to cancel the attempt to connect by throwing an exception in this callback function. You need to catch the exception by wrapping the ConnectToServer function in a try-catch block.
Examples
This example checks whether the failure was called by a bad or missing PIN and returns TRUST_FAIL to call GetPin if it was. If not, it displays the reason why the server failed to verify the certificate chain and prompts the user to choose whether to continue with the session:
long rc string stmp, stmp2 w_response w_ssl_response string ls_rc sslSessionInfo mySessionInfo rc = thesessioninfo._narrow(mySessionInfo, & "thesessioninfo") is_tokenName = mySessionInfo.getProperty( "tokenName" ) CHOOSE CASE reason CASE 4 MessageBox("The SSL session requires a PIN", & "Please enter the PIN for access to the " + & is_tokenName + " certificate database.") return 2 CASE 5 MessageBox("The PIN you entered is incorrect", & "Please reenter the PIN for access to the " + & is_tokenName + " certificate database.") return 2 CASE 1 MessageBox("Certificate verification failed", & "Servers certificate chain is incomplete.ORB " & + "~nis unable to complete the chain using the " & + "CA certificates in the " & + "~nSybase PKCS11 Token.") CASE 2 MessageBox("Certificate verification failed", & "Servers certificate chain expired. One or " & + " more of the certificates in the " &
1160
PowerBuilder
CHAPTER 10
PowerScript Functions
+ "chain is no longer valid.") CASE 3 MessageBox("Certificate verification failed", & "Servers certificate chain contains an " & + "unknown root certification authority. " & + "This CA is not found in the trust data in " & + "the Sybase PKCS11 Token.") END CHOOSE sTmp = "~nVersion: " stmp += mySessionInfo.getProperty( "Version" ) sTmp = "~nHost: " stmp += mySessionInfo.getProperty( "host" ) stmp += "~nport: " stmp += mySessionInfo.getProperty( "port" ) stmp += "~nciphersuite: " stmp += mySessionInfo.getProperty( "ciphersuite" ) stmp += "~nCertificateLabel: " stmp += mySessionInfo.getProperty( "certificateLabel" ) stmp += "~nUserData: " stmp += mySessionInfo.getProperty( "UserData" ) stmp += "~ntokenName: " stmp += mySessionInfo.getProperty( "tokenName" ) stmp += "~npkcs11Module: " stmp += mySessionInfo.getProperty( "pkcs11Module" ) stmp += "~nPlease enter your choice: " stmp += "~n 1: Accept this connection" stmp += "~n 2: Reject this connection" stmp += "~n 3: Accept this connection and mark CA as trusted" stmp += "~n 4: Reject this connection and mark CA as untrusted" stmp += "~n 5: Accept this CA throughout this session" stmp += "~n 6: Reject this CA throughout this session" // Display information in a response window and return // response with CloseWithReturn openwithparm(w_response, stmp) ls_rc = Message.StringParm return long(ls_rc) See also
1161
TypeOf
TypeOf
Description Applies to Syntax
Determines the type of an object or control, reported as a value of the Object enumerated datatype. Any object
objectname.TypeOf ( ) Argument objectname Description The name of the object or control for which you want the type
Object enumerated datatype. Returns the type of objectname. If objectname is NULL, TypeOf returns NULL. Use TypeOf to determine the type of a selected or dragged control. If dw_Customer is a DataWindow control, this statement returns DataWindow!:
dw_Customer.Typeof()
This example looks at the first five controls in the w_dept windows Control array property. The loop executes some statements for each control that is a CheckBox:
integer n FOR n = 1 to 5 IF w_dept.Control[n].TypeOf() = CheckBox! THEN ... // Some processing END IF NEXT
This loop stores in the winobject array the type of each object in the windows Control array property:
object winobjecttype[] long ll_count FOR ll_count = 1 to UpperBound(Control[]) winobjecttype[ll_count] = & TypeOf(Control[ll_count]) NEXT
1162
PowerBuilder
CHAPTER 10
PowerScript Functions
If you do not know the type of a control passed via PowerObjectParm in the Message object, the following example assigns the passed object to a graphic object variable, the ancestor of all the control types, and assigns the type to a variable of type object, which is the enumerated datatype that TypeOf returns. The CHOOSE CASE statement can include processing for each control type that you want to handle. This code would be in the Open event for a window that was opened with OpenWithParm:
graphicobject stp_obj object type_obj stp_obj = Message.PowerObjectParm type_obj = stp_obj.TypeOf() CHOOSE CASE type_obj CASE DataWindow! MessageBox("The object"," Is a datawindow") CASE SingleLineEdit! MessageBox("The object"," Is a sle") ... // Cases for additional object types CASE ELSE MessageBox("The object"," Is irrelevant!") END CHOOSE See also
ClassName
1163
Uncheck
Uncheck
Description Applies to Syntax
Removes the checkmark, if any, next to an item a drop-down or cascading menu and sets the items Checked property to FALSE. Menu objects
menuname.Uncheck ( ) Argument menuname Description The fully qualified name of the menu selection from which you want to remove the checkmark, if any. The menu must be on a dropdown or cascading menu, not an item on a menu bar.
Integer. Returns 1 if it succeeds and -1 if an error occurs. If menuname is NULL, Uncheck returns NULL.
A checkmark next to a menu item indicates that the menu option is currently on and that the user can turn the option on and off by choosing it. For example, in the Window painters Design menu, a checkmark is displayed next to Grid when the grid is on. You can use Check in an items Clicked script to mark a menu item when the user turns the option on and Uncheck to remove the check when the user turns the option off.
Equivalent syntax You can set the objects Checked property instead of calling Uncheck: menuname.Checked = FALSE
This statement:
m_appl.m_view.m_grid.Checked = FALSE
is equivalent to:
m_appl.m_view.m_grid.Uncheck() Examples
This statement removes the checkmark next to the m_grid menu selection in the drop-down menu m_view on the menu bar m_appl:
m_appl.m_view.m_grid.Uncheck()
1164
PowerBuilder
CHAPTER 10
PowerScript Functions
This example checks whether the m_grid menu selection in the drop-down menu m_view of the menu bar m_appl is currently checked. If so, the script unchecks the item. If it is not checked, the script checks the item:
IF m_appl.m_view.m_grid.Checked = TRUE THEN m_appl.m_view.m_grid.Uncheck() ELSE m_appl.m_view.m_grid.Check() END IF See also
Check
1165
Undo
Undo
Description Applies to Syntax
Cancels the last edit in an edit control, restoring the text to the content before the last change. DataWindow, MultiLineEdit, RichTextEdit, and SingleLineEdit controls
editname.Undo ( ) Argument editname Description The name of the DataWindow control, MultiLineEdit, RichTextEdit, or SingleLineEdit in which you want to cancel (reverse) the last edit. For a DataWindow control, reverses the last edit in the edit control over the current row and column.
Integer. Returns 1 when it succeeds and -1 if an error occurs. If editname is NULL, Undo returns NULL.
To determine whether the last action can be canceled, call the CanUndo function. This statement reverses the last edit in MultiLineEdit mle_Contact:
mle_Contact.Undo()
The following statement checks to see if the last edit in the MultiLineEdit mle_Contact can be reversed, and if so reverse it:
IF mle_Contact.CanUndo() THEN mle_Contact.Undo() See also
CanUndo
1166
PowerBuilder
CHAPTER 10
PowerScript Functions
UnitsToPixels
Description
Converts PowerBuilder units to pixels and reports the measurement. Because pixels are not usually square, you also specify whether to convert in the horizontal or vertical direction.
UnitsToPixels ( units, type ) Argument units type Description An integer whose value is the number of PowerBuilder units you want to convert to pixels A value of the ConvertType enumerated datatype indicating how to convert the value: XUnitsToPixels! Convert the units in the horizontal direction YUnitsToPixels! Convert the units in the vertical direction
Syntax
Integer. Returns the converted value if it succeeds and -1 if an error occurs. If any arguments value is NULL, UnitsToPixels returns NULL.
These statements convert 350 vertical PowerBuilder units to vertical pixels and set value equal to the converted value:
integer Value Value = UnitsToPixels(350, YUnitsToPixels!)
See also
PixelsToUnits
1167
UpdateLinksDialog
UpdateLinksDialog
Description
Attempts to find a file linked to an OLE container. If the linked file is not found, a dialog box tells the user and lets them bring up a second dialog box for find the file or changing the link. OLE controls and OLE DWObjects (objects within a DataWindow object that is within a DataWindow control)
objectref.UpdateLinksDialog ( ) Argument objectref Description The name of the OLE control or the fully qualified name of a OLE DWObject within a DataWindow control that contains the object for which you want to establish a link. The fully qualified name for a DWObject has this syntax:
dwcontrol.Object.dwobjectname
Applies to Syntax
If a containers LinkUpdateOptions property is set for automatic update, PowerBuilder tries to update the link when the OLE container is created and the object is loaded (for example, when the window is opened). If the linked file is not found, a message informs the user and he or she can choose to edit the link (for example, break the link or browse for the correct file).
UpdateLinksDialog and LinkTo are useful when a linked file has been moved and the containers LinkUpdateOptions property is set for manual update.
UpdateLinksDialog Calling this function triggers the same process that occurs for automatic update. PowerBuilder tries to find the file and if it fails it gives the user the opportunity to edit the link. LinkTo If you want to establish a link without involving the user, call the LinkTo function. Its arguments specify the file and item you want to link. If you
want to display your own dialog for selecting the linked file, you can take the information the user specifies and call the LinkTo function. If the OLE container holds an embedded object, calling UpdateLinksDialog has no effect. It returns zero because no link is broken. For more information about updating links, see Application Techniques.
Examples
This example looks for the linked file for an OLE control ole_report. If the file is missing, it prompts the user to display the Links dialog and edit the link:
ole_report.UpdateLinksDialog()
1168
PowerBuilder
CHAPTER 10
PowerScript Functions
This example looks for the linked file for an OLE DWObject ole_word in the DataWindow control dw_customer_data. If the file is missing, the user can choose to edit the link using the Links dialog:
dw_customer_data.Object.ole_word.UpdateLinksDialog() See also
InsertObject LinkTo
1169
Upper
Upper
Description Syntax
Return value
String. Returns string with lowercase letters changed to uppercase if it succeeds and the empty string ("") if an error occurs. If string is NULL, Upper returns NULL.
Examples
See also
Lower Upper method for DataWindows in the DataWindow Reference or online Help
1170
PowerBuilder
CHAPTER 10
PowerScript Functions
UpperBound
Description Syntax
Return value
Long. Returns the upper bound of dimension n of array. If n is greater than the number of dimensions of the array, UpperBound returns -1. If any arguments value is NULL, UpperBound returns NULL.
Usage
For variable-size arrays, memory is allocated for the array when you assign values to it. UpperBound returns the largest value that has been defined for the array in the current script. Before you assign values, the lower bound is 1 and the upper bound is 0. For fixed arrays, whose size is specified when it is declared, UpperBound always returns the declared size. The following statements illustrate the values UpperBound reports for fixed-size arrays and for variable-size arrays before and after memory has been allocated:
integer a[5] UpperBound(a) // Returns 5 UpperBound(a,1) // Returns 5 UpperBound(a,2) // Returns -1; no 2nd dimension integer b[10,20] UpperBound(b,1) // Returns 10 UpperBound(b,2) // Returns 20 integer c[ ] UpperBound(c) c[50] = 900 UpperBound(c) c[60] = 800 UpperBound(c) c[60] = 800 c[50] = 700 UpperBound(c)
Examples
// Returns 60
1171
UpperBound
This example determines the position of a menu bar item called File, and if the item has a cascading menu with an item called Update, disables the Update item. The code could be a script for a control in a window. The code includes a rather complicated construct: Parent.Menuid.Item. Its components are: Parent The parent window of the control that is running the script. Menuid A property of a window whose value identifies the menu associated with the window. Item A property of a menu that is an array of items in that menu. If Item is itself a drop-down or cascading menu, it has its own item array, which can be a fourth qualifier.
LowerBound
1172
PowerBuilder
CHAPTER 10
PowerScript Functions
Which
Description Applies to Syntax
Allows a component to find out whether it is running on a transaction server. TransactionServer objects
transactionserver.Which ( ) Argument transactionserver Description Reference to the TransactionServer service instance
Integer. Returns 0 if the object is not running on a transaction server, 1 if it is running on EAServer, or 2 if it is running on Microsoft MTS or IIS4.
The Which function allows a custom class user object to perform different processing depending on its runtime context. The code in the following example checks to see whether the runtime context is a transaction server (EAServer or MTS). If it is, it uses transaction semantics that are appropriate for a transaction server; otherwise, it uses COMMIT and ROLLBACK to communicate directly with the database:
// Instance variables: // DataStore ids_datastore // TransactionServer ts Integer li_rc long ll_rv li_rc = this.GetContextService("TransactionServer", & ts) IF li_rc <> 1 THEN // handle the error END IF ... ... ll_rv = ids_datastore.Update() IF ts.Which() > 0 THEN IF ll_rv = 1 THEN ts.EnableCommit() ELSE ts.DisableCommit() END IF
1173
Which
ELSE IF ll_rv = 1 THEN COMMIT USING SQLCA; ELSE ROLLBACK USING SQLCA; END IF END IF See also
1174
PowerBuilder
CHAPTER 10
PowerScript Functions
WordCap
Description Applies to Syntax
Capitalizes the first letter of each word in a passed script. It sets the remaining letters in each word to lowercase. All text objects
WordCap ( text ) Argument text Description String to be modified
Return value
String. If it succeeds, returns the text passed in the function argument with the first letter of each word in uppercase and the remaining letters in lowercase. Returns NULL if an error occurs.
Examples
This example takes user-entered text from a SingleLineEdit control, capitalizing the first letter in each word and setting the other letters to lowercase, before passing it in a string variable:
string ls_fullname ls_fullname = WordCap (sle_1.text)
The text joe MaCdonald would be rendered as Joe Macdonald by the WordCap function.
1175
WorkSpaceHeight
WorkSpaceHeight
Description Applies to Syntax
Obtains the height of the workspace within the boundaries of the specified window. Window objects
windowname.WorkSpaceHeight ( ) Argument windowname Description The name of the window for which you want the height of the workspace area
Return value
Integer. Returns the height of the workspace area in PowerBuilder units in windowname. If an error occurs, WorkSpaceHeight returns -1. If windowname is NULL, WorkSpaceHeight returns NULL.
Usage
The workspace height does not include the thickness of the frame, the title bar, menu bar, horizontal scrollbar, or any toolbars at the top or bottom. The workspace height includes the MicroHelp status bar. The workspace width does not include the thickness of the frame, the vertical scrollbar, or any toolbars on the left or right.
Examples
This example returns the height of the workspace area in the w_employee window:
Integer Height Height = W_employee.WorkSpaceHeight()
This example resizes the client area of a custom MDI frame window (that is, a frame window in which you have placed controls). P_logo is the control that has been placed on the window. The code belongs in the script for the frames Resize event:
integer lw, lh // Get the current workspace measurements lw = This.WorkSpaceWidth() lh = This.WorkSpaceHeight() // Subtract the logo, MicroHelp from the height lh = lh - (p_logo.Y + p_logo.Height) lh = lh - MDI_1.MicroHelpHeight // // // lh Add the distance between the top of the frame (just below the menu bar or toolbar, if any) and top of the workspace. = lh + This.WorkspaceY( )
1176
PowerBuilder
CHAPTER 10
PowerScript Functions
// Move the client area below the picture control MDI_1.Move(This.WorkspaceX( ), & p_logo.Y + p_logo.Height) // Resize the client area using the calculated dims mdi_1.Resize(lw, lh) See also
1177
WorkSpaceWidth
WorkSpaceWidth
Description Applies to Syntax
Obtains the width of the workspace within the boundaries of the specified window. Window objects
windowname.WorkSpaceWidth ( ) Argument windowname Description The name of the window for which you want the width of the workspace area
Return value
Integer. Returns the width of the workspace area (in PowerBuilder units) in windowname. If an error occurs, WorkSpaceWidth returns -1. If windowname is NULL, WorkSpaceWidth returns NULL.
Usage
The workspace height does not include the thickness of the frame, the title bar, menu bar, horizontal scrollbar, or any toolbars at the top or bottom. The workspace height includes the MicroHelp status bar. The workspace width does not include the thickness of the frame, the vertical scrollbar, or any toolbars on the left or right.
Examples
This example returns the width of the workspace area in the w_employee window:
integer Width Width = w_employee.WorkSpaceWidth()
See also
1178
PowerBuilder
CHAPTER 10
PowerScript Functions
WorkSpaceX
Description
Obtains the distance between the left edge of a windows workspace and the left edge of the screen. For custom MDI frames, WorkSpaceX obtains the distance between the left edge of the frame window and the left side of the workspace area.
Applies to Syntax
Window objects
windowname.WorkSpaceX ( ) Argument windowname Description The name of the window for which you want the distance between the left edge of the workspace area and the left edge of the screen
Return value
Integer. Returns the distance that the left edge of the workspace area of windowname is from the left edge of the screen (in PowerBuilder units). WorkSpaceX returns -1 if an error occurs. If windowname is NULL, WorkSpaceX returns NULL.
Usage
The workspace area is the area between the sides of the window (not including the thickness of the frame or the vertical scrollbar, if any) and the top and bottom of the window (not including the thickness of the frame or the title bar, menu bar, or horizontal scrollbar, if any). This example returns the distance from the left edge of the screen to the left edge of the workspace area in the w_employee window:
integer workx workx = w_employee.WorkSpaceX()
Examples
See also
1179
WorkSpaceY
WorkSpaceY
Description
Obtains the distance between the top of a windows workspace and the top of the screen. For custom MDI frames, WorkSpaceY obtains the distance from the top of the frame window and the top of the workspace area. The top of the frame window is the lower edge of the menu bar or toolbar, if any.
Applies to Syntax
Window objects
windowname.WorkSpaceY ( ) Argument windowname Description The name of the window for which you want the distance between the top of the workspace area and the top of the screen
Return value
Integer. Returns the distance that the top of the workspace area of windowname
is from the top of the screen (in PowerBuilder units). If an error occurs,
WorkSpaceY returns -1. If windowname is NULL, WorkSpaceY returns NULL.
Usage
The workspace area is the area between the sides of the window (not including the thickness of the frame or the vertical scrollbar, if any) and the top and bottom of the window (not including the thickness of the frame or the title bar, menu bar, or horizontal scrollbar, if any). This example returns the distance from the top of the screen to the top of the workspace area in the w_employee window:
integer worky worky = w_employee.WorkSpaceY()
Examples
See also
1180
PowerBuilder
CHAPTER 10
PowerScript Functions
Write
Description Applies to Syntax
Return value
Integer. Returns the number of characters or bytes written if it succeeds and one of the following negative values if an error occurs:
-1 -2 -9
This example opens an OLE object in the file MYSTUFF.OLE and assigns it to the OLEStorage object olest_stuff. Then it opens the stream called info in olest_stuff and assigns it to the stream object olestr_info. It writes the contents of the blob variable lb_info to the stream olestr_info. Finally, it saves the storage olest_stuff:
boolean lb_memexists OLEStorage olest_stuff OLEStream olestr_info integer result olest_stuff = CREATE OLEStorage result = olest_stuff.Open("c:\ole2\mystuff.ole") IF result <> 0 THEN RETURN result = olestr_info.Open(olest_stuff, "info", & stgReadWrite!, stgExclusive!) IF result <> 0 THEN RETURN result = olestr_info.Write(lb_info) IF result = 0 THEN olest_stuff.Save()
See also
1181
XMLParseFile
XMLParseFile
Description Syntax
Parses an XML file and determines whether the file is well formed or complies with a specified grammar.
XMLParseFile ( xmlfilename {, validationscheme }{, parsingerrors } {, namespaceprocessing {, schemaprocessing {, schemafullchecking }}}) Argument xmlstring validationscheme (optional) Description A string whose value is the name of the XML file to be parsed. A value of the ValSchemeType enumerated datatype specifying the validation method used by the SAX parser. Values are: ValNever! Do not report validation errors. ValAlways! Always report validation errors. ValAuto! (default) Report validation errors only if a grammar is specified. A string buffer to which error messages can be saved. If not specified or set to NULL, errors display in a message box. A boolean specifying whether name space rules are enforced. When set to TRUE, the parser enforces the constraints and rules defined by the W3C recommendation on namespaces in XML. If validationscheme is set to ValAlways! or ValAuto!, the document must contain a grammar that supports the use of namespaces. The default is FALSE. schemaprocessing (optional) A boolean specifying whether schema support is enabled. When set to FALSE, the parser does not process any schema found. If schemaprocessing is TRUE, namespaceprocessing must also be set to TRUE. schemafullchecking (optional) The default is FALSE. A boolean specifying whether schema constraints are checked. When set to TRUE, the schema grammar is checked for errors. Setting schemafullchecking to TRUE has no effect unless schemaprocessing is also set to TRUE. The default is FALSE.
1182
PowerBuilder
CHAPTER 10
PowerScript Functions
Return value
Long. Returns 0 for success and one of the following negative values if an error
Use XMLParseFile to validate an XML file against a DTD or XML schema before proceeding with additional processing. If no DTD or schema is included or referenced in the file, XMLParseFile checks whether the document contains well-formed XML. If the XML document fails validation or is not well-formed, XMLParseFile returns -1. To suppress the display of message boxes if errors occur, specify a string value for the parsingerrors argument. The files pbxercesNN.dll and xerces-c_XX.dll, where NN represents the PowerBuilder version and XX represents the Xerces version, must be deployed with the other PowerBuilder runtime files in the search path of any application or component that uses this function.
Examples
These statements parse an XML document. If a DTD is included or referenced, the document is validated. Otherwise the parser checks for well-formedness. If the document passes validation, it is imported into a DataWindow control:
long ll_ret ll_ret = XMLParseFile("c:\temp\mydoc.xml") if ll_ret = 0 then dw_1.ImportFile("c:\temp\mydoc.xml")
These statements parse an XML document and save any errors in the string variable ls_err. If errors occur, no message boxes display. If a DTD is included or referenced, the document is validated. Otherwise the parser checks for well-formedness:
long ll_ret string ls_err ll_ret = XMLParseFile("c:\temp\mydoc.xml", ls_err)
These statements parse an XML document. If an XMLSchema is included or referenced, the document is validated, otherwise the parser checks for well-formedness:
long ll_ret ll_ret = XMLParseFile("c:\temp\mydoc.xml", TRUE, TRUE)
1183
XMLParseFile
These statements parse an XML document, validate against a given XML schema, and save any errors that occur in a string variable. If errors occur, no message boxes display. If no schema is included or referenced in the file, XMLParseFile returns -1:
long ll_ret string ls_err ll_ret = XMLParseFile("c:\temp\mydoc.xml", ValAlways!, ls_err, TRUE, TRUE)
These statements parse an XML document, validate against a given XML schema, and parse the schema itself for additional errors. If no schema is included or referenced in the file, XMLParseFile returns -1:
long ll_ret string ls_err ll_ret = XMLParseFile("c:\temp\mydoc.xml", ValAlways!, ls_err, TRUE, TRUE, TRUE)
These statements parse an XML document, validate against a given DTD, and save any errors that occur in a string variable. If errors occur, no message boxes display. If no DTD is included or referenced in the file, XMLParseFile returns -1:
long ll_ret string ls_err ll_ret = XMLParseFile("c:\temp\mydoc.xml", ValAlways!, ls_err) See also
1184
PowerBuilder
CHAPTER 10
PowerScript Functions
XMLParseString
Description Syntax
Parses an XML string and determines whether the string is well formed or complies with a specified grammar.
XMLParseString ( xmlstring {, validationscheme }{, parsingerrors } {, namespaceprocessing {, schemaprocessing {, schemafullchecking }}}) Argument xmlstring validationscheme (optional) Description A string that holds the XML document to be parsed. A value of the ValSchemeType enumerated datatype specifying the validation method used by the SAX parser. Values are: ValNever! Do not report validation errors. ValAlways! Always report validation errors. ValAuto! (default) Report validation errors only if a grammar is specified. parsingerrors (optional) namespaceprocessing (optional) A string buffer to which error messages can be saved. If not specified or set to NULL, errors are shown to the user in a dialog box. A boolean specifying whether name space rules are enforced. When set to TRUE, the parser enforces the constraints and rules defined by the W3C recommendation on namespaces in XML. If validationscheme is set to ValAlways! or ValAuto!, the document must contain a grammar that supports the use of namespaces. The default is FALSE. schemaprocessing (optional) A boolean specifying whether schema support is enabled. When set to FALSE, the parser does not process any schema found. If schemaprocessing is TRUE, namespaceprocessing must also be set to TRUE. The default is FALSE. schemafullchecking (optional) A boolean specifying whether schema constraints are checked. When set to TRUE, the schema grammar is checked for errors. Setting schemafullchecking to TRUE has no effect unless schemaprocessing is also set to TRUE. The default is FALSE.
1185
XMLParseString
Return value
Long. Returns 0 for success and one of the following negative values if an error occurs:
Use XMLParseString to validate an XML string against a DTD or XML schema before proceeding with additional processing. If no DTD or schema is included or referenced in the string, XMLParseString checks whether the string contains well-formed XML. If the XML string fails validation or is not well-formed, XMLParseString returns -1. To suppress the display of message boxes if errors occur, specify a string value for the parsingerrors argument. The files pbxercesNN.dll and xerces-c_XX.dll, where NN represents the PowerBuilder version and XX represents the Xerces version, must be deployed with the other PowerBuilder runtime files in the search path of any application or component that uses this function.
Examples
These statements parse an XML string. If a DTD is included or referenced, the string is validated. Otherwise the parser checks for well-formedness:
// string argument as_xmlstring passed in long ll_ret ll_ret = XMLParseString(as_xmlstring)
These statements parse an XML string, validate against a given XML schema, and save any errors that occur in a string variable. If errors occur, no message boxes display. If no schema is included or referenced in the string, XMLParseString returns -1:
long ll_ret string ls_xmlstr, ls_err ll_ret = XMLParseString(ls_xmlstr, ValAlways!, ls_err, TRUE, TRUE)
These statements parse an XML string, validate against a given DTD, and save any errors that occur in a string variable. If errors occur, no message boxes display. If no DTD is included or referenced in the string, XMLParseString returns -1. If the string passes validation, it is imported into a DataWindow control:
long ll_ret string ls_xmlstr, ls_err
1186
PowerBuilder
CHAPTER 10
PowerScript Functions
1187
Year
Year
Description Syntax
Return value
Integer. Returns an integer whose value is a 4-digit year adapted from the year portion of date if it succeeds and 1900 if an error occurs. If date is NULL, Year returns NULL.
When you convert a string that has a two-digit year to a date, then PowerBuilder chooses the century, as follows. If the year is between 00 to 49, PowerBuilder assumes 20 as the first two digits; if it is between 50 and 99, PowerBuilder assumes 19.
Usage
PowerBuilder handles years from 1000 to 3000 inclusive. If your data includes date before 1950, such as birth dates, always specify a 4-digit year so that Year and other PowerBuilder functions, such as Sort, interpret the date as intended.
Windows settings
To make sure you get correct return values for the year, you must verify that yyyy is the Short Date Style for year in the Regional Settings of the users Control Panel. Your program can check this with the RegistryGet function. If the setting is not correct, you can ask the user to change it manually or have the application change it (by calling the RegistrySet function). The user may need to reboot after the setting is changed.
Examples
See also
Day Month Year method for DataWindows in the DataWindow Reference or online Help
1188
PowerBuilder
CHAPTER 10
PowerScript Functions
Yield
Description
Yields control to other graphic objects, including objects that are not PowerBuilder objects. Yield checks the message queue and if there are messages in the queue, it pulls them from the queue.
Yield ( )
Boolean. Returns TRUE if it pulls messages from the message queue and FALSE if there are no messages.
Include Yield within a loop so that other processes can happen. For example, use Yield to allow end users to interrupt a loop. By yielding control, you allow the user time to click on a cancel button in another window. Then code in the loop can check whether a global variables status has changed. You can also use Yield in a loop in which you are waiting for something to finish so that other processing can take place, in either your or some other application.
Using other applications while retrieving data
Although the user cannot do other activities in a PowerBuilder application while retrieving data, you can allow them to use other applications on their system. Put Yield in the RetrieveRow event so that other applications can run during the retrieval. Of course, Yield will make your PowerBuilder application run slower because processing time will be shared with other applications.
Examples
In this example, some code is processing a long task. A second window includes a button that the user can click to interrupt the loop by setting a shared boolean variable sb_interrupt. When the user clicks the button, its Clicked script sets sb_interrupt, shown here:
sb_interrupt = TRUE
The script that is doing the processing checks the shared variable sb_interrupt and interrupts the processing if it is TRUE. The Yield function allows a break in the processing so the user has the opportunity to click the button:
integer n // sb_interrupt is a shared variable. sb_interrupt = FALSE
1189
Yield
FOR n = 1 to 3000 Yield() IF sb_interrupt THEN // var set in other script MessageBox("Debug","Interrupted!") sb_interrupt = FALSE EXIT ELSE ... // Some processing END IF NEXT
In this example, this script doing some processing runs in one window while users interact with controls in a second window. Without Yield, users could click in the second window, but they would not see focus change or their actions processed until the loop completed:
integer n FOR n = 1 to 3000 Yield() ... // Some processing NEXT
In this example, a script wants to open a DDE channel with Lotus Notes, whose executable name is stored in the variable mailprogram. If the program is not running, the script starts it and loops, waiting until the programs startup is finished and it can establish a DDE channel. The loop includes Yield, so that the computer can spend time actually starting the other program:
time starttime long hndl SetPointer(HourGlass!) //Try to establish a handle; SendMail is the topic. hndl = OpenChannel("Notes","SendMail") //If the program is not running, start it IF hndl < 1 then Run(mailprogram, Minimized!) starttime = Now() // Wait up to 2 minutes for Notes to load // and the user to log on.
1190
PowerBuilder
CHAPTER 10
PowerScript Functions
DO //Yield control occasionally. Yield() //Is Notes active yet? hndl = OpenChannel("Notes","SendMail") // If Notes is active. IF hndl > 0 THEN EXIT LOOP Until SecondsAfter(StartTime,Now()) > 120 // If 2 minutes pass without opening a channel IF hndl < 1 THEN MessageBox("Error", & "Cant start Notes.", StopSign!) SetPointer(Arrow!) RETURN END IF END IF
1191
Yield
1192
PowerBuilder
Index
118
Symbols
! (enumerated value) 28 & see ampersand * (multiplication) 66 + (addition) 66 ++, += (assignment shortcuts) 118 / (division) 66 // (comments) 4 /= (assignment shortcut) 118 ; (SQL) 15 < (less than) 68 <= (less than or equal) 68 = (assignment) 38 = (relational) 68 > (greater than) 68 >= (greater than or equal) 68 ? (dynamic SQL) 173, 174, 177 ^ (exponentiation) 66 _Is_A function 666 _Narrow function 766 ~ see tilde see quotes
A
Abs function 312 absolute value 312 access levels functions 57 group label 43 variables 40 ACos function 313 Activate event 184 Activate function 314 PowerScript Reference Volume 2
active sheet 792 active window 834 Adaptive Server Enterprise 1121 AddCategory function 316 AddColumn function 317 AddData function 318 AddItem function 321 addition operator 66 AddLargePicture function 326 AddPicture function 327 address keyword 1153 address, mail 726, 737, 739 AddSeries function 328 AddSmallPicture function 330 AddStatePicture function 331 AddToLibraryList function 332 AllowEdit property 973 ampersand (&) 15 ancestor calling function or event 109 hierarchy 359 objects 80 return values from events 110 script, calling 119 AncestorReturnValue variable 110 AND operator 68 angle calculating arccosine 313 calculating arcsine 337 calculating arctangent 338 calculating cosine 400 calculating sine 1088 calculating tangent 1126 converting to/from radians 830 ANSI, string conversion 494, 495, 1134, 1140 Any data type 24 API and database handles 422 application closing DDE channel 370 connecting to 383, 385, 387, 390
1193
Index
elapsed time 401 exporting object as syntax 705 handle 501, 600 listing objects 701 posting messages 844 recreating objects from syntax 706 restarting 924 retrieving arguments 379 running 939 server 1103, 1109 terminating 133 yielding to 1189 application name 1101, 1103, 1109 Application objects, SetTransPool function Arabic functions IsAllArabic 668 IsAnyArabic 670 IsArabic 672 IsArabicAndNumbers 673 arccosine 313 arcsine 337 arctangent 338 arguments command line 379 for events 182 functions and events 101 hot link 1101, 1108 server application 1103, 1109 arithmetic operators 66 Arrange function 334 ArrangeOpen enumerated data type 792 ArrangeSheets function 335 ArrangeTypes enumerated data type 335 array functions LowerBound 725 UpperBound 1171 arraylists 53 arrays about 45 assigning values 51, 53, 116 chars and strings 74 copying 116 default values 49 errors 54 example 336 initializing 53
1073
input parameter for dynamic SQL mailRecipient 726 message ID 728 passing as arguments 103 stream 896, 1181 variable-size 50 arrow pointer 1038 Asc function 336 ASCII values converting characters to 336 of nonprinting characters 877 ASin function 337 assignment arrays 49, 51, 53 overflow 72 shortcut operators 118 statements 116 asterisk in text patterns 747 ATan function 338 AttachmentFile property 736 audio (beep) 338 AutoCommit 1121 Autoinstantiate setting 82 automation 994, 996, 997 axis, graphs categories 316, 350, 424, 632 inserting data 636
1016
B
back quote 119 background color, graphs data points 529, 1009 series 581, 1052 background layer of DataWindow 1040 backslash in text patterns 746 backspace, specifying 7 bands, DataWindow, moving objects to 1040 BAT file 939 batch applications 845 beam pointer 1038 Beep function 338 BeginDrag event 185 BeginLabelEdit event 188 BeginRightDrag event 190
1194
PowerBuilder
Index
BeginTransaction function 339 birth dates 1188 bitmaps assigning to picture control 1037 in rich text 657 printing 857 retrieving from clipboard 363 blob data type 19 Blob function 341 blob functions Blob 341 BlobEdit 342 BlobMid 343 Len 696, 697 LenW 696 BlobEdit function 342 BlobMid function 343 blobs assigning to picture control 1037 converting to string 341, 1110 declaring 35 extracting values from 412, 417, 423, 660, 715, 717, 898, 1129 inserting data into 342 reading streams into 896 selecting from database 162 updating 165 writing to stream 1181 boolean data type 19 border determining distance from 832, 833 printing 869, 872, 874 bottom layer of DataWindow 1040 bound 725, 1171 brackets in text patterns 747 BuildModel function 345 Cancel button 753 Cancel function 348 cancellation allowing 1189 of edits 1166 of pipeline object 348 of printing 858 CanUndo function 349 capitalization in category names 316, 632 in series names 328 lowercase 724 uppercase 1170 caret in text patterns 746 carriage return in INI files 891 specifying 7 cascaded windows, arranging sheets 335 cascading opened windows 792 case sensitivity, comparisons 68 categories, graphs adding data values to series 316, 318 adding to a series 316 clicked 770 counting 350 deleting 424, 916 identifying 350, 351 importing data 608, 611, 615 InsertCategory function 316 inserting 632 new 316 CategoryCount function 350 CategoryName function 351 Ceiling function 352 century 1188 ChangeDirectory function 353 ChangeMenu function 354 channel, DDE 370, 790 char data type about 20 array 74 converting to string 74 Char function 355 character array 1181 characters array 896
C
C functions decoding returned values passing values to 715 CALL statement about 119 not using 182 663
1195
Index
changing capitalization 724, 1170 converting to ASCII values 336 extracting 355, 755 mask 1028 matching 746 returning rightmost 931 selected 964, 967 selecting 977 Check function 356 Checked property 1164 child windows obtaining parent 824 opening 777, 815 CHOOSE CASE statement 120 ChooseColor function 357 class contrasted with object 76 of object 359 OLE 634 class hierarchy 27 class user objects 78 ClassDefinition objects, FindMatchingFunction ClassList function 358 ClassName function 359 Clear function 361 clearing text 361 Clicked event 192, 771 clipboard contents as replacement text 914 copying 396 cutting 407 importing data from 608 pasting and linking 827 pasting from 825 retrieving and replacing contents 363 Clipboard function 363 CLOSE Cursor statement 145 Close event 198, 366, 924 Close function 366 CLOSE Procedure statement 146 CloseChannel function 370 CloseQuery event 200, 366 CloseTab function 371 CloseUserObject function 373 CloseWithReturn function 375 closing
488
DDE channel 370 print job 860 windows 366 code generating DataWindow 1120 object 705 reusing 846 cold link 456, 577, 790, 1048 CollapseItem function 378 colors and edit masks 1028 data point 529, 919, 1009 red, green, and blue components of 929 series 580, 1052 supported 544 table of standard colors 929 ColumnClick event 202 columns determining insertion point position 839 in list 635 pasting text into 825 COM file 939 command line, retrieving arguments 379 CommandParm function 379 commands getting from DDE client 511 receiving form DDE application 923 comments in library 699 using 4 COMMIT statement 147 CommitTransaction function 381 comparing numbers 659, 749, 758 comparing strings 68 computer beeping 338 reporting CPU time 401 concatenation operator 69 condensed mode 877 configuration settings reading 889, 891 saving 1042 CONNECT statement 148 Connection objects ConnectToServer function 393
1196
PowerBuilder
Index
CreateInstance function 404 DisconnectServer function 444 connections, to OLE object 383, 385 ConnectToNewObject function 383 ConnectToNewRemoteObject function 385 ConnectToServer function 393 constants assigning values 38 declaring 44 where to declare 31 Constructor event 204 ContextInformation objects GetCompanyName function 513 GetFixesVersion function 553 GetHostObject function 557 GetMajorVersion function 564 GetMinorVersion function 566 GetName function 567 GetShortName function 586 GetVersionName function 599 ContextKeyword objects, GetContextKeywords function 514 context-sensitive Help 1083 continuation character 15 CONTINUE statement 122 continuous line style setting for data points 1011 setting for series 1054 Control array 806, 808 control structures CHOOSE CASE 120 DO...LOOP 127 FOR...NEXT 130 IF...THEN 134 controls determining type 1162 dragging 447 focus of 554, 1019 hiding 602, 763 moving 763 obtaining handle 600 redrawing 1047 referencing 376 resizing 920 yielding 1189 conventions xxiv coordinates ListView items 570 of print cursor 887, 888 of print objects 857, 869, 872, 874 Copy function 396 copying importing from clipboard 608 to clipboard 396 CopyRTF function 398 CORBACurrent, initializing 620 Cos function 400 cosine 400 count, of data points in a series 409 CPU getting information about 544 time 401 Cpu function 401 CREATE statement 123, 834 CreateDirectory function 401 CreateInstance function 404 CreatePage function 406 cross mouse pointer 1038 crosstabs, creating from source code 1120 current row and scrolling 953, 955 sheet 792 cursor custom 1038 displaying popup menus 834 print 853 cursors, database closing 145 declaring 144, 149 opening 158 custom class user objects 81 Cut function 407 cutting, to clipboard 407
D
dash line style about 1011, 1054 setting for series 1054 dashes, prohibiting in variable names DashesInIdentifiers option 5
1197
Index
data adding to a graph series 318, 320 clearing 915 converting to type long 715, 717 correcting pipeline 911 finding in DataWindow 477 from OLE server 523 getting DDE 525 importing 608 inserting into a blob 342 obtaining from control 520 receiving from DDE application 923 sending to DDE client 1005 sharing 410 to OLE server 1003 transferring 1094 writing to file 474 writing to stream 1181 data expressions Any data type 26 Data Pipeline painter 348, 1095 data points adding to a scatter graph 320 clicked 770 deleting 424 inserting 636 reporting appearance of 529 reporting explosion percent 527 resetting colors 919 setting style 1009 value of 520, 535 data type checking and conversion functions Asc 336 Char 355 Date 412 DateTime 416 Dec 423 Double 445 Integer 660 IsDate 676 IsNull 681 IsNumber 682 IsTime 685 Long 715, 717 Real 898 String 1110
Time 1129 data type mappings, EAServer 29 data types about 19 assignment 72 blob 341 date 415 determining 359 effect of operators 71 enumerated 28 external functions 59 literals 20, 21, 22, 24, 72 mismatch when pasting 825 numeric 71 promotion 71 promotion for function arguments 100 real 898 setting to NULL 1032 standard 19 string 1110 system object 27 time 1129 unknown 24 windows 775 database stored procedures 141 databases canceling changes 159 commiting changes 147 connecting to 148 cursor, opening 158 deleting rows 152, 153 disconnecting from 154 fetching rows 156 handle 422 inserting rows 157 on restart 924 repairing 911 selecting rows 160 transactions 1073 transferring data between 1094 updating 164 updating cursored row 167 DataChange event 205 DataSource function 410 DataWindow control data expressions and Any data type 26
1198
PowerBuilder
Index
for pipline errors 1095 DataWindow functions CanUndo 349 CategoryCount 350 CategoryName 351 Clear 361 Clipboard 363 Copy 396 Cut 407 DataCount 409 FindCategory 479 FindNext 490 FindSeries 491 GetData 520 GetDataPieExplode 527 GetDataStyle 529 GetSeriesStyle 580 LineCount 708 ObjectAtPointer 770 Paste 825 PasteRTF 828 Position 839 ReplaceText 914 ResetDataColors 919 Scroll 951 SelectedLength 964 SelectedLine 965 SelectedStart 967 SelectedText 968 SelectText 977 SeriesCount 987 SeriesName 988 SetDataPieExplode 1007 SetDataStyle 1009 SetPosition 1040 SetSeriesStyle 1052 TextLine 1128 Undo 1166 DataWindow object creating from SELECT statement deleting from libraries 700 exporting as syntax 705 listing 701 recreating from syntax 706 date data type 20 Date function 412 date, day, and time functions Day 418 DayName 419 DayNumber 420 DaysAfter 421 Hour 603 Minute 758 Month 762 Now 769 RelativeDate 906 RelativeTime 907 Second 957 SecondsAfter 958 Today 1135 Year 1188 dates checking string 676 converting to 413 DateTime data type 412, 416 day of week 419, 420 determining interval 421 getting dynamic 537, 539 in blobs 412 obtaining current 1135 obtaining day of month 418 DateTime data type 20 DateTime function 416 Day function 418 DayName function 419 DayNumber function 420 DaysAfter function 421 dBase file, importing data from 611, 615 DBHandle function 422 DDE channel closing 370 requesting data 578 DDE client functions CloseChannel 370 ExecRemote 456 GetDataDDE 525 GetDataDDEOrigin 526 GetRemote 577 OpenChannel 790 RespondRemote 923 SetRemote 1048 StartHotLink 1101
1120
1199
Index
StopHotLink 1108 DDE server functions GetCommandDDE 511 GetCommandDDEOrigin 512 GetDataDDE 525 GetDataDDEOrigin 526 RespondRemote 923 SetDataDDE 1005 StartServerDDE 1103 StopServerDDE 1109 DDL, executing through dynamic SQL 172, 173 Deactivate event 205 DebugBreak function 422 Dec function 423 decimal data type about 20 converting to 423 declaring 35 declarations access levels 40 arrays 45 constants 44 expressions as initial values 39 syntax 35 variables 31 where to declare 31 DECLARE Cursor statement 149 DECLARE Procedure statement 150 definition, font for printing 862 DELETE statement 152 DELETE Where Current of Cursor statement 153 DeleteAllItems event 206 DeleteCategory function 424 DeleteColumn function 425 DeleteColumns function 425 DeleteData function 426 DeleteItem event 206 DeleteItem function 427 DeleteLargePicture function 431 DeleteLargePictures function 431 DeletePicture function 432 DeletePictures function 432 DeleteSeries function 433 DeleteSmallPicture function 434 DeleteSmallPictures function 434 DeleteStatePicture function 435
DeleteStatePictures function 435 descendant determining class of 359 opening user object 798, 799, 807, 809 opening window 778 return values from events 110 DESTROY statement about 126 ending a mail session 732 DestroyModel function 436 Destructor event 208, 371, 373 detail bands, moving objects to 1040 diagonal fill pattern 1013, 1055 dialog Insert Object 656 Open File 546 PasteSpecial 829 Save File 550 diamond fill pattern 1013, 1056 dimension 725 dimension of array 1171 directory, of library 701, 703 DirectoryExists function 437 DirList function 438 DirSelect function 440 Disable function 441 DisableCommit function 442 DISCONNECT statement 154 DisconnectObject function 443 DisconnectServer function 444 display format, applying to string 1110 distributed applications ConnectToServer function 393 DisconnectServer function 444 SharedObjectDirectory function 1075 SharedObjectGet function 1076 SharedObjectRegister function 1079, 1080 division 759 division operator 66, 67 DLL files executing functions from 61 DLLs for external functions 57 DO...LOOP statement 127 document windows 792 dollar sign in text patterns 746 dot notation
1200
PowerBuilder
Index
about 34 instance variables 33 structures 75 dotted line style setting for data points 1011 setting for series 1054 double colon 119 double data type 21 Double function 445 DoubleClicked event 209 DoubleParm property 795, 802, 804, 811, 813 DoVerb function 446 Drag function 447 DragDrop event 213 DragEnter event 217 DraggedObject function 449 dragging, TreeView items 1015 DragLeave event 218 DragObject functions ClassName 359 Drag 447 Hide 602 Move 763 PointerX 832 PointerY 833 PostEvent 845 Print 851 Resize 920 SetFocus 1019 SetPosition 1039 SetRedraw 1047 Show 1081 TriggerEvent 1153 TypeOf 1162 DragWithin event 220 Draw function 450 drawing objects and SetFocus function 1019 posting events 845 setting color of 929 DrawObject functions ClassName 359 Hide 602 Move 763 Print 851 Resize 920 Show 1081 TypeOf 1162 DropDownListBox control, deleting text DropDownListBox functions AddItem 321 Clear 361 Copy 396 Cut 407 DeleteItem 427 DirList 438 DirSelect 440 DraggedObject 449 FindItem 482 InsertItem 642 Paste 825 Position 839 Post 844 ReplaceText 914 Reset 915 SelectedLength 964 SelectedStart 967 SelectedText 968 SelectItem 971 SelectText 977 Text 1127 TotalItems 1138 DropDownPictureListBox functions AddItem 322 AddPicture 327 Clear 361 Copy 396 Cut 407 DeletePicture 432 DeletePictures 432 FindItem 482 InsertItem 643 Paste 825 Position 839 ReplaceText 914 SelectedLength 964 SelectedStart 967 SelectedText 968 SelectItem 971 SelectText 977 Text 1127 TotalItems 1138
361
1201
Index
DWObjects, OLE functions 314, 396, 446, 1168 dynamic calls 94 errors 96 dynamic libraries 332, 1026 dynamic library (DLL) 1101 dynamic SQL about 168 considerations 170 DynamicDescriptionArea 169 DynamicStagingArea 169 Format 1 172 Format 2 173 Format 3 174 Format 4 177 formats listed 168 NULL values 173, 174 ordering statements 170 preparing DynamicStagingArea 170 statements 169 dynamic SQL functions GetDynamicDate 537 GetDynamicDateTime 539 GetDynamicNumber 541 GetDynamicString 542 GetDynamicTime 543 SetDynamicParm 1016 DynamicDescriptionArea about 169 properties 178 DynamicStagingArea about 169 preparing 170
E
EAServer data type mappings 29 edit control counting lines in 708 deleting text from 361 determining insertion point position inserting clipboard contents 363 replacing text 914 selected text 964, 967 EditLabel function 402, 451 EditMask functions
839
CanUndo 349 Clear 361 Copy 396 Cut 407 GetData 522 LineCount 708 LineLength 709 Paste 825 Position 839 ReplaceText 914 Scroll 951 SelectedLength 964 SelectedLine 965 SelectedStart 967 SelectedText 968 SelectText 977 SetMask 1028 TextLine 1128 Undo 1166 embedded SQL 141 Enable function 453 EnableCommit function 454 Enabled property 602, 1047 EndLabelEdit event 223 EntryList function 455 enumerated data types 28 envelope, mail message header 735 environment getting information about 544 TEMP variable 736 error checking cascaded calls 106 compiling scripts 95 Error DataWindow 911 Error event 225 error handling after SQL statements 143 calling functions or events 96, 98 error objects, creating 123 errors displaying pipeline 1095 during execution 67 escape sequences 877 events about 87, 181 adding to queue 845
1202
PowerBuilder
Index
ancestor 109 and hidden objects 602 and print jobs 860 arguments 101, 182 cascaded calls 105, 108 defined 88 errors when calling 96 extending 101 finding 91 overriding 101 posting 91, 106, 1124 return codes 182 return values 105, 182 similarities to functions 89 static and dynamic 93 system 88, 181 triggering 91, 182, 1125, 1153 user-defined 181, 183 exclamation point icon 753 exclusive share mode 782, 785, 786 ExecRemote function 456 executable returning application handle 600 running 939 EXECUTE statement 155, 1016 execution errors 95 EXIT statement 129 Exp function 459 ExpandAll function 460 ExpandItem function 461 exponent 459 exponentiation operator 66 expressions Any data type 25 checking for NULL 681 data type promotion 71 data types 71 DataWindows and Any data type 26 in declaration 39 literals 72 operators and data types 71 external functions 55 ExternalException event 228
F
Fact function 461 FETCH statement 156 file functions FileClose 462 FileDelete 464 FileExists 465 FileLength 466 FileOpen 468 FileRead 470 FileSeek 473 FileWrite 474 GetFileOpenName 546 GetFileSaveName 550 FileClose function 462 FileCopy function 463 FileDelete function 464 FileExists event 231 FileExists function 465 FileLength function 466 FileMove function 467 FileOpen function 468 FileRead function 470 files importing data from 611 linking 711 security and sharing violation 466 FileSeek function 473 FileWrite function 474 Fill function about 476, 477 and printing 476, 477 FillPattern 531, 1012, 1055 FillW function 476, 477 filtering filenames 546, 550 Find function 477 FindCategory function 479 FindClassDefinition function 480 FindFunctionDefinition function 481 FindItem function 482 FindMatchingFunction function 488 FindNext function 490 FindSeries function 491 FindTypeDefinition function 492 flicker 1047 focus
1203
Index
and line length 709 finding control with 554 selected text 964, 967, 968, 977 setting 1019 folder 701 fonts and string length when printing 886 defining for printing 862 FontFamily enumerated data type 862 FontPitch enumerated data type 862 names and sizes 863 setting 879 when printing 853 when printing DataWindow controls 861 footer, moving objects to 1040 foreground color data points 529, 1009 series 581, 1052 foreground layer of DataWindow 1040 Form presentation style 1120 formats, applying to strings 1110 formfeed, specifying 7 frame window 834, 1179, 1180 FromAnsi function 494 FromUnicode function 495 function object exporting as syntax 705 listing 701 re-creating from syntax 706 functions about 87 access level for external 57 ancestor 109 arguments 101 calling global and system 107 cascaded calls 105, 108 case sensitivity 107 chars as arguments 74 DLLs 57 errors when calling 96 external 55 external data types 59 external, defined 88 external, mail 731 external, reporting database handle 422 finding 90
overloading 99 overriding 99 posting 91, 106 return values 104 similarities to events 89 static and dynamic 93 system, defined 88 triggering 91 type promotion 100 user-defined 88
G
garbage collection 80, 124, 126 GarbageCollect function 497 GarbageCollectGetTimeLimit function 497 GarbageCollectSetTimeLimit function 498 GetActiveSheet function 499 GetAlignment function 500 GetApplication function 501 GetArgElement function 502 GetAutomationNativePointer function 503 GetCertificateLabel function 504 GetChildrenList function 507 GetColumn function 509 GetCommandDDE function 511 GetCommandDDEOrigin function 512 GetCompanyName function 513 GetContextKeywords function 514 GetContextService function 515 GetCredentialAttribute function 517 GetCurrentDirectory function 519 GetData function 520 GetDataDDE function 525 GetDataDDEOrigin function 526 GetDataPieExplode function 527 GetDataStyle function 529 GetDataValue function 535 GetDynamicDate 178 GetDynamicDate function 537 GetDynamicDateTime 178 GetDynamicDateTime function 539 GetDynamicNumber 178 GetDynamicNumber function 541 GetDynamicString 178
1204
PowerBuilder
Index
GetDynamicString function 542 GetDynamicTime 178 GetDynamicTime function 543 GetEnvironment function 544 GetFileOpenName function 546 GetFileSaveName function 550 GetFirstSheet function 552 GetFixesVersion function 553 GetFocus event 232 GetFocus function 554 GetFolder function 555 GetGlobalProperty function 556 GetHostObject function 557 GetItem function 558 GetItemAtPointer function 561 GetLastReturn function 562 GetLibraryList function 563 GetMajorVersion function 564 GetMinorVersion function 566 GetName function 567 GetNativePointer function 568 GetNextSheet function 569 GetOrigin function 570 GetParagraphSetting function 571 GetParent function 572 GetPin function 574 GetRecordSet function 576 GetRemote function 577 GetSeriesStyle function 580 GetShortName function 586 GetStatus function 588 GetToolbar function 592 GetToolbarPos function 594, 1067 GetTransactionName function 597 GetURL function 598 GetVersionName function 599 global functions calling 107 defined 88 global scope operator 33 global variables about 32 scope operator 33 GOTO statement 132 Graph functions AddCategory 316 AddData 318 AddSeries 328 CategoryCount 350 CategoryName 351 Clipboard 364 DataCount 409 DeleteCategory 424 DeleteData 426 DeleteSeries 433 FindCategory 479 FindSeries 491 GetData 520 GetDataPieExplode 527 GetDataStyle 529 GetSeriesStyle 580 ImportClipboard 608 ImportFile 611 ImportString 615 InsertCategory 632 InsertData 636 InsertSeries 658 ModifyData 760 Reset 915 SaveAs 943 SeriesCount 987 SeriesName 988 SetDataPieExplode 1007 SetDataStyle 1009 SetSeriesStyle 1052 graphics, printing 857 graphs categories 318 overlay 585 series 328 grColorType enumerated data type 529 grDataType enumerated data type 520, 535 Grid presentation style 1120 grObjectType enumerated data type 770 Group presentation style 1120 grResetType enumerated data type 916 grSymbolType enumerated data type 1056
H
HALT statement 133
1205
Index
handle database 422 DDE 370, 790, 1103 mailSession object 731, 985 validating 687 Handle function 600 header band, moving objects to 1040 Hebrew functions IsAllHebrew 669 IsAnyHebrew 671 IsHebrew 677 IsHebrewAndNumbers 678 height object 920 workspace 1176 Help calling Winhelp 1083 displaying MicroHelp 1031 Help event 233 Help Search window 1083 hidden objects 1081 Hide event 234 Hide function 602 hierarchies child items in a list 648, 650, 653 items in TreeView 378, 461 sorting 1091 sorting children 1089 system 27, 359 high word of long 663 highlighting items in lists 971, 1105 scrolling 955 setting 1060 horizontal fill pattern 1013, 1056 horizontal scrollbar for lists 321 horizontal scrolling, when adding items to lists host variables in SQL 142 hot link about 1005 determining origin of 526 determining source of data 526 establishing 1101 terminating 1108 HotLinkAlarm event 234 Hour function 603
hourglass pointer 1038 HyperlinkToURL function 604 hyphens, prohibiting in variable names
I
icons arranging in ListView 334 arranging windows 335 in message box 753 identifier names, rules for 5 Idle event 235 IDs for events 181 IF...THEN statement about 134 multiline 135 single-line 134 image assigning to picture control 1037 retrieving from clipboard 363 ImpersonateClient function 607 ImportClipboard function 608 ImportFile function 611 importing, data 611, 615 ImportString function 615 inbox deleting messages from 728 downloading messages to 734 reading mail messages 735 retrieving message IDs from 728, 729 saving messages in 742 IncomingCallList function 618 index highlight state of 1060, 1105 obtaining top 1136 of listbox item 962, 972 indicator variables in SQL 142 Inet objects GetURL function 598 HyperlinkToURL function 604 PostURL function 848 Information icon 753 inheritance 80 back quote 119 double colon 119
321
1206
PowerBuilder
Index
PowerBuilder objects 27 INI file reading 889, 891 writing values to 1042 Init function 620, 621 input fields in rich text 624, 626, 627, 628, 629, 630 InputFieldChangeData function 624 InputFieldCurrentName function 626 InputFieldDeleteCurrent function 627 InputFieldGetData function 628 InputFieldInsert function 629 InputFieldLocate function 630 InputFieldSelected event 236 Insert Object dialog 656 INSERT statement 157 InsertCategory function 632 InsertClass function 634 InsertColumn function 635 InsertData function 636 InsertFile function 641 inserting strings 912, 913 insertion point character position 961 in editable controls 709 in text line 965, 1128 when pasting from clipboard 825 InsertItem event 237 InsertItem function 642 InsertItemFirst function 648 InsertItemLast function 650 InsertItemSort function 653 InsertObject function 656 InsertPicture function 657 InsertSeries function 658 instance variables about 32 class of 359 dot notation 33 initialized 40 instances checking if valid 687 defined 76 of user object 797, 801, 806, 810 Int function 659 integer combining into long value 715, 717 converting to 660 converting to char 355 obtaining from blob 660 integer data type 21 Integer function 660 Intel 544 InternetData function 662 InternetRequest objects, InternetData function interpersonal messages 729 interprocess messages 729 interval 1132 IntHigh function 663 IntLow function 663 InvokePBFunction function 664 Is_A ( _Is_A ) function 666 IsAlive function 667 IsAllArabic function 668 IsAllHebrew function 669 IsAnyArabic function 670 IsAnyHebrew function 671 IsArabic function 672 IsArabicAndNumbers function 673 IsCallerInRole function 674 IsDate function 676 IsHebrew function 677 IsHebrewAndNumbers function 678 IsImpersonating function 679 IsInTransaction function 680 IsNull function 681 IsNumber function 660, 682 IsPreview function 683 IsSecurityEnabled function 684 IsTime function 685 IsTransactionAborted function 686 IsValid function about 687 and Handle function 600 description 687 getting active sheet 499 getting open sheets 552, 569 ItemActivate event 238 ItemChanging event 240 ItemCollapsed event 241 ItemCollapsing event 242 ItemExpanded event 243 ItemExpanding event 244
662
1207
Index
ItemPopulate event 245 items adding to lists 321, 642 deleting from list 427, 915 determining number of selected 1139 determining total number of 1138 highlight state of 1060, 1105 index number of 962 linking 711 selecting 971 text of 963, 1127 top 1071, 1136
J
JaguarORB, initializing 620
K
Key event 246 keyboard determining key pressed 687 selecting text 397 KeyCode enumerated data type about 687 values 688 KeyDown function 688 keywords 9
L
Label presentation style 1120 labels for GOTO 6 language for OLE automation 994, 997 LastPos function 691 Layer enumerated data type 335 Layered window 794 layering opened windows 792 layout 861 Left function 693, 694 LeftTrim function 695 LeftTrimW function 695 LeftW function 693, 694
Len function 696, 697 length line 709 OLE stream 698 selected text 964 string or blob 696, 697 Length function 698 LenW function 696 LibDirType enumerated data type 701, 703 LibExportType enumerated data type 705 libraries deleting objects from 701, 703 pasting and linking object from 827 search path 332, 563, 1026 Library functions LibraryCreate 699 LibraryDelete 700 LibraryDirectory 701 LibraryDirectoryEx 703 LibraryExport 705 LibraryImport 706 LibraryCreate function 699 LibraryDelete function 700 LibraryDirectory function 701 LibraryDirectoryEx function 703 LibraryExport function 705 LibraryImport function 706 limit, numeric 352 line spacing setting 881 when printing text 853 LineCount function 708 LineDown event 248 LineLeft event 249 LineLength function 709 LineList function 710 LineRight event 250 lines and SetFocus function 1019 color for data points 529 counting number of 708 determining length 709 graphs, color for data points 1009 graphs, color for series 581, 1052 graphs, style for data points 531, 1011 graphs, style for series 582, 583, 1054
1208
PowerBuilder
Index
printing 866, 884 scrolling 951 selected text 965 spacing in rich text 587 text 1128 width 531 LineUp event 251 linking clipboard contents 827, 829 establishing 711 LinkTo function 711 ListBox functions AddItem 321 DeleteItem 427 DirList 438 DirSelect 440 FindItem 482 InsertItem 642 Reset 915 SelectedIndex 962 SelectedItem 963 SelectItem 971 SetState 1060 SetTop 1071 State 1105 Text 1127 Top 1136 TotalItems 1138 TotalSelected 1139 lists adding items 642 adding new item 321 deleting items from 915 horizontal scrollbar 321 of files in listbox 438 of objects in libraries 701, 703 sorted 322 ListView control, columns 1022 ListView functions AddColumn 317 AddItem 323, 324 AddLargePicture 326 AddSmallPicture 330 AddStatePicture 331 Arrange 334 DeleteColumn 425 DeleteColumns 425 DeleteItem 428 DeleteLargePicture 431 DeleteLargePictures 431 DeleteSmallPicture 434 DeleteSmallPictures 434 DeleteStatePicture 435 DeleteStatePictures 435 EditLabel 451 FindItem 483, 484 GetColumn 509 GetItem 559 GetOrigin 570 InsertColumn 635 InsertItem 644 ListView 1137 SelectedIndex 962 SetItem 1021 SetOverlayPicture 1033 Sort 1090 TotalItems 1138 TotalSelected 1139 literals data types of 72 specifying 20, 21, 22, 24 local variables 32 Log function about 713 inverse 712 natural logarithm 712 logarithms 712, 714 logical operators 68 LogTen function about 714 inverse 714 long data type about 21 converting to 715, 717 returning high word 663 returning low word 663 Long function 715, 717 LongParm posting events 845 specifying values for 715 triggering events 1153 Lookup function 719
1209
Index
loops about 127 iterative 130 leaving 129 skipping current iteration yielding within 1189 LoseFocus event 252, 754 low word of long 663 Lower function 724 LowerBound function 725 lowercase 724
122
M
mail functions mailAddress 726 mailDeleteMessage 728 mailGetMessages 729 mailHandle 731 mailLogoff 732 mailLogon 733 mailReadMessage 735 mailRecipientDetails 737 mailResolveRecipient 739 mailReturnCode 733 mailSaveMessage 742 mailSend 744 mailAddress function 726 mailDeleteMessage function 728 mailHandle function 731 mailLogoff function 732 mailLogon function 733 mailLogonOption enumerated data type 733 mailReadMessage function 735 mailReadOption enumerated data type 736 mailRecipient structure 739 mailRecipientDetails function 737 mailResolveRecipient function 739 mailReturnCode function 733 mailSaveMessage function 742 mailSend function 744 main window 763 MAPI 731 margins 853, 877, 1036 masks
applying to strings 1110 matching 746 reporting length of 709 setting 1028 Match function 746 MatchW function 746 Max function 749 maximum value below a limit 659 maximum value of two numbers 749 MDI Client (MDI_1) functions ClassName 359 Hide 602 Print 851 Resize 920 SetRedraw 1047 Show 1081 TypeOf 1162 MDI frame arranging windows 335 changing menus 354 displaying popup menus 834 getting active 499 opening sheets 777, 792, 794 specifying MicroHelp text 1031 MDI frame functions ArrangeSheets 335 GetActiveSheet 499 GetFirstSheet 552 GetNextSheet 569 GetToolbar 592 GetToolbarPos 594, 1067 OpenSheet 792 OpenSheetWithParm 794 Print 851 SetMicroHelp 1031 SetToolbar 1065 measurement 1167 member, OLE 750, 751, 752 MemberDelete function 750 MemberExists function 751 MemberRename function 752 memory allocation for arrays 50 and variable-sized arrays 1171 releasing after mail session 732 Menu functions
1210
PowerBuilder
Index
Check 356 ClassName 359 Disable 441 Enable 453 PopMenu 834 Show 1081 TriggerEvent 1153 TypeOf 1162 Uncheck 1164 Menu objects exporting as syntax 705 listing 701 recreating from syntax 706 menus changing 354 Checked property 356 creating object 123 displaying 834 for sheet 792 message ID array 729 Message object accessing parameters 815 and TriggerEvent function 1153 close return value 375 creating 123 determining type 1164 extracting strings from 1111, 1114 open sheet parameters 794 PowerObjectParm property 375 properties 802, 804, 811, 813 specifying values for 715 MessageBox function 753, 867 messages deleting 728 posting 844 saving 742, 744 sending to a window 985 metacharacters 746 MicroHelp 1031 Microsoft Windows and DDE 577 and timers 1132 calling Winhelp 1083 defining fonts for printing 863 displaying Save File response window events and messages in 846 getting filenames 546 getting information about 544 message numbers 985 obtaining handle 600 returned messages 663 RightToLeft version 668, 669, 670, 671, 672, 673, 677, 678, 927 Mid function 755 MidW function 755, 757 Min function 758 minimum value above a limit 352 of two numbers 758 Minute function 758 miscellaneous functions IsValid 687 KeyDown 688 MessageBox 831 PixelsToUnits 831 RGB 929 SetNull 1032 SetPointer 1038 TypeOf 1162 UnitsToPixels 1167 Mod function 759 Modified event 254 ModifyData function 760 modulus 759 monitor 544 Month function 762 month, obtaining the day of 418 More Windows menu item 793 mouse selecting text 397 setting shape of pointer 1038 MouseDown event 256 MouseMove event 258 MouseUp event 262 Move function 763 Moved event 265 multidimensional arrays 48, 52 MultiLineEdit functions CanUndo 349 Clear 361 Copy 396 Cut 407
550
1211
Index
LineCount 708 LineLength 709 Paste 825 Position 839 ReplaceText 914 Scroll 951 SelectedLength 964 SelectedLine 965 SelectedStart 967 SelectedText 968 SelectText 977 TextLine 1128 Undo 1166 multiplication operator 66, 67 MultiSelect property highlighted state 1060, 1108 selecting items 962, 963, 973
N
names, rules for 5 naming conventions 37 Narrow ( _Narrow ) function 766 negative numbers 1086 nested OLE objects 783, 786 newline, specifying 7 NextActivity function 767 NOT operator 68 Now function 769 null object references 795, 802, 804, 811, 813, 816, 818 NULL values about 8 checking 681 dynamic SQL 174 in boolean expressions 68 setting variables to 1032 testing for 8 numbers category 351 checking string 682 comparing 749, 758 converting char 355, 413, 423 determining maximum 352 determining sign of 1086 getting dynamic 541
logarithm of 712, 714 multiplying by pi 830 of day of week 420 of lines, counting 708 random 893, 894 returning remainder 759 rounding 937 truncating 1158 numeric functions Abs 312 ACos 313 ASin 337 ATan 338 Ceiling 352 Cos 400 Exp 459 Fact 461 Int 659 Log 712 Max 749 Min 758 Mod 759 Pi 830 Rand 893 Randomize 894 Round 937 Sign 1086 Sin 1088 Sqrt 1093 Tan 1126 Truncate 1158 N-Up presentation style 1120
O
ObjectAtPointer function 770 objects about 76 ancestor 80 assignment 82 changing position 1040 creating instance 123 deleting from libraries 700 destroying instance 126 determining class of 359
1212
PowerBuilder
Index
determining type 1162 garbage collection 80, 126 general references 10 hiding 602, 763 inserting 634, 641, 656 instantiating 79 linking 711 loading 332, 1026 moving 763 obtaining handle 600 parent object 572 passing as arguments 102 posting events 845 recreating 706 redrawing 1047 reference handle 76 saving OLE 941 selecting 975 setting focus 1019 triggering events 1153 under pointer 770 objects, Connection ConnectToServer function 393 CreateInstance function 402, 404 DisconnectServer function 444 objects, shared SharedObjectDirectory function 1075 SharedObjectGet function 1076 SharedObjectRegister function 1079 SharedObjectUnregister function 1080 ObjectToString function 773 OffsetPos function 774 Offsite enumerated data type 314 OK button 753 OLE DWObject functions Activate 314 Copy 396 DoVerb 446 UpdateLinksDialog 1168 OLE expressions and Any data type 26 OLEControl functions Activate 314 Clear 361 Copy 396 Cut 407 DoVerb 446 GetData 523 GetNativePointer 568 InsertClass 634 InsertFile 641 InsertObject 656 LinkTo 711 Open 775 Paste 825 PasteLink 827 PasteSpecial 829 ReleaseAutomationPointer 909 Save 941 SaveAs 945, 946 SelectObject 975 SetAutomationLocale 994 SetData 1003 UpdateLinksDialog 1168 OLECustomControl functions GetData 523 GetNativePointer 568 ReleaseAutomationPointer 909 SetAutomationLocale 994 SetData 1003 OLEObject functions ConnectNewToObject 383 ConnectToNewRemoteObject 385 ConnectToObject 387 ConnectToRemoteObject 390 DisconnectObject 443 GetAutomationNativePointer 503 ReleaseAutomationPointer 908 SetAutomationPointer 996 SetAutomationTimeout 997 OLEStorage functions Clear 361 Close 367 MemberDelete 750 MemberExists 751 MemberRename 752 Open 775 SaveAs 947, 948 OLEStream functions Close 368 Length 698 Open 775 Read 895
1213
Index
Seek 959 Write 1181 OPEN Cursor statement 158 Open event 266, 924 Open function 775 OpenChannel function 790 OpenSheet function 792 OpenSheetWithParm 794 OpenTab function 797 OpenTabWithParm function 801 OpenUserObject function 806 OpenUserObjectWithParm function 810 OpenWithParm 815 operating system information about 544 RightToLeft version 668, 669, 670, 671, 672, 673, 677, 678, 927 operators about 65 arithmetic 66 assignment shortcuts 116, 118 concatenation 69 effect on data types 71 logical 68 precedence 70 relational 68 OR operator 68 Original window 794 Other event 269 OutgoingCallList function 820 oval and SetFocus function 1019 printing 869 overflow on assignment 72 overlay 585, 1057 overloading functions 99 overriding functions 99
P
page printing 871 printing borders 869, 872, 874 size 853 PageCreated function 823
PageDown event 270 PageLeft event 271 PageRight event 272 PageUp event 273 paging functions ScrollNextPage 952 ScrollPriorPage 954 paragraphs 1036 parameters command line 379 opening sheets with 794 opening tab pages with 801 opening user objects with 798, 799, 807, 809, 810 opening windows with 815 specifying for DynamicDescriptionArea 1016 Parent pronoun 12 parent window changing position relative to 763 obtaining 824 of open window 776, 777, 815 parentheses in expressions 70 ParentWindow function 824 parsing strings 837, 838 password 733 Paste function 825 PasteLink function 827 PasteSpecial function 829 pasting embedding or linking 829 from clipboard 825, 827 path of library file 699 OLE storage 777 returning 546 saving files 550 pattern matching 746 PBL file creating 699 deleting 700 listing contents of 701, 703 pbm_dwngraphcreate event 1053 PDB file 778 performance and Yield function 1189 Any data type 27 dynamic function and event calls 95
1214
PowerBuilder
Index
period in text patterns 746 Pi function 830 Picture functions ClassName 359 Drag 447 Draw 450 Hide 602 Move 763 PointerX 832 PointerY 833 PostEvent 845 Print 851 SetFocus 1019 SetPicture 1037 SetPosition 1039 SetRedraw 1047 Show 1081 TriggerEvent 1153 TypeOf 1162 PictureListBox functions AddItem 322 AddPicture 327 DeletePicture 432 DeletePictures 432 FindItem 482 InsertItem 643 SelectedItem 963 SelectItem 971 SetTop 1071 State 1105 Text 1127 Top 1136 TotalItems 1138 TotalSelected 1139 pictures for TreeView items 1025 in listboxes 327 in rich text 657 in TreeView controls 327 ListView controls 326, 330, 331 overlay in lists 1033 TreeView controls 331 PictureSelected event 274 pie graphs 527, 1007 PIF file 939 PipeEnd event 275 Pipeline functions Cancel 348 Repair 911 Start 1094 PipeMeter event 276 PipeStart event 277 pixels 831, 1167 PixelsToUnits function 831 plus sign in text patterns 747 point size 862 pointer determining distance from edge 832 distance from top 833 file 473, 474 read/write 959 returning object under 770 setting shape 1038 PointerX function 832 PointerY function 833 polymorphism for functions and events 93 PopMenu function 834 PopulateError function 836 popup windows moving 763 obtaining parent 824 opening 777, 815 Pos function 837, 838 position changing 763 of insertion point 839 setting for control 1039 Position function 839 positive numbers 1086 Post function 844 PostEvent function 845 posting functions or events 91 PostURL function 848 PosW function 837 PowerBuilder units 831, 1167 PowerBuilder, data types for external functions PowerObject base class 27, 77 PowerObject functions ClassName 359 GetContextService 515 GetParent 572 PowerObjectParm
59
1215
Index
and CloseWithReturn function 375 determining type 1164 opening sheets with parameters 795, 802, 804, 811, 813 PowerScript statements 116 precedence of numeric data types 71 precedence of operators 70 presentation styles 1120 print cursor getting coordinates of 887, 888 in print jobs 853 Print function 851 print functions Print 851 PrintBitmap 857 PrintCancel 858 PrintClose 860 PrintDataWindow 861 PrintDefineFont 862 PrintOpen 867 PrintOval 869 PrintPage 871 PrintRect 872 PrintRoundRect 874 PrintScreen 876 PrintSend 877 PrintSetFont 879 PrintSetSpacing 881 PrintSetup 882 PrintText 884 PrintWidth 886 PrintX 887 PrintY 888 print job 867 PrintBitmap function 857 PrintCancel function 858 PrintClose function 860 PrintDataWindow function 861 PrintDefineFont function 862 printer setup 877 Printer Setup dialog box 882 PrintFooter event 278 PrintGetPrinter function 864 PrintGetPrinters function 865 PrintHeader event 279 PrintLine function 866
PrintOpen function about 867 and message boxes 754 PrintOval function 869 PrintPage function 871 PrintRect function 872 PrintRoundRect function 874 PrintScreen function 876 PrintSend function 877 PrintSetFont function 879 PrintSetPrinter function 880 PrintSetSpacing function 881 PrintSetup function 882 PrintSetupPrinter function 883 PrintText function 884 PrintWidth function 886 PrintX function 887 PrintY function 888 private access functions 57 variables and constants 41 PRIVATEREAD access modifier 41 PRIVATEWRITE access modifier 41 processor 544 profile files reading 889, 891 writing to 1042 ProfileClass objects, RoutineList function 938 ProfileInt function 889 ProfileLine objects, OutgoingCallList function 820 ProfileRoutine objects IncomingCallList function 618 LineList function 710 OutgoingCallList function 820 ProfileString function 891 Profiling functions BuildModel 345 ClassList 358 DestroyModel 436 RoutineList 938 SetTraceFileName 1072 SystemRoutine 1123 pronouns about 10 instance variables 34 Parent 12
1216
PowerBuilder
Index
Super 14 This 13 properties and GetFocus function 554 font, for printing 862 getting and setting 501 Message object 795 setting width and height 920 window 776, 778 property expressions Any data type 26 PropertyChanged event 280 PropertyRequestEdit event 281 protected access functions 57 variables and constants 41 PROTECTEDREAD access modifier 41 PROTECTEDWRITE access modifier 41 public access functions 57 variables and constants 41 RButtonUp event 284 Read function 895 read-only arguments 102 real data type 21 Real function 898 recipient, mail 737 rectangle and SetFocus function 1019 printing 872, 874 references and CloseWithReturn function 376 passing arguments by 102 passing parameters 795, 802, 804, 811, 813, 816, 818 Registration database 636 RegistryDelete function 899 RegistryGet function 900 RegistryKeys function 902 RegistrySet function 903 RegistryValues function 905 relational operators 68 RelativeDate function 906 RelativeTime function 907 ReleaseAutomationNativePointer function 908 ReleaseNativePointer function 909 remainder 759 remote DDE application 923 remote procedure calls declaring 62 defined 88 RemoteExec event 284, 511, 1103 RemoteHotLink event 285 RemoteHotLinkStart event 1103 RemoteHotLinkStop event 286, 1103 RemoteRequest event 287, 1005, 1103 RemoteSend event 287, 526, 1103 RemoveDirectory function 910 Rename event 288 Repair function 911 repairing pipeline, canceling 348 Replace function 912, 913 ReplaceText function 914 ReplaceW function 912 report view for ListView 559 reserved words 9 Reset function 915
Q
question mark dynamic SQL 173, 174, 177 icon in message box 753 in text patterns 747 quoted strings, continuing 15 quotes nesting 22 rules for 23 specifying 7 with tilde 22
R
radians 830 Rand function 893 random numbers initializing generator 894 obtaining 893 Randomize function 894 RButtonDown event 282
1217
Index
ResetArgElements function 918 ResetDataColors function 919 Resize event 289 Resize function 920 ResolveInitialReferences function 921 RespondRemote function 923 response windows closing 375 moving 763 Restart function 924 ResumeTransaction function 925 retry button 753 RETURN statement 136 return values about 104 event return codes 182 from ancestor events 110 from mail session 733 TriggerEvent function 1153 Reverse function 927 RevertToSelf function 928 RGB function 929 rich text alignment 500, 992 and data 410 copying with formatting 398, 828 data 624, 626, 627, 628, 629, 630 determining insertion point position 840 editing header and footer 1082 find again 490 finding text 477 formatting 571, 587, 591, 1036 line spacing 1059 preview 683 preview document 683, 850 printing 856 save file 950 selecting 978 selecting a line 982 selecting a word 983 selecting all 981 text color 590, 1061 text settings 1062 RichTextEdit functions CanUndo 349 Clear 361
Copy 396 CopyRTF 398 Cut 407 DataSource 410 Find 477 FindNext 490 GetAlignment 500 GetParagraphSetting 571 GetSpacing 587 GetTextColor 590 GetTextStyle 591 InputFieldChangeData 624 InputFieldCurrentName 626 InputFieldDeleteCurrent 627 InputFieldGetData 628 InputFieldInsert 629 InputFieldLocate 630 InsertPicture 657 IsPreview 683 LineCount 708 LineLength 709 Paste 825 PasteRTF 828 Position 840 Preview 850 Print 856 ReplaceText 914 SaveDocument 950 Scroll 951 ScrollNextPage 952, 953 ScrollPriorPage 954 ScrollPriorRow 955 ScrollToRow 956 SelectedColumn 961 SelectedLength 964 SelectedLine 965 SelectedPage 966 SelectedStart 967 SelectedText 968 SelectText 978 SelectTextAll 981 SelectTextLine 982 SelectTextWord 983 SetAlignment 992 SetParagraphSetting 1036 SetSpacing 1059
1218
PowerBuilder
Index
SetTextColor 1061 SetTextStyle 1062 ShowHeadFoot 1082 Undo 1166 Right function 931 RightClicked event 290 RightDoubleClicked event 292 RightToLeft operating system 927 RightToLeft software 668, 669, 670, 671, 672, 673, 677, 678 RightTrim function 932 RightTrimW function 932 RightW function 931 ROLLBACK statement 159 RollbackOnly function 933 RollbackTransaction function 935 Round function 937 RoutineList function 938 rows correcting pipeline data 911 determining insertion point position 839 scrolling 952, 953, 955, 956 rows, database deleting 152, 153 fetching 156 inserting 157 updating 164 updating cursored row 167 RPC see remote procedure calls Run function 939 scope operator 108 screen changing position relative to 763 display 544 distance to workspace 1179, 1180 printing 876 scripts stopping execution 924 terminating 136 triggering events 1153 Scroll function 951 ScrollHorizontal event 754 scrolling ListBox 1071 TreeView 1018 scrolling functions Scroll 951 ScrollNextPage 952 ScrollNextRow 953 ScrollPriorPage 954 ScrollPriorRow 955 ScrollToRow 956 Top 1136 ScrollNextPage function 952 ScrollNextRow function 953 ScrollPriorPage function 954 ScrollPriorRow function 955 ScrollToRow function 956 ScrollVertical event 754 searching, rich text 477, 490 Second function 957 SecondsAfter function 958 Seek function 959 SeekType enumerated data type 959 SELECT statement 160 SELECTBLOB statement 162 Selected event 296, 1031 SelectedColumn function 961 SelectedIndex function 962 SelectedItem function 963 SelectedLength function 964 SelectedLine function 965 SelectedPage function 966 SelectedStart function 967 SelectedText function 968 selection, clearing in list 972
S
Save As dialog box 944 Save event 294 Save File response window 550 Save function 941 SaveDocument function 950 SaveObject event 295 scatter graphs adding values to series 320 changing data point values 761 importing data 608, 611, 613, 615 inserting data from strings 616 obtaining data point values 520
1219
Index
SelectionChanged event 297 SelectionChanging event 300 SelectionRange function 970 SelectItem function 971 SelectObject function 975 SelectText function about 977 copying to clipboard 397 SelectTextAll function 981 SelectTextLine function 982 SelectTextWord function 983 Send function 985 sender 735 SendMessage function 985 series, graphs adding to 328 adding values to 318 clicked 770 counting 987 data points 409, 426, 520, 535, 760, 919 deleting 433, 916 finding number of 491 importing 608, 611, 615 inserting 658 inserting data 636 obtaining name 988 reporting appearance of 580 setting style 1052 SeriesCount function 987 SeriesName function 988 server application activating 314, 975 closing DDE channel 373 connecting to 383, 385, 387, 388, 390 DDE support 791 pasting and linking 827 providing data 577 sending data to 1048 sending to DDE client 1005 stopping 1109 SetAbort function 989 SetAlignment function 992 SetArgElement function 993 SetAutomationPointer function 996 SetAutomationTimeout function 997 SetComplete function 1000
SetData function 1003 SetDataDDE function 1005 SetDataPieExplode function 1007 SetDataStyle function 1009 SetDropHighlight function 1015 SetDynamicParm function 1016 SetFirstVisible function 1018 SetFocus function 1019 SetGlobalProperty function 1020 SetItem function 1021 SetLevelPictures function 1025 SetLibraryList function 1026 SetMask function 1028 SetMicroHelp function 1031 SetNull function 1032 SetOverlayPicture function 1033 SetPicture function 1037 SetPointer function 1038 SetPosition function 1039 SetProfileString function 1042 SetRange function 1044 SetRecordSet function 1045 SetRedraw function 1047 SetRemote function 1048 SetResultSet function 1051 SetSeriesStyle function 1052 SetState function 1060 SetTimeout function 1063 SetToolbar function 1065 SetTop function 1071 SetTraceFileName function 1072 SetTransPool function 1073 setup printer 877 shade data points 529, 1009 series 581, 1052 shapes mouse pointer 1038 printing 869, 872, 874 shared objects about 1077 SharedObjectDirectory function 1075 SharedObjectGet function 1076 SharedObjectRegister function 1079 SharedObjectUnregister function 1080 shared variables
1220
PowerBuilder
Index
about 32 initialized 39 SharedObjectDirectory function 1075 SharedObjectGet function 1076 SharedObjectRegister function 1079 SharedObjectUnregister function 1080 sharing data 410 sheets arranging 335 getting active 499 getting first open 552 getting next open 569 obtaining parent 824 opening 777, 792, 794 toolbars 592, 594, 1065, 1067 Show event 302 Show function 1081 ShowHeadFoot function 1082 ShowHelp function 1083 ShowPopupHelp function 1085 Sign function 1086 SignalError function 1087 Sin function 1088 sine 1088 SingleLineEdit functions CanUndo 349 Clear 361 Copy 396 Cut 407 Move 763 Paste 825 Position 839 ReplaceText 914 SelectedLength 964 SelectedStart 967 SelectedText 968 SelectText 977 Undo 1166 size changing 920 of screen 544 of string or blob 696, 697 Sleep function 1088 solid fill pattern 1013, 1056 Sort event 303 Sort function 1089 sort order and GetCalc function 600 when inserting items into lists 642 SortAll function 1091 sounds (beep) 338 source database 1094 Space function 1092 spaces deleting leading 695 deleting trailing 932 inserting in a string 1092 removing from strings 1157 special ASCII characters in strings 6 SQL statements about 142 CLOSE Cursor 145 CLOSE Procedure 146 COMMIT 147 CONNECT 148 continuing 15 DECLARE Procedure 150 DISCONNECT 154 error handling 143 EXECUTE 155, 1016 FETCH 156 in pipeline execution 1095 INSERT 157 OPEN 1016 OPEN Cursor 158 painting 144 ROLLBACK 159 SELECT 160 SELECTBLOB 162 UPDATE 164 UPDATE Where Current of Cursor 167 UPDATEBLOB 165 SQLCode property 143 SQLDBCode property 143 SQLErrText property 143 Sqrt function 1093 square fill pattern 1013, 1056 square root 1093 Start function about 1094 canceling pipeline 348 server application 387, 390
1221
Index
StartHotLink function 1101 StartServerDDE function 1103 state of listbox items 1105 setting highlighted 1060 State function 1105 statements, PowerScript assignment 116 CALL 119 CHOOSE CASE 120 CONTINUE 122 CREATE 123 DESTROY 126 DO...LOOP 127 EXIT 129 FOR...NEXT 130 GOTO 132 HALT 133 IF...THEN 134 listed 115 RETURN 136 separating 16 static calls 94 StaticText control, inserting clipboard 363 stgShareMode enumerated data type 782, 785, 786 Stop function 1107 stop sign icon 753 StopHotLink function 1108 StopServerDDE function 1109 storages, OLE file 945 releasing 367 saving 941 stored procedures closing 146 declaring 144, 150 executing 155 streams, OLE checking 751 deleting 750 renaming 752 string data type 21 String function 1110 string functions Asc 336 Char 355
Fill 476, 477 FillW 476, 477 Left 693, 694 LeftTrim 695 LeftTrimW 695 LeftW 693, 694 Len 696, 697 LenW 696 Lower 724 Match 746 MatchW 746 Mid 755 MidW 755 Pos 837, 838 PosW 837 Replace 912, 913 ReplaceW 912 Right 931 RightTrim 932 RightTrimW 932 RightW 931 Space 1092 Trim 1157 TrimW 1157 Upper 1170 StringParm property 795, 802, 804, 811, 813 strings char arrays 74 comparing 68 concatenating 69 continuing 15 converting 336, 341, 413, 423, 445, 715, 717, 898 converting to char 74 deleting leading spaces 695 detecting contents 676, 682, 685 determining width for printing 886 extracting 355, 755 finding substrings 837, 838 getting dynamic 542 importing data from 615 lowercase 724 nested 22 uppercase 1170 writing to stream 1181 StringToObject function 1115 structure objects
1222
PowerBuilder
Index
exporting as syntax 705 listing 701 recreating from syntax 706 structures about 75 assignment 82 autoinstantiated user objects 82 for return values 375 mailRecipient 739 passing as arguments 103 passing to external functions 61 passing values as 816, 818 substorages, OLE checking 751 deleting 750 renaming 752 saving 945 substrings extracting 755 finding 837, 838 replacing 912, 913 subtraction operator 66 surrounded by spaces 16, 66 summary, moving objects to 1040 Super pronoun 14 SuspendTransaction function 1118 symbol types, graphs data points 531, 1012 series 1055 syntax exporting object as 705 recreating objects from 706 SyntaxFromSQL function 1120 system date 1135 events 181, 844 events, defined 88 functions 107 object classes 77 object data types 27 object hierarchy 27 registry 899, 900, 902, 903, 905 time 769 system and environment functions Clipboard 363 CommandParm 379 DebugBreak 422 FindClassDefinition 480 FindFunctionDefinition 481 FindTypeDefinition 492 GarbageCollect 497 GarbageCollectGetTimeLimit 497 GarbageCollectSetTimeLimit 498 GetApplication 501 GetEnvironment 544 Handle 600 PopulateError 836 Post 844 ProfileInt 889 ProfileString 891 Restart 924 Run 939 Send 985 SetProfileString 1042 ShowHelp 1083 SignalError 1087 Yield 1189 SystemError event 306 SystemKey event 307 SYSTEMREAD modifier 42 SystemRoutine function 1123 SYSTEMWRITE modifier 42
T
tab character, specifying 7 Tab functions CloseTab 371 MoveTab 765 SelectTab 976 TabPostEvent 1124 TabTriggerEvent 1125 tab pages changing order 765 CreatePage function 406 opening user objects 797, 801 PageCreated function 823 selecting 976 tables, database, transferring data between databases 1094 Tabular presentation style 1120
1223
Index
Tag property and GetFocus function 554 storing MicroHelp text 1031 Tan function 1126 tangent 1126 target database for pipeline 1094 temporary files 735 terminator for string 343 text deleting from edit controls 361 finding in RichTextEdit 477, 490 finding substrings 837, 838 importing data from string 615 line spacing when printing 853 metacharacters 746 MicroHelp 1031 obtaining current line 1127, 1128 of listbox item 963 of message box 753 on clipboard 363, 397, 407 pasting over 825 printing 852, 884 replacing 914 restoring 1166 save rich text as ASCII 950 selecting 964, 968, 977 setting color of 929 text file importing data from 611 saving to 943 Text function 1127 Text property 554 TextLine function 1128 This pronoun 13 tilde in strings 22 rules for 23 specifying 7 time checking string 685 converting to data type 1129 CPU 401 DateTime data type 416 getting dynamic 539, 543 minutes 758 now 769
relative 907 seconds 957, 958 time data type 23 Time function 1129 Timer event 308 Timer function 1132 timers, triggering event 1132 timing functions CPU 401 Idle 605 Timer 1132 timing object starting 1096 stopping 1107 title of message box 753 ToAnsi function 1134 Today function 1135 ToolbarMoved event 310 toolbars 592, 594, 1065, 1067 top bringing object to 1081 determining distance from 833 moving listbox item to 1071 moving objects to 1040 Top function 1136 topics calling Help 1083 ending server application 1109 starting server application 1103 TotalColumns function 1137 TotalItems function 1138 TotalSelected function 1139 ToUnicode 1140 ToUnicode function 1140 Trace file functions, Open 775 TraceBegin function 1141 TraceClose function 1143 TraceDisableActivity function 1144 TraceEnableActivity function 1146 TraceEnd function 1148 TraceError function 1149 TraceFile objects Close function 368 NextActivity function 767 Reset function 916 TraceOpen function 1150
1224
PowerBuilder
Index
TraceTree objects BuildModel function 345 DestroyModel function 436 EntryList function 455 SetTraceFileName function 1072 TraceTreeGarbageCollect objects, GetChildrenList function 507 TraceTreeObject objects, GetChildrenList function 507 TraceTreeRoutine objects, GetChildrenList function 507 TraceUser function 1152 tracing functions TraceBegin 1141 TraceClose 1143 TraceDisableActivity 1144 TraceEnableActivity 1146 TraceEnd 1148 TraceError 1149 TraceOpen 1150 TraceUser 1152 trailer, moving objects to 1040 Transaction object functions DBHandle 422 SyntaxFromSQL 1120 Transaction objects, creating 123 transparent line style, graphs setting for data points 1011 setting for series 1054 TreeView functions AddPicture 327 CollapseItem 378 DeleteItem 429 DeletePicture 432 DeletePictures 432 DeleteStatePicture 435 DeleteStatePictures 435 EditLabel 452 ExpandAll 460 ExpandItem 461 FindItem 486 GetItem 560 InsertItem 646, 647 InsertItemFirst 648 InsertItemLast 650 InsertItemSort 653 SelectItem 974 SetDropHighlight 1015 SetFirstVisible 1018 SetItem 1023 SetLevelPictures 1025 SetOverlayPicture 1033 Sort 1089 SortAll 1091 TrigEvent enumerated data type 845 TriggerEvent function 1153 triggering events 182 functions or events 91 TriggerPBEvent function 1155 Trim function 1157 TrimW function 1157 Truncate function 1158 TrustVerify function 1159 TypeOf function 1162 typographical conventions xxiv
U
Uncheck function 1164 Undo function 1166 Undo, testing 349 Unicode, string conversion 494, 495, 1134, 1140 Uniform Data Transfer 523, 1003 units converting from pixels 831 converting to pixels 1167 distance from edge 832 UnitsToPixels function 1167 unread messages 729 unsigned integer data type 24 unsigned long data type 24 UPDATE statement 164 UPDATE Where Current of Cursor statement 167 UPDATEBLOB statement 165 Upper function 1170 UpperBound function 1171 uppercase 1170 user events defined 88 pbm_dwngraphcreate 1053
1225
Index
user ID 733 user name 739 user objects about 77 autoinstantiated 82 closing 373 closing tab page 371 creating 123 creating dynamically 124 exporting as syntax 705 listing 701 opening 797, 798, 799, 806, 807, 809, 810 pipeline 1094 re-creating from syntax 706 tab pages 797, 801 used like structures 81 user-defined events 181, 183
referencing in SQL 142 search order 33 setting to NULL 8, 1032 validating 688 where to declare 31 variable-size arrays, memory allocation vertical fill pattern 1013, 1056 video monitor 544 ViewChange event 310 Visible property and SetRedraw function 1047 displaying popup menus 834 setting 1081 visual user objects 77
50, 1171
W
warm link 456, 578, 790, 1049 week, day of 419, 420 Which function 1173 white space 16 width data points line 1011 series line 1054 setting 920 string 886 workspace 1178 Window ActiveX controls GetArgElement function 502 GetLastReturn function 562 InvokePBFunction function 664 ResetArgElements function 918 SetArgElement function 993 TriggerPBEvent function 1155 Window functions ArrangeSheets 335 ChangeMenu 354 ClassName 359 CloseUserObject 373 Draw 450 GetActiveSheet 499 GetFirstSheet 552 GetNextSheet 569 Hide 602 Move 763
V
value, passing arguments by 101 values adding to lists 321 checking for NULL 681 data points 535 deleting from list 427 detecting numeric 682 inserting into lists 642 variables access levels 40 assigning literals 20, 21, 22, 24 assigning values 38 checking for NULL 681 data type 37 declaring 31 declaring initial values 38 default values 38 determining data type of 359 extracting data from a blob 343 host 142 indicator 142 initializing with expression 39 inserting data into a blob 342 names 37 OLEObject 388
1226
PowerBuilder
Index
Open 775 OpenSheet 792 OpenSheetWith Parm 794 OpenTab 797 OpenUserObject 806 OpenWith Parm 815 ParentWindow 824 PointerX 832 PointerY 833 PostEvent 845 print 851 Resize 920 SetFocus 1019 SetMicroHelp 1031 SetPosition 1039 SetRedraw 1047 Show 1081 TriggerEvent 1153 TypeOf 1162 WorkSpaceHeight 1176 WorkSpaceWidth 1178 WorkSpaceX 1179 WorkSpaceY 1180 Window objects closing user objects 373 exporting as syntax 705 listing 701, 703 recreating from syntax 706 Window painter 806, 808 windows adding user objects 797, 806, 810 arranging 335, 792 changing menus 354 closing 366 custom frames 1179, 1180 data type of 775 DDE conversation handle 1103 getting active 499 obtaining handle 600 obtaining workspace height 1176 obtaining workspace width 1178 opening 775, 815 posting messages 844 setting position of 1039 WordCap function 1175 WordParm field and TriggerEvent function 1153 posting events 845 workspace distance to screen 1179, 1180 obtaining height of 1176 obtaining width 1178 WorkSpaceHeight function 1176 WorkSpaceWidth function 1178 WorkSpaceX function 1179 WorkSpaceY function 1180 Write function 1181 Writes 1181
X
x value data point 520, 535, 761 importing data 608, 611, 613, 615 inserting from strings 616 XMLParseFile function 1182 XMLParseString function 1185 xValue enumerated data type 520, 535
Y
y value data point 520, 535, 761 importing data 608, 611, 613, 615 inserting from strings 616 Year function 1188 year, about 415 Yield function 1189 yValue enumerated data type 520, 535
Z
zero, determining 1086
1227
Index
1228
PowerBuilder