Hack4Colorado 2013 – Civic Hackathon

Do you live in Colorado and want to have fun playing with code, learn new APIs and datasets, and generally testing your coding “skillz” while under pressure and competing with other hotshot developers for prizes? If you answered “yes”, then I strongly recommend you check out the opportunities at the Hack4Colorado event which takes place on the weekend of May 31st. This event is part of a national civic hacking day where other States, Counties and Cities around the country are doing exactly the same thing.

The concept is simple. These events help promote open government data that can be used within applications that you build to solve everyday problems. So, these organizations provide you with cool data sets to choose from and you have fun building an application around it. Ideas include find the nearest rent-a-bike location, explore local hiking trails and so much more.

Full disclosure, Esri has also graciously offered to provide bountiful cash (yes, cash!) prizes. Other sponsors are offering Rokus, Kinects, and even Big Wheels (yes you also heard that right!). I even have an application in mind that I might try to build when I’m not helping other folks out.

What do you think? Hopefully I’ll see you there.

Share
Tags: , ,
Posted in Conferences | No Comments »

Easy enums for custom JavaScript libraries

There’s a ton of information on the internet related to the best way to create JavaScript enums. This post is different in that it focuses on using enums that are immutable and cannot be changed within your own custom libraries.

The challenge with enum usage in JavaScript is global variable leakage can accidentally cause unexpected changes within your application, especially in cases of large, complex applications that may involve your own JavaScript libraries along-side 3rd party libraries. Global variable leakage means two variables can potentially have the same name, and this may not cause an error. Good debuggers help to avoid this problem by using jslint. But, if someone else is using your libraries then you can’t depend on them using best practices. So, variable leakage can cause unexplainable/unpredictable problems and create hard to track bugs. What we need is a coding pattern to protect enums so that we can guarantee that we always get the value expected.

As of today, JavaScript doesn’t have a universally accepted, built-in cross-browser solution for guaranteeing that specific variables can be made immutable. In other words, if we create a statement var BLUE = “blue” there is no way to enforce that something elsewhere in an application, or code that someone else wrote that is running the same application cannot ever change the value of BLUE.

In comparison, strongly typed languages such as C# and Java let you declare constants. If you accidentally try to change them in your code you get a compiler error that prevents the application from running. The compile-time checking can help prevent bugs in your code later on. Here are several examples from Java and C#:

 final int RADIUS = 1000; //Java
 const int RADIUS = 1000; //C#

So here we go. I’ll use six use cases to illustrate a variety of ways to make certain your enums are immutable. This list is not designed to be all inclusive, its intent is to demonstrate patterns that you can use to learn more about JavaScript enums. You can try these out using the following jsfiddle.

USE CASE 1 – Basic public enum function with no namespace protection. This use cases offers the least amount of protection against global variable leakage. I’d only expect to see this type of enum in very small, stand-alone applications.

function basicEnum() {
    var values = {
         BLACK: '#000000',
         RED: '#FF0000',
         GREEN: '#00FF00'
    }

    return values;
}

console.log("test0 " + basicEnum().BLACK); //test0 #000000

USE CASE 2 – Basic public enum that uses an internal, privately scoped namespace in which to define the enum object. This use case offers slightly more protection than Use Case 1, but the public function itself is still not protected within the global namespace. It’s possible there could be two functions with the same name “colorEnum”. And, the larger the application gets the higher probability there is of having accidental name duplication.

function colorEnum() {
    var values = values || {}
    values.colorEnum = {
         BLACK: '#000000',
         RED: '#FF0000',
         GREEN: '#00FF00'
      };

      return values;
};

console.log("test1 " + colorEnum().colorEnum.GREEN); //test1 #00FF00

USE CASE 3 – Public enum with no namespace protection using an anonymous function expression to define the enum. This is a variation of Use Case 2 showing you can define multiple categories of enums. And, like Use Case 2 it still offers zero public/global namespace protection. I’m using the terms public and global to mean the same thing.

