Migrating Data to FatFractal with Node.js

One of the long term goals that I have for an app I’m working on is to move the backend over to FatFractal. This was not a consideration that I made lightly. Moving from one backend system, no matter if it is homegrown or using BaaS, is a daunting task. Schemas, permissions, number of records, order of operations, migration scripts, etc. Is the juice worth the squeeze? In my case it is. Even after careful evaluation of the pros and cons of staying on the current provider or moving to FatFractal I threw together a proof of concept with sample data. Because the data structure paradigms are so different between the two platforms I wanted to see what the migration effort would be. How would I accommodate for exceptions in the model? What I mean by this is that even if the PoC was successful I knew that we wouldn’t do the migration for several months and that the current provider’s schema would be changed and I didn’t want to have to go back and make large scale changes to my import scripts. We are talking about >50,000 users and ~300,000 object records including static files.

Most of the BaaS providers that I’ve used allow for dynamic schema creation, but generally in the context origination not in migration. Parse does allow for [file importation of data]((http://blog.parse.com/2012/05/22/import-your-csv-data-to-parse/) . Stackmob has pretty cool python script for importing data directly from Parse, but the limitations are important to take note, especially the level of subobjects and large datasets.

Though FatFractal doesn’t have an official migration tool to/from a specific provider, setting up a migration is extremely easy using node.js and their server side js lib. An added benefit was being able to test everything locally, including a production migration run before I ran it against cloud migration.

Mystique is the sample project which has two components. First is the actual FatFractal application and second is the importer. Inside of the Importer directory there are two json files which would represent your data. Obviously you have a lot more when doing a migration of any significant size, but in this sample project I wanted to highlight the functionality that makes migration with FatFractal so easy. The big “aha!” in making all this work is in FatFractal’s Definition Language (FFDL) which allows for objects, collections and properties to be automatically determined at runtime. I don’t have to explicitly define any objects, properties or collections in the FFDL.

Post-migration you can explicitly add object definitions in the FFDL for what has been auto-generated at runtime during the import process… but it’s not required. The app will work perfectly well without your intervention.

You can find the project on GitHub.

Open Source - The Ultimate Community Service

Open Source - A Discussion

Wednesday I spoke at the Chattanooga Technology Council’s luncheon on open source. It was geared toward the “culture” of open source and why it should be considered for larger companies that have traditionally avoided or ignored these as options.

OPEN SOURCE DEVELOPMENT IS ONE OF CHATTANOOGA’S FASTEST GROWING SKILL SETS. PARTLY BECAUSE CHATTANOOGA IS BECOMING A HOT BED FOR START-UP COMPANIES WHO CAN TAKE ADVANTAGE OF THESE FREE PROGRAMMING LANGUAGES, BUT LARGER COMPANIES ARE SEEING THE BENEFIT TOO. THE AUDIENCE WILL BE INTRODUCED TO OPEN SOURCE DEVELOPERS IN THE CHATTANOOGA AREA. THE DEVELOPERS WILL DISCUSS HOW THEY USE OPEN SOURCE TECHNOLOGIES, WHY THEY USE OPEN SOURCE. IF YOUR COMPANY IS USING OPEN SOURCE TECHNOLOGIES WE INVITE YOU TO COME AND MEET THESE DEVELOPERS IN PERSON.

Source: https://www.chattanoogatechnologycouncil.org/event/

I really enjoy these forums because of the town hall type enviornment that allows individuals to provide different insight to questions concerning a topic. My fellow panelists provide amazing thoughts, reflections and advice that is at the core of most open source communities.

The What

I was asked what I defined “open source” as. In the simpliest terms I could think of I defined it as both innovation and progress. I got a few laughs in the crowd, but I further elaborated that “open source” as a concept has been around for 1,000’s of years and without it we would be reinventing the wheel every week. Open source is knowledge. While many of the members in the crowd had never really used or contributed to what we know as open source projects I reminded them that libraries are filled with “open source” projects. Cookbooks, IMHO, are one of the earliest examples of open source repositories. Someone came up with an awesome receipe, published it, you bought, traded it, checked it out from the library, learned from it and more times than not tweaked the receipe for your needs and passed that on.

The follow up question was around how open source projects are benefitting apps or companies outside of startups. I love these types of questions. While 2 out of the 5 examples that I gave are startups that have HUGE user base. I first asked members of the audience who had heard or used Mailchimp. 80% raised their hands….I informed them that the Mailchimp iPad app uses DTCoreText/DTRichTextEditor written by Oliver Dropnick. Next example, who uses Pinterest apps, almost 100% raised their hands…informed them that AFNetworking, (written by Mattt Thompson), powers that app. Finally I pointed out that if you browse the web, buy anything off Amazon or stream any Netflix movies then you should thank the open source community. All of those products/services are built on open source software, and in most cases those companies open source many of their services or they contribute to existing projects.

So basically if you use a computer or browse the internet you have benefited from open source technology.

The Why

One of the final questions was, “Why open source?”. That question always makes smile a bit because it reminds me of the question, “What is the meaning of life?”. It depends, but it is generally ends up with something centered around happiness as it relates to that individual. Why someone should use or contribute to open source varies as much, but at it’s core (IMHO) it is the best example of community service devs participate in by evangelizing and contributing in projects and communities. Open source community participants are passionate about whatever project they are involved in. We don’t care that we aren’t paid. It is one of the last remaining aspects in any career were you do it purely for the “love of the game”. It is the perfect balance between intrensic and externsic reward.

My closing and unapologic remark on the why was because frankly these projects and solutions are better than many of the paid for vendor delievered solutions.

Hypocrite?

One of the best questions, and I expected it, was “Are you being a bit hyprocritiacal regarding open source considering you make your living off developing/supporting a closed system?” There is no question that iOS and MacOS are closed systems, but at their core is open source based technology, the language used for Cocoa/CocoaTouch IS open source and the that surrounds and supports these platforms is one of the largest and thriving that I’ve been apart of, especially considering that iOS has only been in extistance ~5 years.

Community Service

As stated by one of my fellow panelist, open source is the highest form of community service that anyone can participate in if you are in technology, but I would venture that you can apply that same attitude and opprotunity to any field. It is our obligation as technologist to set that example.

Go and play your small part in something big.

Test Drive Evaluation

Test Driven Evaluation

To better explain what Test Drive Evaluation (TDE) is let’s first look at what the principle is based upon…Test Drive Development (TDD)

Source:

Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards. Kent Beck, who is credited with having developed or 'rediscovered' the technique, stated in 2003 that TDD encourages simple designs and inspires confidence.[1]

Test-driven development is related to the test-first programming concepts of extreme programming, begun in 1999,[2] but more recently has created more general interest in its own right.[3]

Programmers also apply the concept to improving and debugging legacy code developed with older techniques.[4]

Emphasis mine

Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards. Kent Beck, who is credited with having developed or ‘rediscovered’ the technique, stated in 2003 that TDD encourages simple designs and inspires confidence.

With the growth, popularity and increased acquisitions of BaaS providers it becomes harder and harder for newcomers to properly evaluate which one will provide the best value added to their application. Please note that I didn’t specify mobile application. While I personally subscribe to the “mobile first” approach…native desktop applications and traditional web applications shouldn’t/can’t be seen as second class citizens, thus BaaS should provide support for those as well.

Myself and many others have written on the pro’s / con’s of the top BaaS players. Unforunately, there hasn’t been a set of standard tests that could be run and give a definitive “pass or fail” result for the features that the providers offered. The KitchenSync project aims to provide the tests for these features.

Everything and the KitchenSync

It doesn’t matter if you’re a developer, project manager or analyst there is never enough time to implement every feature, RTFMs or write POC’s (when evaluating different vendors, technology, etc) for an application. We tend to cut corners, take for face value what is on the brochure or go with a solution just because it was featured as the latest/greatest startup on Techcruch.

For example:

  • What does it take implement object level security?
  • Does the BaaS provide static file / webhosting?
  • Which providers will allow full text searching?
  • How many API calls to it take perform request abc

What is the Best Option?

Antonio Martinez does a great job of summarizing:

Source: http://www.raywenderlich.com/20482/how-to-choose-the-best-backend-provider-for-your-ios-app-parse-vs-stackmob-vs-appcelerator-cloud-and-more

The most important factor here is to evaluate each service’s features and their usefulness to you — and your app! Preconfigured objects might seem attractive, unless your idea of what those objects should be differs from those of the service provider.

Services that offer just “users” along with general purpose objects might initially seem more difficult, until you see that substantial flexibility comes with the user-based approach.

Will you need a support agreement; and should you be paying for phone support? How accessible are the engineers if you need them, and what kind of user community support can you expect?

Take a close look at the documentation. This is one time you should read it thoroughly, even though the sample projects have given you enough to get started! :] The quality, coverage and currency of the documentation will give you a good idea of how committed each company is to your success.

Make yourself aware of the costs you will incur in using the service. This will require you to project your future usage for best case and worst case scenarios. Should you find yourself with 100 million users, will your app generate enough income to pay for the level of service you will require?

If your app is going to require a paid plan from the start but it flops, can you afford that? Some services require you to contact sales before you know what these costs will be; don’t skip this step!

Doing a search for the name of your service on discussion boards might expose interesting bits of information you might not have found otherwise. If you get no hits at all, how popular is the service — and what are the chances it will be around in six months? If all the hits say “it’s awesome” that might be a good indication – but pay attention to the negative comments as well!

You can arrive to most of the answers just by reading the documenation, but where the 1’s and 0’s meet the compiler is at implementation. Enter the KitchenSync project.

Even with my own evaluations and recommendations I wanted to give developers, analysts and just the curious, a set of common unit tests to run against each of the providers so that informed decisions could be made with the utmost transparency, while providiing a forum for feedback, additions and bug fixes.

All the tests are open for anyone to use for your own evaluations - just download and run them. In addition, as mentioned above, anyone is welcome to join the party - all enhancements, corrections and suggestions are welcome. There are a number of additional vendors as well - and I invite them, or any developers familiar with them to contribute implementations for them as well and I will be happy to add them to the report as time permits or I can get to them.

You Forgot About Feature ‘X’ and Provider ‘CDW’

No, I didn’t. There had to be a version 1.0 so I chose the providers that I’ve used (Parse, Stackmob, Kinvey and FatFractal) and a basic set of tests. I will be adding more tests just as quickly as I can write them, but I’m hoping for as many pull-requests as I can get. Specifically for new providers.

Disclaimer

I am not employed by any of the providers nor paid, bribed or coerced into writing this article or performing the tests nor is this an endorsement of my employer. I wrote it because…well…no one else had.

Asynchronous Unit Tests for iOS

Handling Asynchronous Unit Tests

I’ve been following through on my goal of writing more unit tests for my iOS projects. Though there is definitely an upfront cost, the pay off is priceless. I’m by no means an expert on the subject, but with each test_ that is written I become that much more proficient.

If you are new to the subject checkout these articles

What I’m not a fan of is the repeated logic to handle asynchronous logic for my unit tests. Asynchronous code is much more common now due to GCD and blocks; unforunately it isn’t clear as to how to handle it via unit tests. My testing framework of choice is SenTest. There are many others, but I like you stock components and you get the setup for free when starting an Xcode project, but SenTest “assumes” that all the tests return synchronously. What this essentially means is that your tests will finish before your background executed code completes. #notgood

In order to synchronize your asynchronous code you need to interact with the currentRunLoop. By taking this approach you’ll essentially “pause” any other code execution until your block has finished and returned to the main thread.

DRY

With this block I can interact with the currentRunLoop and properly execute my asynchrous tests.

Universal App Template Rewrite

Almost 3 Years Ago

Just when I thought I had a somewhat decent grasp on developing and deploying iOS apps Apple came out with the iPad and threw a whole new element in the mix when it comes to developing.

It was almost three years ago that I published the first blog about my Universal App Template. I was inspired by, at the time, a little tutorial by a guy you might have heard of…Ray Wenderlich). His tutorial really helped me with a project I was working on and get through stumbling blocks. I wanted to provide a set of examples that any iOS developer could refer to that was straightforward and get up and running with creating a universal app in as short of time as possible.

