Friday, December 20, 2013

How To Prepare for a Hackathon?

In a previous post I wrote of why I like to participate in hackathons. This time I'd like to talk about how to participate. What sort of prep work you will need to to get ready.

Understand the Theme and the Sponsors
You may have the most awesome idea for an app, but if it doesn't fit the theme of the hackathon you will lose. If the theme is "Teaching Kids", in some way your app must help teach kids. If it doesn't, you lose. 

So take the time to fully understand the theme of the hackathon. I recently participated in the Tizen Devlab and Hackathon in Los Angeles. The theme was to increase the apps in their store and to raise awareness of their mobile platform. The apps which won, including my own, were something the judges felt were both store worthy and could be finished in a reasonable amount of time. "Pie in the sky" apps didn't win.

Also take the time to know who are the sponsors and judges. If the some of the judges work for Yahoo for example, your app will probably be rated higher if it uses Yahoo's APIs. In many hackathons, use of the APIs is the theme. I have see developers make many mind blowing fails, like not using the API of the company sponsoring the event and instead using one of their competitors. I haven't seen any of those devs win yet.

Schedule
Take a look at when the event start and ends. Make sure it is something that you can fit into your schedule. Not just the time at the event but the time you will have to spend preparing for it. You don't want to have to tell the judges that your app is crap because you didn't have enough time to prepare. Everyone gets the same amount of time. You should only participate if you are prepared to bring it.

R.T.F.M.
The very first thing you should do in order to prepare for a hackathon is to read all of the instruction. This is more than just the web page announcing the hackathon, you will want to read everything. All of the rules, regulations, and the fine print stuff. The bigger the prize, the more thoroughly you should read everything. If you are part of team, every member should read the instructions. It would absolutely suck to have coded your heart out only to be disqualified in the end for a minor rule violation.

Keep a special eye out for things which would disqualify you like being an employee of one of the sponsors. Many companies have very complicated structures and you may not even be aware that your company and the corporate sponsor are both owned by the same parent company, which may make you disqualified. If you have questions, be sure write the sponsors ahead of time.

Create a To Do List
For nearly every hackathon there are things you must do. Some are explicit and others implicit, but all should be on a to do list. For example if you need to use a sponsor's API, it will help to know the API before the day of the event. If the hackathon is in another city, you may need to buy travel tickets or make hotel reservations, both things you wouldn't want to forget, plus you usually save money by doing them early. My favorite tool for this kind of thing is Trello.com. It is free and it is easy to use. But a pen and paper also works.

Scout the Venue
Google Maps is an essential tool for scouting the venue. If you are driving, it is critical to know where you are going to park. Some venues provide parking but many don't. Even when provided, the lot may be small and parking scarce. So I like to scout out the location. Find a free or cheap parking lot and map how to get from the lot to the venue. Be sure to be aware of city parking regulations. Few things suck more than getting a parking ticket or worse getting towed.

Pack
You need to make sure to pack everything you may need. I have seen devs scrambling around for items which they forgot at home at every hackathon I've attended. Things as crucial as power supplies or as easy to forget as a video connector. I travel with my machine so much that I have two power supplies and to video connectors, one travels, one stays home. I check my travel box before I leave home and the venue to make sure I don't forget anything. Most venues will have video connectors for PCs, if you are on a Mac like me, remember to bring your own. In order for judges to fairly rate your app, they need to be able to see it.

Think about the noise level of the event. You may want to bring headphones or ear plugs so that you can concentrate. I bring my headphones, their charger, and my USB cable to charge my phone. 

I also recommend bringing your own snacks. Most venues will supply snacks and water, but you are at their mercy as to what constitutes a snack. I prefer to bring my own snacks. Along this line, be careful of too much caffeine. I see people drinking energy drinks like water and you can see it "weirding" them out. I usually drink just one energy drink per event and I save it for that long period of time from midnight until dawn. To keep from falling to sleep, I usually focus on my to do list, listen to fast music, and go for walks when thinking. 

Get Plenty of Sleep 
The night before the hackathon be sure to get plenty of sleep. Many times developers try to get too much done that last night and wind up hitting the sleep wall and fading early. Instead, be sure to get at least eight hours of sleep. And avoid doing anything too strenuous, save all of your energy for coding. 

Arrive Early
There are many benefits to arriving a bit early: parking is easier to find, you can scout out a good location to set up (some place away from the restroom and kitchen), and you can unwind and get yourself into a good coding frame of mind. 

Know When to Say When
I have been guilty of coding until the last minute and it is a bad thing to do. The judges aren't expecting a finished app, but they would like to see a demonstrable one. Stand before them and trying to talk your way through a crashed app won't impress them. Instead stop coding before the deadline and make sure your app works. 

