Pages

Showing posts with label Powerbuilder. Show all posts
Showing posts with label Powerbuilder. Show all posts

Thursday, April 28, 2011

Create Object Programmatically with Powerbuilder - Part 1

In Powerbuilder, we can create an object programmatically, means that you can create whenever you need or conditionally.

In this first part, I trying to explain how to create "static" picture object when user clicking the button. Static mean that we only create the object, without script associated inside the object. The function that will be used it's called: openuserobject

For detail explanation of openuserobject function, please see the official help of Powerbuilder. 

First, create a button, and type this follow script inside Clicked event.
picture p_2  // declare the picture variable
p_2 = create picture  // create the picture object

p_2.x = 100  // x position of the object
p_2.y = 100  // y position of the object
p_2.height = 250 // height value of the object
p_2.width = 250 // with value of the object
p_2.picturename = "redalert.bmp" // name of the picture inc full path

parent.openuserobject( p_2, "p_2", 100, 100) // ok, let's create the object


»»  READMORE...

Wednesday, April 27, 2011

Click and Drag with Powerbuilder

This article will show you how to make an object to be click and drag capable in Powerbuilder. In this case, I'm using Powerbuilder 9.0 and Picture Object. In this version, I found DragAuto property in the list of the picture property, one that I can't found in version 6.5. I'm not sure, since when Sybase added this property.

The Drag Auto property determines whether PowerBuilder puts the control into drag mode automatically. If the property is enabled, when the user clicks the control and starts dragging it, PowerBuilder puts the control in drag mode. Clicking the control triggers a DragDrop event, not a Clicked event.

If Drag Auto is not enabled, then when the user clicks the control, PowerBuilder does not put the control in drag mode. You have to call the Drag function to put the control into drag mode.

In the Window, put 1 Picture object, and set the name of the file, and turn on the DragAuto option, in other tabs of property, and named it as p_1


Add the following script in p_1's clicked event
this.Drag(begin!)

At the p_1's dragleave event, put this following script:
this.x = parent.pointerx( ) - (this.width / 2)
this.y = parent.pointery( ) - (this.height / 2)
parent.setredraw(true)
this.setredraw(true)

And finally, at p_1's dragdrop event, add this following script:
parent.setredraw(true)
this.setredraw(true)
this.Drag(end!)
»»  READMORE...

Tuesday, December 21, 2010

Sending email with Powerbuilder

Several months ago, I posted the article which explain how to create Outlook Calendar Appointment with Powerbuilder. One of the reader asked me to how if  we want to send an email with Powerbuilder via Microsoft Outlook.

Well, several years ago, I wrote this PBL which have a window inside that can read the Address Book of Microsoft Outlook, and put as the recipients and send the email via Microsoft Outlook. Since I am not using Microsoft Outlook anymore, I don't know it will be run smoothly or not in Outlook version 2007 or 2010.

You can download it by clicking here
»»  READMORE...

New features in Powerbuilder 12.1

In 21 Sept 2010, Sybase launched the EBF for Powerbuilder version 12 with 12.1 as the minor version.

According to PowerbuilderTV.Com, there are some new features in version 12.1 such :

  • XAML Editor Enhancements
  • 3rd Party Control Support
  • OLE Control Support in WPF Application
  • WPF DW RightToLeft Enhancements

But still there are some limitations like
  • No support for dynamically creating OLE controls in PowerScript
  • No support for saving and retrieving the structure storage of an OLE control
  • Must install .NET framework SDK 2.0 or later before you migrate OLE controls to WPF
For detail, visit this link to see the complete video. The duration is about 40 minutes. And you can download the version 12.1 EBF file from Sybase official download site
»»  READMORE...

Friday, December 10, 2010

Set Local Computer Time with Powerbuilder

With External Function feature, we can set the Local Computer's time with Powerbuilder.

First, we need to declare the external function, called SetLocalTime from kernel32.dll

FUNCTION long SetLocalTime(ref str_SYSTEMTIME lpSystemTime ) LIBRARY "kernel32.dll" alias for "SetLocalTimeA"

To use the function, just pass a datetime variable when you call the function.

Example:

DataTime dtToday
dtToday = DateTime(Today(),Now())
SetLocalTime(dtToday)

»»  READMORE...

Wednesday, December 1, 2010

Integer versus Long Data Type in Powerbuilder

When you have an INTEGER column type in a table on your database, you must be aware to script in Powerscript.

