vrijdag 15 juni 2012

RemObjects integration in Smart Mobile Studio (part 1)

In the next update (planned the 18th) of Smart Mobile Studio (SMS), full support for RemObjects SDK services will be added.
With RemObjects (RO) it is very easy to make multi tier applications. For example, you can create one or more RO services (as middle tier) to centralize your main business logic. And with the next SMS update, it is very easy to create nice looking mobile and web front ends (presentation tier) for these remote services!

In this blog, I will try to explain the basis steps to create a RemObjects service. And in the next blog I will explain how to use this RO service in (then updated) Smart Mobile Studio.

Under the hood

Under the hood, the SMS RO integration is actually a typed wrapper around "RemObjects for Javascript" (SMS generates javascript (JS) code after all :) ), and not a complete new implementation. This way, the high RO quality is maintained and all RO features are supported. Also future updates of "RO for JS" can be applied. However, SMS cannot apply smart linking and obfuscation to this external JS code.

Basic RemObjects service

First, we will create a very basic RemObjects service in Delphi, using the nice and easy RO wizard:
(Delphi -> File -> New -> Other -> RemObjects SDK)

We choose for "VCL Standalone", because this is the easiest to start with (but if you plan to create a Windows service (for Intranet deployment), I can recommend to use the "Combo Service/Standalone" option). The first page of the RO wizard will be shown:

We choose a project name and folder, and we click on the "Advanced Project Options" for some more settings:

Here you can name the first "RO service" within the "RO library" (normally you will create a number of services, e.g. an OrderService for all order functions, and one library per Windows service). Most important is the HTTP "Server class" (in this case based on Indy, but you can choose other implementations), because this is the only option supported by "RO for JS" to communicate with the server (a browser cannot use plain TCP or Windows messages, however I already made a websocket server class). Next, we can choose between JSON and Binary message format. JSON is supported by all browsers, but binary is not fully supported by Internet Explorer (IE), so we choose for JSON to be on the safe side.

When we finish the wizard, RO will generate a server project for us:

The first thing we do is setting the "SendCrossOriginHeader" to true! This is needed, because our Smart app will run standalone and seperate from the http server. However modern web clients do not allow to call other foreign web servers (for safety reasons). There are other ways to solve this, but for internal use this single setting is the easiest :).

The next step is less obvious for first time RO users: we start the seperate "RemObjects Service Builder" tool  (via Delphi -> RemObjects SDK -> Edit service library). The RO wizard has created our BasicService with default 2 functions: "Sum" and "GetServerTime":

We can add more functions, structures, arrays, etc but we will leave this for now. We just close this tool and compile our server project in Delphi. Every time we create a new RO service within the RO Service Builder tool, the RO integration in Delphi will ask once at the next compile to create a implementation unit for the defined service:

We now have a "BasicService_Impl.pas" datamodule, which contains our 2 functions:
    function Sum(const A: Integer; const B: Integer): Integer;
    function GetServerTime: DateTime;
We will implement the simple :) functionality as follows:
    function TBasicService.Sum(const A: Integer; const B: Integer): Integer;
    begin
      Result := A + B;
    end; 
    function TBasicService.GetServerTime: DateTime;
    begin
      Result := Now;
    end;
This is all we have to do for our first RemObjects service, easy isn't it? :)
In the next blog post we will create a Smart client to use this remote service.

vrijdag 1 juni 2012

Remobjects via Websockets and in Node.js

After playing with Smart Mobile Studio (SMS) and RemObjects for Javascript, I thought it would be cool to have a HTML5 websocket communication channel (instead of only http). Note: websockets are some kind of "TCP over HTTP", so very efficient and fast for e.g. binary data.
At my current customer we use TROIndyTCPChannel and TROBinMessage internally, because this is the fastest option.

Websockets in Delphi

Because RO does not have websocket support (yet), I tried to make a Proof of Concept (PoC) to see if it is possible. I searched and tried some Delphi implementations, but one was old (Indy9, old websocket spec), otherone had no sourcecode yet (Indy10, no  response on my mail so far), etc. I found one which is based on "synapse", which is also included in RO, namely "bauglir-websocket".
I looked at how RO made their TRO***Server and TRO***Channel and made a simple implementation for websockets: uROWebsocketChannel.pas and uROWebsocketServer.pas. This was almost too easy :).
I tested this with a Delphi RO demo server and client (using the RO wizard) and: tada, it works! :).

RO websocket channel

