WELCOME TO OUR BLOG

Titanium without Titanium Studio

We recently built a small project using the Titanum framework for mobile apps. Pretty quickly I realized I wanted to escape from Titanium Studio. What motivated me? Let’s just say Eclipse and I don’t get along. Below I describe how I set up my Titanium dev environment with Webstorm, TIDebugger and typescript.

First things you have to do, which I won’t be describing here:

  • Titanium installed
  • android sdk installed
  • properly set up the PATH variable to reach android binaries (my is C:\android-sdk-win\platform-tools;C:\android-sdk-win\tools)
  • latest java development kit (jdk) 1.7

If your environment is configured correctly you should be able to run the command “android” from your TI project folder to start the “android sdk manager” application.  At the time of this writing, the latest android API was 21, which contains “intel x86 atom system image”. I used this for my “fast” andriod emulator.  Before launching the command line interface, you should create your “Android Virtual Device” (AVD) by “Android Avd Manager”. Open this by running

android avd

from the command line and create a new one as shown here.

02-avd

Save me WebStorm

Ok, now you are ready to free yourself from Titanium Studio.  I have had great experiences with Jetbrains WebStorm with its superb code completion, cutting edge technology support, and it’s cool looking darkula color scheme. You can write code in notepad if that’s what works for you, but at some point you’ll have to do some compiling and deploying. Luckily Titanium has Titanium-CLI – command line interface. This contains tools for building, packaging and deploying app to device/emulator. So far, so good. The call to build titanium for android platform and push the package to emulator is –

titanium build -p android -T emulator

03-cli build 01

It needs to be executed in the project folder, so the CLI will find the project and get its settings. If it hangs on the “waiting on emulator message,” it means the emulator itself hasn’t been started. Just start your emulator manually. Sometimes when the emulator is already running, another one is kicked off in parallel, and the application is deployed to the first one. Similar behavior happened in Android Studio so I suspect the android sdk.

cli04-cli build 0205-emulator

After few minutes you should be able to see something similar as above. On second screenshot you can see how long it took to build and deploy the app – 2 minutes.

OK, so now we are writing code with WebStorm and in a terminal window we are triggering titanium-CLI to build/package/deploy. WebStorm is cool, but the speed of deploy is really an awfully slow process. Doesn’t matter if the package is deployed to device or emulator — it’s painfully slow. On top of that some devices you even have to uninstall previous version before redeploying. Still very uncomfortable and so many steps.

Bring on TIDebugger