Use a version control systems like Git, can save the day. It will allow you to roll back to the last working version instead of wasting time trying to figure out what you broke. While Git is helpful to an individual, it is critical for teams. Nothing sucks more than when someone breaks the build and time is pressing. Version control helps prevent this immensely.

It also helps to spend a bit of time planning out your app. This is even more important if you are partnering up with others. The app needs to broken down into bite sized nuggets and everyone needs to know what they are doing. Once again Trello helps here.

Present
Newbies continue to be surprise by the fact that they will have to present their app. Don't be. Depending on the hackathon, your presentation may be as much as 33% of your weighted score. Now, judges aren't expecting some salesman-slick PowerPoint presentation. What they want is for you to be able to explain usually in less than five minutes, why you think you app has won. This is time to state all of the things from the theme that you used. I recommend writing what you are going to say and present down. I keep 3x5 cards in my go bag. 

Be careful of is bluffing. The judges are usually tech professional and they can smell a lie a mile away. I was at one hackathon where a guy present this great parking, but when ask what was the data source, he crumbled. There is no central repository of parking data and building that up would be a endeavor which would probably require VC money. It was a lot more effort than could be expected of a small mobile app hackathon. The guy didn't win.

Summary
Please don't let this list scare you off. It does take work to win a hackathon, but not too much. Plus, there are hackathons for all skill levels appearing around the world. Some only last a few hours and are geared towards beginners and students. So if you are interested in improving your skills, having fun, and winning prizes, please participate in a hackathon near you. And if you see me, say "hi".

Monday, December 16, 2013

Tizen Devlab & Hackathon

On December 13th and 14th, I participated in the Tizen Devlab & Hackathon. The event, hosted by BeMyApp, was roughly 24 hours long with about 21 hours of actual coding. It was a blast. I ran into quite a few friends from the SoCal development scene. Everyone one was friendly and there was plenty of food and drink. I spent a good chunk of time helping less experience teams while working on my own app.

In the end my app, Lunch-o-rama, took the $500 runner-up prize. The first place prize went to a couple of students from UCLA with their 3D break-out style game. Besides the $500 dollars, I took home:

  • Tizen t-shirt
  • Mashery t-shirt
  • Tizen developer's device
  • PowerTrip - a rechargeable external battery for USB devices
  • Tizen for Dummies book
  • Leap Motion device (being shipped)

I am now working on finishing my app to get it into the store. I plan to have it finished by the end of the month. If I can get done by the 26th, I will also enter it into the appbackr Tizen Challenge and win another $200. 

My next hackathon will be at the AT&T Developer Summit at the Palms Casino Las Vegas, January 4th and 5th. This is a weekend event, so those of us with jobs, don't have to take time off from work. This one is a monster with two separate categories each with $25,000 top prizes. Second and third place will be worth $10,000 and $5,000 respectively. It still isn't too late if you haven't sign up yet, here is the link: https://devsummit.att.com/hackathon



Monday, December 9, 2013

Why Hackathons?

I like to do hackathons. That fact, strangely surprises some who know me. They think after coding more than 40 hours a week, the last thing I would want to do is more code outside of work. And they're wrong. No only do I like it, I like it more.

When I first began programming it was about having fun hacking code. I would simply think something up and start to build it. Now, I rarely finished anything, instead, I would finish enough of the idea to see if it was viable. In many ways, I was doing private hackathons long before I had actually heard the term.

As a corporate developer I rarely get time to have fun. My time is a precious commodity and must be allocated against projects. Projects need to be planned, allocated, and budgeted. Even the most trivial idea can take weeks to work their way through the system. More complicated projects can take months and even a year from start to finish. And the worst thing is that at any point along the way, someone can pull the plug and send all of your work to the trash can.

Hackathons bring the fun back into development. In fact, only two things separate hackathons from those glorious days of hacking nights and weekend: first the theme comes from someone else. Note that I said theme and not idea. Most hackathons have a theme and guidelines which come from the sponsors, but each participant will have their own idea about how to implement. The second thing is prizes! Most hackathons give cash prizes for first and sometimes second place. The amounts of the cash range from a few hundred dollars to a million dollars. And in case you don't get the big money, most give schwag ranging from mugs and t-shirts to phone and tablets.

Hackathons are by definition short. They last any where from a few hours to a few days. Your idea goes from concept to completion quickly. Now the first confusion that many have is that the finish product is code complete and production ready. This never happens. In fact, depending on the venue, there may not be even a single line of code written. Instead hackathons are normally about the quality of your idea. Do other people get your idea and will they embrace it. The bulk of your time is spent on two things: build enough of your idea for people to get it and preparing your presentation so that people will embrace it.

