Category Archives: Software Development

Dynamic List Items in an Ionic/AngularJS App

In an Ionic/AngularJS app when one wants to display a list of model objects, the following will typically be used:

<ion-list>
  <ion-item ng-repeat="item in items">
    Hello, {{item}}!
  </ion-item>
</ion-list>

In an app I’m currently working on, however, I wanted to make use of different items in a list dynamically, with the appearance of each item depending on various properties of the given model object in the list. I’d imagine that to solve this problem there are various ways of doing so, but I ended up using html view templates and the ng-include directive to achieve this. Below is a step-by-step walkthrough of the method I used:

  • Define HTML view templates for the different list items to be displayed.

TemplateA.html

{{modelObject.name}}

TemplateB.html

<img class="full-image" ng-src="{{modelObject.image.url}}">
<p>
	{{modelObject.description}}
</p>
  • Add functions in the controller to determine the correct class & view template to use based on properties of the provided model object.

HomeCtrl.js

.controller('HomeCtrl', function($scope) {
  var vm = $scope;

  // Determines the correct CSS class to use based
  // on properties of the provided model object
  vm.itemClass = function(modelObject) {
    if (modelObject.type == 0) {
      return "class-A";
    }
    else {
      return "class-B"
    }
  };

  // Determines the correct html view template to use based
  // on properties of the provided model object
  vm.itemTemplate = function(modelObject) {
    if (modelObject.type == 0) {
      return "app/path_to_template/templateA.html";
    }
    else {
      return "app/path_to_template/templateB.html";
    }
  };
});
  • Then in the view displaying the list, it’s as simple as referencing the relevant controller functions to dynamically determine the correct class and template to use for each item in the list at runtime.

Home.html

    <ion-list>
      <ion-item ng-repeat="modelObject in modelObjects" ng-class="itemClass(modelObject)">
        <ng-include src="itemTemplate(modelObject)"></ng-include>
      </ion-item>
    </ion-list>
Advertisements

Uploading a base64 image to Parse with the REST API in AngularJS

Screen Shot 2015-05-31 at 8.34.44 PM

I was recently working on an Ionic/AngularJS app which needed to do the following:

– Upload a base64 image file (taken with the camera) to the Parse servers using the REST API.

– Associate the uploaded image file with an object and save the object to Parse using the REST API.

 

The Parse documentation didn’t seem to explain this specific case and other examples online seemed to all offer different details on how to get this done… so I ended up jumping through a few hoops until I eventually got it working. Below is an example of what I used to achieve this.

ImageSubmissionCtrl

// camera is simply an injected service, wrapping the cordova APIs
.controller('ImageSubmissionCtrl', function($scope, $http, camera) {

  var vm = $scope;
  var imageData;

  // Object to save to Parse that includes an image
  var object = {
    text: "",
    image: null
  };

  // Function to take a picture using the device camera
  vm.takePicture = function() {

    // Define various properties for getting an image using the camera
    var cameraOptions = {
      quality : 75,
      // This ensures the actual base64 data is returned, and not the file URI
      destinationType: Camera.DestinationType.DATA_URL,
      encodingType : Camera.EncodingType.JPEG
    };

    // Use the Cordova Camera APIs to get a picture. For brevity, camera
    // is simply an injected service
    camera.getPicture(cameraOptions).then(function(returnedImageData) {
      imageData = returnedImageData;

    }, function(err) {
      console.log("Error taking picture: " + err);
    });
  };

  // Function to submit the object to Parse using the REST API
  vm.submitObject = function() {

    // This part is important. As part of the JSON that we send to Parse,
    // we need to specify the content type here as a field(__ContentType)
    // along with the image data. Notice that the Content-Type specified
    // in the headers is actually "plain/text"
    var dataToSubmit = {__ContentType : "image/jpeg", base64 : imageData};

    // First upload the image file
    $http.post("https://api.parse.com/1/files/image.jpg", dataToSubmit, {
           headers: {
               "X-Parse-Application-Id": PARSE_APP_ID,
               "X-Parse-REST-API-Key": PARSE_REST_API_KEY,
               "Content-Type": "plain/text"
           }
    })
    .success(function(result) {
      // Now associated the image file with the object
      coupleImageFileWithObject(result.name);
    })
    .error(function(result) {
      console.log("Error uploading image file: " + err);
    });
  };

  // Function to associate the image file with an object and save the
  // object to Parse using the REST API
  function coupleImageFileWithObject(fileName) {

    // Assign the filename to our object prior to saving it to Parse
    object.image = {name : fileName, __type : "File"};

    // The 'ObjectClass' in the url should be replaced by the class name
    // of the object you are saving
    $http.post("https://api.parse.com/1/classes/ObjectClass", object, {
           headers: {
               "X-Parse-Application-Id": PARSE_APP_ID,
               "X-Parse-REST-API-Key": PARSE_REST_API_KEY
             }
      })
      .success(function(result) {
        console.log("Object successfully saved.");
      })
      .error(function(result) {
        console.log("Error coupling image file with object: " + err);
      });
  };
});