The Integer data type in Powerbuilder just have the 16-bit signed characteristic, which mean only can store the integer number between -32768 to +32767. It's totally different with the Integer data type in your SQL database engine. I'm talking about Ms. SQL Server 2000/2005 in this case.

Make sure always using LONG data type in your variable, instead of INTEGER, to prevent the value outside -32768 or +32767.

For example, if the value of the column in your database is 34000, you'll get an error if you store the value into the integer variable on your script.
»»  READMORE...

Monday, November 1, 2010

Powerbuilder Window Function

On my last post about Powerbuilder function, I have mention that there are 2 types of function in Powerbuilder. Now, I will try to explain another function called Window Function.

The main different between Window Function and function, is Window Function must be declared in Window Object, and it should be related with windows object inside.

The way to declare the Window function is almost the same when you declare the function. But for the first step, you need to open your window first, where you want to put the window function inside. Click Declare at drop down menu, then select Windows Functions sub menu.



Specify the name of the function, the arguments, the return value and specify where the function can be used: Public (in any script in the application), Private (only in scripts for events in the object in which the function is defined), or Protected (only in scripts for the object in which the function is defined and its descendants).


Type the script, then save and name wf_datechecked. The script will compare the 2 variables (one is the argument, one is the today's date)

// sample window function, named wf_datechecked
// argument or parameter is dtDateTransaction
// will return TRUE if comparation between dtDateTransaction is smaller than dtToday
// will return FALSE if comparation between dtDateTransaction is bigger or equal than dtToday


DateTime dtToday

dtToday = DateTime(Today(),Now())

If dtDateTransaction >= dtToday THEN
   RETURN FALSE
ELSE
   RETURN TRUE
END IF


To call the function, type script below (on Clicked event of b_checked, for example)
Assumed that you have datawindow called dw_1, and has column inside name dateofbirth.

Boolean bValidDate

bValidDate = wf_datechecked(dw_1.GetItemDateTime(row,"dateofbirth"))

IF bValidDate THEN
   Messagebox("Information","The Date is valid")
ELSE
   Messagebox("Information!","The Date is invalid. You must input the date smaller than today")
END IF
»»  READMORE...

Thursday, October 28, 2010

Powerbuilder Function

In every modern programming languages, there is a feature call FUNCTION, as well as Powerbuilder.

FUNCTION is a collection of scripts or statment which it can be re-used. Normally, FUNCTION has a return value.

In Powerbuilder, there are 2 types of FUNCTION: Function and Window Function. The different is FUNCTION can be use anywhere in object that has capabilities to call function, but Window Function just can called in the window itself.

In this article, I will show you the steps how to declare the function in Powerbuilder. I'm using Powerbuilder version 6.5 and I'm sure it will be the same for all versions above

In the main toolbar, click Function painter.


Click New to create a new Function


Type the name of the function, in the example: f_yearafter
Also specify the type of return variable, in this example: date
Function can has many parameters. Parameters can used to passing some value(s) into function, so later can be used to process or calculate something in the script of function. Beside the name of parameters, you must specify the type of parameters, and the Pass By. There are 3 types of Pass by: value, reference, and readonly. Use reference if you want to change the value parameter then inside the function script.
Click OK to create.


Now you can type the script inside the.
In this example, we create a function call f_yearafter. The function will return a date type value, which it is the date result after some year added.

Once the function created, you can't change or rename the function name, but you can still change the return value, the parameter, etc. Please pay the attention, changing all of that value, will affect into the script inside the function. You can click the function painter icon in the toolbar, to edit the function



To call the function, just add the script like this:

Date dReturnFunction

//add 2 years for the date
dReturnFunction = f_yearafter("01/01/2008",2) // will return "01/01/2010"

»»  READMORE...

Wednesday, October 20, 2010

Powerbuilder Pipeline

Another feature in Powerbuilder programming is Pipeline.
According to manual help of Powerbuilder, a Pipeline system object is used to manage a data pipeline during execution.

You use a Pipeline object by defining a standard class user object inherited from the built-in Pipeline object in the User Object painter. You can then access the Pipeline events by writing scripts that contain code for the events.

Now I will show you how to execute pipeline by writing the script.

The scenario of this case is you want to pipeline a table from one database to another database. So, first you need at least 2 transaction objects, which mean we must declare first in the top of the script. Since we have a default database connection SQLCA, we only have declare another new transaction object called SQLCAtarget, which represent for the target database connection. Remember, in this case, SQLCA will be the source of database connection

transaction SQLCAtarget // declare this variable as INSTANT variable

SQLCA.DBMS = 'your source dbms name'
SQLCA.Database = 'your source database name'
SQLCA.LogId = 'your source database login id'
SQLCA.LogPass = 'your source database password'
SQLCA.ServerName = 'your source database server'
CONNECT USING SQLCA;

SQLCAtarget = CREATE transaction
SQLCAtarget.DBMS = 'your target dbms name'
SQLCAtarget.Database = 'your target database login id'
SQLCAtarget.LogPass = 'your target database password'
SQLCAtarget.ServerName = 'your target database server'
SQLCAtarget.LogId = 'your target database login id'
CONNECT USING SQLCAtarget;

Next step, you need to build pipeline object by clicking Pipeline painter in main toolbar. Remember, use MAIN TOOLBAR, if you want to pipeline the data to ANOTHER DATABASE.
Setup your source database and the target database profile, chooce the table(s), column(s) and criteria(s), then save as pl_mypipeline.



Choose source and target of Pipeline

Set the table, column and criteria of your pipeline


save your pipeline


Create a window, then put 1 datawindow object and 1 button object. You don't need to put dataobject for the datawindow, just keep it blank. And put the script below at clicked event in button object.

integer iReturn
pipeline myPipeline
myPipeline = CREATE pipeline

myPipeline.DataObject = "pl_mypipeline"
iReturn = myPipeline.Start(SQLCA, SQLCAtarget, dw_1)

// always disconnect your database connection
DISCONNECT USING SQLCA;
DISCONNECT USING SQLCAtarget;

iReturn should be has 0 (zero) value if the pipeline run smoothly.
»»  READMORE...

Wednesday, October 13, 2010

Modify Compute Field Expression in Powerbuilder

Compute Field is an object in Powerbuilder programming, which can be inserted in datawindow. One of mandatory property of Compute Field is Expression.

Expression is set of statement or syntax which represent what you want to show at this compute field. Can be static text, calculation, or the other things.

When you create a datawindow and insert a compute field object, you can set the expression visually. But some times, you want to change the expression statement dynamically, which mean the expression will change depending of condition. Let say, if one of condition is fulfilled, you want to show: OK in the compute field, otherwise is NO.

Let say, in a Datawindow named dw_1, we create 1 compute object named co_1. The default expression is if(kd_kategori=2,'OK','NO'). It's mean if kd_kategori's value is 2, then we want to show text: OK, otherwise is: NO.




But, in some condition you want to change the default expression into if(kd_kategori=200,'OK','NO'), let say if someone in STAFF level is accessing the application.



Then you must create a script like below:

IF userlevel='STAFF' THEN
   dw_1.object.co_1.expression = "if(kd_kategori=200,'OK','NO')"
ELSE
   dw_1.object.co_1.expression = "if(kd_kategori=2,'OK','NO')"
END IF
»»  READMORE...

Wednesday, October 6, 2010

How to program Right Click Event in Powerbuilder

As we know at least there are 2 buttons in every mouse that you use with your computer. Known as Left and Right button.

For right-handed user, Left Button is for SELECT purpose. And Right button usually is for displaying the Popup Menu to shortcut the steps.

Now, I am trying to explain how to script Right button to show the Popup Menu in Powerbuilder.

In almost objects in Powerbuilder, there is an event called RBUTTONDOWN. In this case I will use with Windows object.

First, you need to create Menu object with 3 choices, then save as m_rightpopup.




Create new window and save as w_main, and put this script at RBUTTONDOWN event.

m_rightpopup popMenu
popMenu = CREATE m_rightpopup
popMenu.PopMenu(w_main.PointerX(), w_main.PointerY())

The script above, will shown a Popup Menu when you try to click the right button of your mouse, located exactly at your mouse pointer

»»  READMORE...

Tuesday, October 5, 2010

How to connect to 2 databases in Powerbuilder

How to connect to more than 1 database in Powerbuilder

Some times, you need to connect to more than 1 database in your application. In Powerbuilder, there's 1 object for database connection that you can create programmatically. The object call: TRANSACTION.

In this example, I will explain how to connect to 2 databases, which mean 1 is with default database connection object (named SQLCA), and the other is the object that we create mannualy.

I'm using Microsoft SQL Server 2000 as a database engine.

First of all, we need to create a transaction object. It's depending on what the purpose of the transaction. You can declare with Instance, Global or even Local variable for this object.

Let's say we create Instant Variable, called: SQLCAID

transaction SQLCAID;


On Open Event, we must create first the transaction object, then setup the properties of the object.

Note: You can try first on the Database painter, to get the right property values, and to make sure that you can connect to the database. Then copy and paste the script.

SQLCAID = CREATE transaction;
SQLCAID.DBMS = "MSS Microsoft SQL Server"
SQLCAID.Database = "database1"
SQLCAID.LogPass = "password"
SQLCAID.ServerName = "localhost"
SQLCAID.LogId = "sa"
SQLCAID.AutoCommit = False
SQLCAID.DBParm = ""


// Try to connect the database
// REMEMBER, you must add USING SQLCAID statement at the end of your SQL Statement, every times you want to execute your database that related with SQLCAID transaction

CONNECT USING SQLCAID;

// Trap the error if the object can't connect to database

IF SQLCAID.SQLCode <> 0 THEN
    MessageBox("Connection Error to "+SQLCAID.Database, &
        "Unable to connect to database. Make sure you type the correct password." + &
        "~r~nTry Again. If the problem persists, contact IT Officer" + &
        "~r~nSQLDBCode = " + String(SQLCAID.SQLDBCode) + &
        "~r~nSQLErrText = " + SQLCAID.SQLErrText)
   HALT
END IF



At the other side, you still must declare the DEFAULT SQLCA transaction object.

SQLCA.DBMS = "MSS Microsoft SQL Server"
SQLCA.Database = "databasedefault"
SQLCA.LogPass = "password"
SQLCA.ServerName = "localhost"
SQLCA.LogId = "sa"
SQLCA.AutoCommit = False
SQLCA.DBParm = ""


// Just for make sure that you connect with SQLCA transaction

CONNECT USING SQLCA;


// Trap the error if the object can't connect to database
IF SQLCA.SQLCode <> 0 THEN
    MessageBox("Connection Error to "+SQLCA.Database, &
        "Unable to connect to database. Make sure you type the correct password." + &
        "~r~nTry Again. If the problem persists, contact IT Officer" + &
        "~r~nSQLDBCode = " + String(SQLCA.SQLDBCode) + &
        "~r~nSQLErrText = " + SQLCA.SQLErrText)
   HALT
END IF


Now you already connected with 2 databases.

Remember, always put USING SQLCA or USING SQLCAID statement at the end of your SQL Statement to make sure that the SQL Statement will execute into the database that you purpose

Example:

string sProductID, sProductName

// will retrieve the product_id and product_name column from SQLCAID transaction
SELECT product_id, product_name INTO :sProductID, :sProductName FROM product_master USING SQLCAID;

// will retrieve the product_id and product_name column from SQLCA (Default) transaction
SELECT product_id, product_name INTO :sProductID, :sProductName FROM product_master USING SQLCA;
»»  READMORE...

Thursday, August 26, 2010

Using .NET object in Powerbuilder

For all of you who still using Powerbuilder version 9.0 to above, and want to using .NET object, you can try this trick to do that.

You'll need Microsoft Visual Studio (in this case, I'm using version 2005 with .NET 2.0 framework). And also, you must download Interop Forms Toolkit version 2.1 at Microsoft MSDN site.