Next I had to make a websocket channel in "RemObjects for Javascript", and after some copy and paste I added this to the end of the RemObjectsSDK.js file. I made a simple html test file and this one works too!

Node.js

Okay, what can we do next? Make a websocket server in html? Hmm, websockets (in html) can only make client connections and cannot act as a server...
Maybe I can use it in Node.js? Note: Node.js is a server side javascript implementation, based on the Google V8 Javascript engine.
I found a websocket chat demo in Node.js, so it should be possible... Because it is not easy to debug in Node.js, I tried to make it work in Google Chrome first, by using the "websocket.onmessage" event and by sending a fetched JSON string (using the network debug tab in Chrome) when the html page connects to my  Delphi server. After some hacking I could read the RO message, do the "sum" and send the data back to the client. Sweet!
After some little more hacking I also had it working in Node.js! So both my html page and my Delphi client can connect to the Node.js server. Ain't that cool! :)

Download and test

If you want to test it yourself, you can download the zip file, and do the following:
- start "ROWebSocketsServer.exe"
- start "ROWebSocketsClient.exe" and open "\client\client.html"
- push the sum buttons, both should work

- stop "ROWebSocketsServer.exe"
- start the node.js server via "\node\start RO.node.bat"
- push the sum buttons in the clients (maybe restart them?), both should work too :)


woensdag 9 mei 2012

I made a Proof of Concept debugger for "DWS to Javascript" (so it's also possible with Smart Mobile Studio :) ), using the WebKit Remote Debugging Protocol of Google Chrome. The protocol is JSON based over WebSocket. The specification of these communication JSON objects is nicely documented here, for example the supported debugger commands.

My PoC is a modified version of the MandelbrotJS demo of DWS. I used the websocket implementation of "Delphi on Rails" and for JSON handling I used "superobject". This made the PoC very easy to make!

Some screenshots of the PoC in action:
First, when it's started:

Next, after the "Compile and Run" button is pressed:
(note: chrome.exe is started with "--app" and embedded afterwards in the tab, so no TChromium but the latest version of Google Chrome! I also added a "setInterval" so we can add breakpoints to executing JS code)

Now we can click the "Remote Connect" button to connect to the remote Chrome.exe instance via the remote debugging protocol. When this button is pressed, the debugger is activated and gets (async) a list of loaded script files (in our case only 1 html file). We click on the "Load debug script" button to load the latest script in our debugger:

The debugger is running (we can only "pause" now), and we can add a breakpoint by double clicking on a line, for example line 14:

Because of the "setInterval" this code is executed every second, so we get soon a real breakpoint! Because of my "/*@15*/" code added to the generate JS, the debugger can determine the original Delphi/Pascal source line (with extra offset of "<%pas2js"), which is highlighted and selected in SynEdit (see above).
Also the current stack and the "scope" (local variables) and the properties/values of the local variables are loaded and shown at the left side (note: double clicking on the stack of scope also works: source code position is updated, local variables etc). And hoovering above a variable shows the current value (and the JSON object is also shown for debug purpose).

Pressing the "Step over" button continues the execution to the next line. Because DWS has no line numbering info for each symbol and line, I could not add the magic "/*@" to all the code, so the debugger now shows the current line in the Javascript code:
(note: I stepped a bit further than line 16)
The values of variables are updated, so it gets refreshed every time. The debugger really works!

And to show the stack and scope can be inspected too (double click on the item):
(note: line 61 is selected, is not shown here. And yes it should be line 60, nice off by one error...)

So go ahead, grab the code and play with it!

Conclusion: it it possible the debug Delphi/Pascal code in "DWS to Javascript", but DWS should be modified a bit more, so debug info is generated for each line (in a different debug symbol file?).

donderdag 12 januari 2012

"Smart" business (OP4JS, Delphi/Pascal for Javascript)


After reading various blog posts about OP4JS (now named “Smart Mobile Studio”), I was very curious if I could use it for my current customer. We have a couple of RemObjects services, which contain our business logic (multi tier, SOA (service oriented architecture)), and we would like to create a HTML client for it (for iPad and Android).
I did a simple test with the latest alpha release, and it turned out to be relative easy! (it is an alpha, so no code completion, internal debugging, delphi shortcuts etc yet, so I had to do everything by hand :-) ).

First I made a simple RemObjects server using the Delphi Wizard:
Delphi -> New -> Other -> RemObjects SDK -> VCL Standalone:
I selected HTTP server + JSON message format (needed for Javascript communication).