It’s important to understand that the first step is to upload the file to Parse independently of the containing object, and then only on a successful response associate the file handle with the object and save the object itself to Parse.

 

Authenticated Google Cloud Endpoint call from an iOS client

In my last post I mentioned the Google Cloud Endpoint framework which is a great way to produce an API that can be consumed across multiple platforms. Even though it is in preview release and subject to some teething problems, I highly recommend checking it out.

In a nutshell, the framework allows you to develop a backend and then generates the necessary data and proxy classes to use in your client projects to talk to the API. This means you no longer have to be concerned with the mechanics of making an API call, parsing the response data, etc., but can interface with the entire API through objects.

I’ve been playing around with the framework in bits and pieces and recently explored making an authenticated API call from an iOS client when I discovered a rather annoying issue: after successfully authenticating a user with OAuth 2, the local dev server would reject any subsequent API calls with the following error:

Cannot authorize request with scheme http

My iOS simulator and local dev server were just not getting along….

I knew that the problem was my local dev server was plain old http and that something, somewhere required https. After several attempts and the lack of any obvious info online, I started digging around the source code of the generated client classes…and, bingo!

The problem turned out to be that the iOS OAuth2 library would not authorize non-https requests, which meant I could not test authenticated calls locally. I eventually found a flag in the GTMOAuth2Authentication class of the iOS OAuth2 library which allows the library to authorize all requests (including non-https):

// Property indicating if this object will authorize plain http request
// (as well as any non-https requests.) Default is NO, only requests with the
// scheme https are authorized, since security may be compromised if tokens
// are sent over the wire using an unencrypted protocol like http.
@property (assign) BOOL shouldAuthorizeAllRequests;

By default this flag is set to NO. To update this flag to work with my outgoing requests, I changed its value in the OAUTH callback method prior to making any API requests:

- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
      finishedWithAuth:(GTMOAuth2Authentication *)auth
                 error:(NSError *)error {
    [self dismissViewControllerAnimated:YES completion:nil];

    if (error != nil) {
        // Authentication failed
        ...
    } else {
        // Authentication succeeded
        ...

        // TODO: for development purposes only to use non-https....remove for release.
        auth.shouldAuthorizeAllRequests = YES;

        // Make some API calls
        ...
    }
}

Ta-da.

Tidbits

Just some interesting bits and pieces I have come across recently:

Flat UI Colors: a neat website that displays a colour palette, allowing you to click on a colour to copy its value to the clipboard. #design

ColorHex #android App: a simple colour picking app that that also allows one to store favourite colours. #design

Butter Knife: an interesting view injection framework for #android, created by Jake Wharton who also developed the ActionbarSherlock framework.

Latest Android Dashboard Stats: personally, I was surprised to see that as much as 9.9% of devices still fall under the small, ldpi configuration. #android


#programming #object-orientation

I recently did a bit of a refresh on some principles and guidelines for object orientated programming:


#server-side

I spent a bit of time recently developing a simple REST web-service using Google go and Google App Engine. Here are some useful links and examples:

  • Gorca: a utility package for RESTful go applications on App Engine.
  • Home: a simple App Engine application using go and Angular JS.
  • RESTful web-services in go: useful information on developing RESTful web-services using Google go.

Anyone interested in developing web-service APIs that need to be consumed by mobile apps and the web, should definitely have a look at Google Cloud Endpoints… I also played around with this cool feature for Java and below are some useful links:

Premature Optimization

I recently had a Java feature to implement which required some thought around read/write thread synchronization and performance. I don’t pretend to be expert on the topic of synchronization, and in fact, it’s an area of programming I have A LOT to learn about. It’s the kind of complex topic that often results in the panicky, overzealous and irrational behaviour you see in developers prior to yet another prematurely optimized solution being dumped on the world. When I approached this particular feature, I thought I wouldn’t fall into this trap. I was wrong.