The Interop Forms Toolkit 2.1 is a free Visual Studio add-in that simplifies the process of displaying .NET forms and controls in a Visual Basic 6 application. Instead of upgrading the entire code base, these applications can now be extended one form at a time. The goal is a phased upgrade, with production releases at the end of each iteration containing both Visual Basic 6 and Visual Basic .NET forms running in the same Visual Basic 6 process.

Close your VS2005 before you install the Interop Form Toolkit.

Since almost all the objects which made for Visual Basic 6, can used by Powerbuilder application, I'm sure we can use this technique in Powerbuilder too.

Now, here's the steps

Creating .NET Object
  • Open VS, and create new project with Project Type: Windows, and template: VB6 Interop UserControl

  • You'll see like figure above, at the Solution Explorer windows.

  • Open InteropUserControl.vb and create an application. You can use the third party object too.

  • Save and try to rebuild and run the application by pressing F5 button.
  • That's all for the creating .NET object.

Using .NET Object in Powerbuilder
  • Open your Powerbuilder. I'm using version 6.5 in this example.
  • Create new application, then create new window.
  • Insert OLEObject into the new window. You should see the InteropUserControlLibrary1 object in INSERT CONTROL tab. If you can't see the object, do the registering system.dll step. See at the bottom of this article to do that.

  • Choose the InteropUserControlLibrary1 object and place somewhere inside the window.

  • Save and try to run the application.

  • Now, you have .NET object in your Powerbuilder application.