Default it already contains 2 functions: “Sum(A,B: Integer): Integer” and “GetServerTime: TDatetime” (see below for screenshot of the RemObjects Service Builder). When compiling the server for first time, it will generate a datamodule for the server side implementation for these 2 functions (I won’t post the implemention: a “sum” function is too simple :-) ). So we have a RemObjects HTTP server now, which listens to the default port 8099 and uses the JSON data format (normally we use TCP + Binary messages for fast and low overhead messaging).

Next, we need to generate some code for the client side. In the RemObjects Service Builder we can generate various client implementations: C++, PHP, Delphi (also automatic done in Delphi IDE) and also Javascript. In the latest RemObjects release they added a completely new Javascript implementation but I could not get it working yet, so I have taken the "old" JSON RPC implementation:

You need to download some extra Javascript files, because it is dependent on the Yahoo YUI toolkit (I have tested the RemObjects Javascript implementation before, so I already had these files).

After that, I started “Smart Mobile Studio” and played with the delivered demos. I created a new “visual project”, and added 2 edits, a button, and another edit to the form (all typing by hand, no designer yet):

Procedure TForm1.InitializeObject;
Begin
 inherited;

 FEdit1:=TW3EditBox.Create(self);
 FEdit1.setBounds(10,10,100,32);
 FEdit1.text:='2';

 FEdit2:=TW3EditBox.Create(self);
 FEdit2.setBounds(10,50,100,32);
 FEdit2.text:='3';

 FBackBtn:=TW3Button.Create(self);
 FBackBtn.setBounds(10,95,100,32);
 FBackBtn.Caption:='Sum';
 FBackBtn.Visible:=true;
 FBackBtn.OnClick := ButtonClicked;

 FEdit3:=TW3EditBox.Create(self);
 FEdit3.setBounds(10,140,100,32);
 FEdit3.text:='';
End;
I created a “button click” procedure, which calls my RemObjects server. Because I have to call some pure Javascript code, I used the “asm” keyword for my “low level” code:
Procedure TForm1.ButtonClicked(Sender:TObject);
var
 s1, s2, s3: string;
Begin
 s1 := Self.FEdit1.text;
 s2 := Self.FEdit2.text;
 asm
   var service = new NewService("http://localhost:8099/JSON");
   service.Sum(@s1,
               @s2,
               function(sumresult)
               {
                  TW3EditBox.setText(Self.FEdit3,sumresult);
               });
 end;
End;
Note: I had to put the values of the 2 edits in seperate variables, because I could not directly use “@FEdit1.text” in the “asm” block? For the result callback (async!) I had to do something different, so I used “TW3EditBox.setText(FEdit3,result)” because this code is generated by SmartMobileStudio too when you type “FEdit3.text := ‘value’.

This code almost works: I have to include the client Javascript files somewhere. You can include Javascript in the project, but also in the main index.html (like you normally do with html).   
 script type="text/javascript" src="lib/yahoo.js">
 script type="text/javascript" src="lib/event.js">
 script type="text/javascript" src="lib/json.js">
 script type="text/javascript" src="lib/connection.js">
However, SmartMobileStudio uses a temp dir when running from the IDE (so it misses my extra .js files), so I just compiled the project, and ran the generated index.html directly from the project dir in Google Chrome.

So it’s done now? No, I got an error in Chrome, because I call an other HTTP server from my (local) index.html:
I had to enable cross site calls in myRemObjects HTTP server:
 ROServer.SendCrossOriginHeader := True;
But then Chrome complains about “Access-Control-Allow-Headers”, so I manually changed this by overriding the RemObjects implementation of the internal Indy “Other” function:

ROHttpServerCommandOther           := ROServer.IndyServer.OnCommandOther; ROServer.IndyServer.OnCommandOther := InternalServerCommandOther;

