Category Archives: Tutorials

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.

Flexing StepGreen – Chapter 3

So we’ve joined StepGreen, and installed Adobe Flash Builder.

Decisions, Decisions…

We have a couple of decisions to make: what type of authentication to use, and what kind of app are we making?

To OAuth Or Not OAuth?… That Is The Question

As you may know from reading the StepGreen API documentation, StepGreen offers two authentication systems for clients. The first, and preferred, is OAuth. The second is based on HTTP Basic.

OAuth is an industry wide recognised methodology for secure authentication between user clients and resources. If you’re interested in learning more, take a look at OAuth.net.

The PAPI/HTTP Basic Authentication that StepGreen also offers is great for manually taking a look around the StepGreen API, but really is not suitable for use in a real life application. One of the major issues with it is that it requires sending the users login and password (AKA credentials) with every request. Whilst it may be fine for quickly throwing something together for your own use and testing, it should never be used for anything you might want other people to use, and you shouldn’t really use it for your own things either. As an authentication method it may be deprecated at any time, and will not appear in future versions of the StepGreen API.

Basically, use OAuth.

What Type of App?

Adobe Flash Builder allows you to develop apps for a variety of platforms – the most well known being the web apps that you see on websites every day. But it also allows you to develop desktop applications using AIR and also mobile apps for the Android mobile platform. (the ability to create Apple iPhone apps is uncertain since Apples decision that they don’t like Flash).

For the purposes of this tutorial, we’re going to develop an Adobe AIR application – the simple reason being it’s the easiest and requires nothing further (such as a phone or website) to get going.

Telling StepGreen what we’re doing

First off, we need to tell StepGreen that we’re going to create an OAuth application. This is so that it can generate your apps key and secret that are used to secure the communication between your app and the StepGreen API. The important thing to remember here is that for every different app you develop (that gets published publicly) you should generate a new key and secret. However you don’t need a new one for every copy of the same app that people use.

Log in to StepGreen and go to the Developer section. In the menu on the left, select “Clients”, then click on the link to “Register a new client”.

For the Client Name  you need to try to think of something unique – after all it’s how people are going to know your app in the future! If you want to, you can always rename it later as long as the new name is also unique.

For the Client Type dropdown menu, you should select ‘Desktop’. All the other fields for now can be left blank – but you will need to fill them in later if you ever choose to publish an application.

Click Save – AND WAIT. You should now have a screen which shows you your Consumer Key and Consumer Token. You will to take note of these  – either copy and paste them for now into a text document, or you can always come back here later to copy them directly into your applications source code.

You’ll also see some links there relating to OAuth. This is because OAuth is standard – but not quite that standard. Some websites modify the actual locations of these services, or may have them on a different domain. You need to be aware that you might need them – if it wasn’t for a helpful library StepGreen makes available to help you out.

Making OAuth Easy

In the left hand menu, click “Resources”. You will see a section named “Helper Libraries” containing a link to something called the AS3 Access Control Library. Download this file. It contains some ActionScript goodness to make working with the StepGreen API and OAuth a lot easier. Basically it provides a wrapper around Iotashans OAuth library that makes it easier to generate OAuth requests for the StepGreen API without having to worry about anything behind the scenes. It also lets you develop an initial app using the PAPI/HTTP Basic Authentication and easily update to using OAuth, but we wont go there.

Now that you’re all set up, we can create our first app.

Flexing StepGreen – Chapter 2

In Chapter 1, we looked at getting an account on StepGreen, and gaining access to the developer resources.

Here, we will get setup with Adobe Flash Builder (previously known as Adobe Flex Builder). If you already have this, you can skip this chapter.

Getting Flex

There are a few different options for getting Adobe Flash Builder:

  • Free trial
  • Through your school/college/university
  • Educators version
  • Purchase
  • Use the Open Source Flex SDK

Most of these options start with going to http://www.adobe.com/products/flashbuilder/. If you want to get it through Adobe’s Education program, take a look at the FAQ which talks you through the process.

No matter which route you go, you can easily start by downloading the demo – you can then upgrade to a full version either by purchasing, getting a licence through the Adobe Education program, or through a program at your institution.

Once you have downloaded the software, follow the instructions to install, fire it up and take a look around. The help comes with some short tutorials and there are others available in the online documentation and the Flash Builder Community Help.

Next time: Starting Development

Flexing StepGreen – Chapter 1

Welcome to ‘Flexing StepGreen‘. This is an occasional series on developing for StepGreen using the API.

First off, a couple of disclaimers:

  • the API and associated documentation is currently (January 2011) considered in Beta. It may change… but we hope it doesn’t. Changes should be restricted to improving the documentation and fixing any issues that occur. As a developer it’s up to you to ensure that your client stays in sync with the API.
  • the code presented may not constitute best practices – it’s purpose is primarily to educate on how to achieve certain results, not how to produce robust code.

Now that’s out of that’s out of the way, let us begin.

One assumption that is made is that you (and the potential users of your application if they are not you) are members of StepGreen. So if you have not yet signed up, now is the perfect time to do so! Pay a visit to http://www.stepgreen.org/signup.

Once you have signed up and explored the site, you will need to request access to the developer resources. Go to your ‘Account’ page, then scroll down until you get to a section called “Developer”. Check the “I want access to StepGreen’s developer resources.” checkbox and click on “Save Changes”.

After a moment the page will return  – but you wont see any other changes until you re-enter the site. Close the browser window, then open up a new one and re-enter StepGreen. In the navigation menu you should now see a “Developer” option. Click on that. Looking around here you will find that there is not much you can do until you agree to the API Consent. Take a read of that, understand it, and if you agree, click on “I agree”. You are now free to look around the rest of the developer documentation.

Next time we will look at setting up to develop a Flash application using the API and Adobe Flash Builder/Flex Builder. (goto Chapter 2)