The crux of the synchronization problem was that I wanted to be able to handle frequent concurrent read and writes to a Java ArrayList data structure in a thread-safe manner. It’s not that I didn’t know of a solution, but that I didn’t know of the best solution. After initially over-thinking the problem, I decided to post up on stackoverflow.com just to see how other developers out there with more experience on the subject would approach it. Fortunately, within minutes the community was already asking me questions in the comments that had me realise I never even had adequate data/info as to the load this feature would have to endure; yes, someday it may have to scale big time… but right now, it doesn’t!

Regardless of the process taken, I still managed to learn quite a bit about different synchronization techniques:

  • Collections.synchronizedList(): Automatically performs synchronization for single atomic operations (add, remove, get, etc.). Easy solution and likely suitable for most purposes.
  • CopyOnWriteArrayList: This results in a copy of the ArrayList being made each time it is modified to prevent exceptions when other threads are traversing the ArrayList. I couldn’t go with this option due to the high number of mutations required in the feature.
  • ReadWriteLock: Allows one to manually apply read & write locks to parts of the code requiring synchronization. The great thing with this solution is the ability to have thread-safe concurrent read operations, with the downside being more manual effort and synchronization code.

The funny thing is that as development of the feature continued, requirements changed and it turned out that having random access to the data wasn’t even necessary; as the only requirements needed were then traversals and mutations, the end solution changed to using the ConcurrentLinkedQueue data structure…..meaning all that initial over-thinking was, well, lame :/

 

Otto Event Bus for Android

In case you haven’t already checked out this cool framework, Otto is an event bus designed to help parts of your application communicate more effectively and in a more decoupled manner.

With respect to Android, one particular area where the Otto event bus can be really useful is in the passing of complex data objects between the Activity andFragment objects in your application. For instance, when passing a data object between two fragments, traditional methods relied on passing the object via the parent activity or by using the setTargetFragment()/getTargetFragment() methods of the Fragment class; a downside to these approaches is that it couples your fragments/activities to one another. Whilst one can use Interfaces to alleviate the coupling, it requires additional boilerplate code and if more than a single object is required one can be faced with handling the code and coupling of many Interfaces, which is often excessive. The following is a simple Java example of how Otto can simplify the communication amongst components and reduce coupling and boilerplate code.

We have a weather service which periodically needs to provide weather updates to various components. Without the use of Otto, the following is an example of how this could be achieved:

WeatherService Class

 public class WeatherService
{
	private String weatherDescription;
	private List<WeatherListener> listeners = new ArrayList<WeatherListener>();

	
	public void weatherHasBeenUpdatedFromSomewhere(String weatherDescription)
	{
		this.weatherDescription = weatherDescription;
		
		if (listeners != null)
		{
			for (WeatherListener listener : listeners)
			{
				listener.weatherUpdated(weatherDescription);
			}
		}
	}
	
	public void addListener(WeatherListener listener)
	{
		listeners.add(listener);
	}
}

This class has to maintain a list of listeners which it publishes updates to. Notice that although it isn’t coupled with any concrete class, it still has to know about an interface which does very little. Also notice how a large amount of the code is concerned with managing the listeners.
 
WeatherListener Interface


public interface WeatherListener
{
	public void weatherUpdated(String weatherDescription);
}

A simple listener interface. This is largely just boilerplate code given how little this interface achieves.
 
WeatherScreen Class


public class WeatherScreen implements WeatherListener, SomeOtherRandomService
{
	private String weatherDescription;

	@Override
	public void weatherUpdated(String weatherDescription)
	{
		this.weatherDescription = weatherDescription;
		
		// Do something...
	}

	@Override
	public void randomAction(RandomObject randomObject)
	{
		// Do something...
	}
}

Nothing fancy here, the WeatherScreen class listens for weather updates and possibly information from other services. One can easily see how it’s possible for these publisher/listener connections to result in a lot of unnecessary coupling and boilerplate code.

If we take the same example and use the Otto event bus to manage a lot of these connections, we end up with something like the following:

OttoWeatherService Class

public class OttoWeatherService
{
	private String weatherDescription;
	private Bus eventBus;
	
	public OttoWeatherService(Bus eventBus)
	{
		this.eventBus = eventBus;
		eventBus.register(this);
	}
	
	public void weatherHasBeenUpdatedFromSomewhere(String weatherDescription)
	{
		this.weatherDescription = weatherDescription;
		
		// post the updated weather on the event bus.
		eventBus.post(weatherDescription);
	}
	