All of the hackathon contestants I have ever spoke to get the first part, but many don't get the second part. In fact some are surprised that they need to prepare a presentation. But getting people to embrace your idea is key and fun part of the hackathon. 

So now you know a bit about why I like hackathons. Next time I will talk about what you should do if you want to participate in a hackathon.






Friday, November 8, 2013

jQuery Deferred Object - Creating Your Own

In my last post, jQuery Deferred Object - Your New Best Friend, I gave a quick overview of what a deferred object is and how to use it. This time let's go a bit deeper and explore creating your own deferred object for a much more practical use - asynchronous downloading and processing of audio files.

One of my favorite web sites is HTML5Rocks. They have all of the latest information on developing cutting edge HTML5 web apps. As I continue building my HTML5 game, I've turned to them for more information on several topics including the Web Audio API. In one of their articles,  Getting Started with Web Audio API, they create a BufferLoader class.


I thought it would be fun to convert this class to use a deferred object and streamline it even more by getting rid of the object constructor and instead use a closure. So let's get started.

Getting Rid of the Constructor
The BufferLoader uses a function as an object creator. There is nothing wrong with that per se, it is just a pattern which I rarely use these days. Instead I normally prefer to use a closure. Think about why they are creating an object. Since both the loading and the converting of the files are asynchronous operations they want to be to support multiple calls into the same code. Using a constructor will guarantee that each instance has access to its own set of variables and won't interfere with any other call. A closure does the same thing, but more succinctly. So we will delete the constructor function. We also will wrap our entire code in a function to isolate from any other code in the browser. We use a single global object, RocknCoder, to hold all of our global stuff. We make the loadBuffer() method an internal method of the new RocknCoder.loadAudioFiles() method. This also makes it accessible globally.

Creating the Closure
Most of the instance variables are moved or passed into the loadAudioFiles() method. The this variable or its alternate name, loader, is no longer necessary, so we delete it to. All of its uses become the name without the "loader.", for example "loader.context" becomes simply "context". I don't know about you, but too much using of "this" in JavaScript, gets really confusing. To create the closure we call the loadBuffer method. When this method is called, it essentially creates a snapshot of the environment, all of the variables and their values become frozen, so that when an async callback happens, the state of the variables is restored. Note the subtle change of the parameters passed to loadBuffer(). Previously it was passed a single URL and index which was to the bufferList[] array. Now it is passed all of the URLs as an array and an index value which indicates which URL is currently being loaded. Once a URL is loaded and processed, index is incremented and if we haven't loaded all of the URLs yet, loadBuffer() is called recursively. Do it this way also eliminates the need for load() function, so we delete it too.

Making Use of the Deferred Object
Right off the back in the loadAudioFile() method, we create our deferred object by calling the jQuery $.Deferred() method. The last line of the method returns the deferred object, myDeferred to the caller. Keep mind that this method, will continue to run even after it returns to the caller since their are multiple asynchronous callback going on here. In the method we curiously use the XMLHttpRequest object instead of using jQuery's version of it. This is mainly because the XMLHttpRequest object supports the "arraybuffer" type which allows us to load binary data, very important for audio.

If we encounter an error along the way we can call the reject() method and pass some error information all with it. This will cause our deferred object to fail and the information passed to it will be available to the fail() method.

Once all of our audio files has loaded and been processed, we simply resolve() our deferred object. In this case we pass our bufferList, which contains all of our processed audio files to our deferred object. This will make them available to our done() method. Also note how we eliminated the need to track the index count on bufferList by using the push() method instead an index.

We could have also used the deferred object's progress() method each time we successfully finished either loading or processing a file. That would allow the caller to update a UI element to keep the user informed as to our progress. Oh well, maybe next time.

Summary
We started with roughly 46 lines of code in three methods and converted into roughly 42 lines in one method. Doesn't seem like too great of a win but the code is cleaner to read and most of the win is for the caller. Instead of having to deal with a single callback, where they have to sort out the results. They now get separate done() and fail() methods. Plus the deferred object passed here can be combined with others in a when() statement. An example of this is in the game I am building. We wait for all of the audio files, the sprite map, and a minimum of three seconds to pass before we leave the splash screen. An example of which is below.

If you would like to see more of the game, be sure to check out my repo on GitHub at: https://github.com/Rockncoder/planegame. Be sure to check out the first post of this series: jQuery Deferred Object - Your New Best Friend.

Thursday, November 7, 2013

jQuery Deferred Object - Your New Best Friend

Part 2 of this series is at: jQuery Deferred Object - Creating Your Own

Here's your scenario: you are creating the splash page for an HTML5 mobile game. While you are loading resources, you display a wait spinner and a text message. This all works well except for when people have really fast internet connections - they don't have enough time to see the splash page or read the message. What you'd like to do is set a minimum amount of time for the message to show, say three seconds. But you aren't looking forward to writing a bunch of nested callback code. What should you do? Deferred object.

