Welcome to the Appeon Community!

Learn, share knowledge, and get help.

 

Featured Blogs

Featured Articles

Git Enhancements in PowerBuilder 2017 R3

Support for using Git as a source control system without going through a bridge product was added in 2017 R2 and covered in a previous blog post.  In this blog post we're going to look at the enhancements that were added to that feature in 2017 R3. 

Read more

Comments (0)

There are no comments posted here yet

JSON Enhancements in PowerBuilder 2017 R3

There were some JSON features introduced in 2017 R2, in particular the JSONGenerator and JSONParser, which were covered in a previous blog post.  2017 R3 introduces additional important JSON features, in particular JSON import/export from a DataWindow, and a JSONPackage object that is used to merge/extract JSON data sets.  Those will be covered in this blog post.

Read more

Comments (1)

  1. Mir Dader Ali

Very Helpful article , PowerBuilder still a great language . BUT....

PowerBuilder's licensing policy i.e "per year per developer" is not competitive as comparison to other programing languages like c#, Java etc. This policy is one of discouraging factor for clients to continue with PowerBuilder ,this is my personal industrial experience as a consultant .

 
There are no comments posted here yet

PowerBuilder 2017 R2 New Feature: REST

One of the new features added to PowerBuilder 2017 R2 is support for REST web services.  This feature isn't 100% complete, as additional REST functionality is planned for 2017 R3.  There's still a lot in the R2 release to look at though.

To make things simple for the demo, we're going to use a online REST web service called JSONPlaceHolder..  The service doesn't require creating an account or user authentication.  While the GET (retrieve) methods are fully functional the POST ( insert ), PUT/PATCH ( update ) and DELETE (delete) methods are placeholders.  They return result codes or in the case of POST the id value of the inserted row, but they don't actually modify the data.

Note that while REST web services can return data in any internet mime encodable format, the vast majority of them use JSON  and JSON is the only data format supported by the REST client object in PowerBuilder 2017.

Read more

Comments (7)

  1. Hani EL Dabet

Dear Mr. Armstrong,

I am trying to consume a webservice using powerbuilder 2017R2. I have consume the same service in C# and trying now to do the same in powerbuilder. I have created a WCF proxy to access the web service and able to connect. However, in order to call any function I need to add soap header for the API key.  similar to the code in c#:

 //add a soap header for API Key
MessageHeader ApiMessageHeader = MessageHeader.CreateHeader("API_KEY", "http://tempuri.org;", API_KEY);
                    System.ServiceModel.OperationContext.Current.OutgoingMessageHeaders.Add(ApiMessageHeader);


string userName = "username";
string passWord = "xxxxxx.";
string Provider = "dsadsa";
calls the authenticate user
if the authentication is successful it will assign the token variable the appropriate value         

client.AUEAuthenticateUser(userName, passWord, Provider, ref token);

--------------

How to add soap message header in  powerbuilder before calling the method AUEAuthenticateUser.

 

Thanks for your reply

 
  1. Bruce Armstrong

Please post this question in the regular forums.

 
  1. Chris Pollach

Hi Bruce;

Great article .. thanks!

Just a minor point .. the JSON returned must be formed within array brackets ... for example:

[


{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

]

  If not, the DWO data transformation will not occur.

Regards .. Chris

 
  1. Richard Bianco

Hi Bruce,

Enjoyed the article as I prepare for a presentation will be doing for the conference.

I'm in the (mundane) process of wiring up REST endpoints to datawindows and wanted to ask if there was anything I could do to help with coding for the REST improvements being delivered for PB2018? I'm probably re-inventing the wheel doing some of the same things you might be doing as I'm trying to write my own utility that takes an endpoint address say... https://api.binance.com/api/v1/klines?symbol=ETHBTC&;interval=1m and creating my own datawindow from the actual Json returned.

The code you have was helpful as a first step. Some changes I'd make are adding support for Json when there the Json isn't surrounded by [ ] and is only surrounded by { } .

Other things I'm trying to write into an ancestor are handling of more than two levels of hierarchy, adding support for boolean, and adding support for automatically converting numbers surrounded by double quotes to be converted to number/decimal in the datawindow. Right now I load the Json into a rough datawindow, then perform transformations on data and moving row by row to another datawindow and saving to database.

I don't have much experience with extending PowerBuilder (at internal level via PBNI) but ideally it would be cool to extend RestClient to handle some of the things I talked about. I downloaded your PBNISMTP project on GitHub and trying to figure it out. If you'd be able/willing to share that code with me- I'd be more than happy to provide enhancements made so you can decide if you want to incorporate them into the tool. I would be honored to think that some of my code made it into the actual release and would expect no compensation. Though if you want to hire me as consultant I'd work for a very reasonable rate (for PB developer).

You should have access to my email via the site but will post it here anyway as this page is member only: rich@displacedguy.com or displacedguy@gmail.com I'm not the best about responding quickly but would really appreciate a response. I have some time and can surely help with any work you have.

p.s I'm also working on a wizard type window that I provide REST endpoint address (like above) and parse the Json into datawindow allowing me to set column name, data type, etc., with as much info derived as possible. Also I'd add ability to generate a database table to store result and have ideas on defining the Json fragments (complex object types) into my database so the definition of Json is data driven. Yeah I have a lot on my plate but it's fun.

Sincerely,
Rich Bianco

  Comment was last edited about 2 months ago by Richard Bianco Richard Bianco
  1. Armeen Mazda    Richard Bianco

I don't know about the feasibility if this could really cover all situations of automatically creating the DataWindow from the endpoint, but boy if you could do that it would be so cool and save time!

 
  1. Bertrand Terlat

Hi

These informations are really useful thanks a lot.

I have a question which concerns the command "http.sendrequest" I saw it was possible to call the function with the first parameter 'CONNECT' such as


http.sendrequest( 'CONNECT', 'https://jsonplaceholder.typicode.com/posts' ..... I don't understand how to use it.

Would you please have an example using the parameter value 'CONNECT' ?

I have the case it's required to autenticate to the url to use it and I also tried to use '&token_auth' without any success in my case.

The result of http.GetResponseStatusCode() gives :

<title>401 - Unauthorized: Access is denied due to invalid credentials.</title>


Thanks in advance for help!!!

Kind Regards,

Bertrand

 
  1. Bruce Armstrong    Bertrand Terlat

I don't know where you saw it was possible to call it using "CONNECT", or why you would want to. That verb is used in the initial connection to the service that is done under the covers. It's not one of the HTTP verbs you would use for a REST service.

If you need to authenticate to the service, you would do that through request headers added prior to sending the request.

Rather than follow up here, I would suggest asking your question in the regular Q&A forums and I can follow up there.

 
There are no comments posted here yet

Most Popular Articles

Exporting Datawindows to Excel / Html without losing Format

I have a function called "GuardarAExcel2()" which uses a step datawindow called "d_filafichero". With this function you generate an excel with the same visual aspect as your datawindow. I hope it helps you:

Example of use:

GuardarAExcel2( dw_1, "c:\Report.xls")
GuardarAExcel2( dw_1, "c:\Report.html")

Result in datawindow:

 

Read more

Comments (20)

  1. Byron Guaman

Hola Eduardo G, intento ejecutar tu funcion pero falta el objeto ds_datastore, puedes publicarlo por favor para probar tu funcion saludos.

 
  1. Eduardo G.

Hola Byron, ds_datastore (UserObject) está heredado de datastore, puedes reemplazarlo por lo siguiente:

Hello Byron, ds_datastore (UserObject) is inherited from datastore, you can replace it with the following:

datastore dsHTML
dsHTML = CREATE datastore
dsHTML.DataObject = "d_FilaFichero"
dsHTML.ImportFile( Text!, spRuta )

Un saludo.

 
  1. jhon sparky

hello eduardo G,

it's work for me..but all border in cell not view..still loosing format..

 
  1. Leonardo Velazquez

Hola.... muchas gracias por el aporte.... en Chrome se ve muy bien... pero en Excel me divide en 2 renglones cada registro.... 

http://i304.photobucket.com/albums/nn178/leviatanMX/reporte.png

 
  1. Eduardo G.

Hola,
Te ocurre debido a que los objetos column que tienes en el detail no deben de estar a la misma altura o tienes alguno superpuesto a otro. Es muy aconsejable que los objetos no estén uno encima del otro para que funcione correctamente.

Un saludo.

 

Hello. Hi,
It happens to you because the column objects you have in the detail must not be at the same height or you have some superimposed to another. It is highly advisable that the objects are not on top of each other for them to function properly.
A greeting.

 
  1. luis miguel sanchez ordoñez

Buenos dias amigo me sale error en la funcion F_global_replace .

podrias especificar el tipo de valor y sus argumentos. Gracias es muy importante poner a prueba tu funcion 

 
  1. Eduardo G.

 

//f_global_replace(fuente,buscar,poner)

/*

Argument Type >> Argument Name

string >> source

string >> look_for

string >> replace_with

Return Type string

 

A String Occurrence Search and Replace Routine

The following code demonstrates a string occurrence search and replace routine.

This routine works generically for any string. For example, 

if old_str = "red" and new_str = "green", all occurrences of 

 "red" inside of mystring will be replaced with "green".

*/

int start_pos=1,len_look_for

len_look_for = len(look_for)

 

//find the first occurrence of look_for ...

start_pos = Pos(source,look_for,start_pos)

//only enter the loop if you find whats in look_for

DO WHILE start_pos > 0

//replace look_for with replace_with ...

source = Replace(source,start_pos,Len_look_for,replace_with)

//find the next occurrence of look_for

start_pos = Pos(source,look_for,start_pos+Len(replace_with))

LOOP

return source

 

 

 

 


// Función: f_cuenta_char

// Descripción: Cuenta todas las ocurrencias de as_char en  la cadena as_source

// Ambito: publica

// Argumentos: as_source {cadena de la que se desea borrar las ocurrencias de as_char}

//    as_char   {caracter a ser contado de la cadena as_source}

// Retorna: Integer {numero de ocurrencias encontradas}

//////////////////////////////////////////////////////////////////////////////////////

int li_pos

int ncuenta=0

 

li_pos = Pos (as_source, as_char, 1)

do while li_pos > 0

ncuenta+=1

as_source = Left (as_source, li_pos - 1) + &

Right (as_source, Len (as_source) - li_pos)

li_pos = Pos (as_source, as_char, 1)

loop

 

return ncuenta

 
  1. Eduardo G.

Ya lo tienes :-D

 
  1. Ivan Mesarc

Hello, it does not respect custome date format for datetime columns. Could you help please?

Thanks

 
  1. Eduardo G.

Hello, check the block "// Prevent text with / convert to date" to adapt it to your needs.
A greeting.

 
There are no comments posted here yet

PowerBuilder 2017 R2 New Feature: Git source control support

In a previous blog article we looked at the new feature of PowerBuilder 2017 R2 for Subversion source control support. In this blog article we're going to look at a very similar feature, Git source control support.  I'm not going to go through the history of source code support in PowerBuilder again, I'd refer you to that previous blog article for that.  We're going dive straight in to how the Git feature works.

Setting up Git

For this demo, we're going to use Bonobo Git Server.  One reason I like it is because it provide a web based admin console for managing the server, so I don't have to use the Git command line to do that.

Because it's an ASP.Net application, the machine where we're going to install it must have IIS and the .Net Framework 4.6 installed on it.  To install Bonobo Git once you've downloaded it you simply need to:

Read more

Comments (3)

  1. Michael Kiefer

Thanks for this article; it has been helpful.

I am hoping that Appeon improves the overall experience when working with Git as there are a few things that are less than ideal.

The workarounds for cloning/specifying the URL for the repo with some very-common GIT servers are a big problem. This is particularly true since after creating a new clone manually you must "Add to source control" files that are already in source control. This creates an unnecessary commit for what is essentially a "no change" situation. This could also lead to merge conflicts on binary files.

Fortunately, I found a workaround for this extra "Add to source control" step, which is to create the appropriate registry entries manually (or write a script to do it), so that the PB UI things the code is already under source control. For example:

Windows Registry Editor Version 5.00

[HKEY_USERS\S-1-5-21-1234567890-1234567890-839522115-2208969\Software\Sybase\PowerBuilder\17.0\Workspace\C:$dev$git$MyApp$myworkspace.pbw\SourceControlVersion2]
"Type"="Git"
"Name"=""
"ServerURL"=""
"LocalPath"="C:\\dev\\git\\MyApp"
"Author"="My Name"
"email"="myname@company.com"
"LogAllActivity"=""
"LogFilePath"=""
"AppenOverWrite"=""
"Comments"=""
"RefreshRate"=""

A better solution, would be for the PB UI to automatically detect that the workspace is located in a git repo and use the configuration information from the git repo directly instead of trying to maintain it separately in the registry.

I also dislike the fact that we are still storing binary files like PBLs -- particularly large ones -- in git. This is a very bad practice and leads to bad performance and huge repos. It should be possible to easily rebuild a PBL from a set of text-based source files (i.e. *.pbg, *.sr*). Unfortunately, it seems that the direction with PB2017 R3 is to go the opposite direction and eliminate the pbg files all together.

 
  1. Michael Kiefer

In case anyone wants the script for the above:

Function New-GitCloneForPowerBuilder { [CmdLetBinding()] Param( [Parameter(Mandatory = $true)] [string] $RepoUrl,

[Parameter(Mandatory = $true)] [string] $CloneLocation,

[Parameter(Mandatory = $true)] [string] $RelativePbwPath )

$pushedLocation = $false try { $ErrorActionPreference = 'Stop'

git clone $RepoUrl $CloneLocation $CloneLocation = Resolve-Path $CloneLocation Push-Location $CloneLocation $pushedLocation = $true

#get Git settings as set by the clone because we need to put them in the registry for PB $userEmail = git config --get user.email $userName = git config --get user.name

#Verify the workspace element exists $registryRoot = "HKCU:\Software\Sybase\PowerBuilder\17.0\Workspace" if (-not (Test-Path $registryRoot)) { New-Item -Path $registryRoot -Force| Out-Null }

#Create the specific workspace element $registryPath = $registryRoot + '\\' + ((Resolve-Path (Join-Path $CloneLocation $RelativePbwPath)) -replace '\\', '$') if (-not (Test-Path $registryPath)) { New-Item -Path $registryPath -Force | Out-Null }

$registryPath = $registryPath + '\\SourceControlVersion2' if (-not (Test-Path $registryPath)) { New-Item -Path $registryPath -Force | Out-Null }

$properties = @{ "Type" = "Git"; "Name" = ""; "ServerURL" = ""; "LocalPath" = $CloneLocation; "Author" = $userName; "email" = $userEmail; "LogAllActivity" = ""; "LogFilePath" = ""; "AppenOverWrite" = ""; "Comments" = ""; "RefreshRate" = ""; } foreach ($p in $properties.Keys) { New-ItemProperty -Path $registryPath -Name $p -Value $properties[$p] | Out-Null }

} catch { throw ("Unable to setup Git repo clone for PB workspace {0}`n{1}" -f $_.Exception.Message, $_.InvocationInfo.PositionMessage) } finally { if ($pushedLocation) { Pop-Location } } }

 
  1. jhon perker

I did not have many knowledge about PowerBuilder, but after your post, I am getting some knowledge about it, I want more information about that matter, and i also glad to know that PowerBuilder 2017 R2 release New Feature,But when I try to update it I face some technical error, so I decide to go hp printer won't print black they told me the process which I really need.

 
There are no comments posted here yet

PowerBuilder 2017 R2 New Feature: Subversion (SVN) source control support

PowerBuilder's initial support for version control systems required drivers for specific vendors (e.g., PVCS) and often for specific versions of that vendor's products.  It was not unusual to find that you needed to wait to upgrade your source control product until PowerBuilder released an updated driver for it.  And if your source control provider wasn't supported by PowerBuilder you were simply out of luck.

 

 

That changed with PowerBuilder 6.  With that release, PowerBuilder abandoned the vendor specific drivers in favor of the recently introduced Microsoft Source Code Control Interface (MSSCCI).  Essentially an ODBC for version control, it freed the IDE from vendor lock-in.  Provide the source control provide provides an MSSCCI complaint interface, or there was a 'bridge' product available that could convert MSSCCI calls into the source control providers native API calls, PowerBuilder could use the product.

Read more

Comments (5)

  1. Maurice Losier

Hi Bruce,

Great write up it did help put everything in context. I'm looking to move to R2 for the benefit of no proxy / svn. My challenge is that we have over 10 years of History origanally from CVS and migrated to SVN. I'd like to maintain history but obviously we don't have the right structure. Any opinion strategy etc. would help

 

 

 
  1. David Sutton

While I love the idea of a move towards a native client we will still need MSSCCI support until this native client becomes more feature complete.

Can you confirm that MSSCCI support is still functional and has not changed in R2?

 
  1. Bruce Armstrong

We did our migration from PVSC to SVN back in 2009, and we used the SVNImporter tool to convert over our existing repositories.

https://polarion.plm.automation.siemens.com/products/svn/svn_importer

They have a version there for CVS as well. It worked quite well in our experience.

 

 
  1. Bruce Armstrong

Nothing in MSSCCI has changed.  You can still continue to use that.

I'm curious as to what features you think it's missing that are preventing you from moving to it.  Anything you can't do in the PB IDE you can still do through TortoiseSVN, it's just a tab bit more work.




 

 
  1. Jay Thangam

Burce,

We successfully integrated our PB code with Git Repository.
But when I try to push my changes from local to remote as I am getting below error.
Even I have tried this with colleague pc as we are getting the same error.
Any advice?

PB Version: 2017 R2
Git Server : VSTS
Client : Git Tortoise 2.1.8

---------- Source Control
Git push
Starting to push workspace...
Git client is pushing workspace. Please wait...
Git client error: Generic error..
Failed to push workspace.
Git push
---------- Done Source Control

 
There are no comments posted here yet

Using PowerBuilder 2017 with TFS source control

This article is a guide to connect Powerbuilder 2017 with TFS. It is important to follow the steps in the order listed in the article.

The prerequisite includes

  • PB17 installed on a local machine.
  • TFS server running with access to the user. A collection is required where the code will be checked in. 

Next follow the below points:

  1. Team explorer 2013 : Yes the first thing needed is to install Visual studio team explorer. I know the first question pop ups in mind is if Visual studio needs to be installed on every machine !! Well the answer is NO. All you need is Team explorer 2013 to access the TFS. Second question is why 2013 ? Well there comes the 32 bit and 64 bit compatibility issues, moreover there is no standalone installer for Team explorer 2015. If you figured out a way to do it with later versions, then mention it in the comments. 
Read more

Comments (10)

  1. Frank Frey

Nice article. Would this also be applicable to PB12.6 classic?

 
  1. Nasir Ahmad

Yes, It should work for 12.6 classic version and 12.5 as well. 

 
  1. Vollie Sanders Jr

Question I have is what TFS server version do we need to use, Corp office has TFS2010 and TFS2015. will ether of these work?

 
  1. LUIS GUTIERREZ

Frank, I am writing a similar document for PB 12.6 with TFS2017 (server), using VS2015. I hope to share it soon. My initial recommendation for you, is to create a folder for each PBL.

 
  1. Nasir Ahmad

TFS2015 server will work as per my knowledge since MSSCCI and team explorer i tested was for TFS 2013, which worked for TFS 2017.  

For earlier versions of TFS you test and find MSSCCI, Team explorer which are compatible with that version. 

 
  1. Van Sederburg

Worked perfectly!

 
  1. Armeen Mazda

Another way to use PB 2017 with TFS is to switch the repository from the legacy TFVC to Git. With recent versions of TFS the default repository is actually Git, and Microsoft recently acquired GitHub. The advantage of switching is that PB 2017 natively interfaces with Git rather than using the legacy MSSCCI interface, which gets you support for more source control features and faster performance of source control operations.

 
  1. iliyan iliev

MSSCCI dosn't works with TFS 2018 ! Any idea how to use tfs 2018 ?!

 
  1. Nasir Ahmad    iliyan iliev

Is your team explorer connecting to TFS? which version of visual studio team explorer are you using ?

I would recommend you to move from TFVC to Git as recommended by Armeen Mazda in above comment.

 
  1. iliyan iliev    Nasir Ahmad

I'm use VSTE 2017

 
There are no comments posted here yet

RESTClient

The first thing we'll look at is the new RESTClient.  It's the primary mechanism to get the DataWindow to use a REST web service.  Right now it only supports Retrieve.  Support for update operations is planned for R3.  Note that in order to use a DataWindow to display data from a REST web service the data set it returns will need to be a simple array.  More complex nested structures would still need to be handled through the techniques we'll cover later in this article.

For this sample, we're going to pull the list of posts from the JSONPlaceHolder site.  The first thing we're going to need to do is create an external DataWindow object that has columns that match the data element names returned by the service.  For posts, JSONPalceHolder returns data like this:

 {  
  "userId": 1,  
  "id": 1,  
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",  
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"  
 }  

So my DataWindow object looks like this:

The code to retrieve the data from the service and then populate the DataWindow object with it is then rather trivial:

 RESTClient rest  
 rest = create RESTClient  
 rest.Retrieve( dw_1, "https://jsonplaceholder.typicode.com/posts")  

The results look like this:

The RESTClient has a number of other properties and functions that are of interest, though we didn't need to use them here:

Property

Purpose

SecureProtocol

Enumerated integer value used to set the secure protocol used by the client (SSL2, SSL3, TLS 1.0, TLS 1.1 or TLS 1.2).  The default ( 0 ) means to detect the protocol used by the service and match it.

Timeout

Long value for the timeout for the client in seconds.  Defaults to 60 seconds.  Setting it to 0 means no timeout.

 

Function

Purpose

{Get/Set/Clear}RequestHeader{s}

Manipulate the request headers used in the REST request.

GetResponseStatusCode

Returns the status code from the REST service (2xx = OK, 3xx = Redirected, 4xx = Client Error, 5xx = Server Error.

 

Particular success codes:

  200 OK

  201 Created

  202 Accepted

GetResponseStatusText

The text description for the response

 

HTTPClient, JSONGenerator and JSONParser

For dealing with more complex return data structures - and for dealing with updates -  we can use the HTTPClient, JSONGenerator and JSONParser.  First we're going to retrieve that same data from that same REST web service, but doing it with the HTTPClient.  This involves a bit more code:

 integer    li_rc  
 long       ll_id, ll_userid,ll_row,ll_root,ll_index,ll_child,ll_count  
 string     ls_string,ls_result,ls_body,ls_title  
 httpclient http  
 http = create httpclient  
 li_rc = http.sendrequest( 'GET', 'https://jsonplaceholder.typicode.com/posts')  
 if li_rc = 1 and http.GetResponseStatusCode() = 200 then  
     http.GetResponseBody(ls_string)  
 end if  
 JSONParser json  
 json = create JSONParser  
 ls_result = json.loadstring( ls_string )  
 ll_root = json.getrootitem( )  
 ll_count = json.getchildcount( ll_root )  
 dw_1.Reset()  
 for ll_index = 1 to ll_count  
     ll_row = dw_1.InsertRow(0)  
     ll_child = json.getchilditem( ll_root, ll_index )  
     ll_id = json.getitemnumber( ll_child, "id" )  
     dw_1.setItem(ll_row, "id", ll_id)  
     ll_userid = json.getitemnumber( ll_child, "userid" )  
     dw_1.setItem(ll_row, "userid", ll_userid)  
     ls_title = json.getitemstring( ll_child, "title")  
     dw_1.setItem(ll_row, "title", ls_title)  
     ls_body = json.getitemstring( ll_child, "body")  
     dw_1.setItem(ll_row, "body", ls_body)  
 next  

We use the HTTPClient SendRequest method to call the REST service method, check the response status code using GetResponseStatusCode and, if success, get the data in JSON format using GetResponseBody.  We will then use the JSONParser to parse the JSON data, looping through it and sticking individual data elements in individual rows and columns.

Now lets see how we can perform updates through the REST web service from the DataWindow using those objects:

 integer  li_rc, li_rsc  
 long    ll_index, ll_count, ll_id, ll_root  
 constant integer OK = 200  
 constant integer CREATED = 201  
 String      ls_json, ls_result  
 dwItemStatus  status  
 HttpClient     hc  
 JSONGenerator jg  
 JSONParser   jp  
 hc = create HttpClient  
 jg = create JSONGenerator  
 jp = create JSONParser  
 dw_1.AcceptText()  
 ll_count = dw_1.Rowcount( )  
 FOR ll_index = 1 TO ll_count  
     status = dw_1.GetItemStatus ( ll_index, 0, Primary! )  
     CHOOSE CASE status  
         CASE NewModified!, DataModified!  
             //Inserted or Modified Rows  
             ll_root = jg.createjsonobject( )  
             jg.AddItemNumber(ll_root, "userid", dw_1.GetItemNumber(ll_index, 'userid'))  
             jg.AddItemString(ll_root,'title',dw_1.GetItemString(ll_index,'title'))  
             jg.AddItemString(ll_root,'body',dw_1.GetItemString(ll_index,'body'))  
             IF status = NewModified! THEN  
                 //Inserted  
                 ls_json = jg.getjsonstring( )  
                 li_rc = hc.sendrequest( 'POST', 'https://jsonplaceholder.typicode.com/posts', ls_json)  
                 li_rsc = hc.GetResponseStatusCode()  
                 IF li_rsc = CREATED THEN  
                     //Get the response, which contains the ID value assigned to the new row  
                     hc.GetResponseBody(ls_json)  
                     ls_result = jp.loadstring( ls_json )  
                     ll_root = jp.getrootitem( )  
                     ll_id = jp.getitemnumber( ll_root, "id" )  
                     //Set it back into the inserted row  
                     dw_1.SetItem ( ll_index, 'id', ll_id )  
                 ELSE  
                     MessageBox ( parent.title, "Insert Failed" )  
                 END IF  
             ELSE  
                 //Updated  
                 ll_id = dw_1.GetItemNumber ( ll_index, 'id' )  
                 jg.AddItemNumber(ll_root,"id", ll_id)  
                 ls_json = jg.getjsonstring( )  
                 li_rc = hc.sendrequest( 'PUT', 'https://jsonplaceholder.typicode.com/posts/' + String ( ll_id ), ls_json)  
                 li_rsc = hc.GetResponseStatusCode()  
                 IF li_rsc <> OK THEN  
                     MessageBox ( parent.title, "Update Failed" )  
                 END IF  
             END IF  
         CASE ELSE  
             //skip this row  
             CONTINUE   
     END CHOOSE  
 NEXT  
 //Deleted Rows  
 ll_count = dw_1.Deletedcount( )  
 FOR ll_index = 1 TO ll_count  
     ll_id = dw_1.GetItemNumber(ll_index, 'id', Delete!, true)  
     li_rc = hc.sendrequest( 'DELETE', 'https://jsonplaceholder.typicode.com/posts/' + String ( ll_id ))  
     li_rsc = hc.GetResponseStatusCode()  
     IF li_rsc <> OK THEN  
         MessageBox ( parent.title, "Delete Failed" )  
     END IF  
 NEXT  
 dw_1.ResetUpdate( )  

What I'm doing here is looping through the Primary DataWindow buffer where the inserts and updates are at.  If I find an insert, I use the JSONGenerator to put together a JSON data string that contains the data elements except for the primary key, since that will be returned to us from the POST call.  I then use the HTTPClient SendRequest method to sent the POST with the JSON data.  We then check the response code using HTTPClient GetResponseStatusCode to ensure it was 201 (CREATED) and, if so, use the HTTPClient GetResponseBody to retrieve the data that was returned from the POST call, included the id value that was assigned to the new row.  We then use JSONParser to parse out the id value and set that value back in the DataWindow for that row.

The approach is very similar if the row was updated rather than inserted.  The main differences are that we a) include the primary key value in the JSON for this request, b) use PUT rather than POST to send the data, c) the URL we use to send the data back includes the id value, d) we check for a response value of 200 (OK) rather than 201 (CREATED) and e) we don't need the response data.

