# Thursday, 08 July 2010

No, not this Trigger... keep reading...

Trigger development (apologies to Roy Rogers' horse) is not done on a daily basis by a typical Force.com Developer.

In my case, Trigger development is similar to using regular expressions (regex) in that I often rely on documentation and previously developed code examples to refresh my memory, do the coding, then put it aside for several weeks/months.

I decided to create a more fluent Trigger template to address the following challenges and prevent me from repeatedly making the same mistakes:

  • Bulkification best practices not provisioned by the Trigger creation wizard
  • Use of the 7 boolean context variables in code (isInsert, isBefore, etc...) greatly impairs readability and long-term maintainability
  • Trigger.old and Trigger.new collections are not available in certain contexts
  • Asynchronous trigger support not natively built-in

The solution was to create a mega-Trigger that handles all events and delegates them accordingly to an Apex trigger handler class.

You may want to customize this template to your own style. Here are some design considerations and assumptions in this template:

  • Use of traditional event method names on the handler class (OnBeforeInsert, OnAfterInsert)
  • Maps are used where they are most relevant
  • Objects in map collections cannot be modified, however there is nothing in the compiler to prevent you from trying. Remove them whenever not needed.
  • Maps are most useful when triggers modify other records by IDs, so they're included in update and delete triggers
  • Encourage use of asynchronous trigger processing by providing pre-built @future methods.
  • @future methods only support collections of native types. ID is preferred using this style.
  • Avoid use of before/after if not relevant. Example: OnUndelete is simpler than OnAfterUndelete (before undelete is not supported)
  • Provide boolean properties for determining trigger context (Is it a Trigger or VF/WebService call?)
  • There are no return values. Handler methods are assumed to assert validation rules using addError() to prevent commit.

Apex Developers Guide - Triggers
Steve Anderson - Two interesting ways to architect Apex triggers


trigger AccountTrigger on Account (after delete, after insert, after undelete, 
after update, before delete, before insert, before update) {
	AccountTriggerHandler handler = new AccountTriggerHandler(Trigger.isExecuting, Trigger.size);
	if(Trigger.isInsert && Trigger.isBefore){
	else if(Trigger.isInsert && Trigger.isAfter){
	else if(Trigger.isUpdate && Trigger.isBefore){
		handler.OnBeforeUpdate(Trigger.old, Trigger.new, Trigger.newMap);
	else if(Trigger.isUpdate && Trigger.isAfter){
		handler.OnAfterUpdate(Trigger.old, Trigger.new, Trigger.newMap);
	else if(Trigger.isDelete && Trigger.isBefore){
		handler.OnBeforeDelete(Trigger.old, Trigger.oldMap);
	else if(Trigger.isDelete && Trigger.isAfter){
		handler.OnAfterDelete(Trigger.old, Trigger.oldMap);
	else if(Trigger.isUnDelete){


public with sharing class AccountTriggerHandler {
	private boolean m_isExecuting = false;
	private integer BatchSize = 0;
	public AccountTriggerHandler(boolean isExecuting, integer size){
		m_isExecuting = isExecuting;
		BatchSize = size;
	public void OnBeforeInsert(Account[] newAccounts){
		//Example usage
		for(Account newAccount : newAccounts){
			if(newAccount.AnnualRevenue == null){
				newAccount.AnnualRevenue.addError('Missing annual revenue');
	public void OnAfterInsert(Account[] newAccounts){
	@future public static void OnAfterInsertAsync(Set<ID> newAccountIDs){
		//Example usage
		List<Account> newAccounts = [select Id, Name from Account where Id IN :newAccountIDs];
	public void OnBeforeUpdate(Account[] oldAccounts, Account[] updatedAccounts, Map<ID, Account> accountMap){
		//Example Map usage
		Map<ID, Contact> contacts = new Map<ID, Contact>( [select Id, FirstName, LastName, Email from Contact where AccountId IN :accountMap.keySet()] );
	public void OnAfterUpdate(Account[] oldAccounts, Account[] updatedAccounts, Map<ID, Account> accountMap){
	@future public static void OnAfterUpdateAsync(Set<ID> updatedAccountIDs){
		List<Account> updatedAccounts = [select Id, Name from Account where Id IN :updatedAccountIDs];
	public void OnBeforeDelete(Account[] accountsToDelete, Map<ID, Account> accountMap){
	public void OnAfterDelete(Account[] deletedAccounts, Map<ID, Account> accountMap){
	@future public static void OnAfterDeleteAsync(Set<ID> deletedAccountIDs){
	public void OnUndelete(Account[] restoredAccounts){
	public boolean IsTriggerContext{
		get{ return m_isExecuting;}
	public boolean IsVisualforcePageContext{
		get{ return !IsTriggerContext;}
	public boolean IsWebServiceContext{
		get{ return !IsTriggerContext;}
	public boolean IsExecuteAnonymousContext{
		get{ return !IsTriggerContext;}
Thursday, 08 July 2010 14:16:12 (Pacific Daylight Time, UTC-07:00)
# Tuesday, 29 June 2010
There are really only 2 tech blogs that I read; TechCrunch.com and ReadWriteWeb.com (RWW). They both provide balanced coverage of the consumer and enterprise markets while remaining objective. You don't get the sense that site sponsors and advertisers are driving the stories. I admire their integrity.

I've been particularly impressed with RWW's coverage on the cloud and the Internet of Things, so I was absolutely thrilled when Alex Williams ran with a story yesterday about Chatter Bot titled "How to Connect an Office Building to an Activity Stream". Check it out! (A hint on the title of this blog :-) )

Tuesday, 29 June 2010 11:32:15 (Pacific Daylight Time, UTC-07:00)
# Thursday, 24 June 2010

Chatter Developer Challenge / Hackathon 2010 Roundup

The Chatter Developer Challenge sponsored by Salesforce encouraged Developers to create a wide variety of applications that demonstrate the new Salesforce Chatter API.

The challenge culminated in a Hackthon event on June 22nd 2010 at the San Jose Convention Center where prizes were awarded for various applications.

My entry, Chatter Bot, demonstrated the use of Chatter within a Facility Management application that captured physical world events and moved them to the cloud to produce Chatter feed posts.

Chatter Bot is a system comprised of 4 major components:

  • Arduino board with motion and light sensors (C/C++)
  • Proxy Service (Java Processing.org Environment)
  • Salesforce Sites HTTP Listener (Visualforce/Apex)
  • Facility Management App (Force.com database and web forms)
(Source code to all components available at the bottom of this post)

I was elated to learn a few days before the hackathon that Chatter Bot had been selected as a finalist and I was strongly encouraged to attend. So I packed up Chatter Bot to take the 2 hour flight from Portland to San Jose.

It wasn't until I arrived at the airport that it suddenly dawned on me how much Chatter Bot bares a striking resemblance to a poorly assembled explosive device. Apparently the TSA agent handling the X-Ray machine thought so too and I was taken aside for the full bomb sniffing and search routine.

It crossed my mind to add a bit levity to the situation by making some kind of remark, but I quickly assessed that I was probably one misinterpreted comment away from being whisked off in handcuffs to some TSA lockup room. Ironically, I had no problem with security in San Jose coming back. They must be accustomed to these types of devices in Silicon Valley.

Upon arriving in San Jose, I setup Chatter Bot and configured the San Jose Convention Center (SJCC) as a Building Facility (Custom object) to be monitored.

Several assets were created to represent some rooms within the SJCC.

Finally, the Chatter Bot was associated with a particular room (Asset) through an intersection object called AssetSensors that relates a device ID (usually a MAC address) and an Asset.

Within minutes the motion and light sensors were communicating to the cloud via my laptop and reporting on activity in the Hackathon room.

Given the high quality and functionality of fellow competitors apps, such as the very cool Chatter for Android app by Jeff Douglas, and observations from the public voting, I thought Chatter Bot might be a little too "out of the box" to take a prize. It was a genuinely surreal and surprising moment when I learned Chatter Bot received the grand prize.

Thank you Salesforce for hosting such a great event and thank you to the coop-etition for the encouraging exchange of ideas and feedback during the challenge!

Arduino Sensor

//the time when the sensor outputs a low impulse
long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low 
//before we assume all motion has stopped
long unsigned int pause = 5000;

boolean lockLow = true;
boolean takeLowTime;  

int LDR_PIN = 2;    // the analog pin for reading the LDR (Light Dependent Resistor)
int PIR_PIN = 3;    // the digital pin connected to the PIR sensor's output
int LED_PIN = 13;

byte LIGHT_ON    = 1;
byte LIGHT_OFF   = 0;
byte previousLightState  = LIGHT_ON;
int lightLastChangeTimestamp = 0;
unsigned int LIGHT_ON_MINIMUM_THRESHOLD = 1015;
unsigned long lastListStateChange = 0; //Used to de-bounce borderline transitions.

// Messages
int SENSOR_LIGHT  = 2;

void setup(){  
  //PIR initialization
  pinMode(PIR_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(PIR_PIN, LOW);

void loop(){
  if(digitalRead(PIR_PIN) == HIGH){
    digitalWrite(LED_PIN, HIGH);   //the led visualizes the sensors output pin state
      //makes sure we wait for a transition to LOW before any further output is made:
      lockLow = false;
      writeMeasure(SENSOR_MOTION, HIGH);
      digitalWrite(LED_PIN, LOW);   //the led visualizes the sensors output pin state
    takeLowTime = true;

  if(digitalRead(PIR_PIN) == LOW){
    digitalWrite(LED_PIN, LOW);  //the led visualizes the sensors output pin state
      lowIn = millis();          //save the time of the transition from high to LOW
      takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    //if the sensor is low for more than the given pause, 
    //we assume that no more motion is going to happen
    if(!lockLow && millis() - lowIn > pause){
      //makes sure this block of code is only executed again after 
      //a new motion sequence has been detected
      lockLow = true;
      writeMeasure(SENSOR_MOTION, LOW);

boolean InitializeLED(){
  Serial.println("INIT: Initializing LED (should see 3 blinks)... ");
  for(int i=0; i < 3; i++){
    digitalWrite(LED_PIN, HIGH);
    digitalWrite(LED_PIN, LOW);

//the time we give the motion sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 10;

boolean InitializeMotionSensor(){
  //give the sensor some time to calibrate
  Serial.print("INIT: Calibrating motion sensor (this takes about ");
  Serial.print(" seconds) ");
  for(int i = 0; i < calibrationTime; i++){
  Serial.println(" done");
  Serial.println("INIT: SENSOR ACTIVE");

boolean InitializeLightSensor(){
  Serial.print("INIT: Initializing light sensor. Light on threashold set to ");
  Serial.println("INIT: 20 samples follow...");
  for(int i = 0; i < 20; i++){
    int lightLevelValue = analogRead(LDR_PIN);
    Serial.print("INIT: ");

boolean ProcessLightSensor(){
  byte currentState = previousLightState;
  int lightLevelValue = analogRead(LDR_PIN);  // returns value 0-1023. 0=max light. 1,023 means no light detected.
  if(lightLevelValue < LIGHT_ON_MINIMUM_THRESHOLD){
     currentState = LIGHT_ON;
     currentState = LIGHT_OFF;
  if(LightStateHasChanged(currentState) && !LightStateIsBouncing() ){
    previousLightState = currentState; 
    if(currentState == LIGHT_ON){
      writeMeasure(SENSOR_LIGHT, HIGH);
      writeMeasure(SENSOR_LIGHT, LOW);
    lightLastChangeTimestamp = millis();
    return true;
    return false; 

boolean LightStateHasChanged(byte currentState){
   return currentState != previousLightState; 

//De-bounce LDR readings in case light switch is being quickly turned on/off
boolean LightStateIsBouncing(){
   if(millis() - lightLastChangeTimestamp < MIN_TIME_BETWEEN_LIGHT_CHANGES){
      return true; 
      return false; 

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 
char deviceID[ ] = "007DEADBEEF0";
//Format MEASURE|version|DeviceID|Sensor Type|State (on/off)
void writeMeasure(int sensorType, int state){
  if(sensorType == SENSOR_MOTION)
  else if(sensorType == SENSOR_LIGHT)
  if(state == HIGH)
  else if(state == LOW)

Chatter Bot Proxy (Processing.org Environment)

import processing.serial.*;

Serial port;
String buffer = "";

void setup()
    port = new Serial(this, "COM7", 9600);

void draw()
  if(port.available() > 0){
    int inByte = port.read();
    print( char(inByte) );
    if(inByte != 10){ //check newline
      buffer = buffer + char(inByte);
       if(buffer.length() > 1){
          buffer = "";

boolean IsMeasurement(String message){
  return message.indexOf("MEASURE") > -1;

void postToForce(String message){
  String[] results = null;
    URL url= new URL("http://listener-developer-edition.na7.force.com/api/measure?data=" + message);
    URLConnection connection = url.openConnection();

    connection.setRequestProperty("User-Agent",  "Mozilla/5.0 (Processing)" );
    connection.setRequestProperty("Accept",  "text/plain,text/html,application/xhtml+xml,application/xml" );
    connection.setRequestProperty("Accept-Language",  "en-us,en" );
    connection.setRequestProperty("Accept-Charset",  "utf-8" );
    connection.setRequestProperty("Keep-Alive",  "300" );
    connection.setRequestProperty("Connection",  "keep-alive" );
    results = loadStrings(connection.getInputStream());  
  catch (Exception e) // MalformedURL, IO

  if (results != null)
    for(int i=0; i < results.length; i++){
      println( results[i] );

Visualforce Site Chatter Listener

<apex:page controller="measureController" action="{!processRequest}" 
contentType="text/plain; charset=utf-8" showHeader="false" 
standardStylesheets="false" sidebar="false">


public with sharing class measureController {
	public void processRequest(){
    	if(Data != null){
    		system.debug('data= ' + Data);
    private void CreateFeedPosts(){
    	if(AssetDeviceBindings.size() == 0)
    	for(AssetSensor__c binding : AssetDeviceBindings){
	    	FeedPost newFeedPost = new FeedPost();
	    	newFeedPost.parentId = binding.Asset__c;
			newFeedPost.Type = 'TextPost';
	        newFeedPost.Body = FeedPostMessage();
	        insert newFeedPost;
    private string FeedPostMessage(){
    	if(AssetDeviceBindings.size() == 0)
    		return '';
    	if(SensorType == 'motion'){
    		if(State == 'on')
    			return 'Motion detected';
    			return 'Motion stopped';
    	else if(SensorType == 'light'){
    		return 'Lights turned ' + State;
    		return 'Unknown sensor event';
    private List<AssetSensor__c> m_assetSensor = null;
    public List<AssetSensor__c> AssetDeviceBindings{
    		if(m_assetSensor == null){
    			m_assetSensor = new List<AssetSensor__c>();
    			if(DeviceID != null){
    				m_assetSensor = [select Id, Name, Asset__c, DeviceID__c from AssetSensor__c where DeviceID__c=:DeviceID limit 500];
    		return m_assetSensor;
    private integer EXPECTED_MESSAGE_PARTS = 5;
    private integer DATA_MESSAGE_TYPE = 0;
    private integer DATA_VERSION	= 1;
    private integer DATA_DEVICEID	= 2;
    private integer DATA_SENSOR_TYPE= 3;
    private integer DATA_STATE		= 4;
    private List<string> m_dataParts = null;
    public List<string> DataParts{
    		if(m_dataParts == null && Data != null){
    			m_dataParts = Data.split('\\|');
    		return m_dataParts;
    public string Version{
    		if(Data != null && DataParts.size() >= EXPECTED_MESSAGE_PARTS){
    			return DataParts[DATA_VERSION];
    			return null;
    public string DeviceID{
    		if(Data != null && DataParts.size() >= EXPECTED_MESSAGE_PARTS){
    			return DataParts[DATA_DEVICEID];
    			return null;
    public string SensorType{
    		if(Data != null && DataParts.size() >= EXPECTED_MESSAGE_PARTS){
    			return DataParts[DATA_SENSOR_TYPE];
    			return null;
    public string State{
    		if(Data != null && DataParts.size() >= EXPECTED_MESSAGE_PARTS){
    			return DataParts[DATA_STATE];
    			return null;
    private string m_data = null;
    public string Data{
    		if(m_data == null && ApexPages.currentPage().getParameters().get('data') != null){
    			m_data = ApexPages.currentPage().getParameters().get('data');
    		return m_data;
    private string m_result = '';
    public String Result{
    		return 'ok';
    public static testMethod void tests(){
    	Asset testAsset = new Asset();
    	testAsset.Name = 'Test Asset';
    	testAsset.AccountID = [select Id from Account order by CreatedDate desc limit 1].Id;
    	insert testAsset;
    	AssetSensor__c binding = new AssetSensor__c();
    	binding.Name = 'Test Binding';
    	binding.DeviceID__c = '007DEADBEEF9';
    	binding.Asset__c = testAsset.Id;
    	insert binding;
    	measureController controller = new measureController();
    	system.assert(controller.Data == null);
    	system.assert(controller.DataParts == null);
    	system.assert(controller.Version == null);
    	system.assert(controller.DeviceID == null);
    	system.assert(controller.SensorType == null);
    	system.assert(controller.State == null);
    	string TEST_MEASURE = 'MEASURE|v1|007DEADBEEF9|motion|on';
    	ApexPages.currentPage().getParameters().put('data', TEST_MEASURE);
    	controller = new measureController();
    	system.assert(controller.Data == TEST_MEASURE);
    	system.assert(controller.DataParts != null);
    	system.assert(controller.DataParts.size() == 5);
    	system.assert(controller.Version == 'v1');
    	system.assert(controller.DeviceID == '007DEADBEEF9');
    	system.assert(controller.SensorType == 'motion');
    	system.assert(controller.State == 'on');
    	system.assert(controller.AssetDeviceBindings != null);
    	system.assert(controller.AssetDeviceBindings.size() == 1);
    	system.assertEquals('007DEADBEEF9', controller.AssetDeviceBindings[0].DeviceID__c);
    	system.assertEquals(testAsset.Id, controller.AssetDeviceBindings[0].Asset__c);
    	system.assert(controller.Result == 'ok');
Thursday, 24 June 2010 18:03:10 (Pacific Daylight Time, UTC-07:00)
# Monday, 21 June 2010
I'm very happy to announce that Cool Sites was released this weekend. Cool Sites provides a gallery of pre-built page templates, plugins, and sites built on Salesforce Sites.

Basic web content management tools and workflows for creating navigation menus and web pages are included. Check it out! http://www.getcoolsites.com

Monday, 21 June 2010 15:43:39 (Pacific Daylight Time, UTC-07:00)
# Sunday, 13 June 2010

Jazz - A Software Development Methodology

Jazz is a software development methodology for the ongoing creation and improvisation around several small apps distributed on open Internet platforms (the "cloud").

Contemporary tools, languages, and distribution platforms of the 21st century make it feasible for software to be created, delivered, and performed similarly to Jazz music of the 20th century.

Software, like music, may be consumed repeatedly throughout the day by audiences.

Software has become ubiquitous and essential to people's everyday lives.

Audiences increasingly are demanding to know more about the personalities and teams behind their favorite software applications.

What (Apps)
Jazz combos seek to build a repertoire of several small apps, as opposed to developing and supporting one large app. Jazz is most suitable for Developers distributing applications through online stores (such as the Apple App Store, Google Marketplace, or Salesforce AppExchange).

The repertoire should consist of at least 10 apps.

Not all apps are for commercial distribution (such as contributions to open source frameworks and proof of concept apps used for marketing purposes).

Only 1 in 10 apps within the repertoire will achieve any significant amount of notoriety or market adoption.

Who (The Combo)
Apps are initially composed by a single person, which are then rehearsed and performed by combos of up to 5-7 people. Apps are occasionally composed by 2 collaborators.

Apps are consumed by audiences (customers).

Where (Spaces)
Jazz is composed, rehearsed, and performed in 3 distinct "spaces".

Composition and practice are done in solitude (home, coffee shop, the beach) but always connected (anywhere with Internet access)

Rehearsals are done with a group about once per week in public meeting places

Performances are ongoing. They occur both virtually and physically. All audience interactions are performances (this includes app store listings, webinars, support, and customizations)

Jazz is not a 9 to 5 job. However, ongoing performances are typically supported by someone during working hours.

Jazz Developers dedicate at least 3 days per week to uninterrupted work (composition and improvisation) and at least 1 day for group rehearsals (meetings) and audience interactions (support and review of customer feedback).

Compositions may take 1 day or 1 year to write. It should take no more than 2 years to accumulate a repertoire of 10 apps.

Team members are often given "the floor" during performances to lead and improvise within a composition. Improvisations are short creative cycles within the overall structure of a composition.

Each member of a Jazz combo owns and maintains their own instruments (tools) that best support their function within the combo.

Academic mastery of instrument and language are assumed before confidence in composition and improvisation can be achieved.

Jazz combos are unified in language presented to audiences, but individually use languages specific to their instrument or function.

Jazz encourages the sharing, remixing, and reuse of ideas through use of creative commons licenses.

All individuals are given public recognition for their contribution to an app.

Performers may practice up to 10 hours for a 1 hour performance (10:1 ratio of effort, unit tests behind released products).

The best performances are achieved through mastery of instrument, confidence in skills, and relaxation of mind.

The result is more important than the means. Don't over think the process to achieving a good performance.

Improvisations often rely on audience feedback to determine the path of a performance.

The Jazz combo may dynamically adjust composition structure during a performance through subtle communication to support an improvisation that may lead to new discoveries or increased levels of audience feedback and participation.
Sunday, 13 June 2010 13:04:29 (Pacific Daylight Time, UTC-07:00)
# Monday, 07 June 2010

Here's a fun video put together for my Salesforce Chatter Developer Challenge entry.

Monday, 07 June 2010 09:57:05 (Pacific Daylight Time, UTC-07:00)
# Friday, 28 May 2010
A true REST interface with full support for HTTP Verbs, status codes, and URIs is currently not available on the Salesforce.com platform. However, a simple REST-like interface for getting objects can be developed using Salesforce Sites, Visualforce, and Apex.

This example uses a free Developer Edition with a Site named 'api' that uses only 2 Visualforce pages named 'rest' and 'error'. The rest page accepts a single parameter named 'soql', executes the SOQL query, and returns a JSON formatted response.

The error page is also used to generically handle all 40x and 50x errors.

The body of the error page returns a simple JSON message that the api is unavailable.
<apex:page contenttype="application/x-JavaScript; charset=utf-8" 
showheader="false" standardstylesheets="false" sidebar="false">
{"status": 500, "error": "api currently not available"}

The rest Visualforce page (full source at bottom of this post) accepts a SOQL parameter and returns JSON results. To get a list of all Leads with their First and Last names, you'd use the SOQL

select Id, FirstName, LastName from Lead
and pass this query to the REST interface in a GET format such as (example here)

Note that the rest page is defined as the default handler for the site named 'api', so it's not required in the URL.
This simple interface supports any flavor of SOQL, including the WHERE and LIMIT keywords, so you can pass queries like

select Id, FirstName, LastName from Lead where LastName='Smith' limit 20
REST interfaces often assume the unique ID of an object is the last portion of the URL request. This can similarly be achieved with a query like (example here)
select Id, FirstName, LastName from Lead where Id='00QA00000019xkpMAA' limit 1

All of these example queries will only return the Id field by default. To fix this, update the Sites Public Access Settings and grant Read access to the Lead object.

The new URL rewriting feature in Summer 10 provides some additional options the necessary means to implementing a RESTful interface with full support for object URIs and linking.

Visualforce Source Code for rest.page
<apex:page controller="RESTController" action="{!processRequest}" 
contentType="application/x-JavaScript; charset=utf-8" showHeader="false" 
standardStylesheets="false" sidebar="false">
Apex Source Code for RESTController.cls
public with sharing class RESTController {
	public void processRequest(){
    	if( HasError )
    	//Add support for other types of verbs here
    static final string ERROR_MISSING_SOQL_PARAM = 'Bad Request. Missing soql parameter';
    static final string ERROR_SOBJECT_MISSING	 = 'Bad Request. Could not parse SObject name from SOQL';
    static final string ERROR_FROM_MISSING		 = 'Bad request. SOQL missing FROM keyword';
    public void validateRequest(){
    	if(Query == null){
    		errorResponse(400, ERROR_MISSING_SOQL_PARAM);
    	else if(sObjectName == null){
    		//Force a get of object name property.
    		//Detailed error response should already be logged by sObjectName parser
    public boolean HasError = False;
    private void errorResponse(integer errorCode, string errorMessage){
    	JSONResponse.putOpt('status', new JSONObject.value(errorCode));
    	JSONResponse.putOpt('error', new JSONObject.value(errorMessage));
    	HasError = True;
    public void processGetQuery(){
    	Map<String, Schema.SObjectField> fieldMap = Schema.getGlobalDescribe().get(SObjectName).getDescribe().fields.getMap();
    	List<JSONObject.value> objectValues = new List<JSONObject.value>();
    	List<sObject> resultList = Database.query(Query);
    	for(sObject obj : resultList){
    		JSONObject json = new JSONObject();
    		json.putOpt('id', new JSONObject.value( obj.Id ));
    		for(SObjectField field : fieldMap.values() ){
    				string f = field.getDescribe().getName();
    				string v = String.valueOf( obj.get(field) );
    				json.putOpt(f, new JSONObject.value( v ));
    			catch(Exception ex){
    				//Ignore. Field not included in query
			objectValues.add(new JSONObject.value(json));
    	JSONResponse.putOpt('status', new JSONObject.value(200));
    	JSONResponse.putOpt('records', new JSONObject.value(objectValues));
    private string m_query = null;
    public string Query{
    		if(m_query == null && ApexPages.currentPage().getParameters().get('soql') != null){
    			m_query = ApexPages.currentPage().getParameters().get('soql');
    		return m_query;

	static final string SOQL_FROM_TOKEN = 'from ';    
    private string m_sObject = null;
    public string sObjectName{
    		if(m_sObject == null && Query != null){
    			string soql = Query.toLowerCase();
    			integer sObjectStartToken = soql.indexOf(SOQL_FROM_TOKEN);
    			if(sObjectStartToken == -1){
    				errorResponse(400, ERROR_FROM_MISSING);
    				return null;
    			sObjectStartToken += SOQL_FROM_TOKEN.length(); 
    			integer sObjectEndToken = soql.indexOf(' ', sObjectStartToken);
    			if(sObjectEndToken == -1)
    				sObjectEndToken = soql.length();
    			m_sObject = Query.substring(sObjectStartToken, sObjectEndToken);
    			m_sObject = m_sObject.trim();
    			system.debug('m_sObject = ' + m_sObject);
    		return m_sObject;
    private JsonObject m_jsonResponse = null;
    public JSONObject JSONResponse{
    		if(m_jsonResponse == null)
    			m_jsonResponse = new JSONObject();
    		return m_jsonResponse;
		set{ m_jsonResponse = value;}
	public String getJSONResult() {
    	return JSONResponse.valueToString();
	public static testMethod void unitTests(){
		RESTController controller = new RESTController();
		system.assertEquals(True, controller.HasError);
		system.assertEquals(True, controller.JSONResponse.has('status'));
		system.assertEquals(400, controller.JSONResponse.getValue('status').num);
		system.assertEquals(True, controller.JSONResponse.has('error'));
		system.assertEquals(ERROR_MISSING_SOQL_PARAM, controller.JSONResponse.getValue('error').str);
		controller = new RESTController();
		ApexPages.currentPage().getParameters().put('soql', 'select Id fro Lead');
		system.assertEquals(True, controller.HasError);
		system.assertEquals(True, controller.JSONResponse.has('status'));
		system.assertEquals(400, controller.JSONResponse.getValue('status').num);
		system.assertEquals(ERROR_FROM_MISSING, controller.JSONResponse.getValue('error').str);
		controller = new RESTController();
		ApexPages.currentPage().getParameters().put('soql', 'select Id from Lead');
		system.assertEquals(False, controller.HasError);
		system.assertEquals('Lead', controller.sObjectName);
		Lead testLead = new Lead(FirstName = 'test', LastName = 'lead', Company='Bedrock', Email='fred@flintstone.com');
        insert testLead;
        controller = new RESTController();
		ApexPages.currentPage().getParameters().put('soql', 'select Id from Lead where email=\'fred@flintstone.com\'');
		system.assertEquals(False, controller.HasError);
		system.assertEquals('Lead', controller.sObjectName);
		system.assertEquals(True, controller.JSONResponse.has('records'));
Friday, 28 May 2010 12:34:08 (Pacific Daylight Time, UTC-07:00)
# Saturday, 22 May 2010
The Google I/O Developer Conference this past week (May 19-20) was a highly anticipated event for both Google web and mobile Developers alike.

With the exception of Chrome OS, all of the technologies and products on my watch list unveiled new and exciting features that re-affirmed my belief that Google is indeed one of the leading cloud platforms to be embraced by all cloud Developers.

The marriage between the Android mobile OS and Google services is simply outstanding. The new Web Store works seamlessly with mobile devices and actions taken on either the desktop or mobile are immediately reflected on the other device.

Google handed out 2 mobile phones to attendees, a Motorola Droid and a HTC EVO 4G, and I was amazed at the ease and speed of syncing both devices with my existing Google Premier Apps account.

The dilemma I faced was whether to write mobile apps natively for Android apps or use HTML5. Geolocation, games, and apps requiring haptic response will most definitely be better served running natively on Android. General web sites and marketing centric apps written in HTML5 will enjoy the benefits of running cross platform (iPhone, Blackberry, Android) but will lack high end graphics and GPS support (although SVG and Geo Javascript extensions could address both of these in HTML5).

Developing for Google in previous years has been something of a hobby for many Developers, since there were few monetization opportunities outside AdWords and AdSense. Google unveiled several new monetization platforms for both desktop and mobile developers that will make Android very attractive to existing iPhone developers (plus Google doesn't discriminate apps uploaded to their Marketplace).

With 100K Android phone activations per day it's becoming very easy to do the quick math and trust that Google Android is a viable and profitable distribution vehicle.

A considerable amount of time was spent on Google Business during the day 1 keynote. The Google/VMWare partnership mirrored closely what was announced for VMForce just a couple weeks ago, although I think Salesforce did a much better job of helping Developers understand what was being offered via SpringSource. Google is serious about the business market and wants Java apps written on their platform.

I think the most underrated business feature is Google Apps Script. This is a free extension to Google Premier Apps that enables complex workflows between spreadsheets, web forms, email, and calendars. I would highly advise SMBs to use Apps Script for their business needs while larger Enterprises would probably benefit more from the SpringSource business platform.

All demonstration hiccups aside, the Google TV announcement was interesting from a consumer perspective. It was quite amazing to see Google's CEO on stage with the other CEO's associated with the launch (Sony, Best Buy, Intel, Logitech, and Adobe). That was some serious firepower and, if anything, really reaffirmed that Google is pursuing a stratified and open platform in contrast to Apple's closed platform.

On a technical note, I enjoyed spending some time with the Chrome development team during their open "Office Hours". The conversation with them inspired me to download the V8 Javascript engine and brush up on my C++ skills in order to contribute some JSON parsing enhancements I requested.

Most of what I was hoping for in HTML5 support was either previewed at the conference or is scheduled for delivery this year. The V8 engine is in the Android 2.2 Froyo release and we can expect 2010 to be a milestone year for evolving browser technology.

The unedited YouTube video below is a 10 minute walkthrough of the conference floor with both Hardware and Software vendors showing their wares (check out the Salesforce booth around minute 3).

Saturday, 22 May 2010 17:02:22 (Pacific Daylight Time, UTC-07:00)
# Monday, 17 May 2010

I'm getting on a plane tomorrow morning for San Francisco to attend the Google I/O conference. If you're a cloud developer and can only attend 1-2 conferences per year, then this conference should be on your calendar (in addition to Dreamforce).

Even though 90%+ of Google's revenue comes from search advertising, they are much more than a search engine these days. They've effectively leveraged their massively scalable Google File System to develop and host hundreds (if not thousands) of applications that are accessible throughout the world using nothing but a web browser.

Google has realized that the best way to increase revenue is not to push more customers towards Google, but to provide more accessibility to the web itself. You can deploy this somewhat altruistic strategy when you have a 72% market share.

Deploying highspeed fiber networks and launching the open source Android mobile operating system are just a couple examples of Google seeking to further enable access to the cloud on the premise that consumers of these networks/devices will eventually utilize the Google search engine and ads.

To see Android phone sales surpass iPhone in the last quarter is quite an amazing feat given the OS has only been available for about 18 months. Google shipped Motorola Droids to all 4,000 Google I/O attendees (including myself) with 30 days pre-paid access via Verizon. My Google G1 phone now seems archaic in comparison and I can't wait for the 2 year Sprint subscription to expire so I can switch over to Verizon and continue using this Moto Droid (I also recently purchased a Verizon MiFi for roaming cloud access and have been very impressed with their coverage)

Moving contacts and calendar events to the cloud is a common first step (I still don't understand why iPhone users tolerate the concept of syncing a device) and the ease of using GMail with Android makes it quite easy for consumers and businesses alike to move to the cloud.

Some key areas/topics I'll be following at the conference:

Chrome OS
I think the formal launch of Chrome OS and ubiquitous distribution through netbook partners will be a next likely step to broaden Google's reach and I expect some exciting announcements about this platform this week.

Android Development
I have the beginnings of an Android app integrated with Salesforce Chatter started, but I need to attain more mastery of debugging techniques, use of the emulator, and package/deployment steps.

Google Apps Marketplace
How to develop for and monetize Google App plugins.
Appirio has a pretty slick demo of embedding a Salesforce widget in Google Mail. I'm hoping Google will open up this API at the conference for others to try it out.

IoT and Google App Engine (GAE)
I'm interested in the potential of using GAE and BigTable as an aggregator for the Internet of Things. One side project I'm working on is to port my Chatter bot to Google.

Chrome Browser and HTML5
Just how far can Javascript be pushed to deliver rich internet applications? I'll be looking for some early indications that Google is serious about implementing HTML5 local storage and video on Chrome.

BI / Google Charts / Visualization
This is a little known API for rendering charts using a RESTful interface and I really dig it. There's great potential for moving business intelligence (BI) apps to the cloud by replicating/aggregating data using GAE and Google charts and visualizations for reporting

Google Sites
As a follow-up to our soon to be released "Cool Sites for AppExchange" app, I'm interested to learn how our template designs can be repurposed for Google Sites.

Google Wave
We've started using Google Wave internally quite a bit internally and it's emerging into an excellent collaboration tool.
Check out some live Google Waves this week. I just may be on some of them :-)

Monday, 17 May 2010 10:58:05 (Pacific Daylight Time, UTC-07:00)
# Friday, 14 May 2010

What if the buildings you worked in could participate in Salesforce Chatter feeds? What if the products you shipped could automatically create Cases in Salesforce when they needed servicing? More objects are becoming embedded with sensors and gaining the ability to communicate. This is enabling the next major advancement in the cloud; the Internet of "Things".

Force.com provides an ideal platform for sensor data with the ability to relate information in the physical world to native or custom objects. My previous blog post on Chatter highlighted the Salesforce user experience and ability for people to interact in the cloud. This post demonstrates using Force.com and Chatter to capture information from objects in the physical world and posting to Chatter feeds using the Chatter web services API.

This application is a very basic Facility Management app. There is a single custom object named "Building" that is comprised of many "Assets", such as Conference Room, Main Entry, Air Conditioner, and Heating System. (See this application in action in the video at the end of this blog post).

Sensors on these assets report their readings to Salesforce in the form of Chatter FeedPost records so that when someone walks into a conference room, the Asset record for that room is updated with Chatter information to the effect of "Motion detected in Conference Room".

The feed posts appear to be created by a Salesforce User named "Environment Bot". This is essentially an API user account for reporting environmental sensor activity.

People can comment on the bot's posts. For example, building maintenance personnel may notice the temperature increasing in some rooms and post comments like "Hey, is anyone on this? The AC appears to be broken on the 3rd floor". Or, a night watchman may notice movement around the Main Entry after business hours and log some comments about what he noticed on patrol. Chatter Bot also has the ability to post pictures and share them as links to Chatter Feeds.

Because the facility management application is utilizing the Chatter API, other Chatter enabled apps may be used to augment and enhance the application. For example, installing the Chatter Timelines application from Ron Hess provides a nice linear visualization of what sensor events occurred and when.

The Chatter Bot is built using an Arduino Duemilanove electronics prototyping platform with Ethernet shield and a Radio Shack breadboard with motion and light sensors.

The Arduino sketch source code just runs in a loop polling the sensors and then notifies Salesforce via a proxy service when environmental changes are detected.

I initially designed the Chatter bot to talk directly to the cloud, but later discovered there are more benefits in having bots communicate through a proxy service to Salesforce.

Industry applications
There are a number of possible industry applications that can leverage this framework:

  • Continuous Emissions Monitoring (CEM) Systems
  • Home / Business Alarm Systems
  • Shipment / Automobile location tracking
  • Environmental Control Systems
  • Healthcare Biosensors

If you'd like to learn more about interfacing Salesforce with the physical world via sensors, then please vote for my proposed session "The Chatter of Things" for Dreamforce in December 2010 to see Chatter Bot live and in action.

The number of objects far exceeds the number of people and there is great potential in using Force.com to enable the Internet of Things. There are many more enhancements I'll be making to this platform. I look forward to sharing them.

This video provides a brief demonstration (4:44) of the Facility Management Chatter Bot in action.

Friday, 14 May 2010 09:46:00 (Pacific Daylight Time, UTC-07:00)