Deferred objects were introduced in jQuery 1.5. And with them came the end of lots of gnarly callback code - if only people would use them. Here is jQuery's official definition of a Deferred Object:

Description: A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

This is a quick post, so I won't fully explain Deferred Objects now. Instead I will show how to use them to solve the posed scenario. We will use three Deferred Objects. Two of them are passed to us by the Ajax get method, when we start to load our graphic and music resources. The third we will create ourselves for our three second timer. 

Once we have create all of our deferreds, we will display our loading message using jQuery Mobile's loading widget. Then we will use the setTimeout function to give us a three second timer. Once it fires we call the timerReady deferred object's resolve() method. This method does exactly what it name says, it sets the state of the deferred object as resolve.

The next bit of code is the when method. When is used to coordinate more than deferred object. Essentially it says once all of the indicated deferred objects have been resolved, run the code inside of me.

It is important to note that none of this code is synchronous. It is all asynchronous. The when method is like a callback, it gets fired once all of the objects gets resolved, whenever that may be.

For every deferred object in the when statement, you will be passed an array in the done method. This is most relevant with the ajax objects, since the array will contain the results of the ajax calls, but you could also create your own data array for your own deferred objects.

There are also a fail method and an always method. Since the always method is always called, it makes a great to remove the loading widget from the screen. 

Below is the code the for the splash screen complete with deferred objects. The complete code is at: https://github.com/Rockncoder/JQMGame. If you would like a more complete example please follow my plane game repo at: https://github.com/Rockncoder/planegame. There I will build the complete game over the next few months.

Part 2 of this series is at: jQuery Deferred Object - Creating Your Own



Sunday, November 3, 2013

Mobile Device Detection and Redirection in Node+Express

One of the challenges of writing a mobile web site is what to do if a user hits the site from a desktop? Of course, some will say that you should simply make the site responsive, able to look good regardless of the browse it is displayed on. But what if the site is a game? I know all of the responsive design true believers will be upset with my solution, but so what, I like it. I "iframe" the mobile site into a 320 x 480 window on the desktop page. This brings up more challenges, like how detect a mobile device and how to route to the correct page?

The first challenge has already been solved by the excellent web site: http://detectmobilebrowsers.com/. They have created a rather long regular expressions which detects a mobile browser by its user agent. The answer to the second challenge comes from the Express.js middleware which makes Node.js a great framework. 

Express allows the developer to inject middleware into the route handler. For our root route we will call the checkForMobile method. If we detect a mobile browser, we will redirect to our mobile route. On all other routes, we won't bother checking for mobile. If a desktop user wishes to navigate directly to the mobile page, we will let them.

Please check out the code sample below to see how it is done. Or if your are interested in the complete, and still in progress, mobile game check it out at: https://github.com/Rockncoder/planegame. To see the live and very much in progress code, go to: http://planegame.herokuapp.com/

I will be talking about the complete game at So Cal Code Camp at USC, the weekend of November 9th & 10th. If you are in the area, be sure to attend. It is a free event: http://www.socalcodecamp.com/





Friday, October 25, 2013

Quick and Dirty Server Side Select Helper for Handlebars,js

Handlebars.js is one of  my favorite templating engines. One of the biggest reason for that is because it is usable both on the client and server sides.  While the client-side is pretty familiar, the server-side has its challenges, not the least of which is there is no DOM. Having no DOM means that some convenient methods like createElement don't exist, but there are times when being able to deliver a ready render HTML page is important. 

In one of my projects, we wanted to do server-side rendering of an edit page. Nothing tricky or flashy, just send the user the data they entered previously for editing. This kind of a page is easy with just about every templating engine around. One problem HTML element is the select tag, because it is a composite element consisting of <select> enclosing one or more <option> tags. Luckily handlebars.js includes the ability create your own helpers, which are bits of code you write yourself and handlerbars invokes. Writing a select helpers is pretty easy on the client since you have access to the DOM. Most client-side helpers will generate the select and each of the options including their value and selected attributes. 

I initially was trying to go this route on the server-side as well. And then I stopped myself. The lack of DOM access caused the code to quickly get more complicated than I liked. So I decided to go another way. Instead of rendering out the select element, I instead decide to render the attributes of the option element. This way my helper is much simpler. To use it simply add:

{{option <value of option> <current value>}}

to each option element. The helper will render out the value attribute and if it is the currently selected option, the selected attribute as well.

I may change my mind and render the entire select element, but for now I like this simpler approach.






Thursday, October 24, 2013

So Cal Code Camp - USC Los Angeles (11/9 & 11/10)