Over the following months I added additional features such as iAd support, tabbar controller and iAd with tabbar support. Since then it is still the most visited article and starred/forked repo that I have.

Bueller, Bueller…

Over the years that followed I got busy and wasn’t able to keep up with the iOS updates, new features requested or bugs. The project was quickly becoming outdated.

I’m happy to say that I’ve carved out sometime to update this project. The plan is to start with the master branch, which is the most basic example, and update it from the ground up. I’ll then move on to the “feature” branches. I’m dropping support for iOS 3.2, 4.x and 5.x. Due to the fact that the iOS upgrades happen so rapidly, thanks to OTA, and iOS 7 is being released in less than a month, this is the perfect time to hit the reset button. The project, as well as, feature branches, will support ARC. I’ve also spent some time cleaning up the code base and removed a lot of duplicated code.

If you still need access to the “old version” I’ve tagged it.

No developer is perfect and I’m sure there are tons of things to improve so please drop me a line or file a bug and I’ll fix it ASAP.

NSValueTransformers: More Than Meets the Eye

Speed Dating

No matter the language dealing with calendars, dates and dateformatters are cumbersome. Even beginners with Cocoa/CocoaTouch learn very quickly that NSDateFormatters are expensive to create. There are various techniques that have been used over the years to improve the speed and efficiency of using NSDateFormatters.

  • Lazy loading
  • Retain the date formatter instance in your class as an attribute
  • Using NSThreadDictionary