	@Produce
	public String produceWeatherUpdate()
	{
		return weatherDescription;
	}
}

When the OttoWeatherService class receives an update, it posts an event on the bus to notify all subscribers. Note that the service class now has less responsibility as it no longer needs to be concerned with a list of listeners and is immediately decoupled from the interface. Also note that this class is a Producer, meaning that as soon as an interested subscriber registers on the bus it will receive the latest update.

OttoWeatherScreen Class

public class OttoWeatherScreen
{
	private String weatherDescription;
	private Bus eventBus;
	
	public OttoWeatherScreen(Bus eventBus)
	{
		this.eventBus = eventBus;
		eventBus.register(this);
	}
	
	@Subscribe
	public void weatherAvailable(String weatherDescription)
	{
		this.weatherDescription = weatherDescription;
		
		// Do something...
	}
	
	@Subscribe
	public void randomObjectAvailable(RandomObject randomObject)
	{
		// Do something...
	}
}

The WeatherScreen class now receives updates from the various services by subscribing for these updates/events on the bus. Otto results in less classes having to be created and less code concerned with connecting your components up, allowing the existing classes to focus on performing core functions.

The above was just one example of how Otto can reduce the complexity surrounding communications/connections in your application. Coupling is reduced but strongly typed event production/subscription is still maintained.
 
I’ve created an OttoSample Android project on GitHub that provides a simple demonstration of how the Otto event bus can be used to communicate an object between two fragments. Please note that this project also makes use of the Android Annotations framework for object/view dependency injection; I plan to discuss and provide feedback on this framework in the near future.

Defensive null checking

Something I’ve often come across – and been guilty of myself – is the habit of programming in an overly defensive manner, specifically with regard to null checking of parameters. When writing a new function or method, I’ve often found myself immediately defending against null parameters, without even taking the time to think through the implications or what it even means. Such an example of code is as follows:

public String getFormattedDateString(String dateString, String dateFormat, String newDateFormat)
	{
		// Check for invalid arguments
		if (dateString == null || dateFormat == null || newDateFormat == null)
		{
			return null;
		}

		...
	}

At first glance, you might think to yourself that this code is reasonable; if null is provided as an argument, then how is it bad practice to simply return null back in this case? However, if you start to ask yourself certain questions about what that means in terms of the function’s purpose, you might reconsider:

  • Is the method for public use or purely for internal use?

This is significant. I feel if a method is simply for internal use by you or your team and does not form part of some public module/API, there is no need to be overly defensive in terms of validating against nulls. If you own the method and understand the internals, you are fully aware of what it expects as input and thus know what to provide; it’s very different to the case where your method is open for public abuse.

  • Does the method signature suggest that the result is viable?

In our example, the method’s purpose is to return a formatted date and states very explicit requirements: you need to provide a suitable date along with its current format and a new format to use. This isn’t a search function where a not found (null) result may be expected, but rather a function where a valid result is expected provided the input is itself valid.

  • If an argument is invalid and you handle it, what does the result communicate to the caller?

In our case, what does returning null communicate to the caller? In some cases if you explicitly document that null is a possible result, the caller can manage this and deal with it accordingly; however, in a lot of cases where null shouldn’t be a suitable result, all the null does is delay a likely null pointer exception (NPE). And this is bad. I’m of the opinion that failing fast is good… it allows one to narrow down the bad code faster and prevents any subsequent errors from obscuring the original cause.

Looking at our example further, one might think that simply throwing an illegal argument exception might be the best bet.

public String getFormattedDateString(String dateString, String dateFormat, String newDateFormat)
	{
		// Check for invalid arguments
		if (dateString == null || dateFormat == null || newDateFormat == null)
		{
			throw new IllegalArgumentException("Please provide valid date, current format and new format strings." );
		}

		...
	}

Whilst I agree that this is a better solution, ask yourself: is throwing this exception more accurate than just allowing the NPE to happen in the first place? I think the illegal argument exception would be more appropriate if a given argument didn’t fit a requirement (such as an invalid date format). In our particular case, however, I feel unless you are going to return/throw something more useful than the NPE, just allow it to bubble up as it presents exactly what has happened.

One other benefit of avoiding this type of defensive programming is the reduction in code clutter which will ultimately help with readability as well as maintenance. Obviously, this post presents just one example and may not necessarily be applicable for all situations. Nonetheless, food for thought.