procedure TServerForm.InternalServerCommandOther(AContext: TIdContext;
 ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
 //original RO handling
 ROHttpServerCommandOther(AContext, ARequestInfo, AResponseInfo);

 //need to set extra allow-header
 if ROServer.SendCrossOriginHeader then
  AResponseInfo.CustomHeaders.Values['Access-Control-Allow-Headers'] := 'Origin,   X-Requested-With, Content-Type';
end;

And then it works! After the initial problems, it should be easy now to extend the functionality further. For example, I would like to create a "Javascript to Delphi wrapper class" generator based on the .rodl interface file, so I have type safety again (no asm sections in code, only in wrapper class).
I hope to blog about this more in the future...

Note: demo code + binaries can be found here. First start "\ROSmartTest\NewProject.exe" and then "\Project1\Project1\index.html"

vrijdag 2 december 2011

LAC 2011, dag 2


De 2e dag van LAC 2011 begon met een leuk filmpje over een jongen van 12 jaar die apps maakt. De achterliggende gedacht hiervan was: de ontwikkelingen gaan snel, en voor je het weet wordt je ingehaald door de volgende generatie.

Dit werd verder uitgewerkt in de keynote van Jan Bosch. Hij heeft onder andere bij Nokia gewerkt, maar is ook bij grote bedrijven van Silicon Valey geweest om te leren hoe ze daar software ontwikkelen. Hij benadrukte dat het vooral gaat om speed, speed, speed. Alleen bedrijven die snel kunnen ontwikkelen, aanpassen en innoveren zijn succesvol. 1 van de redenen dat het slecht met Nokia gaat is dat ze te langzaam zijn, zichzelf niet kunnen veranderen. Dit komt onder andere doordat ze te grote ontwikkelteams heeft. Andere bedrijven zoals Google, Facebook, LinkedIn, Amazon etc hebben meerdere kleine teams volgens de 2 pizza rule: een team moet genoeg hebben aan 2 pizza’s. Uiteraard verschilt dit per persoon :-) dus ter verduidelijking: niet groter dan 6 á 7 personen. Geef elk team zijn eigen verantwoordelijkheid en doel, en zorg voor een goed test systeem. De programmeurs moeten niet bang zijn om te veranderen, dus straf hem ook niet als een bug in de software zit: dit is de verantwoordelijkheid van het test systeem! Dus als je het voor elkaar krijgt om Google.com onderuit te krijgen, ben je juist goed bezig. Op deze manier kun je contineous deployen: code inchecken, automatisch testen en gelijk live! Dit is de ultime ontwikkel methode, waarbij je erg snel kunt veranderen en je ook geen versies meer hebt. Uiteraard moet je eerst contineous intergration en je test systeem goed hebben werken.

En wat betreft architectuur? Deze moet simple simple simple. Als het te ingewikkkeld wordt: opnieuw beginnen. Voor een ingewikkeld systeem een ingewikkelde architectuur maken kan elke “idioot”, maar je bent pas knap als je een simpele architectuur kunt maken!

Innoveren is ook erg belangrijk. De meeste bedrijven zijn te veel bezig met efficiëntie, terwijl dit maar relatief weinig oplevert. Als voorbeeld: je kunt beter voor 10% meer omzet zorgen dan 10% van het R&D budget bezuinigen. Een manier van innoveren is meerdere dingen tegelijk proberen, en de gebruiker laten bepalen welke het beste is. Keuzes maken op basis van data in plaats van de opinie van enkele programmeurs. Dit houdt in dat je verschillende gebruikers verschillende versies geeft en dan meet welke het beste werkt. Zo heeft Google 500 (!) verschillende kleurtinten blauw geprobeerd, en 1 speciale blauwtint zorgde voor een spectaculaire omzetgroei...

Het was een “prikkelende” keynote :-), hij was onder andere van mening dat een crisis juist goed is, omdat je juist dan extra gewongen wordt om te veranderen en innoveren en zorgt dat je scherp blijft.
Nu is bijvoorbeeld contineous deployen niet voor elk bedrijf nodig of uitvoerbaar, maar het geeft wel aan dat “het internet” continue veranderd. Dit kan ook verder doorgevoerd worden, zodat je over enkele jaren een eerste versie van een telefoon of auto koopt, en de software hiervan elke dag geupdate wordt: agile product ontwikkeling.

Deze keynote was zo ongeveer het beste van de dag, de andere sessies vielen een beetje tegen. Zo was er een sessie over een nieuwe manier van ontwikkelen volgens “principles”: bepaalde principles staan vast (soort wetmatigheden) die je niet kunt veranderen, andere principles komen voort uit bijvoorbeeld wensen van gebruikers. Belangrijk is weer te weten “het waarom”. De kernprincipes zijn belangrijk en geen lijvig dictatuur document maken.
Het was een beetje vaag en abstract, waarbij het verzande in een discussie over de exacte betekenis van “requirements” en andere muggenzifterij over woordgebruik. Vervolgens was de tijd om en kon de persoon in kwestie zijn verhaal niet afmaken...

Ik ben toen maar geswitched naar een andere sessie, waarbij uitgelegd werd hoe ze bij het UMC Radboud ziekenhuis innoveren, onder andere door de patient centraal te stellen en om feedback te vragen. Iedereen mag ideeen indienen, die gescreend worden en de beste worden uitgevoerd. De architectuur staat niet vast: anders kun je niet veranderen.