For deletes, we loop through the Delete DataWindow buffer.  For deletes we don't need to send the entire row.  Instead we just get the id value for the row and include that as part of the url for the DELETE call.  As with PUT (Update) we check for a 200 (OK) response from the service.

At the very end of the routine, since we've handled the update of the DataWindow manually, we perform a ResetUpdate to clear the row status flags in the Primary DataWindow buffer and clear the Deleted DataWindow buffer.

As with the RESTClient, the HTTPClient has a number of additional properties and functions that will be of use in specific situations.

Property

Purpose

SecureProtocol

Same as for RESTClient above

Timeout

Same as for RESTClient above

AutoReadData

TRUE/FALSE.  Default is TRUE.  FALSE would be of use primarily if the response set is very large.  If so, you would use the ReadData method to read chunks of the response in a loop.

 

Function

Purpose

{Get/Set/Clear}RequestHeader{s}

Same as for RESTClient above

GetResponseStatusCode

Same as for RESTClient above

GetResponseStatusText

Same as for RESTClient above

PostDataStart/PostData/PostDataEnd

Used to send a large amount of data to the rest service in smaller blocks

ReadData

Used to read a large amount of data from the rest service in smaller blocks

 

Coming Attractions

This is enough to get us operational with REST web services, but in some cases it requires a bit of coding.  PowerBuilder 2017 R3 is expected to deliver additional REST functionality that would make using REST even easier.  In particular:

  • Support of DataWindow updates directly through the RESTClient.
  • Methods to import and export JSON data directly to/from the DataWindow, eliminating the need to use the JSONParser/JSONGenerator to put the JSON data together manually.

