Archive for the ‘Tutorials’ Category

Cappuccino Training Course: iDeveloper TV

Wednesday, October 19th, 2011

I’ve been a big fan of Cappuccino since late 2009 and have written and spoken about it pretty extensively. This past July I went to sunny Tetbury, UK to record a video course entitled “Cappuccino for Cocoa Developers.” Here’s some background on how the course came into being…

In addition to being a tony little country village where Prince Charles has one of his castles, Tetbury is famous for being the home town of iDeveloperTV, a company much loved by indie Mac and iOS developers for putting on NSConference, along with the extensive library of video courses and podcasts it has produced over the years. This past Spring, Steve “Scotty” Scotty invited me to give a presentation on Cappuccino at NSConference in the UK. It was extremely well-received, so I reprised the talk at the first CappCon in San Francisco this past Summer.

My goal for both talks was to show existing Cocoa developers how they can leverage their existing skills to craft desktop-caliber web-apps. In the course of preparing for these presentations, I ended up developing a series of carefully-designed tutorial apps, designed to feel comfortable to Cocoa developers while highlighting some web-specific architectural considerations.

These tutorial applications thus formed the basis of the 4 hour course. We shot the video against a white background so that the “talking-head” video could be mixed-in with the screen capture from my laptop as you see here:

The net effect is quite like having your own personal trainer. Scotty’s role is to make sure that I highlighted the points that may not be obvious to first-time learners.


The video is delivered in high-quality, DRM-free H.264 video that you download to your machine. Sync it to your iPad if you wish, then watch it in bed before dreaming of Cappuccino. The resolution lets you clearly read the code while listening to the discussion. Work along with the same source code shown in the video, adapt it to your needs, then build something meaningful to you. Since data persistence in web-apps is a major consideration, I’ve even included the source code for a simple RESTful Web Service written in Ruby on Rails so you can see how things work end-to-end.

I’m extremely proud of the work I did in creating this course, and I think Dave at iDeveloper TV did a bang-up job with the editing. Scotty has been kind enough to release the course at the exceptional price of US $29.99 in order to put in reach of everyone. Complete details can be found here:

http://ideveloper.tv/video/cappuccinocourse.html

I hope you enjoy the course. Feedback is greatly appreciated. Hopefully, I’ll have the chance to make some additional courseware in the future.

Cappuccino Casts

Saturday, February 7th, 2009

Thomas Balthazar, who’s been doing the recent “This Week in Edge Cappuccino” series (read this week’s post), also started a new site to host screencasts of Cappuccino & Objective-J tutorials. So far he’s created a screencast for the starter tutorial

We’re all looking forward to seeing more screencasts on the site, and if you want to contribute your own screencast, get in touch with Thomas and he’ll add it to the site. Thanks Thomas!

Tutorial on Adding Undo to Your Cappuccino Application Published on ThinkVitamin

Thursday, November 13th, 2008

ThinkVitamin.com is featuring an article by Francisco that goes through the process of adding undo/redo support to an existing application. It uses a “furniture layout” application as the model, and goes through all the steps necessary to make user actions undoable.

This is a great demonstration of one of the powerful built-in features in Cappuccino, and a good read for anyone building an application in Cappuccino. Undo support is one of those features that goes a long way in making your application more enjoyable to use, and customers will love you for it.

So go checkout the tutorial, then get started adding undo support to your own applications!

Getting Started With Cappuccino and Ruby on Rails

Tuesday, November 11th, 2008

Cappuccino is completely server agnostic, meaning Cappuccino applications can be served using any HTTP server (for example Apache, lighttpd, Microsoft IIS, etc) and can communicate with any server side technology over HTTP (Ruby on Rails, Django, PHP, ASP, Java, CouchDB, etc). This lets you choose your server-side components based on whatever criteria is important to you (experience, existing infrastructure, etc).

That said, many people have asked for examples of using Cappuccino with various server side technologies, especially Ruby on Rails. Since Cappuccino is server agnostic, it turns out to be very simple to get started.

Setting Up a Project

The first step is to create your Rails project using the standard “rails appname” command:

rails appname
cd appname

Then create a new Cappuccino project in a temporary directory, either using the “steam create” command, or by downloading the “Starter Package”. Move the contents of the Cappuccino project to the Rails application’s “public” directory. Here’s an example using “steam create” (which will overwrite the default index.html):