Daarna een leuk ervaringsverhaal van de ‘Port of Rotterdam’. Deze haven is erg belangrijk, en de software moest nodig vernieuwd worden (oa ivm uitbreiding van havengebied). De eerste 2 pogingen op de klassieke manier mislukte, waarna ze het over de andere boeg gooiden: geen Waterfall maar Agile, geen externe partij maar weer zelf een (klein) ontwikkelteam samen stellen. Dit team zelf de verantwoordelijkheid geven en zelf laten beslissen, ze niet te veel te beperken en eigen intiatief aanmoedigen. Dit zorgt voor creativiteit en gaan ze extra goed voor “hun kind” zorgen en worden ze enthousiast en betrokken.
Geen starre architectuur maar “just in time” wat op dat moment nodig is. Over een maand veranderd er wel weer iets of komt er iets bij dus niet te veel vooruit werken.
Een valkuil is om te veel op features te richten, maar dit zorgt voor “quality dept”: je architectuur gaat achter lopen, terwijl deze elke keer bijgewerkt moet worden als je iets tegenkomt of ergens mee bezig bent. Ze herkenden veel van de keynote van die morgen: speed, simple, kleine teams, agile, etc.

Tja, wat sommige bedrijven al niet doen om mensen te trekken... In plaats van inhoudelijke tips en trucs over architectuur hadden ze Hans Kazan ingehuurd. Deze hield vooral een verhaal over zichzelf en deed een paar goochel trucs. Niet echt waar ik van hou: of goochelaars zijn erg goed in het mensen voor de gek houden (maar hoe doen ze dat dan?), of het is echt magisch... En dan moet ik denken aan de tovenaars in de bijbel: die konden net als Mozes in Egypte stokken in slangen veranderen. En ja, ik ben een nuchtere noordeling, maar ik heb genoeg meegemaakt om te weten dat er meer is dan alleen een aarde.

Maar goed, weer “on topic”, ik was blij dat deze sessie ten einde was. Nog een sessie gevolgd over de ontwikkeling voor het Landelijk Register Kinderopvang. Echter weinig inhoudelijk en technisch, en ook hierin discussies over andere details, zodat de tijd weer snel voorbij was :-(.
Wel leuk om te horen dat ze het project binnen 2 maanden gereed hadden door Agile (SCRUM) te gebruiken. Anders was het (net als zoveel andere (overheids)projecten) niet gelukt. Ook het opsplitsen van verschillende onderdelen maakte het overzichtelijk en eenvoudiger.

Als laatste nog weer geprobeerd om wat van “principles” op te steken, zoals die door het Kadaster intern gebruikt wordt. Ook hier een algemeen verhaal en meer bedrijfsmatig, leuk om te horen hoe zij het doen, maar niet nuttig (lees: technisch) voor mijzelf.

Tot slot nog een tip (die ik bij het LAC opgedaan heb): als je mooie gelikte presentaties wilt laten zien, iets anders dan Powerpoint, probeer dan een http://prezi.com/. Presentaties worden dan niet meer saai en lineair maar interactief, met mooie zoom en scroll effecten, bijvoorbeeld deze (druk op de play knop om 1 stap vooruit te gaan, of ergens in de presentatie zelf om daar naar toe te springen).

dinsdag 29 november 2011

LAC 2011, dag 1


Vorige week ben ik bij het LAC (Landelijk Architectuur Congres) geweest in Nieuwegein. Ik ben nu een paar jaar Software Architect bij RBK en had dit ooit ergens ingevuld. Heel “toevallig” (toeval bestaat niet :-) ) kreeg ik een uitnodiging voor het LAC 2011. Aangezien ik nog genoeg te leren heb op dit gebied leek het me niet verkeerd om dit 2-daagse congres bij te wonen.

Het was een leuk, interresant en nuttig congres, waarbij ik veel geleerd heb. Het was wel even wennen: het was namelijk geen technisch congres (ik heb maar een keer Java en Oracle voorbij horen komen) wat ook te zien was aan de vele iPads en MacBooks (echte programmeurs hebben niet zo’n ding ;-) ). Veel algemene informatie gehoord, echter helaas weinig inhoudelijk over goede/slechte architecturen, tips, etc.