It is nearly time for my absolute favorite dev event of the year - So Cal Code Camp @USC Los Angeles - November 9th and 10th. There is no place else where being a nerd is so much fun. Last year's event was amazing. I did the full weekend, Saturday, Sunday, the speaker's dinner Friday night, and the not to be missed geek dinner on Saturday night. When I was not giving talks, I sat in and listened to lots of great talk by others.


So Cal Code Camp is a FREE event. Two days of dev talks for FREE, even the geek dinner is FREE. So you have no excuse not to come and hangout with your fellow developers. Plus you may get lucky and win one of the great prizes that will be auctioned off. 

This year I am giving two talks: one on HTML5 Game programming and another on the super cool open source PhoneGap/Cordova framework. 

If you have already seen my HTML5 Game programming, you have to come to this one. The code has been cleaned up and sound, levels, and scoring have been added. So there is a lot to show. I also use the super cool jQuery deferred objects and show how they make your code cleaner.

PhoneGap is an open source framework for making mobile apps. If you can program the web, you can use PhoneGap to make mobile apps. In this talk I will show how simple it is.

If you plan to attend either of these talks be sure to click the interested button. Room sizes are allocated based on the community interest. I had a couple of standing room only talks last year because more people showed up than had indicated their interest. Here are the links to my talks:

Beginning HTML5 Game Programming
Sunday, Nov. 10th at 12:30 PM, Room ZHS 159

Building Mobile Apps with PhoneGap and Backbone
Sunday, Nov. 10th at 10:15 AM, Room SLH 100

For more information check out the website: http://www.socalcodecamp.com/

Wednesday, October 16, 2013

PhoneGap Explained in 5 Minutes


Even though PhoneGap has been around for nearly four years, it is the source of a great deal of confusion by many who have not work with the framework. In order to clear up some of the confusion, I have written this short document.

What is PhoneGap?

Per PhoneGap.com, "PhoneGap is an open source solution for building cross-platform mobile apps with standards-based Web technologies like HTML, JavaScript, CSS." It is important to understand, that a PhoneGap app, runs on a device, not on the web. All of the components of the app, the HTML, CSS, and JavaScript files are on the device. While it is possible for a PhoneGap app to pull user interface from the web, this is not the norm. In general, PhoneGap apps, like other types of mobile apps, use the web only to download and upload data. This is the most prevalent PhoneGap misconception. Many people think that a PhoneGap app is simply a canned website, it is not. While some websites can essentially be lift from the web and placed into a PhoneGap app, most can't. In general, PhoneGap apps are purpose built.

PhoneGap and the App Store

No disrepect, meant to Windows Phone or Blackberry, but mobile has become a two horse race between Apple and Android. Since the Google Play Store doesn't have any overly restrictive requirements, let's talk about Apple's App Store.

Since PhoneGap version 0.8, apps built with it have been accepted into the App Store. They must meet all the requirements that other iOS apps must meet. You should read all of the Apple Store Review Guidelines, but here are some important ones:

  • 2.1 Apps that crash will be rejected
  • 2.8 Apps that download code in any way or form will be rejected
  • 2.12 Apps that are not very useful, unique, are simply web sites bundled as Apps, or do not provide any lasting entertainment value may be rejected
  • 2.17 Apps that browse the web must use the iOS WebKit framework and WebKit Javascript
  • 10.3 Apps that do not use system provided items, such as buttons and icons, correctly and as described in the Apple iOS Human Interface Guidelines may be rejected

While PhoneGap apps are not able to use the system provided icons, its icons must have a similar look to Apple's, for example you can't use a screwdriver to represent settings, since in standard iOS it is represented by a "gear".

The guidelines also clearly state that you can't download code in any form and that your app can't simply be a web site bundled as an app. So if your plan is simply to create an app which is a link to a web site, you may have trouble passing review.

What does PhoneGap source code look like?

A PhoneGap apps source code has four main sub-directories: www, merges, plugins, and platforms. "plugins" is for your PhoneGap plugins. "www" is where your core code goes. It contains the HTML, CSS, and JavaScript of your app. By default PhoneGap will launch your apps index.html file, but you can make this any HTML file you would via configuration. "platforms" is where the "www" code goes after it is built for each platform you are supporting.

And finally there is the "merges" folder, this is where all of the files which are platform specific go. For example, suppose you would like for your app to look iOS-ish on iOS devices and Android-ish on Android devices. You would create different CSS files for each platform with the same name, say "style.css". In "merges/ios" you would place the iOS version of styles.css and in "merges/android", you would place the Android version of styles.css. When PhoneGap builds your app. It will copy the platform specific version of styles.css to the platform directory. In this way, your app can achieve the device appropriate look and feel without resorting to inline device detection.

What does the build command build?