No matter which one of these techniques I used I was never really satisified with the overall performance or their ease of use. I needed to be able to go back and forth between dates and their respective string representations in a non repeated manner. writing the same code/logic repeatedly

ISO Love NSValueTransformer

If you aren’t reading NSHipster then you are missing out on some great Objective-C gems. One of my favorites is @mattt’s post about [NSValueTransformer](http://nshipster.com/nsvaluetransformer/).

Of all the Foundation classes, NSValueTransformer is perhaps the one that fared the worst in the shift from OS X to iOS.

But you know what? NSValueTransformer is ripe for a comeback. With a little bit of re-tooling and some recontextualization, this blast from the past could be the next big thing in your application.

After reading through the TransformerKit and the examples, it dawned on me that I could solve my “date” problems using NSValueTransformer. Since TransformerKit already provides an interface that removed all the boilerplate setup for the subclasses I forked the project and got to work.

The 3 features that I wanted to provide were:

  1. The ability to set a default date formatter.
  2. The ability to cache all custom date formatters
  3. Provide thread safety

After a few hours of work I submitted a pull request.

Kiss the Date Goodbye

Request denied.

This is one of the main reasons why I love open source software. Matt not only took the time to point out where my logic was flawed, but offered a better abstract approach and then provided a better technical solution.

I was trying to be all things to all people with what the transformer would handle for you, but in the end transformers should be used to solve a particular issue.

Exposing them as class variables is a good API decision on that count, but introduces shared state to the point of not being particularly useful (e.g. wanting more than one at one time).

Though the pull request was denied, and rightfully so, a new addition was added that provides the functionality that I needed.

Your patch did remind me of one of the reasons I made this library to begin with: converting between ISO 8601 timestamps and NSDates. I’ve added these in c064303.

Now Playing with Spotify and iTunes

When I started to finalize the features for the WhoNote agent app I knew I wanted to give users the ability to choose multiple music sources. Out of the gate the first two choices I wanted to support were iTunes and Spotify. Arguably the most common sources.

Coming from iOS development I had the naive assumption that there would an Cocoa equivelant of the MediaPlayer Framework. There isn’t. I became one sad panda. I saw quite a number of people “get around the problem” by writing AppleScripts and running them from the command line or including the AppleScript(s) in their apps and calling them directly. That would have worked, but there had a be a native way of interacting with iTunes. My use case is quite simple: Listen for track change notifications and upload meta data.

RTFM

When in doubt one should read the manual. Apple has provided an excellent example of how to natively interact with iTunes. Though the subject of ScriptBridging is much broader than just iTunes, the example couldn’t be better.

Needless to say incorporating iTunes support was a breeze.

Playtime with Spotify

Now that I had a native methodolgy to go by adding in Spotify support was just as easy. First I had to generate the header file:

sdef /Applications/Spotify.app | sdp -fh --basename SpotifyClient

Note

I did get the following error message when I ran the above command:

sdp: warning: class “SpotifyClientApplication” redeclared; use instead.

I’m not sure yet if this is bug in the sdp or if I didn’t pass in a correct param, but basically in your generated header file you’ll have a class forwarding delcaration twice.

@class SpotifyClientApplication, SpotifyClientTrack, SpotifyClientApplication;

Just open the file, remove one and you are good to go.

Being a Good Listener

Though I could interact with both services, the functionality that I needed was to listen for state and song changes. Both services “broadcast” this information through NSDistributedNotificationCenter.

iTunes Notification

com.apple.iTunes.playerInfo

2013-04-08 11:12:13.652 WhoNoteMac[7939:303] notification payload: {
Album = "Collide With the Sky";
"Album Artist" = "Pierce the Veil";
"Album Rating" = 0;
"Album Rating Computed" = 1;
Artist = "Pierce the Veil";
"Artwork Count" = 1;
"Disc Count" = 1;
"Disc Number" = 1;
Genre = Alternative;
"Library PersistentID" = 162261630986489880;
Location = "file://localhost/Users/cwiles/Music/iTunes/iTunes%20Media/Music/Pierce%20the%20Veil/Collide%20With%20the%20Sky/07%20Tangled%20In%20the%20Great%20Escape%20(feat.%20Jason%20Butler).m4a";
Name = "Tangled In the Great Escape (feat. Jason Butler)";
PersistentID = "-7678479651277138133";
"Play Count" = 1;
"Play Date" = "2013-04-08 14:24:50 +0000";
"Player State" = Playing;
"Playlist PersistentID" = 1335587615931680054;
"Rating Computed" = 1;
"Skip Count" = 0;
"Store URL" = "itms://itunes.com/album?p=536038964&i=536039373";
"Total Time" = 356893;
"Track Count" = 13;
"Track Number" = 7;
Year = 2012;
}

Spotify Notification

com.spotify.client.PlaybackStateChanged

2013-04-08 11:18:52.679 WhoNoteMac[8053:303] notification payload: {
Album = "In Search Of Solid Ground";
"Album Artist" = Saosin;
Artist = Saosin;
"Disc Number" = 1;
Duration = 215;
"Has Artwork" = 1;
Location = "/Users/cwiles/Music/iTunes/iTunes Media/Music/Saosin/In Search Of Solid Ground/08 The Worst Of Me.m4a";
Name = "The Worst Of Me";
"Play Count" = 0;
"Playback Position" = 0;
"Player State" = Playing;
Popularity = 38;
Starred = 0;
"Track ID" = "spotify:track:1wiIhmcIU1hJWqEKhcaXcp";
"Track Number" = 8;

}

Finally with all the pieces in places I was able to get all the meta information I need to send to the WhoNote backend. While I do wish there was an official Cocoa framework to interact with iTunes; utilizing ScriptBridging does provide a blessed mechanism for interacting with other installed applications.

Example Implementation

Gist of how it looks

Photo Gallery with UICollectionView

UICollectionView of Awesomeness

I’m just going to say it. UICollectionView is the coolest, most useful addition that shipped with iOS6. The obvious solution to use this for is a grid layout, but that is just the tip of the iceberg. You can transform your views to use a circular layout or cover flow style layout, etc. They are extremely configurable, flexible and extensible.

UICollectionView and UICollectionViewController are the perfect balance between UITableView, UITableViewController, UIScrollView and UIPageController.

There are just as many “photo gallery” libraries out there as there apps that use them. Unforunately, I never found one that I was really happy with. I’ve developed a few of my own, but I wasn’t helped with them either. At times they were too complicated and others they weren’t extensive enough.

UICollectionView of awesomeness to the rescue.

For an great introduction to UICollectionView go and checkout this tutorial on Ray Wenderlich’s site.

Recreating iPhone Photo App

The Introducing Collection Views session at last year’s WWDC was absolutely amazing and really showed the infinite possibilities of using UICollectionView to showcase data in fascinating ways. In my opinion, there is no better way to learn something than to actual use it. So I set out to recreate the native iPhone photos app.

Aside from dealing with some of the headaches with the AssetsLibrary library, laying out a grid and the pagination of the large images was elementary. Though this a very simplicstic example I think it demonstrates how quick and efficient these new classes provide. I’ve used this same project as the basis for loading in remote photo datasources and works just as beautifully.

Bryan Hansen has a great tutorial a custom gallery as well.

CWPhotoViewer on Github

Managing Urban Airship Configuration

Pre-flight Checklist

It has been awhile since I’ve used Urban Airship. The last time was before their SimpleGeo acquistiation. However, I’ve been following their progress over the years and admired the hardwork and features that are offered. I’m in the final development stages for EPB’s iOS app and need to incorporate push notifications. UAS was the clear choice.

When I was going through their getting started tutorials there was one aspect that bothered me. There’s an assumption, really a requirement, that you put your applications key/master credentials into a file called AirshipConfig.plist. I didn’t pay too much attention to this when I was using their example, but when it came time to incorporate the library in the app I didn’t like the setup.

Reworking the Flight Plan

I decided that it made better since to break out the sampled AirshipConfig.plist into a Debug and Release versions. I ended up modifying their checkConfig.sh script to look at the current Xcode configuration and copy the appropriate plist as AirshipConfig.plist and add it as Build Phase for the project: `“$SRCROOT/Scripts/checkUASConfig.sh”

Now the appriopate settings are provide to the library without having to keep everything in one config that has to have runtime checks and extract the necessary values.

Final Approach

I keep my plist in a Configurations directory at the toplevel of the $SRCROOT

https://gist.github.com/kwylez/5007475

11995 Minutes of Development

5 Mins is the New 2 Weeks

When I first started my professional corporate development career it seemed that when I sat down with a project manager to go over my estimates, any sprint or milestone that was over two weeks was too long. For reasons, still unbeknownst to me, managers/executives thought that any small project shouldn’t take more than 2 weeks and large projects should only have milestones that didn’t exceed two weeks.

I have longed since moved on from places like that and refuse to be apart of the madness ever again

The previous articles I’ve written about PaaS/BaaS providers highlight that you can get up and running in as little as 5 mins. Most developers will think to themselves:

WOW! I have this really great app idea and can’t wait to get started, but developing will take me weeks if not months. I’ll use provider ABC and be in immersed in my UITableViewControllers by minute 6.

This statement is pretty close to true. 5 mins has become the new standard for the maximum amount of time it should take to get “up and running” with a PaaS/BaaS.

The Other 11995 Minutes

One of the apps I released last year I spent ~200hrs coding (12,000 mins). Getting setup with one of the providers took the advertised 5 mins, but what about the other 11995 minutes…well that was different story. It wasn’t a complete disaster, but as I got deeper into project I hit the maxed out threshold of the features offered. Object relationships, querying, persistance etc. The support I got was extremely responsive. Their developers and I worked on various solutions to my issues, but they couldn’t change the nature of the platform. I had two choices:

  1. Create a hacky workaround
  2. Move off the service

Moving off service wasn’t a realistic option because of the time and effort. It wasn’t like I was using my own service layer classes or model objects. I was locked in to using their object-types. I ended up coming with a nasty hack to get part of what I needed done.

Considerations

Does the backend have the power/flexibility that allows you do the things that makes your app really cool? This is what deserves the considerations.

The Frontend Shouldn’t Drive Your Backend

Convienence is a funny thing. The instant gratification comes a price. Sometimes that price is worth paying, but there are no shortcuts with development. Sooner or later the “coding gods” must have their sacrifice. Having Login/SignupViewControllers is extremely convenient, but that shouldn’t be a deciding factor in selecting which BaaS provider that you go with. The amount of time saved by not having to write a login/signup viewcontroller is lost exponetially by having to write mounds and mounds of client-side code to manage your actual objects.

It Goes on the Server

WIth every product release cycle, it doesn’t matter the company, mobile devices get more RAM, CPU and disk space, but these resources are still limited and have to be shared across, not only your apps, but the system itself. There has been an unforunate trend that has been accepted as “best practice” in that the client (your phone) is executing tasks that should be done on the server.

Source: https://parse.com/tutorials/anypic#model

- (BOOL)shouldUploadImage:(UIImage *)anImage { 
  // Resize the image to be square (what is shown in the preview)  
  UIImage *resizedImage = [anImage resizedImageWithContentMode:UIViewContentModeScaleAspectFit 
                                            bounds:CGSizeMake(560.0f, 560.0f) 
                            interpolationQuality:kCGInterpolationHigh];
  // Create a thumbnail and add a corner radius for use in table views
  UIImage *thumbnailImage = [anImage thumbnailImage:86.0f
                                  transparentBorder:0.0f
                                       cornerRadius:10.0f             
                               interpolationQuality:kCGInterpolationDefault];

  // Get an NSData representation of our images. We use JPEG for the larger image
  // for better compression and PNG for the thumbnail to keep the corner radius transparency
  NSData *imageData = UIImageJPEGRepresentation(resizedImage, 0.8f);
  NSData *thumbnailImageData = UIImageJPEGRepresentation(thumbnailImage, 0.8f);

  if (!imageData || !thumbnailImageData) {    
      return NO;
  }
}

A common use case in illustrating this point is handling image resizing after a user takes a picture with the camera. Let’s take a look at how Parse handles this scenario

This is to improve performance in the activity feed table view where several thumbnail images are displayed simultaneously. As we’ll see in Section 3, the resizing is done on the client side.

While the amount of code written isn’t too much, the device resources that are utilized are done so unecessarily. Most image processing tasks are for the server. By deferring the image manipulation to server you allow yourself for greater flexibility in time to process, future enhancements/tweaks to the processing itself, and you have a much greater pool of resources at your disposal. Finally, there is the tanglible financial savings of not having repeated calls to the API itself.

Client code should be small, fast and focused on UI. Frequently the libraries required for this kind of operation can bloat your app ridiculous amounts.

Let’s look at how this is done with FatFractal:

Server Side Code

var ff  = require('ffef/FatFractal');
var io  = require ('io'); // standard CommonJS module
var fs  = require ('fs'); // standard CommonJS module
var bin = require ('binary'); // standard CommonJS module
var hc  = require ('ringo/httpclient'); // not standardised by CommonJS yet, hence ringo prefix. see http://ringojs.org

var Scalr   = Packages.org.imgscalr.Scalr; // import the Scalr Java package
var ImageIO = Packages.javax.imageio.ImageIO; // import the imageIo Java packages

function WNTimelinePhoto() {

  this.clazz = "WNTimelinePhoto";

  this.countForUser  = 0;
  this.photoInstance = null;

  return this;
}

function resizeImage(picBytes, width, height) {

  var croppedBytes = null;

  /**
   * We need a BufferedImage for the Scalr processing
   * There are ImageIO read methods for InputStream, File and URL. We've got a
   * ByteArray. So let's create a ByteArrayInputStream.
   */

  try {

    var bais = new java.io.ByteArrayInputStream(picBytes);
    var img  = ImageIO.read(bais);

    /**
     * Crop the picture
     */

    var cropped = Scalr.crop(img, width, height);
    var baos    = new java.io.ByteArrayOutputStream();

    ImageIO.write (cropped, 'JPG', baos);

    /**
     * Get the bytes from the ByteArrayOutputStream
     */

    croppedBytes = new bin.ByteArray(baos.toByteArray());

  } catch (e) {}

  return croppedBytes;
}

exports.resizeImages = function () {

  var data                  = ff.getExtensionRequestData();
  var r                        = ff.response();
  var evnt                  = null;
  var finalResponse = '';
  var usr                    = null;
  var photoInstance = null;

  if (data.httpMethod.toLowerCase() !== 'post') {

    r.responseCode  = "405";
    r.statusMessage = "You must use POST method";
    r.mimeType      = "application/json";
    r.result        = JSON.stringify("REJECTED");
    return;
  }

  photoInstance = ff.getObjFromUri(data.httpContent.photoresource);

  if (photoInstance === null) {

    r.responseCode  = "400";
    r.statusMessage = "Photo Instance Error";
    r.mimeType      = "application/json";
    r.result        = JSON.stringify("The photo instance can't be null: (photo ffurl) " + photoInstance.ffUrl);

    return;
  }

  /**
   * Check and make sure the current user owns the image
   */

  if (data.ffUser !== photoInstance.createdBy) {

    r.responseCode  = "403";
    r.statusMessage = "Don't Think So";
    r.mimeType         = "application/json";
    r.result                  = JSON.stringify("Not Authorized");

    return;
  }

  originalImage  =  ff.getBlob("image", photoInstance);

  if (originalImage === null) {

    r.responseCode  = "400";
    r.statusMessage = "Image Request Failure";
    r.mimeType      = "application/json";
    r.result        = JSON.stringify("Image information can't be null: (photo ffurl) " + photoInstance.ffUrl);

    return;
  }

  previewImage   = resizeImage(originalImage, 280, 75);

  if (previewImage === null) {

    r.responseCode  = "400";
    r.statusMessage = "Preview Resize Failed";
    r.mimeType      = "application/json";
    r.result        = JSON.stringify("Preview information can't be null: (photo ffurl) " + photoInstance.ffUrl);

    return;
  }

  thumbnailImage = resizeImage(originalImage, 100, 100);

  if (thumbnailImage === null) {

    r.responseCode  = "400";
    r.statusMessage = "Thumbnail Resize Failed";
    r.mimeType      = "application/json";
    r.result        = JSON.stringify("Thumbnail information can't be null: (photo ffurl) " + photoInstance.ffUrl);

    return;
  }

  ff.saveBlob(photoInstance, 'previewImage', previewImage, 'image/jpeg');
  ff.saveBlob(photoInstance, 'thumbnailImage', thumbnailImage, 'image/jpeg');

  finalResponse = {"instance" : photoInstance, "raw" : data.ffUser};

  r.responseCode  = "200";
  r.statusMessage = "Meta Information";
  r.mimeType      = "application/json";
  r.result        = JSON.stringify(finalResponse);
};

Client

I defined an POST event handler in my FatFractal FFDL file to be executed after the object is created

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

  [self dismissViewControllerAnimated:YES completion:nil];

  [MBProgressHUD showHUDAddedTo:self.view animated:YES];

  UIImage *anImage = [info valueForKey:UIImagePickerControllerEditedImage];

  if (anImage) {

    NSData *imageData = UIImageJPEGRepresentation(anImage, 0.2);

    WNPhoto *photo = [[WNPhoto alloc] init];

    photo.event = self.currentEvent;
    photo.image = imageData;

    [self.ffMgr.ff createObj:photo
                       atUri:userPhotosUri
                  onComplete:^(NSError *err, id obj, NSHTTPURLResponse *httpResponse) {

                    if (err) {

                      WNLog(@"error saving: %@", err);

                      [ADVAlertView showStandardAlert:@"Error Posting Image"
                                          withMessage:[err localizedDescription]];
                    } else {
                     [ADVAlertView showStandardAlert:@“Success”
                                          withMessage:@“Image upload is complete”];
                    }
                  }];
  } else {

    [MBProgressHUD hideHUDForView:self.view animated:YES];

    [ADVAlertView showStandardAlert:NSLocalizedString(@"Error Saving Image", nil)
                        withMessage:NSLocalizedString(@"There was an error saving your picture", nil)];
  }
}

With FatFractal, I’m able to create as many sizes/formats as I want based upon my model without changing any client code. I’m able to set the permissions, specify the types of images I want (PNG, JPEG, etc) in a consistant manner that is scaled and in theory unlimited resources. I have ensured that my data is consistent and complete because it is handled on the backend.

Regardless of the client: desktop browser, mobile browser, Windows mobile, iOS or Android the client code should stay the same, take a picture and upload, and all get consistent image processing results. Often implementing such features is very different on the various devices, writing once saves time and probably a lot of headaches.

Do You Speak Other Languages (Idiomas, Sprog, Lingue)

With any new technology there is always a learning curve. What is best for the developer is when that technology provides you with lots of options. Most developers tend to work on more than one project at time and require more than one language for those projects. This becomes a real pain when you have to have separate accounts to manage from various BaaS providers (because most only offer one, maybe two languages) or worse you have to setup yourself different development enviornments that support each of the various languages. Why shouldn’t you be able to mix and match code from different languages using the same provider.

FatFractal supports all of this out of the box. No additional modules to request or add-on. They are available to through the engine itself. You can mix/match server-side js with Ruby or Rails or Servlets without the headaches of setting up gems, bundler or java class paths. If Ruby is the better choice for your “Movie” model event handlers and server-side js is better for the “Theater” model event handlers/extensions then you make the choice….not the backend provider. A few releases later if you want to write everything with servlets then go ahead. The backend is agnostic and your client code doesn’t change one bit.

FatFractal – Picking the Lock(in)

In my experiences and writing about FatFractal I have championed some of their unique features:

but the one that I haven’t talked about is the fact that you aren’t locked in so tight to their services that you can’t leave it or use it in pieces and parts. For BaaS to become mainstream, it is imperative that the players make it really easy to move to another service. Dalton Caldwell, from App.net, illustrates…though indirectly, what others have done wrong and what FatFractal has been doing from day one.

Imagine a world in which your social data (e.g. messages, photos, videos) was easier to work with. For instance, imagine you could try out a new photo sharing service without having to move all of your photos and social graph.

In this world, your photos are held in a data store controlled by you. If you want to try out a new service, you can seamlessly login and choose to give permission to that service, and the photos that you have granted access to would be immediately available.

This is one benefit of an “unbundled” social service. Unbundling gives the user power to pick the software that best suits their needs, rather than being forced to use the software made by the company that manages their data.

Source: http://blog.app.net/2013/01/28/announcing-the-app-net-file-api/

FatFractal doesn’t lock you into any particular client side technology for your models (HashMaps, Dictionaries, CoreData) nor server side language or technology. You can use their service as a full stack or you could use it, for example, as an extension to your Heroku app.

Using the image resizing example above, let’s assume you have an existing Rails app that you are happy with, but ImageMagick isn’t performing as well as you want and you want to offload the resizing functionality asynchronously, but be notified when it is complete. You could create a simple server extension with FatFractal and accomplish all of that without having to worry about an extened amount of time coding the service layer, security or scalling…no properitary libraries or syntax to write except for the serverside js FF library, but that is for fetching/saving collections from your backend. If you would rather write it in Ruby/Python/Java, etc. well that is your choice. It is “unbundled”.

Parse has done a great job with their 3rd party integrations, but developers rarely use only the functionality out of the box. They want to extend or write something custom. FatFractal is the only BaaS/PaaS that provides what you need to accomplish everything that you need. It is the balance between OOTB features while leveraging custom code, all the well, trying to not reinvent the wheel with every application.

FatFractal: providing an unbundle platform for the other 11995 minutes of development.