Over het algemeen staat niet vast wat een “architect” nu precies is, de meningen zijn nogal verdeeld. Per bedrijf en situatie is dit anders. Sowieso kunnen verschillende niveaus en typen aangegeven worden: Enterprise, Application, Infrastructuur/Netwerk, Informatie Architect etc.
Wel is duidelijk dat de architect van vroeger niet meer kan: gekscherend de “stugge dictator”. De technische ontwikkelingen gaan snel, veel veranderingen, en als bedrijf moet je snel kunnen veranderen. Dit betekent een flexibele architectuur die meehelpt in plaats van tegenwerkt.

De eerste keynote was van de CIO van ministerie van VWS. Zijn onderwerp: “doe maar klein en gewoon”. Architecten kunnen hele mooie diagrammen en techische documenten maken, en die kunnen echt “heel waar” zijn, maar niet-technische mensen begrijpen die totaal niet. Dus daar moet je bij het management niet mee aankomen. Beter is om een simpele tekening te maken en Jip & Janneke taal te gebruiken. Ook belangrijk is te weten wat bij bestuurders leeft: het aantal gigabytes of de betrouwbaarheid van de opslag, de snelheid of de veiligheid van geheime documenten in cloud?

De volgende keynote was van de Application Architect van de UBS Bank (Engeland). Hij beveelde aan om de “principles” goed te communiceren: plat gezegd het “waarom”. Als bijvoorbeeld op management niveau bepaalde beslissingen genomen worden, moet dit vertaald worden naar een globale technische structuur op het Enterprise niveau. Vervolgens wordt dit omgezet in gedetailleerdere structuur op Application niveau. Als laatste moeten de Developers dit uitvoeren.
Als alleen de kale eisen van hogerhand opgelegd worden, zullen de onderliggende lagen dit proberen te omzeilen. Daarom moet je het “waarom” steeds communiceren, zodat men het doel weet, dat het niet maar zo verzonnen is, etc. De mensen gaan dan meedenken en keuzes maken omdat men begrijpt waarvoor het is. Een belangrijk aspect is dat je feedback krijgt: bepaalde wensen kunnen tegen praktische problemen lopen. Normaal krijg je dit niet te horen, maar door de feedback krijgen de “hogere”lagen de bewustwording dat iets niet uitgevoerd kan worden.

Tussen de sessies door konden bedrijven in een Speakers Corner hun verhaal kwijt. Zo zal volgens Citrix het “Bring Your Own Device” concept steeds belangrijk worden. Werknemers hebben gemiddeld 3 devices (PC, Laptop, Smartphone, tablet, etc). Door deze via Citrix te verbinden kan de gebruiker overal zijn werk doen: sessies en data worden automatisch gesychroniseerd. De gebruiker kan vervolgens zelf zijn eigen device uitkiezen, meenemen of zelfs kopen...

De laatste sessies van de 1e dag die ik gevolgd hebben gingen over Agile en Architectuur. Deze zijn allebei nodig: de Waterfall methode is niet meer te doen in deze tijd, alleen in uitzonderlijke situaties zijn ze nog bruikbaar. Agile is de oplossing om debacles te voorkomen, maar waarbij de architectuur zeker belangrijk is! Ook bij de overheid wordt steeds meer Agile gewerkt, en met succes.

Interresant was te horen hoe Rabobank op deze manier werkt. Eerst hadden ze enkele langzame trage projecten van bijvoorbeeld 2 jaar. Nu hebben ze meerdere verschillende kleine teams met elk een eigen project. Bijna elke week verandert er wel iets (kleins) op www.rabobank.nl. Maar ook interne software wordt op de agile manier gedaan: bijvoorbeeld in een nieuwe versie konden ze een nieuw soort hypotheek/verzekering eerst alleen maar aanmaken, in de volgende week of nog later pas deze muteren. Dit lijkt raar, maar in de praktijk was het erg succesvol: in de 1e week waren er al 300.000 van het nieuwe product waren verkocht! Dus de 1e versie, hoe beperkt, was gelijk succesvol.
Dit agile werken houdt wel in dat de architect anders moet werken: teams werken veel sneller, maar hebben een beperkte scope. De architect heeft wel het overzicht en moet de structuur in de gaten houden. Hij moet “bij” alle teams zijn, maar kan niet “in” elk team zitten. Oftewel ook flexibel kunnen werken en wisselen en goed priotoriseren: zorgen dat niemand op jou wacht.