It is assumed by PhoneGap, that you have already installed the development environment for each platform you wish to support. This means that for iOS development, you must be running on a Mac and have Xcode and iOS SDK installed. Similarly for Windows Phone, you must be on a PC, have Visual Studio and the WP8 SDK installed. Android development can be done on just about any system, but you still need to have the Android SDK installed.

When the command line build command is executed all it does is create the appropriate source code files for each platform. From there you complete the build the process using the platforms development tools. Android is currently the lone exception. It also has the run command. Which when used after the build command will actually compile the code and deploy it to either the Android emulator or an attached device.

In summary

PhoneGap allows you to create cross platform mobile apps using web technologies. It is not a tool for converting websites into apps. While it is easier for web developers to build mobile apps with PhoneGap than to develop them using native tools it is not turnkey or simple. PhoneGap apps require the same level of detail that all well developed apps deserve.

Resources

PhoneGap

Apple App Store Review Guidelines


Apple Human Interface Guidelines

Friday, October 11, 2013

PhoneGap and Backbone in the OC

I will be doing a presentation on developing mobile apps using a sweet combination of PhoneGap and Backbone. The code should work on all of PhoneGap's wide variety of devices, but I have only validated it against iOS and Android. 


HTML5 at one point held the promise of being the unifying platform for desktop and mobile devices. Then big name companies seem to turn their backs on the platform in droves. But don't don't despair, HTML5 isn't dead, in fact it is still a great choice for many mobile applications.


In this session, we will build a simple to understand but easy to enhance mobile app. We will use the latest and greatest version of PhoneGap, 3.0 for cross-platformness. To it we will add the open source MV* framework, Backbone, which will help bring order to the normal chaos of JavaScript development.

This talk is being hosted by the good folks of SoCal .NET Architecture. It is a rare treat for me to do a talk so close to home, last weekend I was talking way up in Silicon Valley. They meet at the offices of the Rancho Santiago Community College District, which is probably the best possible location to have a meeting after work. It is just off the 5 freeway, not far from the 22, 55, 57, and 91 freeways. The talk is on Thursday, October 17th at 7 PM. For more information and directions go to: http://www.scdna.org/.



Thursday, October 3, 2013

Beginning HTML5 Mobile Game Programming - Silicon Valley Code Camp 2013

Want to build your own HTML5 game? Have some starter code. Here are the links to the code and slides for my Beginning HTML5 Mobile Programming.



The Source Code: 

The Slides: 

Sunday, September 15, 2013

Android Twitter API 1.1 App

On June 11, 2013, Twitter turned off version 1.0 of their REST API. The API had been deprecated for quite sometime but still a lot of people were caught by surprise. All over the Internet a crap load of tutorials broke. Twitter was always a favorite for tutorial writers, since their servers were open and always had fresh data. Quite frankly, I was surprised how long Twitter let everyone and anyone use their servers. It was incredibly generous and must have been equally expensive. 

Now the free ride isn't over. Twitter just wants to know who is using their servers. And they are using OAuth to do it. Now OAuth can be a bit tricky to work with, not overly painful, but tricky. It is also a bit of overkill if all you want to do is something as simple as grabbing a user's public timeline. Luckily, there is an easier alternative: Application-Only Authentication.

With application-only authentication, your app is able to make authenticated requests its own. It doesn't need a user's credentials. Now, it can't do everything. Since it is doesn't have a user context, it isn't able to do things like status updates. But it can do things like grabbing a user's timeline, which is what this tutorial will do. 


YOU WILL NEED YOUR OWN CONSUMER KEY & SECRET!

I want to say that up front to hopefully stop people from complaining that the app doesn't work later. Getting a key and secret is easy and free so there is no good reason for not getting one. The app doesn't have a working key or secret. It will build, but it won't run until you replace the mock key and secret, with real ones. 


Getting Your Own Consumer Key and Secret
  1. Simply go to https://dev.twitter.com
  2. Click the "Sign in" link in the upper right hand corner
  3. Enter your credentials and click "Log in"
  4. Hover over your avatar in the upper right hand corner
  5. Click the "My applications" link
  6. Click the "Create a new application" button 
  7. Fill out the application details
  8. Accept the "Developer Rules of the Road"
  9. Complete the captcha
  10. Click the "Create your Twitter application" button
  11. On the "My applications" page, click on your application's name
  12. Your consumer key and secret will listed in the OAuth settings section




Keep your consumer key and secret secure. Don't do anything foolish with them, like publish them in a tutorial.


Android's Listview Adapter and AsyncTask

This app uses a quick and simply listview to render the tweets. It looks absolutely ugly, but this tutorial is about getting access to a user's timeline in API 1.1, not how to render pretty listview in Android. There are already a lot of tutorials out there on how to that. 

