Categories
programming Technology

Upgrading Playbook Beta

If you’re keeping up with the Playbook SDK Betas, you will no doubt have gone through the cycle of getting your signing keys and installing them. Thing is, when you update your SDK version, you don’t want to lose those artifacts. Else, you’ll have to request new keys. So before you update, let me tell what to expect…

You will have -a- version of the SDK setup nicely. You will also have your signing keys installed with the .p12 file artifacts along with some barsigner.csk and barsigner.db files. You will also have updated your bbwp.properties file. Now, when you install the new SDK, it will display a prompt along the lines of: “Detected previous version. Uninstall old version first. Cancel, Ignore, Retry”. Wait.

If you uninstall your old version, you’re going to lose all those artifacts. You WILL need to request new keys and install them all over again. Mission, but not impossible 🙂

You might want to cancel and think it over. I chose “Ignore”.

I ignored the warning and went on with (Plan A) installing the newer SDK alongside the older one. This kinda worked well, but there were some issues with the paths and picking up the correct one (a non-signing SDK alongside the first version of a signing SDK). It got messy. It turned out easier (at this stage) to just uninstall everything, request new keys and start again.

With the next upgrade, I chose “Ignore” again. But this time, I just installed it right over my old installation folder. I got prompted during the install to “Overwrite existing file? Yes/No/Yes To All”.

“Yes to All”, please.

Didn’t need to request new keys or configure any additional paths- it just worked. Re-compiling against 0.9.4 and signing went off without a hitch.

So, based on my experiences, I would say, once you have a 0.9.n version of the SDK setup with signing keys and it’s all good, the next upgrade experience should be relatively safe if you just ignore the previous version warning and install right over the old SDK 🙂

Of course, if it didn’t (or doesn’t) work for you, you probably didn’t (or won’t) do something that I wouldn’t not have not recommended or didn’t suggest you shouldn’t have tried or didn’t do something that wasn’t not unlike the process that I haven’t described in this or any other post that I may not have written (sic) :p

Categories
programming

Right-Align Text On BlackBerry BasicEditField

It would seem a simple thing to do, no? In fact, positioning/aligning text has become such an abundant demand over the last few years, that the ability to do so in most environments is fairly trivial. And if you’re working predominantly in the web field, it’s a no-brainer. The native Java components for BlackBerry are a little different however.

An exhaustive search on RIMs support forums and in general, “the internet” reveals many a frustrated developer struggling with the right-alignment of text within a field. I’m emphasizing that since there’s also a lot of confusion with right-aligning the field itself; an entirely different and altogether more straightforward task.

The gritty: you need to handle drawing the text yourself.
The algorithm:
* blank out the field entirely (i.e. fill the background with white paint)
* drawText() in your label at 0, 0
* drawText() in your text with DrawStyle.RIGHT
* fillRect() a cursor at the right hand side of the input field

The catch:
maintain a local copy of the text value of the field

The bonus:
Along the way I started stumbling across other ideas for highlighting the input field and making it a little more catchy for the user.

Here’s a screenshot of my custom input field with the focus.

Right Aligned Input Field
Right Aligned vs Default

You’ll notice the default field below it (R120) is the BlackBerry standard BasicEditField. The R1234 field is my custom field, with highlighted background, slightly pronounced text and right-aligned with a dark cursor on the right edge.

Kudos, references and inspiration drawn from:
http://stackoverflow.com/questions/2007975/basiceditfield-customization

http://supportforums.blackberry.com/t5/Java-Development/Cursor-Caret-not-appearing-in-EditField/m-p/553556#M112688

http://supportforums.blackberry.com/t5/Java-Development/Custom-TextBoxfield-cursor-problem-in-9800/m-p/597140

Categories
programming

Not All Divisions Are Equal

If you don’t need to pay attention to a particular detail every day, it can sneakily bite you in the derriere. Division is one of N culprits floating around the programmer’s haven. And this little guy thrives on C# .NET code.

Let’s take something simple like

int a=9, b=0;
return (a/b);

You’re expecting something similar to a “can’t divide by zero exception”, right? And indeed you do get one. In fact, all good programming courses will teach you the following idiom:

int a=9, b=0;
return (0==b)?0:(a/b);

Which is to say; only divide by ‘b’ if i’t not zero otherwise return 0 (or any other logical value).

Back to the code; what happens if I change the type from int to a floating point (float or double)? Afterall, no self-respecting programmer would do any financial calculations using integers, right?

double a=9, b=0;
return (a/b);

Divide by zero exception?

Nope.

What?

This is not a divide by zero exception condition. In fact, dividing by 0.00000 (or even -0f, yes, that’s a minus floating point zero) is perfectly acceptable and does give you a result.

What?

Yes. As I mentioned above, this is one of those “stickies” that you don’t often pay attention to, but definitely mess with your fundamental assumptions about life and the universe when you not getting the results you expect.