Registering the system.dll so that it can be used from Powerbuilder
  1. Navigate to Start | Run.
  2. In the Run dialog, enter CMD, and click OK.
  3. Enter cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727.
  4. Enter regasm system.dll.
»»  READMORE...

Monday, August 23, 2010

Twitter with Powerbuilder

Inspired from this article, I trying to made a simple script to post to Twitter from Powerbuilder. All you need is msxml2.dll which located at c:\windows\system32.

And also, you need to create a Twitter's account. Using an OleObject object, try this simple script:

Integer i
OleObject oleTwitter

OleTwitter = CREATE OLEObject
i = oleTwitter.ConnectToNewObject("Msxml2.XMLHTTP")
if i = 0 then
   oleTwitter.Open("POST", "http://youraccount:yourpassword@twitter.com/statuses/update.xml?status=Just for #..., Twitt from Powerbuilder", False)
   oleTwitter.setRequestHeader("Content-Type", "text/xml")
   oleTwitter.Send()
else
   MessageBox("Error","Cannot connect to Object"
end if

Please beware, I don't give a guarantee for any security matters that will caused for your Twitter's account, since I don't have any deep experiences using the XML.

And this is the result:

»»  READMORE...

Friday, August 20, 2010

Creating Outlook Calendar Appointment with Powerbuilder

Microsoft Outlook is a popular Personal Information Management application. It is part of Microsoft Office package, which many users use it. Fortunately, Microsoft, as the maker Microsoft Outlook, has prepared the SDK to allows programmers to create their own applications that can interact seamlessly into the application Microsoft Outlook

One of the Outlook's feature is Calendar which it make possible to user to create their own schedule and will remind for it. It's very useful for people who has many schedules in their life.

In this part of session, I will try to explain how to insert or create a new appointment in outlook, programmatically, with Powerbuilder. One thing you should learn and know is Outlook Object Model, which you can find at Microsoft's MSDN site


Microsoft has prepared the AppointmentItem Class which has many properties, to create a new Appointment Object in Microsoft Outlook Calendar. Some properties that are commonly used for the calendar class are: Subject, Start, Duration, and Reminder.


First, you (or PC clients) must has Microsoft Outlook installed. Then at the script, you must declare OleObject variable type, than try to create the object and connect to Microsoft Outlook Object. In this example, I'm using Microsoft Outlook 2007 and Powerbuilder 6.5. Here's the full script to create a new Appointment Object:


// declare OleObject variable and Constant Variable
oleobject oleOutlook
oleobject oleAppt
Constant Integer olAppointmentItem = 1

// create the Object
oleOutlook = create oleobject

// Connect To the Outlook Object
oleOutlook.ConnectToNewObject ('Outlook.Application')

// Create the Appointment Object
oleAppt = oleOutlook.CreateItem (olAppointmentItem)

// Set some common properties of Appointment Object
oleAppt.Location = "Home"
oleAppt.Subject = "Watch Fulham vs Manchester United Live"
oleAppt.Start = "08/21/2010 19:00"
oleAppt.ReminderMinutesBeforeStart = 1  // in minute
oleAppt.Duration = 120 // in minute
oleAppt.Body = "Go MU !!! Go !!!"

// Save the Appointment
oleAppt.Save



And here the result of the example:









»»  READMORE...

Thursday, August 19, 2010

Microsoft Agent programming with Powerbuilder

According of wikipedia site, Microsoft Agent is a technology developed by Microsoft which employs animated characters, text-to-speech engines, and speech recognition software to enhance interaction with computer users. Thus it is an example of an embodied agent. It comes preinstalled as part of Microsoft Windows 2000 through Windows Vista (it is not part of Windows 7). Microsoft Agent functionality is exposed as an ActiveX control that can be used by web pages.

Before you can use the Agent in Powerbuilder, you need to download Microsoft Agent from Microsoft Agent site and install it into your computer. There 2 cores that you must download, one is Microsoft Agent core component, and the other is the Agent Character, which have 4 characters officially from Microsoft.

In this sample, I use Peedy, a green talking bird as a character

The next step is try to insert OLE Object at Powerbuilder's windows object. Choose the Microsoft Agent 2.0 from the Insert Control Tab.

Add Microsoft Agent Control 2.0 from the list

Agent OLE Object after inserted
In the Open event of window w_agent, type this script below:

//  set the agent, and named as Clippit
ole_1.Object.Characters.Load("Clippit","c:\windows\msagent\chars\peedy.acs")

// show the Clippit
ole_1.Object.Characters("Clippit").Show

// move the Clippit to position 400,200
ole_1.Object.Characters("Clippit").MoveTo(400,200)

// ask Clippit to play animation Greeting
ole_1.Object.Characters("Clippit").Play("Greet")

// ask Clippit to say something
ole_1.Object.Characters("Clippit").Speak("Hello World !!! I am Peedy !!! Called by Powerbuilder !!!")

If you have a speaker (and I bet you have), you can hear the voice speaking from Character.
Run the script, and you will get like this image


There's many build in functions in Agent character, and also many third party characters which you can find at Microsoft Agent's ring.

You can learn more about the functions and properties at Microsoft Agent official site, including the guidelines if you want to create your own character.

Of course, if you want to deploy your Powerbuilder applications with Microsoft Agent object, you also need to install Microsoft Agent cores at the PC Client.
»»  READMORE...

Powerbuilder function to get business day

The function is to get total business days between 2 dates, it means we ignore the Saturday and Sunday.
The function need 2 parameters to pass with datetime type, called: adt_awal and adt_akhir, and will return Long type.


integer i, counter, li_daynumber, li_weeks, li_daysremained
long ll_daysafter

ll_daysafter = DaysAfter(date(adt_awal), date(adt_akhir))
li_weeks = ll_daysafter / 7
li_daysremained = mod(ll_daysafter,7)
counter = li_daysremained

FOR i = 1 TO counter
    li_daynumber = DayNumber(RelativeDate(date(adt_awal), i))
    IF li_daynumber = 1 OR li_daynumber = 7 THEN
       li_daysremained --
    END IF
NEXT

RETURN (li_weeks * 5) + li_daysremained

To use this function, just type this script:

Long lBusinessDay
lBusinessDay = f_businessday(DateStart,DateEnd)
»»  READMORE...

Array in Powerbuilder

Array is an indexed collection of elements of a single data type. An array can have one or more dimensions. One-dimensional arrays can have a fixed of variable size; multidimensional array always have a fixed size.

In Powerbuilder, any simple variable declaration becomes an array when you specify brackets [] after the variable name. For fixed-size arrays, you specify the sizes of the dimensions inside those brackets.

There are 2 types of array in Powerbuilder:
1. Variable Array
2. Fixed Array.

Samples in Powerbuilder script to declare an array

integer ali_number[ ] //Array of integers.
decimal {2} ald_harga[ ] // Array of decimal with 2 digits of precision
date ald_birthdate[ ] // array of date
integer ali_number[3] // fixed array of 3 integers
string als_daysname[7] // fixed array of 7 strings
integer ali_score[2,3] // 2 dimensional array of integer, means that we declare a 6-elements
long all_days[3,300,50] // 3 dimensional array of long, which have 45000 elements of array

There are 2 functions that provided for array data type in Powerbuilder: upperbound, lowerbound
»»  READMORE...

Wednesday, August 18, 2010

Money in Word function with Powerbuilder

Usually, we must write down the value of money in Invoice Document, to prevent user to cheat the value. Let say, US$ 99,80 will write as Ninety Nine Dollar and Eighty Cent.

This is the function script to write the money value in string.

First, we create f_translate function below. The function has a variable to pass called iNilai with Integer as data type. iNilai will represent the value of number that will return in word. So, the function will return a variable in string. This function will called at the main function.

string aSatuan[19], str, aPuluhan[9]
integer nRatus, nPuluh
aSatuan = { "one", "two", "three", "four", "five", &
            "six", "seven", "eight", "nine", "ten", &
            "eleven", "twelve", "thirteen", "forteen", &
            "fifteen", "sixteen", "seventeen", "eighteen", &
            "nineteen" }
aPuluhan = { "ten", "twenty", "thirty", "forty", "fifty", &
             "sixty", "seventy", "eighty", "ninety"}
               
IF nilai >= 100 THEN
   nRatus = Integer(String(nilai/100))
   IF nRatus = 1 THEN
      str += "one hundred"
   ELSE
      str += aSatuan[nRatus] + " hundreds"
   END IF
   IF nilai > 0 THEN nilai -= nRatus * 100
END IF

IF nilai >= 20 THEN
   nPuluh = Integer(String(nilai/10))
   IF nRatus > 0 THEN
      str += " and " + aPuluhan[nPuluh]
   ELSE
      str += aPuluhan[nPuluh]
   END IF
   nilai -= nPuluh * 10
   IF nilai > 0 THEN str += " " + aSatuan[nilai]
ELSE
   IF nilai > 0 THEN
      IF nRatus > 0 THEN
         str += " and " + aSatuan[nilai]
      ELSE
         str += aSatuan[nilai]
      END IF
   END IF
END IF   
                 
RETURN str


The main function is called f_moneystr with amount as a decimal variable to pass.

string str
decimal nMilyar, nJuta, nRibu

IF amount < 0 THEN RETURN ""
IF amount < 1 THEN str = "zero"

IF amount >= 1000000000000.00 THEN
   nMilyar = Integer(String(amount/1000000000000.00))
   str += f_Translate(nMilyar) + " trillion "
   amount -= (nMilyar * 1000000000000.00)
END IF

IF amount >= 1000000000 THEN
   nMilyar = Integer(String(amount/1000000000))
   IF nMilyar = 1 THEN
      str += "one billion "
   ELSE
      str += f_Translate(nMilyar) + " billion "
   END IF
   amount -= (nMilyar * 1000000000)
END IF

IF amount >= 1000000 THEN
   nJuta = Integer(String(amount/1000000))
   IF nJuta = 1 THEN
      str += "one million "
   ELSE
      str += f_Translate(nJuta) + " millions "
   END IF
   amount -= (nJuta * 1000000)
END IF

IF amount >= 1000 THEN
   nRibu = Integer(String(amount/1000))
   IF nRibu = 1 THEN
      str += "one thousand "
   ELSE
      str += f_Translate(nRibu) + " thousands "
   END IF
   amount -= (nRibu * 1000)
END IF

str += f_Translate(Integer(String(amount)))
str = RightTrim(str) + " US Dollar"
amount -= Integer(String(amount))
IF amount > 0 THEN
   amount *= 100
   str += " and " + f_Translate(amount) + " cent"
END IF
   
return str

To use this function, just call with this statement:

string sMoney
sMoney = f_moneystr(99.80)

Note: Thanks to Mr. AGP for the script :)
»»  READMORE...