DoSomething = (function(){

    var constValues = constValues || {}
    constValues.color = {"BLACK" : "#000000" }
    constValues.error = {"ERROR_TIMEOUT" : "Connection Timeout" }
    return constValues;
});

console.log("test2 " + DoSomething().color.BLACK); //test2 #000000
console.log("test3 " + DoSomething().error.ERROR_TIMEOUT); //test3 Connection Timeout

USE CASE 4 – Public enum with namespace protection using an anonymous function expression and internal (private) namespaces to differentiate multiple categories of custom enum objects. This use case starts to offer better protection against global variable leakage by wrapping the public function in a namespace.

var my_test = my_test || {}
my_test.DoSomething = (function(){

    var constValues = constValues || {}
    constValues.color = {
        "BLACK" : "#000000",
        "RED" : "#FF0000"
    }
    constValues.error = {
        "ERROR_TIMEOUT" : "Connection Timeout",
        "ERROR_FAULT" : "Connection problem"
    }
    return constValues;
});

console.log("test4 " + my_test.DoSomething().color.BLACK); //test4 #000000
console.log("test5 " + my_test.DoSomething().error.ERROR_TIMEOUT); //test5 Connection Timeout

USE CASE 5 – Namespace protected public anonymous function expression along with an internally (private) scoped function that defines the enum. This is a variation of Use Case 5 showing how to use switch/case statements along with a privately scoped function that are all wrapped inside the anonymous function.

var my_second_test = my_second_test || {};
my_second_test.DoSomething = (function(val){

    var color;

    switch(val)
    {
        case 1:
            color = basicEnum().BLACK;
            break;
        case 2:
            color = basicEnum().RED;
            break;
        case 3:
            color = basicEnum().GREEN;
            break;
    }

    function basicEnum() {
        var values = {
             BLACK: '#000000',
             RED: '#FF0000',
             GREEN: '#00FF00'
        }

        return values;
    }

    return color;
});

console.log("test6 " + my_second_test.DoSomething(2)); //test6 #FF0000

USE CASE 6 – This Use Case shows placing a privately scoped anonymous function expression defining the enum inside a public anonymous function expression, and finally accessed through another prototyped anonymous function expression. Yikes, that was a lot of technical mumbo-jumbo verbiage, right?! It also offers several tests to validate if the enum is immutable or not.

var my_third_test = my_third_test || {};
my_third_test.DoSomething = (function(){

    this.basicEnum = (function() {
        var values = {
             BLACK: '#000000',
             RED: '#FF0000',
             GREEN: '#00FF00'
        }

        return values;
    });

});

my_third_test.DoSomething.prototype.findColor = (function(val){
    var color;

    switch(val)
    {
        case 1:
            color = this.basicEnum().BLACK;
            break;
        case 2:
            color = this.basicEnum().RED;
            break;
        case 3:
            color = this.basicEnum().GREEN;
            break;
    }

    return color;
});

var myColor = new my_third_test.DoSomething();

console.log("test7 " + myColor.findColor(3)); //test7 #00FF00

//The enum properties cannot be changed
myColor.basicEnum().BLACK = "test";

console.log("test8 " + myColor.basicEnum().BLACK); //test8 #000000

try{
    //test that basicEnum() is immutable
    myColor.basicEnum() = "test"; //Throws ERROR!
}
catch(err){
    console.log("test9 " + err);
    //test9 ReferenceError: Invalid left-hand side in assignment
}

Conclusion. So that’s all there is to it. Hopefully these examples help to not only demonstrate some patterns to protect your data, but also give you ideas for saving time while building larger applications.

Reference.

JSFiddle project

Share
Tags: , ,
Posted in JavaScript | No Comments »

jQuery Mobile – Setting full content width

Here are some hints to help get all of your jQuery content stretched to the full width of your mobile browser screen regardless of screen size or orientation. These techniques have been tested on jQuery 1.7.x, jQuery 2.0 and jQuery mobile 1.3.1.

Lets start with a look at the minimum required CSS:

html,body,div[data-role ="page"], div[data-role="content"] {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px;
}

Problem – Using the minimum CSS above, leaves a spacer on the top and left hand sides of the app, and the right hand border and/or bottom border disappears. I noticed the right hand margin extends approximately 9 to 15 pixels (or greater depending on device) beyond the visible view. I verified this behavior on Android 4.1 native browser and Chrome 26, as well as on iPad 3 using Safari and Chrome 25.

Solution – set certain CSS width properties as shown below. This solution has been tested on Android 4.1 native and Chome 26, Android 2.3.2 native, and on iPad Safari and Chrome 25. Just a bit of a warning that if displayed on a desktop browser you will see vertical scrollbars. But, you should be detecting the different between mobile and desktop anyway, right!

Note: this solution doesn’t address the problem with content height, it only looks at width. So, yes, you will notice that the height of my sample is off the page.


<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=7,IE=9">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

    <title>jQuery Test</title>

    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />

    <script type="text/javascript" src="http://code.jquery.com/jquery-2.0.0.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.js"></script>
<style>
        html,body, div[data-role ="page"] {
            height: 100%;
            width: 100%;
            margin: 0px;
            padding: 0px;
        }

         .ui-content{
            height: 100%;
            width: 100%;
            margin: 0px;
            padding: 0px;
            border-style: solid;
            border-color: chartreuse;
            border-width: 5px;
        }

        #map {
            height: 100%;
            width: 100%;
            padding: 0px;
            border-style: solid;
            border-color: crimson;
            border-width: 10px;
        }
</style>
</head>

<body>

<div data-role="page" id="page1" >

    <div data-role="content">
        <div id="map"</div>
    </div>

</div>
</body>

References

Determining the dimensions of an [HTML] element

Check HTML5 Browser Height and Width using Canvas

[Modified April 26, 2013 - fixed code bug]

Share
Tags: , , ,
Posted in JavaScript, jQuery | No Comments »

Smartphone devs, yes SD card speed matters!

If you want to get the highest performance out of your SD cards then read on. The purpose of this article is to raise awareness and spark your curiosity about SD card performance considerations.

Micro SD Class 2

Many developers I talk to aren’t aware that the read/write speeds of SD memory cards can have a significant affect on performance. This is especially true if you are moving around lots of data between a smartphone and the SD card. The good news is there is quite a bit of information out there to help you maximize performance, and a lot of it comes from high-end, camera aficionados believe it or not.

The most common feedback I get is developers typically buy cards with the most capacity at the lowest price. Depending on what you are doing, cheapest and slower isn’t always better. With little bit of research your read/write performance could get significantly better.

To start with there are four common speed classes: 2, 4, 6 and 10 and they represent an approximate minimum performance rating. You can find this number on the front of your card:

  • Class 2 ~ 2 Mbytes/sec
  • Class 4 ~ 4 Mbytes/sec
  • Class 6 ~ 6 Mbytes/sec
  • Class 10 ~ 10 Mbytes/sec

Read/write performance to your phones SD card really depends on HOW your application reads and writes data. You may have to do some testing to find out what works best. It depends on the consideration of multiple factors including:

  • Typical file types (e.g. video vs. text vs. image, etc)
  • Average file or data transaction size
  • Percentage of reads to writes
  • Duty cycle (percentage of reads or writes over a fixed time period)
  • Usage pattern

Usage pattern deserves a bit more attention and really starts to tell the story of what your application does behind-the-scenes. I think the best way to describe it is through some common use cases:

  • Many small reads and writes to/from a local database.
  • Occasional small reads and writes to local database.
  • Occasional large reads from local database.
  • Occasional large reads and writes to/from local database.
  • Large read upon application startup and large write upon application shutdown.

Wikipedia has noted that speed can differ significantly depending on what you are writing to the card. The article notes that writing large files versus writing many small files has widely different affects on performance. I’d seen similar observations when I worked on ultra-high performance server systems. So, the concept still remains today and provides excellent hints on how to tweak every extra millisecond of user experience.