There is a project TiShadow and based on this, the TIDebugger (https://www.npmjs.com/package/tidebugger). I didn’t believe it at first, but this tool is really the key to happy application development with Titanium!  Trust me, you’re going to want to install this. Installation is through NPM, and is straight forward.

Ok, what is it? It’s a hook to the Titanium build/package/deploy process. It provides a kind of client/server application deploy infrastructure. It means that the client (emulator/device) is connected to server (developer machine) over IP network.  The server can handle multiple clients and can push to these clients modified version of javascript files.  If you’re unfamiliar with the way Titaium works, you might not yet see how this can help us. Part of the appeal of the Titanium UI layer is that the resulting applications have real platform controls, but the code you’re writing is Javascript and it’s important to know that it’s never compiled. Instead, it’s packaged and the interpreted on-device.  Due to this architecture design, it’s possible to update ONLY the javascript and, after simply restarting the application, we can immediately see our changes. This is approximately 1000% faster than rebuilding, redeploying and THEN launching the app. Plus or minus.

05-tidebugger 01 06-tidebugger 02

After you’ve installed tidebugger, trigger your Titanium build using the tidebugger option to titanium-cli:

titanium build -p android -T emulator --itdebugger

It’ll ask for some details about the server IP address and target device to deploy on. This –tidebugger option triggers the build/package/deploy, starts the server and does even more. It starts the filewatcher on .js files, which triggers the automatic new file version deploy. This leads to the current modern style of rapid web coding using grunt library with filewatchers, less compilers, test tasks and so on.

Well I wrote how cool it is, but also it has few limitations

  • you cannot add new .js file. In case you want to, you have redeploy the app
  • you cannot hit created breakpoint and read variables. As workaround the console.log would be enough
  • sometimes the ADB (android debugger bridge) or client/server of tidebugger broke, so you have to restart adb and redeploy the app

But in meanwhile it does work well, I really enjoyed the speed of the loop – change the code, ctrl+s and see the result.

Bringing in Typescript

I’ve been addicted to typescript for a while, so time to bring that into the fold, especially since WebStorm supports “compiling” TS  to javascript using file watchers.  So let’s say we have some modules written in TS, compiled to JS.. now the question is how to use them in a Titanium project.  Titanium is using CJS module style (module.exports and require(‘path/module’) – http://addyosmani.com/writing-modular-js/ ). So in TS file at bottom you just add “module.exports = ClassName”. This is compiled to JS literally equal, so it follows the CJS guide. Then in JS code you will write “var ClassName = require(‘path/ClassName’)” and you call constructor of ClassName. We’ll get to an example soon.

But again, there is one drawback with existing workaround :D. As I wrote above, tidebugger is using filewatchers to trigger the update of the JS files on emulator/device. But the WebStorm TS compiler filewatcher does no update the JS files with final content. It deletes whole content, and then writes the new JS content. So each file is updated more than once, which really confuses the tidebugger on device/emulator side so much that it fails and stops. The solution is to modify tidebugger not to trigger push to clients immediately.

It’s a bit of a hack, but it can be done just by commenting a few lines in tidebugger npm. You have to find where your tidebugger npm is located – I install it globally, so I have it in C:\Users\zdenek\AppData\Roaming\npm\node_modules\tidebugger. Or if you install it locally to project, it will be in node_modules folder. Then you will find tidebugger file in cli subfolder, open it in editor and comment notifier settings like this:

.action(function(env) { // run package notifier but only on server command.
// var notifier = updateNotifier({
// packagePath: "../package.json",
// updateCheckInterval: 1000 * 60 * 60 * 24 * 7
// 1 week // });

// if (notifier.update) { // notifier.notify(); // }

config.init(env); require("../server/app.js"); });

Once you’ve done this, the auto trigger will be disabled. That means you have to trigger it manually by executing

tidebugger run

from command line. There are several switches to the command which are nicely described here: https://www.npmjs.com/package/tidebugger#what-you-can-do-with-tidebugger

So that’s it!  Hopefully this improves your Titanium development experience.  Please leave any questions or comments below!

The Geometry of Culture

It’s a triangle graphic I’ve seen many times while working in development centers here in the Czech Republic.  The brain child of Richard D. Lewis, a polyglot cross-cultural wizard and author of “When Cultures Collide.” He plotted countries along the edges of an equilateral triangle for use as a tool for cultural comparison.  The vertices of the triangle each represent one of his three cultural classifications: Linear-Active, Multi-Actives and Reactive.  Countries are plotted along the edges of the triangle, with their distance from the vertices indicating the ratio of attributes their culture takes from the nearest vertices. The graphic pops up periodically in power point presentations here, so if you haven’t heard about it, read on.

The classifications, associated graphic and attribute lists are part of a much larger dialog on navigating cultural difference, but let’s just look at the triangle for now.  Always keep in mind that Lewis acknowledges that this model does rely on generalizations and not every individual in a particular culture will exhibit all characteristics.  Nevertheless, it is still a useful tool for putting your interactions with people from different cultures into a contextual framework.  It’s also a good way to see how well developed your cultural stereotypes are!

In the first corner, we have the Linear Actives.  Linear-Active Cultures are thought to: “Plan ahead step by step,” “Confront with logic” and “Respect officialdom.”  Now, let’s dig into our grab bag of cultural stereotypes and try to decide who could be possibly the poster boy for these attributes?  No, it’s not the Vulcans but rather the industrious Germans.  The Swiss and Luxembourgers round out the proto linear actives.  Seems logical to me.

 

In the next corner we’ve got those that are “Emotional,” have “Unlimited body language” and “Flexible truth.”  These impulsive extroverts are the Multi-Actives, and there are a ton of prototypical cultures that top this triangle.  Imagine an emotional talker, waving his hands about as he explains eloquently how the referee mistreated his football club.  Yes, the Italians are first-listed culture on this vertices.  Lewis rounds out this vertices with several other South American countries.  It must be something about the weather!

The final corner of this triangle of stereotypes would be the Reactive cultures.  These folks are “Polite yet indirect,” they “Conceal feelings” and “Must not lose face.” You get partial credit if you guessed Japan as the king of this corner but, in fact, the most Reactive is apparently Vietnam. Japan is actually a penultimate member, sitting one tick closer to Linear Active.  This whole corner is rounded out by Asian cultures who are described as being courteous, amiable and accommodating.

The next three noteworthy points would be the midpoints of each side.  These halfling cultures exhibit a blend of traits of each of their more pure neighbors.  So, you just have to ask yourself – what do you get if you cross Germany with Vietnam?  This is not a joke, per say, but the answer seems like one at first.  Canada.  Yes, that’s right, Germany + Vietnam / 2 = Canada.  If you got that one, you clearly cheated and looked ahead at the triangle.  Still, though, that stereotype math can work if you think about it!  I’ll leave it to you.

Next we have the emotional robots, equidistant from Linear-Active and Multi-Active.  Belgium, Isreal and South Africa end up here.  It’s hard for me to decide if those countries make the most sense as I haven’t met many people from Belgium but, again, it does feel right at the gut level, particularly when you look at the entire continuum.

Finally, we look at the point furthest from Linear Active.  What culture is the furthest from being a German as possible whilst still remaining on this triangle? We’re looking for a culture that exhibits a blend of Multi-Active and Reactive traits.  Turns out it’s Indian and Pakistan.

So there you have it.  A concise representation of most of the main countries on the planet, mapped out in a logical way.  I joke about it, but as you walk node-by-node around the triangle, it’s hard not to nod your head with a pensive frown thinking, “yeah, that makes sense.”

the_lewis_model_712

And then you watch an America give a talk

As already mentioned, the Czech Republic inhabits an enviable position on the triangle, from the perspective of an offshoring country, sandwiched between Australia/Ireland on side, and the USA on the other.  As an American living in the Czech Republic for 15+ years, and having traveled extensively both inside and outside of Europe, I do believe living here is less of a culture shock living here than there would be if I’d settled in, say, Vietnam.  That said, there are still some pretty significant cultural differences (as illustrated in the indie film Rex-patriates).  Back when I worked at Sun Microsystems, I saw these differences on display whenever some high level exec would come in from the States, power point presentation packed with subtle (or not so subtle) witticisms and rah-rah, and energetically present to a completely silent room.   In the most painful instance of this, one of the execs tried to get the audience to clap along with him.  I still shake my head thinking of the awkwardness.

Again, this isn’t as severe as Lost in Translation, but it’s critical that you know your audience and realize that what works in the US might not go over as well elsewhere – even when it’s a country that is presumably so culturally similar.  Instances like these illustrate a bit how cultural difference cannot be fully illustrated in a 2 dimensional graph.

OK So what does it mean?

Very often when I’m talking with customers who have had poor experiences offshoring, it wasn’t necessarily because they didn’t find the technical expertise they were looking for.  Rather they found that there were issues in communication, particularly when the projects started to hit the inevitable speed bumps.  Often times the exact problems they’re describing could be explained by this triangle, and looking how far the two cultures are from each other on the list.  Clearly, the two sides take different approaches to handling the key stress moments, which can be high risk for project success.

While, again, this is painting with broad strokes, it is a compelling argument and one that holds water with other companies who are offshoring here. It helps to explain to a new client why it might be a more comfortable experience offshoring to a place like the Czech Republic, if you’re a US or German based client, rather than one of the other popular offshoring locations.  It can also help, partially, to explain why it can be worth paying a premium over those other locations to source your project in this city.

At the end of the day, success with offshoring depends on a variety of factors which we’ll be looking at over the next few posts.

TCP networking in Cordova

Network communication is trivial in Cordova based projects. You have two main options to communicate with a server: HTTP or WebSockets.
You start having problems when you want to use something more low level. For example if you want to implement client to communicate with legacy services (like Telnet, IRC, etc), you need to use native TCP sockets.

Current W3C web APIs don’t expose any standardized interface and proposals like TCPSocket (https://developer.mozilla.org/en-US/docs/Web/API/TCPSocket) are still far from being implemented in web browsers.

We wanted to implement phone and tablet application for online chess playing, that runs on three major operating systems: iOS, Android and Windows Phone. We didn’t want to reinvent the wheel, by implementing our own chess server, so we decided to build the application on time-honored Free Internet Chess Server (http://www.freechess.org/).

The problem is that FICS uses old fashioned TCP text based protocol, so use of standard Web API was not an option. We could use websocket-to-socket bridge with intermediate service, but it requires hosting of service on some infrastructure and it slightly worse reliability. Finally we decided to implement our own Cordova plugin for TCP communication. I’ll describe it here in this blog post.

Usage

You can install plugin to your Cordova project with command line:

cordova plugin add cz.blocshop.socketsforcordova

Usage is simple, you just have to create instance of socket object:

var socket = new Socket();

Then you need to setup data consumer, error and close handlers:

socket.onData = function(data) {
// invoked after new batch of data is received (typed array of bytes Uint8Array)
};
socket.onError = function(errorMessage) {
// invoked after error occurs during connection
};
socket.onClose = function(hasError) {
// invoked after connection close
};

Finally you can connect to server:

socket.open(
"someremoteserver.com",
1234,
function() {
// invoked after successful opening of socket
},
function(errorMessage) {
// invoked after unsuccessful opening of socket
});

At this point, socket instance is in connected state and you started to receive events to handlers you setup above.
Write method of the socket accepts only Uint8Array, so you have to convert your string data. This code shows how to do it:

var dataString = "Hello world";
var data = new Uint8Array(dataString.length);
for (var i = 0; i < data.length; i++) {
data[i] = dataString.charCodeAt(i);
}
socket.write(data);

There are 2 options of how to close the connection.

1) You can close the connection gracefully by sending FIN packet using shutdownWrite method:

socket.shutdownWrite();

After you call this method, you should wait until server sends all data to you and closes the connection. After that, you receive socket.onClose event.

2) Second options is to close socket immediately:

socket.close();

You receive socket.onClose event shortly after you call this method. Writing data to closed socket is not allowed.

More info

We created sample Cordova project on GitHub https://github.com/blocshop/sockets-for-cordova-tester.
Cordova plugin itself is also available on GitHub https://github.com/blocshop/sockets-for-cordova

 

blogpost1

Sockets for Cordova tester – connection screen

 

blogpost2

Sockets for Cordova tester – connected to FICS

 

To see how this plugin works in real world application, you can download our Blindfold Chess Trainer game in your mobile app store (Android, iOS, WP8) and play online. Enjoy!

 

BLindfold chess - online playing

Blindfold chess – online playing

Posted by Martin Obrátil.