Monday, August 16, 2010

Powerbuilder Structure

One of Powerbuilder's feature is Structure. Structure is a object which made possible for the programmer to store and passing the parameters in different types.

The example below is to explain how to use Structure in Powerbuilder

Let say, you need to passing 4 parameters which have 3 different data types: string, datetime and decimal, when you open a new window.

First, you need to create a new Structure. At the main painter, click Structure button.


Click New to create a new structure


Fill the variables that you want to pass. You can set the different type for each variables.


Save by clicking Save button (of Choose menu File than Save). Type str_dailydiscountreport as a name. str_ is a prefix to represent that the object is a Structure.

In the script that will open the new window, type following code. This code is to declare the new structure variable which pointed to str_dailydiscountreport structure that we have build in the first.

// declare new structure variable
str_dailydiscountreport strReport

// fill each variable in the structure
strReport.sProductCode = sle_productcode.text
strReport.dtDateFrom = datetime(em_datefrom.text)
strReport.dtDateUntil = datetime(em_datefrom.text)
strReport.dDiscount = Dec(em_discount.text)

// Open the new window with passing the structure
OpenWithParm(w_report,strReport)



How to received?
In event Open of the w_report window, do same with the script above.

// declare new structure variable
str_dailydiscountreport strReport

// receive the structure that passed from the window caller by using message object with PowerobjectParm as property
strReport = message.PowerobjectParm

// extract all the variables inside the structure
MessageBox("Product Code",strReport.sProductCode)
MessageBox("Date From",Str(strReport.dtDateFrom,'dd/mm/yyyy')
MessageBox("Date Until",Str(strReport.stDateUntil,'dd/mm/yyyy')
MessageBox("Discount",Str(strReport.dDiscount,'##.##') + "%"
»»  READMORE...