For a little more history on the problem, you can always refer to WikiPedia.

Is all hope lost? No. Just be careful out there because programming _is_ hard (for this and countless other reasons).

Categories
programming

Manage Cookies with BlackBerry Java

When interacting with [generally and widely interpreted] web services, you may be required to communicate state (usually a login authentication token). This [usually] takes the form of a cookie and in our interconnected wide world of interwebs, browsers handle cookies just fine; custom-built clients not always. On the BlackBerry, if you’re putting together a Java app, and using the HttpConnection class to communicate with said server, you need to manage that cookie (and hence state) by yourself. Fortunately, it’s not rocket science.

The basic workflow is: you connect to the endpoint and POST some data. On the response, you need to read the headers and look for the “Set-Cookie” field. From that value, you can extra the data you need. On all subsequent requests, you set the “Cookie” field on the header. Simple. Time for some code.

NOTE: Exception handling omitted for brevity and readability.

The first request is just a regular POST in this instance. The buffer variable is a byte[].

HttpConnectionFactory factory = new HttpConnectionFactory(endpoint);
HttpConnection connection = factory.getNextConnection();
connection.setRequestProperty("User-Agent", "BlackBerry Client");
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod(HttpConnection.POST);
OutputStream output = connection.openOutputStream();
output.write(buffer);

From that request, we wait for the response and read that. In this example, I am looking for the PHPSESSID field that was set as part of the response in the header.

String cookie = connection.getHeaderField("Set-Cookie");
if(null != cookie) {
  int php = cookie.indexOf("PHPSESSID=");
    if(0 <= php) {
      php += "PHPSESSID=".length();
      int term = cookie.indexOf(";", php);
      if(0 <= term) {
        _session = cookie.substring(php, term);
      }
  }
}

Now I have the token required (cookie) that I can now send on every subsequent request. The code for that is for all intensive purpose, the same as the first code snippet with one additional line:

connection.setRequestProperty("Cookie", "PHPSESSID=" + _session + ";");

The order of the setting of the request properties won’t make a difference, so just use that anywhere before you open the output stream for writing.

Categories
programming

Radio Streaming

So of late, I’ve had the opportunity to work with the 2oceansvibe crew and one of the best advantages of the gig has been listening to 2oceansvibe Radio while coding. Major Plus!

So as it is, there’s practically no excuse for not getting in on the coolest radio station this side of the sun.
They have an iPhone app, a BlackBerry app, a web app and now a Facebook app in addition to being able to listen/stream from just about any media player (Real, Winamp, iTunes).

So, for kicks, here’s an audio streamer for the Mac, recompiled to default to 2oceansvibe Radio. Download StreamingAudioPlayer. Yes, you can listen through iTunes. And indeed, 90% of the times I would just use what’s already there (i.e. iTunes) but like most projects, it’s sometimes just cool to be able to roll your own, plus it’s a really decent sample codebase for an in-the-wild cocoa app.

NOTE:
All code on this project is originally developed by mattgallager and code can be found here on the project site.

Categories
programming

Sort, BinarySearch and Anonymous Delegates

Generics has undoubtedly made life a lot easier in the world of 1s and 0s and so this code snippet will only deal with the generics version since the code reads a lot easier. This is also a great bookmark post for future reference…

public class Foo {
 public string Alpha {get;set;}
 public string Omega {get;set;}
}

This shouldn’t bother you too much, we just got Foo. Nice. But now we want to sort a bunch of instantiated Foos, as a “once-off” ascending, according to Alpha.

List<Foo> result = new List<Foo>();
.
.
results.Sort(delegate(Foo lhs, Foo rhs) {
                     return lhs.Alpha.CompareTo(rhs.Alpha);
                   });

Straightforward. Using the anonymous delegate to achieve that once-off without creating an unnecessary class. You might think you could do the same thing with BinarySearch.

Foo sample = new Foo{Alpha="a", Omega="z"};
results.BinarySearch(sample, delegate(Foo lhs, Foo rhs) { return lhs.Alpha.CompareTo(rhs.Alpha); });

But you can’t. In this case, you actually do need to create an unnecessary class.

Foo sample = new Foo{Alpha="a", Omega="z"};
srchIdx = results.BinarySearch(sample, new FooAlphaComparer());
.
.
.
internal class FooAlphaComparer : IComparer<Foo> {
			public int Compare(Foo lhs, Foo rhs) {
				return lhs.Alpha.CompareTo(rhs.Alpha);
			}
		}

Same one liner in the Compare function, but this time, it has to be a class.

However (there’s always a BUT somewhere even if you call it a ‘however’), with a bit of kung-fu and ninja superpowers (apparently) there is a way to plumb this and make it work- but i tend to shift the complexity in other areas of the problem domain. It gets complicated. Moving right along…