We also make use of one of Android's cooler features, AsyncTasks. I hope that we all know by now, that we aren't suppose to do anything which takes a long time on the main UI thread, you know things like calling web services. The AsyncTask is probably the easiest way to avoid getting an ANR. And it is so dead simple to use. 


The app uses a private class, DownloadTwitterTask which inherits from AsyncTask. Its job is to download the current batch of tweets on the user's timeline. The doInBackground method does all of the grunt work. It grabs the user's screen name, and calls the getTwitterStream method. This is what makes the AsyncTask class cool. You don't have to think about multi-tasking or other such complexity, just what is long running task you want to do, and do it. 

Once your task is complete, return your object and AsyncTask will pass it on to the onPostExecute method which runs on the UI thread. This is the perfect time to update your UI. Now for us the string passed to the onPostExecute method is the user's timeline in JSON format, so we convert it to a Twitter object which we define as an array list of Tweets. We use Google's excellent Gson library to do that conversion and a few others. And finally we feed our tweets to the list adapter for rendering.



Getting Authenticated and a User's Timeline

We have rendered our tweets to our list view, but how did we get them? Once you have your key and secret, it is surprisingly simple to get to a user's timeline, just make a few HTTPS calls. In fact, Twitter lists out how to do it in three steps, well OK there are some sub-steps. The getTwitterStream method lists out all of the steps necessary to authenticate your app and then get some tweets. 

Step 1: Encode consumer key and secret

First, we need to URL encode the consumer key and secret. Java has this function built-in, URLEncoder, be sure to pass your encoding. Then we concatenate the encoded strings with a semi-colon separating them and Base64 encode the whole thing. This is the one spot where I ran into some trouble. I wasn't sure what flag to pass. I initially tried, Base64.DEFAULT, which didn't work. Luckily there weren't that many options, when I tried Base64.NO_WRAP, it worked. 

Step 2: Obtain a bearer token

In order to get the bearer token, you need to make a post request to the Twitter token URL. With the request, you need to pass a few header keys. If each of the keys isn't correct, your request will be rejected. Also the request body must only contain "grant_type=client_credentials", or your request will be rejected. 

If everything went well, you will now have your bearer token. Be sure to check it as well. Its token should equal "bearer". 

Step 3: Authenticate API requests with bearer token

With our token, we can now make API requests. Simply set the Authorization header equal to the string "Bearer " plus our access token. For both the Http Post and the Http Get, I use the same method getResponseBody to read the entire HTTP stream and return it as a string. Everywhere, if we encounter an exception, no attempt is made to recover, we usually return an empty string or a null.

Summary

Again, please don't forget to replace the dummy consumer key and secret with your own. The code will not work without it. The project is in IntelliJ IDEA format. I just can't bring myself to use Eclipse. If you use Eclipse, simply copy the files into your project. Please feel free to use the code however you'd like. 

Resources






Sunday, September 1, 2013

Bold Numbers on Ordered List

At the heart of the web apps I write, once you strip away all of the libraries, is just HTML and CSS. At times I forget that and tend to over-think problems. Recently I needed to make the numbers of an ordered list bold without making the content of the list items <li> bold. For a short time I was stumped. The number is considered by HTML to be part of <li> tag, but there is no way to address it individually.

On the web I ran across a lot of solutions to this issue, none of which felt right to me, they were all too complicated. The solution I chose was so simple, I don't why I had to think about. 

The contents of the <li> tags is completely under my control, so instead of trying to think of a way to address the numbers, I instead decided to address the <li> tags. All I needed to do was to put a <span> tag inside of each <li> tag, I would then be able to address the <li> without affecting the number. So I made the <ol> tag have bold text and made the <li><span> combination have normal text. Problem solved.

Friday, August 30, 2013

jQuery Mobile Workshop

I will be presenting two workshops in the month of September each covering a technology which is near and dear to my heart: jQuery Mobile and Google Maps. Each of these workshops will be hosted by the good folks at the South Bay Mobile User Group.  


jQuery Mobile Deep Dive

On Saturday, September 7th, I will be in Culver City at the cool offices of M-GO, for jQuery Mobile Deep Dive. The idea of this class is simple, to show you how to build jQuery Mobile apps in a professional manner. This workshop teaches all of the techniques you've always wanted to learn but weren't quite sure where to begin. Things like:

  • How to Build Web Apps Which Behave Like Native Device Apps
  • How to Implement Responsive Design in Mobile Web Apps
  • How to Utilize Backbone.js
  • How to Performance Optimize Mobile Web Apps
  • How to Perform Unit Testing
  • How to Minimize JavaScript for Improved Throughput
  • HTML5 Offline Applications
  • And MORE!