Om echt te profiteren van de snelle en flexibele software afdeling, moet het bedrijf in zijn geheel agile gaan werken. Want je hebt niets aan een 2 wekelijkse update als de implementatie afdeling maar per half jaar updates uitrolt. Meestal kan de QA/Test afdeling goed agile werken, en vinden de testers dit erg prettig: snelle feedback en betere samenwerking. De business en implementatie afdelingen (bovenste c.q. laagste laag) leveren meestal problemen op. Deze moeten erg wennen aan de nauwere betrokkenheid, meer en gerichte vragen, meer updates, etc.

Niet alleen software kun je agile maken, maar ook als bedrijf in het algemeen. Je kunt dan een bepaald business onderdeel of dienst agile maken, zodat je snel op marktveranderingen kunt reageren. Hierbij is het nodig dat je weet wat de barrières in je bedrijf zijn, wat de hotspots zijn (risico, belangrijk, impact, etc), welke je eventueel kunt uitbesteden, etc.

“Lean” kun je ook gebruiken: dit is echter een niveau hoger dan agile: eerst heb je bijvoorbeeld XP (coding standards, test driven development, contineous intergration, design patterns, etc), daarbovenop komt agile (als proces: korte sprints, alleen documenteren wat nodig is, etc). Lean is weer algemener en kun je gebruiken om binnen je bedrijf te kijken welke bedrijfsprocessen je kunt optimaliseren: bijvoorbeeld onderzoeken hoe lang het duurt totdat een bugmelding opgelost is, en waar de meeste tijd/vertraging in zit.

Als laatste werd een reallife casus besproken waarbij SOA (Service Oriëntend Architechture) gebruikt werd. Deze sessie was wel praktischer, hoewel ook een beetje simpel. Gedemonstreerd werd dat je door alleen RPCs (remote procedure call) en (web)services te gebruiken je niet direct flexibeler hoeft te zijn. Belangrijk is dat de business logica op 1 plek ligt (in de service) en niet bij alle clients: als een business rule verandert dan moeten alle clients geupdate worden. Eenvoudig en logisch maar misschien juist daarom snel over het hoofd gezien?

(dit was dag 1, hopelijk de volgende keer dag 2)

vrijdag 18 november 2011

Remote Control: automated GUI test with Delphi and DUnit


Why...
For my current customer I wanted to do GUI testing too. I already made unit tests for the most important parts, but with a large code base it is impossible to test all functionality, especially when you have limited time...

Because users use the GUI to make orders and do all other stuff, I thought: why not start top-down instead of bottom-up? (I known, normally you should start bottom up, but again: I had limited time). 80% of the time they use 20% of the functionality, so it should be easy to test those parts which are mostly used. And when I click the same buttons in the GUI, a lot of stuff is automatically tested! (black box testing: you don’t know if each function is properly working, you only check the final result, which is okay: better do a coarse test than nothing!).

There are several tools to do GUI automation, but I wanted to program all stuff in Delphi and with DUnit: we have a good framework with a nice data tier and business tier, so it would be a lot easier to use the existing stuff to create for example an order with order lines, check in the database if the order is created with the correct values, and check if the new order is loaded in the GUI, press some buttons, and check the database again.

And also important: I do not want to “pollute” all applications with all DUnit stuff, and I want to test the GUI app “as is”: the same .exe the customer will use.

The idea...
So I started thinking:
  • we have RemObjects SDK, so I can very easy make a remote call from DUnitTesting.exe to our Client.exe (and start it with a command line option to enable the new remote control)
  • we have Delphi 2010 with new RTTI, so I can very easy invoke a function with an array of parameters etc.
  • we have HitXML (open source edition), so I can make a simple object tree with properties to sub objects, which are automatically created by HitXML, and I can save/load the whole object with XML. By using the same technique (auto create subobjets using rtti) I can name each object with its property name, and make a back link of the child to the parent. This way I can do a reverse lookup to retrieve a full object path.
Okay, maybe I can create a “lightweight remote interface proxy facade” thingy with HitXML, using the same object path and same component names as the client, so I can search for a button by using “TComponent.FindComponent”? And send the full path with RemObjects, including an array of parameters, and use the new RTTI to execute a function by name in the remote client?
Should be possible!