For interest sake, you want to compare by Alpha AND Omega?


public int Compare(Foo lhs, Foo rhs) {
  int cfA = lhs.Alpha.CompareTo(rhs.Alpha);
  int cfO = lhs.Omega.CompareTo(rhs.Omega);
  if(0 != cfA) { //Alphas are not equal
    return cFA;
  } else if(0 != cfO) {   
     return cf0; //Alphas are equal but Omegas aren't
  } else {
    return 0; //Alphas are equal and so are Omegas
  }
}
Categories
programming

Programming For Dummies

I (along with probably 1 000 000 other people) have found the self-help series of Dummies books quite amusing on different levels. As the saying goes, if I had a penny for every time “… for dummies” comes up in a situation joke…

Now there are a number of dummies books covering a host of programming topics. I would be surprised if they haven’t covered every mainstream language, framework and toolset available to the masses. Of course, there’s always “… in 24hrs” to cover what’s missed: C++ in 24hrs. You’ve got ask yourself: “Why, with the abundance of literature available, would a graduate want to spend 3 years (or more, sometimes involuntarily) studying something which can be studies in 24hrs?”

Well, truth be told: software is hard. It’s a popular quote, I’ve said it before and “kids” will probably still be quoting it generations from now. The only thing I could add to that quote is the word “really”. Software is really hard. Not all of it. Not all the time. But it is. Really.

Neither a dummies book, a 24hrs book, or even a 2 week course in learning how to code in c# is going to make you a programmer. In fact, no amount of certification is going to certify you as a competent programmer. The one common trait between certified (and good) programmers and not certified (yet good) programmers is the time spent on the keyboard. Voluntary time. That, and an odd fashion sense says I who doth dare venture out to the mall in my PJs.

Time behind the keyboard is a way of life. You need to develop (if you haven’t been born with it) a particular style of thinking and a particular approach. It’s not a one-style fits all either. There is no ultimate secret recipe to be a programmer (except for the time behind keyboard thing- and quite possibly the poor fashion). In KungFu, you can study the Crane, Tiger, Praying Mantis, Monkey and Snake and there are probably more too. In programming, there are no definitive animals to master. It’s more like a zoo from Star Wars. Looks like Monkey, walks like Snake but eats like Duck. It’s not too important what approach you have, so long as it does the job proper (sic).

Afterall, software is -really- hard but not always rocket-science (the two concepts are mutually exclusive). So don’t be fooled by dummies. It’s simple but not without complication. It’s straightforward but never cut-and-dried. It’s easy but really hard.

Categories
programming Technology

BlackBerry Security

It’s not uncommon when moving across to the BlackBerry platform, to get a little confused or even frustrated. It’s a “who moved my cheese” series of moments because in reality, “we” tend to expect that BlackBerry will do things in exactly the same way as “our” previous handsets. And when it doesn’t, “we” might think it’s broken. Truth be told, BlackBerry does do a lot of things a little differently and IMHO those differences are what make it great.

Note:
I see the same kind of frustration when users migrate from Windows to Ubuntu or Mac.
I see the same kind of disappointment when users switch from Symbian to BlackBerry.
I see the same kind of disillusionment when developers switch from [insert-language-of-choice-here] to Ruby.

Security prompts on the BlackBerry platform are one of those areas that come up for discussion quite often. To understand “why” it does things the way it does things, here’s an 8min video clip which is extremely useful in explaining that. You decide wether that’s good or not, but whatever conclusion you come to, remember, it’s just the way it is.

Personally, I think giving the user (or the BES admin) the final say and control is the better policy when you start examining all the other options available.

Yes, it can be argued that it does demand a level of sophistication on the user’s part, but like anything out there (be it a carving knife, a phone, an OS, an application, a motor vehicle, a bank account or a piece of sports equipment) your understanding of that “thing” is directly related to your proficiency and enjoyment in using that “thing”. A phone, even a BB, is no different.

Categories
programming

Heroku

I’ve mentioned Heroku a couple times before in my posts and I mention them again today. I was impressed way back then when I started 2 years ago, and I’m further impressed today.

I finally managed to get around to moving Morty from the now deprecated HerokuGarden onto the Heroku platform. And it was a cinch! (just one little surprise on the .gems file tripped me up easily sorted though)

The heroku gem makes life (too?) easy and even on a the most basic of basic (read: free) deployments, Morty is running pretty smoothly.

Categories
programming

(Again) Why Test?

When whipping out the Josephus game, I used Jasmine to write the tests… er.. spec for anticipating the behaviour of the code. Among the many reasons I use a “test-driven methodology” (even in the smallest of projects) is that I like to (nay, NEED to) keep a close eye on the strategic direction of the code while I’m minutely engaged in the technical direction. And a picture like this is so easy to read:

Strategy