Monday, January 21, 2013

Get a List of Column Names in a DataWindow using Describe()

string colname, colvariable int i, icount
icount = integer(dw_1.describe('DataWindow.Column.Count'))
FOR i = 1 TO icount
  colvariable = '#'+string(i)+'.name'
  colname = dw_1.describe(colvariable)   // #1.name, #2.name, etc
  Messagebox ('Information', 'Column name of column #' + string (i) + ' is ' + colname)
NEXT

Wednesday, January 16, 2013

VB Scripting in PowerBuilder

You can use Windows Scripting Host on PowerBuilder for many purpose. On sample code below, you can use it to get the network domain, user name and computer name. To do so, you need Windows Scripting Host Object Model component (wshom.ocx)
integer li_rc
OleObject ole_wsh

ole_wsh = CREATE OleObject
li_rc = ole_wsh.ConnectToNewObject ( "WScript.Network" )
IF li_rc = 0 THEN
     MessageBox ("Domain", string( ole_wsh.UserDomain ))
     MessageBox ("User", string( ole_wsh.UserName ))
     MessageBox ("Computer", string( ole_wsh.ComputerName ))
END IF


With WSH, you can execute other application from PowerBuilder application. On example below, Notepad will be called by clicking a button from PowerBuilder application
integer li_rc
OleObject ole_wsh