If you need maximum performance then consider reformatting or defragging your card on a regular basis. I know Windows disk defragmenter utilities work on most SD cards, not sure about Mac. I have also seen multiple articles talk about bigger capacity is better because of memory fragmentation. With memory fragmentation, the card speed starts to decrease over time as the data becomes more fragmented. It’s the same concept as when you “defrag” the hard drive on your laptop.

References

If you want to learn more here are some helpful links:

SD Association – Bus speed

SD Association – Speed Class

Wikipedia – Secure Digital (See Speed Class Rating section)

Does your camera need a fast SD card? (good insight into SD card speed)

Share
Tags: , , ,
Posted in Mobile | No Comments »

Encrypt your OAuth cookies – PHP Example

This post only serves as a reminder that if you decide to use OAuth cookies you should make sure that they are adequately encrypted. I’ve seen a number of web-based OAuth applications recently that left their cookies unencrypted and I wanted to provide a fully working example.

Why should you care?  Any crook with a little bit of knowledge on how to generate header files can use oauth_token and oauth_token_secret and take control of your customers account.

I don’t know why but several of the most popular PHP OAuth libraries don’t mention this as a best practice. So I’m making an effort to shout out that encrypting your cookies is a very good thing to do and it involves the following:

  • Encrypt oath_token and oauth_token_secret
  • Write encrypted values to cookie
  • Read encrypted values when required
  • Provide functionality to delete cookie

Another gotcha is if you allow someone to log out of your app without deleting the cookie, then it’s possible someone else could come along and get the cookie then use it to generate requests on behalf of your client application.

So here’s a fully working PHP example of how to encrypt cookies. You can also access this project through a github repository.

Step 1: generate your key and initialization vector:

<?php
  session_start();
  require_once('config.php');
  require_once('Encrypt.php');
  header('Content-Type: application/json');

  $test = new Encrypt(null,null,DEFAULT_TIME_ZONE);
  echo "\n\n---------\n\nGenerate Key (Base64): " . $test->get_RandomKey();
  echo "\n\n---------\n\nGenerate IV (Base 64): " . $test->get_IV();

?>

Step 2: setup the config file:

<?php

/**
 * @file
 * A single location to store configuration.
 */

//REQUIRED - Encrypt your cookies
//http://si0.twimg.com/images/dev/oauth_diagram.png
//Create your own unique ENCRYPTION_KEY via Encrypt.get_RandomKey()
define('ENCRYPTION_KEY','Q83dBef2tgmHKZ9T1htFA2Y+jZgdler0szN28rjBf8o=');
//Create your own unique initialization vector via Encrypt.get_IV()
define('IV','C2Oez0DLMQ8rCcgYFJwzCw==');
define('DEFAULT_TIME_ZONE','America/Los_Angeles');

?>

Step 3: test ability to set an encrypted cookie and decrypt it.

<?php
session_start();
require_once('config.php');
require_once('Encrypt.php');

$key = base64_decode(ENCRYPTION_KEY);
$iv = base64_decode(IV);
echo "Key: " . $key;
echo "\n\nIV: ". $iv;
$test = new Encrypt($key,$iv,DEFAULT_TIME_ZONE);

if(isset($_COOKIE["twitterapp"]))
{
    header('Content-Type: application/json');

    $retrieved_cookie =  $_COOKIE["twitterapp"];
    echo "\n\nEncrypted value: " . $retrieved_cookie;
    echo "\n\nActual Value: " . "VodG7slxk+w0INvK66gztp4TOLijNzyiWDzI8Z4IU4PTiBJJkRPdkaEbDtXFYUVkCVU=";
    echo "\n\nDecrypted Value: " . $test->decrypt(base64_decode($retrieved_cookie));

}
else
{
    $fake_cookie_string = "VodG7slxk+w0INvK66gztp4TOLijNzyiWDzI8Z4IU4PTiBJJkRPdkaEbDtXFYUVkCVU=";
    $encrypted_cookie = base64_encode($test->encrypt($fake_cookie_string));
    setcookie("twitterapp", $encrypted_cookie, $cookie_life, '/', OAUTH_COOKIE_DOMAIN);
    header('Location: http://your_domain_name/oauthphp/test.php', true, 302);
    exit;

}
?>