Comments (7)

  1. Hani EL Dabet

Dear Mr. Armstrong,

I am trying to consume a webservice using powerbuilder 2017R2. I have consume the same service in C# and trying now to do the same in powerbuilder. I have created a WCF proxy to access the web service and able to connect. However, in order to call any function I need to add soap header for the API key.  similar to the code in c#:

 //add a soap header for API Key
MessageHeader ApiMessageHeader = MessageHeader.CreateHeader("API_KEY", "http://tempuri.org;", API_KEY);
                    System.ServiceModel.OperationContext.Current.OutgoingMessageHeaders.Add(ApiMessageHeader);


string userName = "username";
string passWord = "xxxxxx.";
string Provider = "dsadsa";
calls the authenticate user
if the authentication is successful it will assign the token variable the appropriate value         

client.AUEAuthenticateUser(userName, passWord, Provider, ref token);

--------------

How to add soap message header in  powerbuilder before calling the method AUEAuthenticateUser.

 

Thanks for your reply

 
  1. Bruce Armstrong

Please post this question in the regular forums.

 
  1. Chris Pollach

Hi Bruce;

Great article .. thanks!

Just a minor point .. the JSON returned must be formed within array brackets ... for example:

[


{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

]

  If not, the DWO data transformation will not occur.

Regards .. Chris

 
  1. Richard Bianco

Hi Bruce,

Enjoyed the article as I prepare for a presentation will be doing for the conference.

I'm in the (mundane) process of wiring up REST endpoints to datawindows and wanted to ask if there was anything I could do to help with coding for the REST improvements being delivered for PB2018? I'm probably re-inventing the wheel doing some of the same things you might be doing as I'm trying to write my own utility that takes an endpoint address say... https://api.binance.com/api/v1/klines?symbol=ETHBTC&;interval=1m and creating my own datawindow from the actual Json returned.

The code you have was helpful as a first step. Some changes I'd make are adding support for Json when there the Json isn't surrounded by [ ] and is only surrounded by { } .

Other things I'm trying to write into an ancestor are handling of more than two levels of hierarchy, adding support for boolean, and adding support for automatically converting numbers surrounded by double quotes to be converted to number/decimal in the datawindow. Right now I load the Json into a rough datawindow, then perform transformations on data and moving row by row to another datawindow and saving to database.

I don't have much experience with extending PowerBuilder (at internal level via PBNI) but ideally it would be cool to extend RestClient to handle some of the things I talked about. I downloaded your PBNISMTP project on GitHub and trying to figure it out. If you'd be able/willing to share that code with me- I'd be more than happy to provide enhancements made so you can decide if you want to incorporate them into the tool. I would be honored to think that some of my code made it into the actual release and would expect no compensation. Though if you want to hire me as consultant I'd work for a very reasonable rate (for PB developer).

You should have access to my email via the site but will post it here anyway as this page is member only: rich@displacedguy.com or displacedguy@gmail.com I'm not the best about responding quickly but would really appreciate a response. I have some time and can surely help with any work you have.

p.s I'm also working on a wizard type window that I provide REST endpoint address (like above) and parse the Json into datawindow allowing me to set column name, data type, etc., with as much info derived as possible. Also I'd add ability to generate a database table to store result and have ideas on defining the Json fragments (complex object types) into my database so the definition of Json is data driven. Yeah I have a lot on my plate but it's fun.

Sincerely,
Rich Bianco

  Comment was last edited about 2 months ago by Richard Bianco Richard Bianco
  1. Armeen Mazda    Richard Bianco

I don't know about the feasibility if this could really cover all situations of automatically creating the DataWindow from the endpoint, but boy if you could do that it would be so cool and save time!

 
  1. Bertrand Terlat

Hi

These informations are really useful thanks a lot.

I have a question which concerns the command "http.sendrequest" I saw it was possible to call the function with the first parameter 'CONNECT' such as


http.sendrequest( 'CONNECT', 'https://jsonplaceholder.typicode.com/posts' ..... I don't understand how to use it.

Would you please have an example using the parameter value 'CONNECT' ?

I have the case it's required to autenticate to the url to use it and I also tried to use '&token_auth' without any success in my case.

The result of http.GetResponseStatusCode() gives :

<title>401 - Unauthorized: Access is denied due to invalid credentials.</title>


Thanks in advance for help!!!

Kind Regards,

Bertrand

 
  1. Bruce Armstrong    Bertrand Terlat

I don't know where you saw it was possible to call it using "CONNECT", or why you would want to. That verb is used in the initial connection to the service that is done under the covers. It's not one of the HTTP verbs you would use for a REST service.

If you need to authenticate to the service, you would do that through request headers added prior to sending the request.

Rather than follow up here, I would suggest asking your question in the regular Q&A forums and I can follow up there.

 
There are no comments posted here yet