ole_wsh = CREATE OleObject
li_rc = ole_wsh.ConnectToNewObject ( "WScript.Shell" )
ole_wsh.Run ("Notepad")
ole_wsh.AppActivate("Untitled - Notepad")
Sleep (500)
ole_wsh.SendKeys (''Hello from PB")


Sleep is a function from Win32 API module with a declaration like this :
Subroutine Sleep (Long dwMilliseconds) Library "kernel32" Alias for "Sleep"


You also can run Calculator program and send some key stroke on it
integer li_rc
OleObject ole_wsh

ole_wsh = CREATE OleObject
 li_rc = ole_wsh.ConnectToNewObject ( "WScript.Shell" )
ole_wsh.Run("calc")
ole_wsh.AppActivate ("Calculator", 100)
Sleep (1000)
ole_wsh.SendKeys("1{+}")
Sleep (1000)
ole_wsh.SendKeys("2")
Sleep (1000)
ole_wsh.SendKeys("=")
Sleep (1000)
ole_wsh.SendKeys("*4")
Sleep (1000)
ole_wsh.SendKeys("=")
// 1+2 = ( 3, then) * 4 = 12


You also can run VBScript from PowerBuilder easily. To do that you need Microsoft Script Control component (msscript.ocx)
OleObject ole_wsh
Integer li_rc, i, j, k

ole_wsh = Create OleObject
li_rc = ole_wsh.ConnectToNewObject ("MSScriptControl.ScriptControl")
ole_wsh.language = "vbscript"
ole_wsh.addcode("function retfnc(s) retfnc = s end function")
ole_wsh.executestatement ('if 1 > 1 then msgbox retfnc("true") else 

Windows 7 Shell Commands

Shell commands are incredibly useful when creating shortcuts or quickly accessing hard to get to locations. They can be used to pin shortcuts to the Taskbar or just to make your life easier.  For those that are preceded by “Shell:” when using them in shortcuts you need to add “explorer.exe” in front of them.  It should then look like this: explorer.exe shell:Personal
Windows 7 Only
shell:Libraries
shell:MusicLibrary
shell:VideosLibrary
shell:OtherUsersFolder
shell:Device Metadata Store
shell:PublicSuggestedLocations
shell:DocumentsLibrary
shell:User Pinned
shell:UsersLibrariesFolder
shell:PicturesLibrary
shell:ImplicitAppShortcuts
shell:Ringtones
shell:CommonRingtones
Windows Vista & 7
shell:Common Programs
shell:GameTasks
shell:UserProfiles
shell:MyComputerFolder
shell:SyncSetupFolder
shell:DpapiKeys
shell:SamplePlaylists
shell:Favorites
shell:My Video
shell:SearchHomeFolder
shell:System
shell:CommonVideo
shell:SyncResultsFolder
shell:LocalizedResourcesDir
shell:Cookies
shell:Original Images
shell:CommonMusic
shell:My Pictures
shell:Cache
shell:Downloads
shell:CommonDownloads
shell:AppData
shell:SyncCenterFolder
shell:My Music
shell:ConflictFolder
shell:SavedGames
shell:InternetFolder
shell:Quick Launch
shell:SystemCertificates
shell:Contacts
shell:TreePropertiesFolder
shell:Profile
shell:Start Menu
shell:Common AppData
shell:PhotoAlbums
shell:ConnectionsFolder
shell:Administrative Tools
shell:PrintersFolder
shell:Default Gadgets
shell:ProgramFilesX86
shell:Searches
shell:Common Startup
shell:ControlPanelFolder
shell:SampleVideos
shell:SendTo
shell:ResourceDir
shell:ProgramFiles
shell:CredentialManager
shell:PrintHood
shell:MAPIFolder
shell:CD Burning
shell:AppUpdatesFolder
shell:Common Start Menu
shell:LocalAppDataLow
shell:Templates
shell:Gadgets
shell:Programs
shell:Recent
shell:SampleMusic
shell:Desktop
shell:CommonPictures
shell:RecycleBinFolder
shell:CryptoKeys
shell:Common Templates
shell:Startup
shell:Links
shell:OEM Links
shell:SamplePictures
shell:Common Desktop
shell:NetHood
shell:Games
shell:Common Administrative Tools
shell:NetworkPlacesFolder
shell:SystemX86
shell:History
shell:AddNewProgramsFolder
shell:Playlists
shell:ProgramFilesCommonX86
shell:PublicGameTasks
shell:ChangeRemoveProgramsFolder
shell:Public
shell:Common Documents
shell:CSCFolder
shell:Local AppData
shell:Windows
shell:UsersFilesFolder
shell:ProgramFilesCommon
shell:Fonts
shell:Personal
Windows 7 ShortcutsI compiled the following list with an early Alpha build of Windows 7.  It is possible that some of these have changed with newer versions.  If you find one that is wrong please let me know so I can correct it.

Wireless Networks pop-up
rundll32.exe van.dll,RunVAN
Advanced Restore
sdclt.exe /restorewizardadmin
Restore Files
sdclt.exe /restorewizard
Backup Location & Settings
sdclt.exe /configure
Add Network Location (wizard)
rundll32.exe shwebsvc.dll,AddNetPlaceRunDll
Indexing Options
control.exe srchadmin.dll
Notification Cache
rundll32.exe shell32.dll,Options_RunDLL 5
Aero (Transparency) Off
Rundll32.exe DwmApi #104
Aero (Transparency) On
Rundll32.exe DwmApi #102
Welcome Center
rundll32.exe oobefldr.dll,ShowWelcomeCenter
Add/Remove Programs
RunDll32.exe shell32.dll,Control_RunDLL appwiz.cpl,,0
Content Advisor
RunDll32.exe msrating.dll,RatingSetupUI
Control Panel
RunDll32.exe shell32.dll,Control_RunDLL
Date and Time Properties
RunDll32.exe shell32.dll,Control_RunDLL timedate.cpl
Display Settings
RunDll32.exe shell32.dll,Control_RunDLL access.cpl,,3
Device Manager
RunDll32.exe devmgr.dll DeviceManager_Execute
Folder Options – File Types
RunDll32.exe shell32.dll,Control_Options 2
Folder Options – General
RunDll32.exe shell32.dll,Options_RunDLL 0
Folder Options – Search
RunDll32.exe shell32.dll,Options_RunDLL 2
Folder Options – View
RunDll32.exe shell32.dll,Options_RunDLL 7
Forgotten Password Wizard
RunDll32.exe keymgr.dll,PRShowSaveWizardExW
Hibernate
RunDll32.exe powrprof.dll,SetSuspendState
Keyboard Properties
RunDll32.exe shell32.dll,Control_RunDLL main.cpl @1
Lock Screen
RunDll32.exe user32.dll,LockWorkStation
Mouse Properties
RunDll32.exe shell32.dll,Control_RunDLL main.cpl @0
Map Network Drive
RunDll32.exe shell32.dll,SHHelpShortcuts_RunDLL Connect
Network Connections
RunDll32.exe shell32.dll,Control_RunDLL ncpa.cpl
Power Options
RunDll32.exe Shell32.dll,Control_RunDLL powercfg.cpl
Regional Settings
RunDll32.exe shell32.dll,Control_RunDLL intl.cpl,,3
Stored Usernames and Passwords
RunDll32.exe keymgr.dll,KRShowKeyMgr
System Properties: Advanced
RunDll32.exe shell32.dll,Control_RunDLL sysdm.cpl,,4
System Properties: Automatic Updates
RunDll32.exe shell32.dll,Control_RunDLL sysdm.cpl,,5
Taskbar Properties
RunDll32.exe shell32.dll,Options_RunDLL 1
User Accounts
RunDll32.exe shell32.dll,Control_RunDLL nusrmgr.cpl
Windows Security Center
RunDll32.exe shell32.dll,Control_RunDLL wscui.cpl
Windows – About
RunDll32.exe SHELL32.DLL,ShellAboutW
Unplug/Eject Hardware
RunDll32.exe shell32.dll,Control_RunDLL hotplug.dll
Windows Firewall
RunDll32.exe shell32.dll,Control_RunDLL firewall.cpl
Wireless Network Setup
RunDll32.exe shell32.dll,Control_RunDLL NetSetup.cpl,@0,WNSW
Open Control Panel (All Items)
explorer.exe shell:::{21ec2020-3aea-1069-a2dd-08002b30309d}
Manage Wireless Networks
explorer.exe shell:::{1fa9085f-25a2-489b-85d4-86326eedcd87}
Sound Control Playback Tab
rundll32.exe shell32.dll,Control_RunDLLmmsys.cpl
Sound Control Sounds Tab
rundll32.exe shell32.dll,Control_RunDLLmmsys.cpl,,2
Sound Control Recording Tab
rundll32.exe shell32.dll,Control_RunDLLmmsys.cpl,,1
Add/Remove Programs
rundll32.exe shell32.dll,Control_RunDLL appwiz.cpl
Add/Remove Windows Components
rundll32.exe shell32.dll,Control_RunDLL appwiz.cpl,,2
Set Program Access and Computer Defaults
rundll32.exe shell32.dll,Control_RunDLL appwiz.cpl,,3
People Near Me
rundll32.exe shell32.dll,Control_RunDLL collab.cpl
People Near Me Sign In Tab
rundll32.exe shell32.dll,Control_RunDLL collab.cpl,,1
Screen Resolution
rundll32.exe shell32.dll,Control_RunDLL desk.cpl
Personalization
rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,2
Screen Saver
rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,1
Windows Firewall
rundll32.exe shell32.dll,Control_RunDLL firewall.cpl
Device Manager
rundll32.exe shell32.dll,Control_RunDLL hdwwiz.cpl
Power Options
rundll32.exe shell32.dll,Control_RunDLL powercfg.cpl
Power Options Change Plan Settings
rundll32.exe shell32.dll,Control_RunDLL powercfg.cpl,,1
System Properties
rundll32.exe shell32.dll,Control_RunDLL sysdm.cpl
System Properties Hardware Tab
rundll32.exe shell32.dll,Control_RunDLL sysdm.cpl,,2
System Properties Advanced Tab
rundll32.exe shell32.dll,Control_RunDLL sysdm.cpl,,3
System Properties System Protection Tab
rundll32.exe shell32.dll,Control_RunDLL sysdm.cpl,,4
System Properties Remote Tab
rundll32.exe shell32.dll,Control_RunDLL sysdm.cpl,,5
Pen and Touch Tablet PC Settings
rundll32.exe shell32.dll,Control_RunDLL tabletpc.cpl
Pen and Touch Tablet PC Settings Flicks Tab
rundll32.exe shell32.dll,Control_RunDLL tabletpc.cpl,,1
Pen and Touch Tablet PC Settings Handwriting Tab
rundll32.exe shell32.dll,Control_RunDLL tabletpc.cpl,,2
Phone and Modem Options
rundll32.exe shell32.dll,Control_RunDLL telephon.cpl
Phone and Modem Options Modems Tab
rundll32.exe shell32.dll,Control_RunDLL telephon.cpl,,1
Phone and Modems Options Advanced Tab
rundll32.exe shell32.dll,Control_RunDLL telephon.cpl,,2
Date and Time
rundll32.exe shell32.dll,Control_RunDLL timedate.cpl
Date and Time Additional Clocks
rundll32.exe shell32.dll,Control_RunDLL timedate.cpl,,1
Action Center
rundll32.exe shell32.dll,Control_RunDLL wscui.cpl
Unplug/Eject Hardware
RunDll32.exe shell32.dll,Control_RunDLL hotplug.dll

Internet Explorer Specific Commands

Delete Temporary Internet Files:
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
Delete Cookies:
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2
Delete History:
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1
Delete Form Data:
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16
Delete Passwords:
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32
Delete All:
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255
Delete All + files and settings stored by Add-ons:
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 4351

Miscellaneous Variables

Windows Directory
%WINDIR%
%SYSTEMROOT%
Hard Drive That Contains OS
%HOMEDRIVE%
Users Home Directory
%HOMEPATH%
%USERPROFILE%
Default Temporary Directory
%TEMP%
%TMP%
Program Files
%PROGRAMFILES%
Current Users Application Data Directory
%APPDATA%

RunDll Commands

Add/Remove Programs
RunDll32.exe shell32.dll,Control_RunDLL appwiz.cpl,,0
Content Advisor
RunDll32.exe msrating.dll,RatingSetupUI
Control Panel
RunDll32.exe shell32.dll,Control_RunDLL
Date and Time Properties
RunDll32.exe shell32.dll,Control_RunDLL timedate.cpl
Display Settings
RunDll32.exe shell32.dll,Control_RunDLL access.cpl,,3
Device Manager
RunDll32.exe devmgr.dll DeviceManager_Execute
Folder Options – File Types
RunDll32.exe shell32.dll,Control_Options 2
Folder Options – General
RunDll32.exe shell32.dll,Options_RunDLL 0
Folder Options – Search
RunDll32.exe shell32.dll,Options_RunDLL 2
Folder Options – View
RunDll32.exe shell32.dll,Options_RunDLL 7
Forgotten Password Wizard
RunDll32.exe keymgr.dll,PRShowSaveWizardExW
Hibernate
RunDll32.exe powrprof.dll,SetSuspendState
Keyboard Properties
RunDll32.exe shell32.dll,Control_RunDLL main.cpl @1
Lock Screen
RunDll32.exe user32.dll,LockWorkStation
Mouse Properties
RunDll32.exe shell32.dll,Control_RunDLL main.cpl @0
Map Network Drive
RunDll32.exe shell32.dll,SHHelpShortcuts_RunDLL Connect
Network Connections
RunDll32.exe shell32.dll,Control_RunDLL ncpa.cpl
Power Options
RunDll32.exe Shell32.dll,Control_RunDLL powercfg.cpl
Regional Settings
RunDll32.exe shell32.dll,Control_RunDLL intl.cpl,,3
Stored Usernames and Passwords
RunDll32.exe keymgr.dll,KRShowKeyMgr
System Properties: Advanced
RunDll32.exe shell32.dll,Control_RunDLL sysdm.cpl,,4
System Properties: Automatic Updates
RunDll32.exe shell32.dll,Control_RunDLL sysdm.cpl,,5
Taskbar Properties
RunDll32.exe shell32.dll,Options_RunDLL 1
User Accounts
RunDll32.exe shell32.dll,Control_RunDLL nusrmgr.cpl
Windows Security Center
RunDll32.exe shell32.dll,Control_RunDLL wscui.cpl
Windows – About
RunDll32.exe SHELL32.DLL,ShellAboutW
Unplug/Eject Hardware
RunDll32.exe shell32.dll,Control_RunDLL hotplug.dll
Windows Firewall
RunDll32.exe shell32.dll,Control_RunDLL firewall.cpl
Wireless Network Setup
RunDll32.exe shell32.dll,Control_RunDLL NetSetup.cpl,@0,WNSW

Access Stored User Names and Passwords with rundll32.exe

The Stored User Names and Passwords applet lets you assign user names and passwords to use when needing to authenticate yourself to services in domains other than the one you are currently logged into.  The normal way of running this applet can be difficult to find quickly, so here is a way to launch it using a shortcut using the rundll32.exe program

Click on START - RUN and type the following (follwed by ENTER):
rundll32.exe keymgr.dll,KRShowKeyMgr
:

Tuesday, January 15, 2013

Alternate row color


Place a rectangle with a transparent background color. Place fields on the rectangle. In the expression tab for the rectangle, in the backgound color field :
if ( mod(getrow(),2) = 0, oneColor, anotherColor )

Use a Java class (PB9)

We simply need to build an "EJB proxy" to our class even if it's not an EJB.
Consider the following simple class :
[Simple.java]
public class Simple {
    public Simple() {  }
    public static String sayHello(){
        return "Hello world";
    }
    public String sayNonStaticHello(){
        return "Hello world";
    }    
    public static void main(String[] args) {
        System.out.println(Simple.sayHello());
    }
}
Before generating the proxy, we need a "dummy" SimpleHome class.
[SimpleHome.java]
public interface SimpleHome { }
Compile both files. Now, we will build a Powerbuilder application and use our "Simple" class from Powerscript.
  1. Start Powerbuilder.
  2. Create a new application, call it "pbjsimple", put everything in the same directory(.class and .pbl).
  3. Start the EJB Proxies Wizard, Type "Simple" as the component and the classpath is the folder containing the "Simple.class" file.
  4. Run the project, Powerbuilder will generate proxies for your classes and also for most standard Java classes!
  5. Next, open a window from the application and drop a Button and insert the following Powerscript in the "click event".
    JavaVM lJavaVM
    EJBConnection lEJBConn
    Simple lnv_simple
    long    ll_return
    
    lJavaVM = CREATE JavaVM
    
    // need to specify the classpath form the Simple class
    ll_return = &
       lJavaVM.CreateJavaVM("C:\Applications\rega\dev\Work\pb9\Target3", FALSE)
    CHOOSE CASE ll_return
        CASE 1
        CASE 0
        CASE -1
           MessageBox ( "", "jvm.dll was not found in the classpath.")
        CASE -2
           MessageBox ( "", "pbejbclient90.jar file was not found." )
        CASE ELSE
           MessageBox ( "", "Unknown result (" + String (ll_return ) + ")"  )
    END CHOOSE
    
    IF ll_return < 0 THEN
       DESTROY lJavaVM
    END IF
    
    lEJBConn = CREATE EJBConnection
    ll_return = lEJBConn.CreateJavaInstance( lnv_simple, "Simple")
    IF ll_return <> 0 THEN
       MessageBox("", "CreateJavaInstance returned " +string(ll_return))
       destroy lEJBConn
    ELSE
       TRY
         MessageBox("From Java!" , lnv_simple.sayNonStaticHello())
       CATCH (CreateException ce)
         MessageBox( "Create Exception", ce.getMessage() )
       CATCH (Throwable t)
         MessageBox(" Other Exception", t.getMessage())
       END TRY
    END IF
    
    Note : AFAIK Java static methods are not visible from Powerbuilder.

Scan Window titles

[local function declaration]
FUNCTION LONG GetDesktopWindow() LIBRARY "user32"
FUNCTION LONG GetWindow( long hWnd, long uCmd ) LIBRARY "user32"
FUNCTION LONG GetClassNameA &
   ( long hWnd, Ref String lpClassName, long nMaxCount ) &
      LIBRARY "user32"
FUNCTION LONG GetWindowTextA &
   ( long hWnd, Ref String lpString, long nMaxCount ) &
      LIBRARY "user32"
FUNCTION BOOLEAN IsWindowVisible( long hWnd ) LIBRARY "user32"

[powerscript]
long ll_Desktop,ll_Child
 
string ls_ClassName, ls_WindowName, ls_ieopened
 
Constant long GW_HWNDFIRST = 0
Constant long GW_HWNDLAST = 1
Constant long GW_HWNDNEXT = 2
Constant long GW_HWNDPREV = 3
Constant long GW_OWNER  = 4
Constant long GW_CHILD  = 5
Constant long GW_MAX   = 5
 
Constant long MAX_WIDTH = 255
 
ll_Desktop = GetDesktopWindow()
 
ll_Child = GetWindow( ll_Desktop, GW_CHILD )
 
ls_ieopened = ""
DO WHILE (ll_Child > 0)
   ls_ClassName  = Space(MAX_WIDTH)
   ls_WindowName = Space(MAX_WIDTH)
   // Get window classname
   GetClassNameA( ll_Child, ls_ClassName, MAX_WIDTH )
   // Get window text
   GetWindowTextA( ll_Child, ls_WindowName, MAX_WIDTH )
 
   IF ls_classname = "IEFrame" THEN
      ls_ieopened += ls_ClassName + "(" + ls_WindowName + ") "
   END IF
   ll_Child = GetWindow( ll_Child, GW_HWNDNEXT )
LOOP 
 
Messagebox("" , ls_ieopened)

Detect if running in PB or executable

IF Handle(GetApplication()) = 0 THEN
   MessageBox("Info", "Running in PB environment")
ELSE
   MessageBox("Info", "Running in standalone executable")
END I

Terminate an another application

[local external function declaration]
FUNCTION ulong FindWindowA(ulong classname, String windowname) & 
  LIBRARY "user32.dll"
FUNCTION boolean PostMessageA&
  (ulong hwndle,UINT wmsg,ulong wParam,ulong lParam) & 
  LIBRARY "user32.dll"
  
  
[powerscript]
CONSTANT uint WM_QUIT = 18 // hex 0x0012
ulong     lul_handle
string    ls_app

ls_app = "Calculator"
//  ls_app = "Calculatrice"  in french windows!

lul_handle = FindWindowA(0, ls_app)

IF lul_handle > 0 THEN 
   PostMessageA(lul_handle, WM_QUIT, 0, 0);
ELSE
   MessageBox("Oups", ls_app + " is not running!")
END IF

Evaluate an expression

datastore lds_temp

string ls_result
string ls_expession

string ls_err
// a dummy minimal datastore definition
string ls_dsdef = &
'release 6; datawindow() table(column=(type=char(255) name=a dbname="a") )'

lds_temp = CREATE datastore
lds_temp.Create(ls_dsdef, ls_err)
lds_temp.InsertRow(0)

IF Len(ls_err) > 0 THEN
   MessageBox("ds create", ls_err)
ELSE
   ls_expression = "(2 + 7)  / 3"
   ls_result = &
     lds_temp.Describe ( 'evaluate( " ' + ls_expression + ' " ,1)' )
   MessageBox("ds evaluate", ls_result)
END IF
DESTROY lds_temp

Retrieve an environment variable

// PB6 
ContextKeyword lcxk_base
string ls_Path
string ls_values[]

this.GetContextService("Keyword", lcxk_base)
lcxk_base.GetContextKeywords("path", ls_values)
IF Upperbound(ls_values) > 0 THEN
   ls_Path = ls_values[1]
ELSE
   ls_Path = "*UNDEFINED*"
END IF
 
 
============================================ 
ALLUSERSPROFILE      location of the All Users Profile.
APPDATA              location where applications store data by default.
CD                   current directory string.
CLIENTNAME           client's NETBIOS name when connected to terminal server session.
CMDCMDLINE           command line used to start the current cmd.exe.
CMDEXTVERSION        version number of the current Command Processor Extensions.
CommonProgramFiles   path to the Common Files folder.
COMPUTERNAME         name of the computer.
COMSPEC              path to the command shell executable.
DATE                 current date.
ERRORLEVEL           error code of the most recently used command.
HOMEDRIVE            drive letter is connected to the user's home directory.
HOMEPATH             full path of the user's home directory.
HOMESHARE            network path to the user's shared home directory.
LOGONSEVER           name of the domain controller that validated the current logon session.
NUMBER_OF_PROCESSORS   number of processors installed on the computer.
OS                   name of the operating system. 
                     (Windows XP and Windows 2000 list the operating system as Windows_NT.)
Path                 search path for executable files.
PATHEXT              file extensions that the operating system considers to be executable.
PROCESSOR_ARCHITECTURE   processor's chip architecture.
PROCESSOR_IDENTFIER  description of the processor.
PROCESSOR_LEVEL      model number of the computer's processor.
PROCESSOR_REVISION   revision number of the processor.
ProgramFiles         path to the Program Files folder.
PROMPT               command-prompt settings for the current interpreter.
RANDOM               random decimal number between 0 and 32767.
SESSIONNAME          connection and session names when connected to terminal server session.
SYSTEMDRIVE          drive containing the Windows root directory.
SYSTEMROOT           location of the Windows root directory.
TEMP and TMP         default temporary directories for applications that are available to 
                     users who are currently logged on.
TIME                 current time.
USERDOMAIN           name of the domain that contains the user's account.
USERNAME             name of the user currently logged on.
USERPROFILE          location of the profile for the current user.
WINDIR               location of the OS directory.

Get the executable name

[local external function declaration]
FUNCTION ulong GetModuleFileName (ulong hinstModule, ref string lpszPath, ulong cchPath )  &
   LIBRARY "KERNEL32.DLL" &
   ALIAS FOR "GetModuleFileNameA;ansi"  // ;ansi  required for PB10 or better

[powerscript]
ClassDefinition  lcd

String ls_fullpath 
ulong lul_handle, lul_length = 512

IF handle(getapplication()) = 0 THEN
    // running from the IDE
    lcd=getapplication().classdefinition
    ls_fullpath = lcd.libraryname
ELSE
    // running from EXE
    lul_handle = handle( getapplication() )
    ls_fullpath=space(lul_length) 
    GetModuleFilename( lul_handle, ls_fullpath, lul_length )
END IF

MessageBox("", ls_fullpath)

Wednesday, January 2, 2013

Open the Webapge in PowerBuilder

integer li_rc
inet lcx_inet
li_rc = getcontextservice('Internet',lcx_inet)
If (li_rc <> 1) THEN
    messagebox('Clicked','getcontextservice failed')
ELSE
    lcx_inet.hyperlinktourl('c:\temp\error.xml')
END IF

Creating Registry file Using PowerBuilder

OLEObject PBObject
String GUID
long ll_rtn
PBObject = CREATE OLEObject
ll_rtn = PBObject.ConnectToNewObject("PowerBuilder.Application")
If ll_rtn < 0 Then
   MessageBox("Connect Error","Could not connect to OLE Automation object")
   Return
Else
   //Set the library list
   PBObject.LibraryList = "c:\projects\tax\tax.dll"
   //Specify the library compilation type
   PBObject.MachineCode = True
   //Generate the GUID
   ll_rtn = PBObject.GenerateGUID( REF GUID)
   If ll_rtn < 0 Then
      MessageBox ("Generation Error","Could not generate GUID.")
      Return
   Else
      //Generate the registration file
      ll_rtn = PBObject.GenerateRegFile( GUID, "u_tax_calc", "Tax.Object", 1, 0, &
      "Tax calculations", "c:\projects\tax\tax.reg")
      If ll_rtn < 0 Then
         MessageBox( "Generation Error", "Could not generate registration file")
      End If
   End If
End If

Access PB Code in VB

Dim PBObject As Object
Dim Taxuo As Object
Dim GrossPay as Integer
Dim TaxRate as Integer
 `Connect to the tax object
Set PBObject = CreateObject("PowerBuilder.Application")
If pbobject Is Nothing Then
   MsgBox "Create of PB object failed"
   End Sub
Else
   PBObject.LibraryList = "c:\pbi32\tax.pbd"
   Set Taxuo = PBObject.CreateObject("u_tax_calc")
   If Taxuo Is Nothing Then
      MsgBox "tax uo failed"
      End Sub
   Else
      `Call the tax bracket function
      TaxRate = Taxuo.uf_Tax (GrossPay)
      Set Taxuo = Nothing
   End If
   Set pbobject = Nothing
End If

Accessing Word in PowerBuilder

integer li_rtn
string ls_program
 
ls_program = "c:\msoffice\winword\winword.exe " + &
 "c:\msoffice\winword\unleash.doc"
li_rtn = Run( ls_program, Minimized!)
If li_rtn = -1 then
   MessageBox( "Run Error", "Could not start Word for Windows")
   Return
Else
   il_ddehandle = OpenChannel( "WINWORD", "c:\msoffice\winword\unleash.doc")
   If il_ddehandle < 0 Then
      MessageBox( "Connection Error", "Word is not responding!")
      Return
   End If
End If
 
 

Sending Data

To send data to a DDE server, use the SetRemote() function.
 
SetRemote( "last_name", "Herbert", "Winword", "unleash.doc") 

Requesting Data

If you want to retrieve information from the DDE server application, use the GetRemote() function.

string ls_LastName
GetRemote( "last_name",ls_LastName,"Winword","unleash.doc")

Command
li_rtn = ExecRemote( "FileSave", li_ddehandle)
 
Terminating 
 li_rtn = CloseChannel(il_ddehandle)
If li_rtn <> 1 Then
   MessageBox("Close error","Unable to terminate conversation!")
End If
 
 
OLEObject ole_excel
string ls_string
integer li_int
any la_any
ole_excel = CREATE OLEObject
ole_excel.ConnectToObject( "budget.xls")
la_any = ole_excel.application.cells(10,5).value
Choose Case ClassName( la_any)
   Case "string"
      ls_string = la_any
   Case "int"
      ls_int = la_any
   Case Else
      MessageBox( "Retrieve Error","Unknown data type returned")
      Return
End Choose