Posted tagged ‘PowerBuilder’

Calling .NET from PowerBuilder

February 22, 2010

(This is an old post that I forgot to publish)

We were working with an older version of PowerBuilder (version 8.0) and needed to call out to .NET.  There wasn’t much documented and there were a few stumbling points, but we persisted and have proven to ourselves that it can be done.  However, we did rely on the use of COM.

Things to keep in mind:
– Make sure to restart PowerBuilder after any changes to registry or copying of dll’s. (If something does not work, restart PowerBuilder)
– You will likely need to close PowerBuilder in order to delete the .NET dll.

.NET Class Library (dll)

1) Create a .NET Class Library
2) Check the “Register for COM interop” checkbox on the Build tab of the project properties.
3) Expose the assembly to COM by Setting ComVisible to true in the AssemblyInfo file.  Ex. [assembly: ComVisible(true)]
4) Create a class.  Notice I did not include a Namespace in the example below.  I assume that you could get this to work with a namespace, however, I have not tested it.

using System;
using System.Runtime.InteropServices;

[ClassInterface(ClassInterfaceType.AutoDual)]  // Needed to export the public members of the .NET Component’s class into a default Class Interface in the generated typelibrary.
public class Tester
{
public Tester()
{
// Default constructor required to allow object to be co-creatable from COM.
}

public string Test(string input)
{
return input;
}

}

5) Build your assembly.

Register your dll

You will need to use regasm.exe which can be run using the Visual Studio Command Prompt.

Register on your machine:
regasm YourAssembly.dll

To register on a machine that does not have regasm you can create a registry file as follows:
regasm YourAssembly.dll /regfile:YourAssembly.reg
Then copy both the .dll and the .reg file to the deployment machine and run the .reg file.

Verify the dll works from VBScript (Optional)

For a sanity check create a vbs file with the following code and run it.
dim obj
set obj = CreateObject(“Tester”)

MsgBox(obj.Test(“Hello World”))

PowerBuilder Code

1) Create a PowerBuilder application

2) Place the following code in a button:

OLEObject obj_test

obj_test = CREATE OLEObject
if obj_test.ConnectToNewObject( ‘Tester’ ) = 0 then
MessageBox( ‘Test Function…’, String( obj_test.Test( ‘Hello World’ ) ) )
end if

3) Run it and click the button.  You should see a message box with “Hello World” in it.  If you don’t see it, try putting YourAssembly.dll in the path of your application.  I would first put it in the same directory as the PowerBuilder executable then once it works there start putting it in other directories that are in the path such as System32.

Check out what is exposed using OleView
From the Visual Studio Command Prompt execute OleView YourAssembly.dll

Resources

Awesome Article that goes into detail on .NET and COM interoperablity.
http://www.codeproject.com/KB/COM/cominterop.aspx#PART2