As always, all of the code we work with, is yours to keep. And the slides will be available for download afterwards. This is an 8 hour workshop and lunch will be provided. The price is only $50. Seats are filling up fast so please sign up now.




Wednesday, July 17, 2013

Responsive Design and jQuery Mobile



"Mobile First!", is the new cry of web designers worldwide. But how do you do it? Do you have to scrap all of your current web skills? Is it magic created by wizard-like designers which could never be understood by mere mortals? Believe it or not with the combination of jQuery Mobile and CSS3 Media Queries, you can easily create a site which looks good on phone, tablet, or desktop.

General Responsive Web Features

The web began as responsive. Now admittedly, the web didn't do very much, so being responsive when the Internet was mainly documents was easy. HTML documents naturally wrapped to the next line and flowed down the page.

Along the way things changed. Developers began designing sites in tools like PhotoShop and wanted pixels perfect renderings of those designs. Problem with pixels is that they are not very flexible. It has always been possible to use percentages instead of pixels, but they were clumsier to work with, so pixels remained the favorite.

With the HTML5 and CSS3 there is more support for responsive design. Lets

Meta tags
Meta tags have been the favorite of the SEO crowd for sometime. Meta tags are used to define keywords, descriptions and even redirects. Here are some rules about meta tags:

  • They always go in the <head> section of the page
  • They are never displayed
  • They consist mostly of key/value pairs: name = key and content = value

Viewport
The viewport is a special type of meta tag which defines the screen of a mobile device. In the example program the viewport meta tag looks like:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />

The attributes above mean:
  • width=device-width - converts the pixels to CSS pixels
  • initial-scale=1 - sets the scale level
  • user-scalable=no - turns off scaling

If initial-scale is some other value than 1, the zoom can be smaller or larger. If user-scalable is set to yes, then the user sets the zoom level by tapping, pinching, or whatever zoom gesture the browser supports.

Media Query
Media Queries are the workhorse of responsive design. A media query is a media type and at least one expression that limits the style sheets' scope. Here is an example:

@media screen and (max-width: 1024px) and (orientation:portrait)
{

}

The above media query means:
  • For a screen media type
  • Define the classes only if
    • The width is less that 1023
    • AND the orientation is portrait

The media query begins with @media then a media type, in this case, screen. Other types are: all, braille, embossed, handheld, print, project, speech, tty, and tv. You can compose complex media queries using logical operators like not, and, and only.

  • not - is used to negate an entire media query
  • and - used to combine multiple media features together into a single media query
  • only - used to apply a style only if the entire query matches

Finally there is the comma-separated list which behaves like an or operator. If any media queries return true, the style sheets gets applied.

One pattern for applying the media queries is to define the query for the narrowest device first, then define for a tablet, and finally a desktop. Now all of these definitions are pretty loose and open to interpretation. You may need to adjust them to fit your needs.

If you run the demo on a high pixel phone like a Nexus 4, which has a display 1280x768 resolution, why doesn't it display like a desktop? The key is the viewport meta tag. This tag which read by mobile browsers, redefines the pixels as CSS pixels. The precise number of CSS pixels varies by device, but on the iPhone it is 320 and the Nexus 4 it is 384, both of which are less than the minimum of 480 pixels to be defined as a tablet.

jQuery Mobile Features
So far we haven't looked at jQuery Mobile features. From the get go jQuery Mobile has had responsive features. Some of which are:

  • grid - a simple way to build CSS-based columns that can also be responsive
  • tables - selectively hides or shows table columns based on the display width
  • panels - creates a hidden page which slides left or right to reveal itself

Grids
Grids have been with jQuery Mobile since the beginning. They are essentially self sizing columns which dynamically resize themselves when the size of the page changes. The number of available columns ranges from two to five. To change the number of available columns simply change the class on the root div then add or remove a div from the collection.
  • ui-grid-a = 2 columns
  • ui-grid-b = 3 columns
  • ui-grid-c = 4 columns
  • ui-grid-d = 5 columns

Tables
Tables were added with the release of jQuery Mobile 1.3.0. They allow for the responsive display of tabular data. There are two basic types of tables: reflow which is the default and column toggle. Reflow tables lay the table data horizontally until it reaches a minimum size, then all of the data for each row is grouped together and it re-flows down the page.

In column toggle mode, each column of a table can be given a separate priority, when the data can no longer fit horizontal, the column with the lowest priority number which is still visible is hidden. This continues until a minimum size is reached or there is only one column remaining.

Panels
A panel is a hidden page which reveals itself by sliding from the  left or right on to the page. On it can nearly any support jQuery Mobile widget. When the panel is displayed, clicking any where else on the page will close it.

Best Practices

  • Design styles beginning with "mobile first", then go wider
  • Use "min-width" to constrain styles
  • Prefer percentages and ems to pixels