The result...
After some testing and hacking, I have the following proof of concept (stripped version of what we use internally). By the way: I replaced RemObjects SDK with a simple Indy TCP call because not everybody has RemObjects (but with RO it is easier :-) ).
I made the following simple objects, with the same name and classnames as the real ones in the remote client (a bit simplified for this blog):
 {$METHODINFO ON}    
 TBaseRemoteObject = class
   property Owner: TBaseRemoteObject read FOwner;
   property Name : string                           read FName write FName;
 end;

 TApplication = class(TBaseRemoteObject)
 published
   frmMain : TfrmMain;
   frmTest : TfrmTest;
 end;

 TForm   = class(TBaseRemoteObject);
 TFrame = class(TBaseRemoteFrame);

 TfrmMain = class(TForm)
 published
   btnShowModal: TButton;
 end;

 TfrmTest = class(TForm)
 published
   btnOk: TButton;
   btnCancel: TButton;
   framTest1: TframTest;
 end;

 TframTest = class(TFrame )
 published
   Button1: TButton;
   Edit1: TEdit;
 end;

 TButton = class(TBaseRemoteObject)
 public
   procedure Click;
 end;

 TEdit = class(TBaseRemoteObject)
 public
   property  Text : string  read GetText  write SetText;
 end;
In DUnitTesting I can now make the following calls:
RemoteApp.frmMain.btnShowModal.Click;    //create modal form frmTest RemoteApp.frmTest.framTest1.Edit1.Text := 'test';    //set textCheckEqualsString( RemoteApp.frmTest.framTest1.Edit1.Text, 'test' );  //check text
This would result in clicking “btnShowModal” of the main form, which will do a .ShowModal of “frmTest” (this is programmed in the remote client). All forms are normally accessible via the “Forms.Application” object or “Screen.Forms” array, so we can find “frmTest” in the remote root (RemoteApp). In this form, we have a frame “framTest1” with an editbox “Edit1”. I made a “Text” property which does a remote call in “SetText” and “GetText” to read and write the text:
procedure TEdit.SetText(const Value: string);
begin
 TRemoteControlExecutor.Execute(Self, 'Text', [Value]);   //set “text” property with value
end;

function TEdit.GetText: string;
begin
 Result := TRemoteControlExecutor.Execute(Self, 'Text', []).AsString;
end;
How does it work...
An explanation of how the reading and writing of “Edit.Text” works internally:
The “TRemoteControlExecutor” does a reverse lookup of “Self” (in this case “Edit1”) to get the full path (“frmTest.framTest1.Edit1”). This is send to the remote client, including the function or property we want to read/write (“Text”) and the parameters for it (explained below).
When the remote client receives the call, it does a “TThread.Synchronize” to the mainthread. Then it searches for the form “frmTest”: is it “Screen.ActiveForm”, or somewhere in “Screen.Forms[]” or using “Application.FindComponent()”? When found, it does a recursive lookup for “framTest1” and “Edit1”. After that, it searches for a function named “Text” in component “Edit1” using the Delphi 2010+ rtti. In this case it won’t find such a function, so it searches for a property, and yes: property “Text” does exist :-). Now, a simple trick is done to determine a read or write of a property: if we have 1 parameter it is a write, if we have no parameters it is a read. The rest is easy with the new rtti: .Invoke() for a function, and SetValue()/GetValue() for properties. The result is written and send back to the caller.
This way you can very easy control a remote client! Seems nice and straight forward to me, isn’t it?


Remarks
The TButton.Click is done using WM_LBUTTONDOWN + WM_LBUTTONUP, instead of executing the .Click function: otherwise when a .ShowModal is done we will get a “remote lock”!
I also had to do an “Application.OnIdle” check, because creating and painting can take some time, and when a remote message is executed as the first message after create, it can give some strange results.

Tips
Note: by using the same classnames, it is easy to set up to lightweight remote facade proxy classes: you can just copy the first part of the form, for example:
type
 TfrmMain = class(TForm)
   btnShowModal: TButton;
   btnShowFloating: TButton;
   procedure btnShowModalClick(Sender: TObject);
   procedure btnShowFloatingClick(Sender: TObject);
 private
   { Private declarations }
 public
   { Public declarations }
 end;

Of course, this can automated if needed... :-)

And by the way: by using “Application.OnMessage” and “Application.OnActionExecute” I can record the clicked buttons and actions (WM_LBUTTONDOWN, find control under mouse, etc). Not included in this demo, but can post another demo if needed?

I extended the XMLTestRunner.pas with the duration of each test, very handy to see how long each test functions takes!

With TCP you can also control multiple (infinite?) clients in a whole network, to do a “massive” test :-).


Reactions and comments...
See the code and try it yourself! What do you think about it? A good way to do GUI testing or are there better ways? Please let me know!
http://code.google.com/p/asmprofiler/source/browse/#svn%2Ftrunk%2F-Other-%2FRemoteControl