steam create temp
mv temp/* public/.
rmdir temp

That’s it! Start the Rails webserver using “script/server”. Point your browser to http://localhost:3000/ and you should see the “hello world” Cappuccino application.

Exposing the Data

This alone isn’t particularly interesting. For Rails to be useful in conjunction with Cappuccino you’ll want to be able to transfer data between them. Rails makes this very easy.

Rails offers built in support for two common data exchange formats: JSON and XML. Of the two, JSON is typically prefered in Cappuccino. To output a Ruby data structure as JSON, simply call “render :json => object” in the controller action:


class TestController < ApplicationController
  def movies
    @movies = Movie.find(:all)
    render :json => @movies
  end
end

This is getting all the “Movie” model objects, and simply serializing the array into JSON.

You can also filter or process the array before serializing it. When an ActiveRecord instance is converted to JSON it is wrapped in an extra object that’s usually uneccessary (i.e. { “movie” : { “title” : “something”, “description” : “a description” }}). Creating a plain Ruby object from each ActiveRecord object prevents this. Additionally, it allows you to perform other processing, such as excluding certain properties. Here we use “map” to convert each ActiveRecord object to a plain Ruby object:


def movies
  @movies = Movie.find(:all).map {|m| { :title => m.title, :description => m.description } }
  render :json => @movies
end

Finally, if for some reason you need to use JSONP (be sure you understand why you need it, and the security implications!), Rails makes it very easy to wrap the JSON in callback:


def hello
	render :json => { :hello => "world" }, :callback => params[:jsoncallback]
end

This example also demonstrates accessing parameters that were passed in, namely the “jsoncallback” parameter.

Getting and Submitting Data From Cappuccino

The typical way to retrieve or submit data from a Cappuccino application is to use CPURLConnection. This is discussed extensively in a previous blog post, and all of it applies to using Cappuccino with Rails.

Scaffolding

In addition to HTML views Rails “scaffolding” also provides simple XML web services. You can also easily add JSON versions similar to the following:


def index
  @movies = Movie.find(:all)

  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render <img src='http://cappuccino.org/discuss/wp-includes/images/smilies/icon_mad.gif' alt=':x' class='wp-smiley' /> ml => @movies }
    format.json  { render :json => @movies }
  end
end

Conclusion

This covers the bare essentials of integrating a Cappuccino application with Rails. There is lots of potential for better Cappuccino integration with ActiveRecord and other server-side data technologies. Please feel free to make suggestions, or implement something and contribute it back!

New Cappuccino Automatic Layout Tutorial

Friday, November 7th, 2008

This new tutorial covers Cappuccino’s powerful system of automatic resizing and repositioning support for creating dynamic layouts easily and quickly.  Proper resizing behavior is an important part of polishing any application, so make sure to check it out!

Cappuccino Tools: “bake”

Wednesday, October 29th, 2008

Note: please check the tools page on the wiki for the latest information on Cappuccino’s tools.

In the final installment of the Cappuccino Tool article series (for now), we cover “bake”, an automatic deployment tool. Writing a Cappuccino application does not require using “bake”, but can help with more advanced deployments.

Introduction

“bake” is somewhat analogous to Capistrano, a deployment tool often used for deploying Ruby on Rails and other applications, but “bake” has several features specifically for deploying Cappuccino applications.

The basic idea behind “bake” is to assemble a complete deployable copy of your application by pulling the pieces from various places (Git, Subversion, and local or remote directories via rsync), building it, packing it up, and deploying it to your server(s).

One key feature of bake is the management of multiple deployments over time, which allows three things: atomic deployments, keeping your client side code (the Cappuccino application) synchronized with your server side code, and enabling aggressive caching on all your static resources (code, images, etc). We’ll see later this is done by putting all the new resources in place, then “swinging” a single file, the index.html with a <base> tag.

“Atomic deployments” means that the deployment is updated to the new version in a single operation, which is either successful or not, nothing in between. Every client loading your application receives either the previous deployment, or the new deployment, but never a mixture of the two.

Keeping client code synchronized with server code is (sometimes) important for making sure users who have already loaded the application can continue using it even after you deploy a new version of the server side code that is incompatible with older versions of the client side code.

Aggressive caching of static resources reduces the load time of Cappuccino applications for repeat useres. This is possible because every resources URL is unique in each deployment, so we can set the “Expires” header far in the future (e.x. ‘Expires “Thu, 15 Apr 2010 20:00:00 GMT”‘). While the actual file name is not unique (for example Objective-J/Objective-J.js), in the deployed application the path will be unique (www.yourserver.com/YourApp/1225273279/Objective-J/Objective-J.js where the version number changes for each deployment)

Summary

The configuration for a bake deployment is specified in a “bakefile”, which is in the JSON format with a structure like the following:

{
	"sources" : [
	    {
	        "type"    : "git",
	        "path"    : "git://github.com/280north/cappuccino.git",
	        "parts"   : [
    	        {
    	            "src"       :   "Objective-J",
    	            "dst"       :   "Frameworks/Objective-J",
    	            "build"     :   "ant -DBuild=BUILD_PATH",
    	            "copyFrom"  :   "Release/Objective-J"
    	        },
	            {
    	            "src"       :   "Foundation",
    	            "dst"       :   "Frameworks/Foundation",
    	            "build"     :   "steam build -c Release -b BUILD_PATH",
    	            "copyFrom"  :   "Release/Foundation"
	            },
        	    {
    	            "src"       :   "AppKit",
    	            "dst"       :   "Frameworks/AppKit",
    	            "build"     :   "steam build -c Release -b BUILD_PATH",
    	            "copyFrom"  :   "Release/AppKit"
        	    }
	        ]
	    },
	    {
	        "type"    : "rsync",
	        "path"    : "/Users/username/projects/NewApplication",
	        "parts"   : [
	            {
    	            "src"       :   "",
    	            "dst"       :   "Blah"
	            }
	        ]
	    },
	    {
	        "type"    : "svn",
	        "path"    : "https://svn.youserver.com/Project/trunk",
	        "parts"   : [
	            {
    	            "src"       :   "subdirectory",
    	            "dst"       :   "Something"
	            }
	        ]
	    }
	],
	"deployments" : [
	    { "host" : "deploy@myserver.com", "path" : "/var/www/mysite/public" }
	],
	"templateVars" : {
        "APPLICATION_NAME" : "My Application",
        "BACKGROUND_COLOR" : "black",
        "TEXT_COLOR" : "black"
	}
}

This bakefile contains three “sources”: a git repository, a local directory, and a svn repository. The git repository is the main Cappuccino git repository, hosted on GitHub. You could replace this with a different branch if you needed a specific version, or even your own if you have one. This source contains three “parts”, Objective-J, AppKit, and Foundation. The “src” specifies where in the checkout the part is located, while “dst” specified where in the final built application it should be placed. You can optionally specify a “build” command, which is run from the specified “src” directory. This command should include the placeholder “BUILD_PATH”, which will be filled in by “bake” with the temporary directory where the build results are placed (equivalent to $STEAM_BUILD for any “steam” commands). Additionally, if you specify a “build” command you also need to specify a “copyFrom” parameter, which tells build the subdirectory of the build directory it should copy the built part from.

Once each piece of the application has been built it is copied to the appropriate subdirectory of a uniquely named (using the current Unix timestamp) “versioned” directory. Rather than deploying this versioned directory directly, it is placed within another directory which contains a special index.html file. This file includes a <base> tag that points to the versioned directory, which causes the browser to treat it as the base for all relative URLs, thus loading the correct version of all resources without requiring the application be located at a unique URL. “bake” will fill in “$VERSION” template variable in the base tag of the template with the correct

Additionally, “bake” will calculate the size of all code which needs to be loaded, in order to provide an accurate loading progress bar. The calculated size is inserted into the template variable “$FILES_TOTAL”. You can also specify other template variables such as “$APPLICATION_NAME”, “$BACKGROUND_COLOR”, and “$TEXT_COLOR” in the bakefile.

If you use your own template, the only required variable is the “$VERSION” one, but you can specify as many custom variables as you wish.

Finally, once the application has been built and assembled, it is optionally run through “press”, then gzipped. If the “–deploy” command line parameter was given then the gzipped application is transmitted to the deployment servers, un-gzipped, and copied to the deployment path using a specific sequence of command to ensure the deployment is atomic:

tar xzf 1225273279.tar.gz
mkdir -p /path/to/deployment
mv 1225273279/1225273279/ /path/to/deployment/1225273279
mv 1225273279/index.html path/to/deployment/index.html
rm "1225273279.tar.gz
rmdir 1225273279
cd /path/to/deployment
ln -nsf 1225273279 Current

(version “1225273279″, deplyoment directory “/path/to/deployment”)

One important thing to note about “bake” is that since the old deployment remains live (but hidden) if you deploy a fix for a security vulnerability you should manually purge all the old deployments from your server. If the change doesn’t introduce any incompatibilities between the server and client, you could set up a rewrite rule to direct all requests to the purged deployments to the latest, which is always symlinked to “Current”.

Conclusion

Once again I should stress that this tool is by no means required for writing a Cappuccino application. It was written to help deploy our production application, 280 Slides, but we have made it available for anyone who has similar deployment requirements. If it doesn’t quite fit your requirements, please feel free to suggest improvements, or even better, make improvements yourself and contribute them back!

Download

Cappuccino and Objective-J are licensed under the LGPL. For more information, see our licensing page.

Copyright © 2008-2011 - 280 North, Inc. Cappuccino and Objective-J are registered Trademarks of 280 North. Logo by Sofa. Hosting by Slicehost.