Archive for November, 2012

Node.ACS Tutorial 1: PixGrid photo uploader

Friday, November 30th, 2012

After launching the Node.ACS developer preview 2 last week, we are excited to share with you some real examples of how to write a kickass Node.ACS app that connects to ACS as the data backend. We’ll be sharing several more examples in the coming weeks .

Today I want to walk through a sample Node.ACS app called PixGrid which lets users signup, login, upload and view photos from a web browser. It uses ACS as the data backend to store user data and photos. You can download the source code from Github.

PixGrid is built on Node.ACS’s easy to use MVC Framework. In this app, the M(model) is ACS. We want to let ACS handle all the data storage and only focus on the application logic and view in the Node.ACS part.

config.json

This is one of the entry points of Node.ACS MVC framework projects. This file defines all the routing and filtering logic for the app.

PixGrid Routes

  • Signup
    • { “path”: “/signup”, “method”: “get”, “callback”: “application#signup” }
      This method renders the signup page
    • { “path”: “/signup”, “method”: “post”, “callback”: “user#signup” }
      This method performs the actual signup with ACS
  • Login
    • { “path”: “/login”, “method”: “POST”, “callback”: “session#login” }
      This method performs actual login action with ACS
    • { “path”: “/login”, “method”: “GET”, “callback”: “application#login” }
      This method renders the login page
  • Logout
    • { “path”: “/logout”, “method”: “get”, “callback”: “session#logout” }
      This method performs a call to ACS to logout a user
  • Photo view (query)
    •  { “path”: “/”, “method”: “GET”, “callback”: “application#index” }
      Display login page if a user is not logged in, otherwise, display photos uploaded by the user
  • Photo create
    • { “path”: “/photos/create”, “method”: “post”, “callback”: “photos#_create” }
      Upload a photo to ACS by selecting a photo file
    • { “path”: “/photos/create.json”, “method”: “post”, “callback”: “photos#_create_json” }
      Upload a photo to ACS by ajax drag and drop (only works on Chrome and Firefox)
  • Photo delete
    •  { “path”: “/photos/:id/delete”, “method”: “get”, “callback”: “photos#_destroy” }
      Delete a photo from ACS
  • Page not found
    • { “path”: “*”, “method”: “get”, “callback”: “application#page_not_found” }
      Render a page not found for everything else

 

PixGrid Filter

In PixGrid, most pages require a user to be logged in, so we put a checkUserSession filter to all pages

  • { “path”: “/”, “callback”: “session_filter#checkUserSession” }
    Inside the checkUserSession method, it bypasses /login, /logout and /signup

app.js

app.js is another entry point of Node.ACS MVC framework projects. It initializes the ACS and configures express, which is included in the MVC project by default. Please make sure to update the following line in app.js to fill in your own ACS oauth key and secret.

ACS.init('OAUTH_KEY', 'OAUTH_SECRET_KEY');

ACS user sessions

When writing apps for devices,  it is common to keep user specific information on the device and use it later because only one user can use your app at a time, however, the same code will not work well if it is running on a server because the code would be shared by multiple users.

Use photo upload as an example. If you save an uploaded file to a temp file on your Node.ACS server before sending it to ACS, you need to make sure the filename is unique for each transaction so they won’t get overwritten. For example, if user A uploads a photo to your Node.ACS server, your code stores it as photo.tmp, before the server gets a chance to send this photo to ACS, user B uploads another photo and your code will overwrite user A’s photo.tmp if you choose  to use the same tmp filename.  Check out photo.js method _create_json to see how it handles a file drag and dropped by AJAX calls.

The same goes to ACS user sessions, it is tempting to store an ACS user session on Node.ACS server for subsequent calls. But this session will get overwritten when another user logs in to ACS through the same Node.ACS server. That’s why ACS module for Node.ACS provides additional parameters (req,res) to let you pass through a user session cookie without the need to store it on the server.

ACS.Users.login({
    login: req.body.un,
    password: req.body.pw
  }, function(data) {
     // handling login callback
  }, req, res);
}

It is important to pass the req and res to ACS library so that it will pass along or set the cookies if needed. In the login case, it will set the ACS server returned cookie in res which will be passed back to your device. Most device handles cookies automatically so you don’t need to do anything extra on the device.

Subsequently, the photo upload call will take the cookies stored passed along by the device to ACS.

ACS.Photos.create(data, function(e) {
    if(e.success && e.success === true){
      req.session.flash = {msg:"Successfully create a photo #"+e.photos[0].id, r:0};
      res.redirect('/');
    }else{
      req.session.flash = {msg:e.message, r:0};
      res.redirect('/');
    }
  }, req, res);

As long as you keep this key difference in mind, you can use almost the same code that communicates with ACS in both Titanium and Node.ACS.

Please use Node.ACS google group if you have any questions.

RIM: There is No Better Time – Carpe Diem Devs

Thursday, November 29th, 2012

Guest contributed article by Alec Saunders, VP, Developer Relations & Ecosystems, Research In Motion

We recently announced a partnership with Appcelerator that includes Titanium support for our upcoming BlackBerry 10 platform, as well as an opportunity for developers to receive BlackBerry 10 Dev Alpha, and Appcelerator Cloud Services (ACS) for free. How do you take advantage of this offer? Simple. Build a BlackBerry 10 app.

I don’t build BlackBerry 10 apps, you say. I say, Why not? There’s never been a better time for a developer who wants commercial success for their apps.

And yes, I’ve heard it all before – that BlackBerry is a dinosaur, that it’s hard to develop for, that people aren’t using BlackBerry smartphones, that there are no apps on BlackBerry. It’s not easy to admit this, but there are elements of truth to these statements… or there were.

It is truly amazing the difference that a year can make.

I took over the reins of the BlackBerry Developer Relations team just over a year ago. At that time, my new team had a meeting to talk about where the developer ecosystem on BlackBerry needed to go. This team was chomping at the bit to start changing the world of BlackBerry development.

And we have. Make no mistake – this is not the BlackBerry platform of two years ago. We had our own list of must-dos to save this platform, but we went to developers and asked them what they needed to get building, and, more importantly, what would entice them to a platform.

We started building out partnerships with open source leaders. We placed our WebWorks and Ripple Emulator platforms on GitHub. We embraced a new native development platform. Gone are the days of native development for BlackBerry in Java. We are now a C/C++ native environment on both BlackBerry PlayBook today, and BlackBerry 10 when it launches in January, 2013.

We partnered with gaming frameworks to help developers port games and content quickly, including Marmalade and Unity. We even opened BlackBerry PlayBook and BlackBerry 10 to Android developers with our Android Runtime and developer tools, so developers could port Android apps in minutes.

When we asked developers what they wanted, they told us a market opportunity – at last count in September, we had 80 million customers downloading almost 180 million apps each month. We have a brand new platform launching that brings a first-to-market advantage that is unrivalled in this crowded app marketplace.

Developers said they wanted hardware to test – we shipped testing devices so they could start building their BlackBerry 10 apps months ahead of launch. They asked for road map information on our tools – we launched arrival boards that show status and timing of tools, and even drill down to API-level information.

Developers told us that they wanted to start making money – regularly. We support carrier billing with over 50 carrier partners in our application store, BlackBerry World. BlackBerry developers make more than 40% more than Android developers per app per month, according to Vision Mobile’s Developer economics Study, 2012.

We are uber confident that developers will make money on BlackBerry 10. So confident, in fact, that we have introduced a 10k commitment to developers. If you build an approved BlackBerry 10 application, you could qualify for a bump up on your app revenue to $10,000. Conditions do apply.

So, we are partnering with Appcelerator to not only have support for BlackBerry 10 by a platform you already know and trust, but also to provide cost-saving incentives to develop for BlackBerry 10. We are committed to developer success and will put our money where our mouth is to the tune of $10,000. We have formed partnerships to allow for simpler porting. We support open source in a way I would argue outshines all our competitors. We have tools and frameworks for C/C++, HTML5, Adobe AIR and Android. And we have fans and loyal customers clamoring for information about our upcoming launch of BlackBerry 10.

When you do not give an opportunity like this a try, you sell your own business short. I guarantee this is a different BlackBerry and a different ecosystem. Follow me at @asaunders. Let’s start this conversation.

Read the RIM/Appcelerator joint press release about mobile developer incentive programs.

Introducing the Titanium Code Processor

Wednesday, November 21st, 2012

Today we’re here to talk about an exciting new tool being integrated with the Titanium family of products: the Titanium Code Processor. We’re always striving to help you generate optimal code and kickass mobile apps, so we’re delivering the Code Processor to perform in-depth dynamic analysis of your Titanium Mobile projects to optimize your code and help reduce errors. The Code Processor performs various types of error checking, code conformance, and optimizations. It is composed of a core analysis engine that performs generic analysis, and a plugin architecture used to analyze the results from the core analysis engine.

The core analysis engine is a specialized JavaScript engine that has been designed to work in an offline environment. By performing dynamic analysis, instead of the more traditional static analysis, we are able to obtain significantly more accurate results.

The core analysis engine, by itself, can only report runtime exceptions. Plugins tie into the core analysis engine to do things that are of much more value. There are currently 6 analysis plugins, with more on the way:

  • Analysis Coverage: determines how much of a project was analyzed by the code processor. This is useful for finding dead code as well as debugging the Code Processor itself.
  • Require Finder: determines all modules/files required by the project.
  • Titanium Deprecation Finder: throws a warning anytime a deprecated API is used.
  • Titanium Platform Validator: makes sure that all references to platform specific APIs are not referenced by the wrong platforms and throws an error if they are used incorrectly.
  • Titanium API Usage Finder: finds all Titanium APIs used by the project.
  • Titanium Include Finder: determines all files Ti.include()’d by the project.

To show the power of the code processor, consider the following two buggy files:
app.js:

var foo = require('foo');
if (foo.run(Ti.Platform.osname)) {
	a();
} else {
	b();
}

foo.js:

module.exports.run = function (platform) {
	if (platform === 'iphone') {
		return Ti.Platform.Android.API_LEVEL;
	} else {
		return Ti.UI.iPhone.AnimationStyle.CURL_DOWN;
	}
};

The code processor, when run with exception recovery enabled and for iphone, gives the following results:

{
	"errors": [
		{
			"name": "recoveredFromException",
			"description": "An exception was thrown but not caught: Cannot dereference a of undefined",
			"data": {
				"description": "Uncaught exception",
				"exception": {
					"className": "ReferenceError",
					"extensible": true,
					"type": "Object"
				}
			},
			"file": "/Users/bhughes/Work/workspace/CodeProcessorTests/Resources/app.js",
			"line": 3,
			"column": 2
		},
		{
			"name": "recoveredFromException",
			"description": "An exception was thrown but not caught: Cannot dereference b of undefined",
			"data": {
				"description": "Uncaught exception",
				"exception": {
					"className": "ReferenceError",
					"extensible": true,
					"type": "Object"
				}
			},
			"file": "/Users/bhughes/Work/workspace/CodeProcessorTests/Resources/app.js",
			"line": 5,
			"column": 2
		}
	],
	"warnings": [
		{
			"name": "invalidPlatformReferenced",
			"description": "Property \"Titanium.Platform.Android\" is not supported on iphone",
			"data": {
				"property": "Titanium.Platform.Android",
				"platform": "iphone"
			},
			"file": "/Users/bhughes/Work/workspace/CodeProcessorTests/Resources/foo.js",
			"line": 3,
			"column": 10
		}
	],
	"plugins": {
		"analysis-coverage": {
			"details": {
				"/Users/bhughes/Work/workspace/CodeProcessorTests/Resources/app.js": {
					"numNodesVisited": 20,
					"numTotalNodes": 20
				},
				"/Users/bhughes/Work/workspace/CodeProcessorTests/Resources/foo.js": {
					"numNodesVisited": 17,
					"numTotalNodes": 24
				}
			},
			"numNodesVisited": 37,
			"numTotalNodes": 44
		},
		"require-finder": {
			"resolved": [
				{
					"name": "requireResolved",
					"description": "The require path \"/Users/bhughes/Work/workspace/CodeProcessorTests/Resources/foo.js\" was resolved",
					"data": {
						"name": "/Users/bhughes/Work/workspace/CodeProcessorTests/Resources/foo.js"
					},
					"file": "/Users/bhughes/Work/workspace/CodeProcessorTests/Resources/app.js",
					"line": 1,
					"column": 11
				}
			],
			"unresolved": [],
			"missing": []
		},
		"ti-api-platform-validator": {
			"Titanium.Platform.Android": 1
		},
		"ti-api-usage-finder": {
			"Titanium.Platform": 2,
			"Titanium.Platform.osname": 1,
			"Titanium.Platform.Android": 1
		}
	}
}

Here we see that the Code Processor correctly identified that Ti.Platform.Android was being invalidly accessed when compiled for iphone. But what happened next? This would normally throw an exception, but since we have exception recovery enabled, it returns an “unknown” value. Since the code processor doesn’t know if it’s truthy or falsey, it evaluates both branches of the if statement, hence the two exceptions listed for a and b being unknown identifiers.

Sound interesting? To start experimenting with the Code Processor, make sure you have the Titanium CLI installed and then install the code processor using npm:

[sudo] npm install -g titanium-code-processor

To run the code processor:

titanium-code-processor -o [platform] [path-to-project]

For more information and advanced usage options, check out the Code Processor on GitHub. Since this product is still beta, we could really use your help! If you find any problems with the code processor, please let us know at the CLI Google Group. There is also a reporting mechanism built into the code processor itself. By adding the -r flag, the results will be uploaded to ACS for us to review. You can also use the -m flag to add a message to the report.

Update: The command usage information in this blog post is outdated. Please visit the titanium-code-processor homepage on GitHub for the most up-to-date information.

Node.ACS Developer Preview 2 is now available

Tuesday, November 20th, 2012

I am thrilled to announce the availability of the second Node.ACS developer preview. Using Node.ACS allows you to create and publish Node.js applications to the cloud. You can create custom services that extend the functionality of ACS or simply host your existing Node.js applications on the Appcelerator Cloud. Node.ACS is fully integrated with Titanium and ACS, simplifying the development of your mobile applications server side code.

The 1st developer preview was released in October and we received great feedback. We listened to your responses and made some changes.  We’ve added several important features and resources that you requested. Specifically:

  • Node.ACS MVC framework – We heard that developing Node.js applications was challenging. Therefore, we’ve added an easy to use MVC framework designed to increase your productivity when creating Node.js applications. The Node.ACS MVC framework supports all the standard Node.js functionality
  • Support for out of box Node.js applications – Are you using your own web framework? Now you can use Node.ACS to run any Node.js application on our Node.ACS cloud
  • Clearer Error Logs – We’ve added syntax errors and runtime exceptions in the logs to help you understand where your app fails
  • New Accesslog command – Using the new accesslog command you can retrieve logs detailing the usage of your application
  • Improved documentation and sample code

 

Getting started with Node.ACS

As part of this developer preview, we put together a quickstart guide taking you through setting up your environment and creating a simple Node.ACS app. Access it here to get started and find out more about Node.ACS.

More resources

  • To use Node.ACS with Titanium Studio, download the latest version of studio with Node.ACS integration and check out the Docs.
  • To learn how to port your existing Node.js application over to Node.ACS cloud, please follow these steps.
  • Check the complete Node.ACS CLI documentation here
  • View sample Node.ACS apps here

 

Porting from previous Node.ACS releases

This is a major upgrade from last Node.ACS Developer Preview, if you already have an app that is running in the old preview Node.ACS cloud, you will need to rewrite parts of your app to make it work in the new Developer Preview Node.ACS app. Please post questions at Node.ACS google group if you need help migrating your apps.

What’s next

This release contains many features, and there are many more to come. Support of background jobs and cron jobs, more improvements in the Studio integration, the Node.ACS CLI, error reporting, analytics and of course more sample apps showcasing the capabilities of Node.ACS.

Please continue using Node.ACS google group to ask questions and get support. We are looking forward to your feedback!

Titanium Studio/SDK Beta 2 Now Available

Monday, November 19th, 2012

Today we release the second beta of the newest version of our Titanium platform–SDK and Studio 3.0.0. This version includes several additional features as well as bug fixes uncovered during our (and your) testing. Read on below, and for full information, please see the release notes.

This release includes several new features related to the Android action bar.

  • TIMOB-11601 Android: Expose ActionBar methods.
  • TIMOB-11602 Android: Expose activity.invalidateOptionsMenu to allow changing action items in Android 3.0 and above.

Fixed since 3.0 Beta 1

  • TIMOB-6891 Android: Tab’s window property is null if set via creation arguments.
  • TIMOB-6906 Tooling: tiapp.xml – line breaks in description field break compilation.
  • TIMOB-10363 Android: Picker “add” method is dead slow
  • TIMOB-11525 Android: Relative path for Window URL does not work on 3_0_X.
  • TIMOB-11585 CLI: Error messaging is showing undefined for SDK version.
  • TIMOB-11598 CLI: iOS: generated xcode project cannot find “node”.
  • TIMOB-11599 CLI: Using XCode to run app on device won’t work.
  • TIMOB-11664 Android: TabGroup: Tabgroup focus event fired twice on application launch and one of those with source as undefined. This was a regression in 3.0.
  • TIMOB-11678 CLI: iOS: iPad Simulator launches as iPhone Simulator.
  • TIMOB-11685 iOS: Packaging – Packaged application logs messages in Xcode console. This was a regression occurring in Release 3.0 and 2.1.3.
  • TIMOB-11710 CLI build failure reason is only available when tracing is on.
  • TIMOB-11751 Android: HTTPClient.onreadystatechange not dispatched. This was a regression in 3.0.

Note: This is a beta release, and as such may contain regressions or other issues. Please do not use it in production, and keep backups of all important projects and data. We will follow with a release candidate in the coming weeks. If you find an issue, please report it in JIRA with a reproducible test case.

How to Update

These are links to continuous integration builds. To install them, choose “Help Menu > Install Specific Titanium SDK…” from inside Titanium Studio.

To update Studio, please visit http://preview.appcelerator.com and follow the instructions to update to the RC stream, or to download a new install.

New Features in Titanium SDK 3.0.0

The docs are all available at: http://docs.appcelerator.com/titanium/3.0/

As a reminder, some of the new features coming in SDK Platform 3.0:

  • On-Device Debugging
  • Alloy Framework
  • Titanium Command-Line Interface
  • Event Bubbling API Changes
  • Android Action Bar Support
  • Accessibility Features

New Features in Titanium Studio 3.0.0

One of the major differences with version 3.0 of the Titanium SDK is that a number of projects come as node modules. Studio will look for a Node.js installation on your system. If it does not find it, it will install it, and then prompt you to install the necessary modules via NPM.

  • Performance Improvements
  • Alloy Integration
  • Node.ACS Integration
  • On-Device Debugging
  • Deprecation Warnings