And, here is the Encrypt Class:

<?php
class Encrypt{
	/*
	* Basic encryption Class
	* Version: 1.0
	* Author: Andy Gup
	*/
    private $key;
    private $iv;

    function __construct($encryption_key,$iv,$time_zone) {
        $this->key = $encryption_key;
	$this->iv = $iv;
	date_default_timezone_set($time_zone);
     }

     public function encrypt($value){
          $final = null;
          if($value == null || $this->key == null || $this->iv == null)
          {
               header("HTTP/1.0 400 Error");
               echo "\n\n\nERROR: Null value detected: check your inputs";
               exit;
          }
          else
          {
              try
              {
                   $final = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, $value, MCRYPT_MODE_CFB,$this->iv);
              }
              catch(Exception $e)
              {
                   header("HTTP/1.0 400 Error");
                   echo "\n\n\nERROR: Failed encryption. " .$e->getMessage();
                   exit;
	      }
          }
          return  $final;
    }

    public function decrypt($value){
        return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, $value, MCRYPT_MODE_CFB,$this->iv);
    }

    public function get_RandomKey(){
        $result = openssl_random_pseudo_bytes(32, $secure);
        return base64_encode($result);
    }

    public function get_IV(){
        $size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB);
        return base64_encode(mcrypt_create_iv($size, MCRYPT_RAND));
    }
}
?>

Resources

Github repository

PHP for Windows - the Mcrypt library seems to come with this installation. Mac users may have to install MAMP.

PHP Manual for Mcrypt

OAuth Community

[Modified: April 27, 2013 - added link to github repo.]

Share
Tags: , , ,
Posted in OAuth, PHP | No Comments »

Why does anyone still need a desktop computer?

Who are these people that are still buying desktop computers? You would think this is a moot point in the year 2013. The writing has been on the wall for several years now that laptop prices have made them significantly more affordable. Modern laptops are powerful, light-weight and best of all portable. Tablets are running a close second to laptops.

But, I do know some folks (who have requested to remain anonymous at risk of being made fun of) who insist that a desktop is the only way to go. Yes you may be shocked and surprised to learn that many non-geeks don’t have the latest, fastest, sleekest, quietest, thinnest, greenest, most powerful, highest resolution, lightest devices. I know that’s crazy, right? Yet, these people do actually exist. So over the last six months I’ve compiled a list of the desktop crowds desires:

  1. Need a larger screen
  2. Need the full-size keyboard
  3. Need a larger hard drive
  4. Need more power for processing images and videos
  5. Corporate security reasons where they don’t want laptops leaving the building
  6. Laptops are significantly more fragile and don’t last as long.

Now let me briefly present some corresponding counter-arguments suggestions.

  1. You can always hook up an external monitor to a laptop or some tablets.
  2. There are also external USB keyboards that rock.
  3. External storage is awesome these days. There are high-performance 128GB thumb drives, for example and even multiple terabyte external drives.
  4. Number 4 above might be the only reason for making a concession towards using a desktop. If you are professional or graphic artist that has video or image processing jobs that take currently many hours on a high-performance quad-core desktop, then you might not want to heat up your laptop to that extreme. For everyone else doing Facebook processing there are definitely some high-powered laptops that can crank on image processing.
  5. You could always use a permanent security cable like I’ve seen at some hotels and airport lounges.
  6. One of the most common causes of laptop death is failure to keep it cool. Make sure it sits on a hard surface like a table and not on top of your puffy down comforter all night. If you have a problem with dropping your laptop get it a protective case.

In conclusion, there are very few reasons where a desktop computer is the only solution. The next question you ask me should be “so, what type of laptop or tablet do you recommend?”!

Share
Tags:
Posted in Reviews | No Comments »