Flexing StepGreen – Chapter 4

Hello World

Now that you are setup on StepGreen and have the AS3 Access Control library (don’t know what I’m talking about? See Chapter 3), we are ready to create our first StepGreen application.

We’ll start with the ubiquitous “Hello World” and go from there.

Fire up Flash Builder, then select File->New->Flex Project. Give the project a name – this does not have to match the name you gave StepGreen, but it might help stop confusion. So I’m calling mine ‘FlexSG’. Make sure that the Application Type is set to Desktop, accept all the other defaults and click on ‘Next >’. Accept the default build location, clicking on ‘Next >’.

The next page lets you modify source and library paths. Make sure the Library Path tab is selected. This is where we tell our app about the AS3 Access Control Library we downloaded. Click on the ‘SWC’ button, and browse to the location where you saved the file. ‘OK’ to close, then ‘Finish’. Flash Builder will then setup your project, and present you with your apps main ‘.mxml’ file. This will be named after your project – mine is called FlexSG.mxml. It will look something like (also at http://pastie.org/1482733):

xml version="1.0" encoding="utf-8"?>
WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
 xmlns:s="library://ns.adobe.com/flex/spark" 
 xmlns:mx="library://ns.adobe.com/flex/mx">
 <fx:Declarations>
 <!-- Place non-visual elements (e.g., services, value objects) here -->
 </fx:Declarations>
WindowedApplication>

You maybe thinking that we’re going to write an app that displays “Hello World” to the user… nothing so boring! After all, this is a StepGreen app we are writing, so lets display something from StepGreen to the user instead.

Switch to the Design view of the app, and put four elements in the applications canvas. We’ll need one Label, one Button, and two TextAreas. Place the Label at the top, the button directly underneath that, then the two TextAreas beneath that, side by side.

In the label, put a heading for your app  – I have “FlexSG v0.0.1 – Hello World’.

For the button, give it an id of ‘button_1’. You’ll also want to give the TextBox’s ids, call the one on the left ‘text_output_1’ and the one on the right ‘txtDebug’. text_output_1 will display the processed output from the API, whilst txtDebug will display the raw output and other debugging information.

Return to the code view. At the top you’ll see a declaration that looks like

xmlns:... >

Before the closing ‘>’ you’ll want to add a title parameter in the form:

title='your apps title'

Your code should look similar to to http://pastie.org/1483173. If you was to build and run it now, you would be presented with your app showing the label, button and textboxes – but it wouldn’t actually do anything useful. Time to fix that!

In the code view, find the block. After the closing tag, put a couple of blank lines and type . The code completion should pop up and help you. Once you type the closing ‘>’ it should autocomplete giving you

<fx:Script>
 <!--[CDATA[-->

 ]]>
</fx:Script>

Now we have to do some setup. We’ll start by telling Flash Builder what libraries your app is going to use. Immediately inside the CDATA block we’ll add some import statements:

 import mx.rpc.events.FaultEvent;
 import mx.rpc.events.ResultEvent;

 import org.stepgreen.accesscontrol.*;
 import org.stepgreen.accesscontrol.events.*;
 import org.stepgreen.accesscontrol.utils.ApiService;

We then set up some variables we’re going to need:

// STEPGREEN.ORG KEYS
 private static const CONSUMER_KEY:String = "your_key_goes_here";
 private static const CONSUMER_SECRET:String = "your_secret_goes_here";

 private var _consumer:OAuthConsumer;

Insert the key and secret you got from the StepGreen website into the appropriate place. The _consumer variable holds the OAuthConsumer object that we’ll be using to communicate with StepGreen.

Next we need to tell our app what to do when it starts up. We do this by assigning a ‘creationComplete’ attribute to the tag, and defining the function that it calls. In the tag add

creationComplete="onCreationComplete()"

after the title attribute. Then in the fx:Script block after the _consumer variable setup add the following:

// once we're loaded, setup our OAuth Consumer           
 private function onCreationComplete():void{           
 //set up your OAuth Client
 _consumer = new OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
 _consumer.userId = '';

 button_1.label = "Get Action";
 button_1.addEventListener(MouseEvent.CLICK, getAction_Click);
 }

This block of code does a couple of things. It starts off be initializing the _consumer with your key and secret. This causes a few things to happen behind the scenes – your app will connect with StepGreen and get the initial OAuth tokens it needs to continue. Second, we set up our button. Why give the button a label here and not when we first created it? It’s to show that we can assign values to visual elements at any time. During the course of an application running you can use the same button for many tasks – you don’t have to create lots of buttons and hide them. We then add an eventListener to the button so that we know when it has been clicked, and tell it what to do when that happens.

As we’ve told the button to call the getAction_Click function when it is pressed, we had better add that next:

 private function getAction_Click(event:MouseEvent):void{
 getAction();
 }

And since that calls getAction, we’ll also need to define that. In case you’re wondering why we split it into two steps, it’s to allow the getAction function to not need to accept a  MouseEvent as a parameter – this means it could be called by other pieces of code, and potentially moved out to its own library more easily for others to use.

private function getAction():void{
 var params:Object = new Object();
 params["per_page"] = 1;

 var apiCall:ApiService = _consumer.getAPI("actions", params );
 apiCall.addEventListener(ResultEvent.RESULT, actionResult);
 apiCall.addEventListener(FaultEvent.FAULT, actionFault);
 apiCall.send();
 }

The getAction function is the one that initiates communication with the StepGreen API. By setting the per_page parameter to one, we are basically telling StepGreen to return only the first action it finds, without particularly caring which action that is. Once the apiCall is defined we attach a couple of EventListeners to it – one to catch errors, the other to handle a good result. We then send the call off to StepGreen with apiCall.send(). Behind the scenes this ensures that the request is properly formatted for OAuth, signed, sealed and delivered. Next we need to define actionResult and actionFault.

 private function actionResult(event:ResultEvent):void{
 debug("actionResult()\n\n" + event.result);
 getActionsResult(event);
 }

 private function actionFault(event:FaultEvent):void{
 debug("actionFault() " + event.fault.message);
 debug("actionFault() statusCode: " + event.statusCode);
 if( event.statusCode == 401 ){
 // access denied. may need to re-get credentials
 // if this was an authenticated call
 }else{
 // some other fault
 }
 }

In both functions we’ll display what we receive we’ll send the raw results or error message to txtDebug via the debug function which we’ll define later. For actionFault we’re not going to do anything else here, but if we were building a full application we would need to take some action based on it not working. What we do might depend on the type of error we received. In actionResult, we’ll pass the result on to getActionResult to handle the output.

public function getActionsResult(event:ResultEvent):void{
 var xmlNode:XMLNode = event.result as XMLNode;
 var actionsXML:XML = new XML(xmlNode.toString());

 for each (var action:XML in actionsXML.action){
 text_output_1.text += "Title: " + action.short_name + "\n\n";
 text_output_1.text += "Description: " + action.description + "\n\n";
 text_output_1.text += "Tags:\n"

 for each (var tag:XML in action.tag){
 var category:String = tag.attribute("name");
 text_output_1.text += category + "\n"
 }
 }
}

getActionResult does a few things. It starts off by converting the incoming Result into XML. Next, it steps over that XML retrieving the individually defined actions – we may have only asked for one, but if we had asked for more this would still have worked and displayed all of them to us. For each action we then display its title, description and tags in the text_output_1 TextBox.

Lastly, we’ll define the debug function

private function debug(message:String):void{
 txtDebug.text += message + "\n\n";
}

You should end up with something that looks like this  http://pastie.org/1482875.

Time to build and run your app! If all’s well, it should run, and when you click the button you will be shown details about an action you can take on StepGreen.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s