View all posts filed under 'Tutorials'

Cairngorm Getting Started Part One : Overview

Thursday, 19. June 2008 21:58

First things first I need to acknowledge David Tucker for this fantastic post that got me started.

As David Tucker says in his post, though I think he’s lying, I’m no Cairngorm Expert either.  But I have used it recently and I like it.  What I’m doing with this post is to explain it as I get it, so if I’ve made any glaring errors please let me know.  This is also an aide memoir to myself too so I apologise for the slightly jovial tone, I like to keep myself amused while I’m writing.  What I can say with authority though is that I really like Cairngorm even though I’m currently using the PureMVC framework (I hope to post a similar getting started for that framework).

The Cairngorm framework appears to be the main framework suggested by Adobe for use when creating RIAs with Flex.  There are lots of other frameworks, Pure MVC being one of them, but this one is really being pushed as they bought the company that created it (Iteration II – acutally they were bought by Macromedia, who were then bought by Adobe, but the essential theory stands).

Cairngorm is an MVC (Model, View, Controller) framework that aims to seperate these different parts of an application so it is easy to maintain and also easier for large development teams to work on.  As each part of the application is seperate a different developer can work on each bit, after planning the application of course.

In essence with an MVC design pattern the Model should deal with the data, the Controller with telling the Model what to do and the View should site there happily being told by the model what it’s supposed to be display.

I’ll have a go at some pretty diagrams of the MVC pattern (you’ll see I’m no designer) but I’ll mainly explain the way I understand it.

At the most simple level : -

A user interacts with the view.  The view dispatches an event which is mapped to the controller (known as a command), the command makes a change in the model and the model then tells the view what to display.

Image of a simple MVC interaction

Now this is all well and good, but really the whole point of framework is to make it easy to manage the application and that includes data connections.  So the next step is : -

A user interacts with the view.  The view dispatches an event which is mapped to the controller (command).  The command creates a delegate to make a call to a data source and a responder that the result from the data call is mapped to.  The responder makes a change to model (which it is allowed to do as it is a controller) and the model tells the view what to display.

Data MVC interaction

So for a simple app that loads some XML the flow would be : -

  • Application Inititialises
  • Dispatches an “I’m alive” event to a controller class
  • The controller class creates a “GetXMLDelegate” class that calls to load the XML
  • The XML is delivered back to responder (at the control level)
  • The responder changes the model
  • The view displays the data the model holds

OK, OK, I’m laboring the point – but that sort of is the point. It seems very obvious but this is really important.  View talks to Control, Control changes the model, model gets the view to display what it tells it to.

The most important and cardinal rule is ONLY CONTROLLERS (ie. Commands or Responders) CAN CHANGE THE MODEL!  If you stick to this cardinal rule your life with Cairngorm will be much more fruitful.

One other bit of advice is to try and keep things simple. One command does one function. This means you’ll end up with loads of classes, but if something does go tits up then you’ll probably have a good idea as to exactly where the application is failing, and probably the filename of the class that is the problem.

OK – part 2 – lets set up the environment for developing with Cairngorm.

Category:Cairngorm, Flex, Flex Builder, Frameworks, Tutorials | Comments (1) | Author: admin

Flex Dynamic Data Binding 101 – Part Four, Finishing the Contact App

Monday, 14. January 2008 8:23

So we’ve created our basic application in part three. You can see it here.

Adding and deleting is fine, but what about editing? I don’t want to simply add people, I want to be able to change them too. We’re going to need a few more variables and another function.

<mx:Script>
	<![CDATA[
		import mx.collections.ArrayCollection;
		[Bindable]
		private var peopleColl:ArrayCollection = new ArrayCollection();

		[Bindable]
		private var buttonTitle:String = "Add Person";

		private var workflowState:String = "adding";

		private function submitPerson():void
		{
			if (workflowState == "adding")
			{
				addPerson();
			}
		}

		private function addPerson():void
		{
			var obj:Object = new Object();
			obj.firstName = firstName.text;
			obj.lastName = lastName.text;

			peopleColl.addItem(obj);
		}

		private function peopleLabelFunction(item:Object):String
		{
			return item.firstName + " " + item.lastName;
		}

		private function deletePerson():void
		{
			if (people.selectedItem != null)
			{
				peopleColl.removeItemAt(people.selectedIndex);
			}
		}
	]]>
</mx:Script>

We’ve added a buttonTitle and made it bindable, a workflowState variable so we know at what stage the application it at and a submitPerson() function that makes a comparison on the workflowState and triggers the addPerson() function if we are adding. Now we’ll change the add person button.

<mx:Button label="{buttonTitle}" click="submitPerson()"/>

So what have we done here? As far as functionality – nada. It’ll still work the same, but now we are using data bindings for the button title too. Whoopy do. Well actually it is.

However first things first I’ve actually been bad and not added some simple functionality to the form. Once we’ve added a person we need to clear the text fields

I’ll assume now you are familiar enough with the code I can simply show you the bits I’m adding or changing.

 private function addPerson():void
{
	var obj:Object = new Object();
	obj.firstName = firstName.text;
	obj.lastName = lastName.text;

	peopleColl.addItem(obj);

	firstName.text = "";
	lastName.text = "";
}

That’s a bit better.

Now for the editing functionality. First lets add some more binding. When the list is selected we want to populate the text fields with the selected item.

<mx:Form>
	<mx:FormItem label="First Name">
		<mx:TextInput id="firstName" text="{people.selectedItem.firstName}"/>
	</mx:FormItem>
	<mx:FormItem label="Last Name">
		<mx:TextInput id="lastName" text ="{people.selectedItem.lastName}"/>
	</mx:FormItem>
	<mx:Button label="{buttonTitle}" click="submitPerson()"/>
</mx:Form>

Now we’ve bound the text field properties to the items in the list. When the list is selected though we want to set the form to be an edit rather than add form. We’ll do that with this function.

private function doEdit():void
{
	workflowState = "editing";
	buttonTitle = "Edit Person";
}

This simply changes the buttonTitle, which if you remember is bound to the form button. And it sets the workflow state to editing. This means we can write the next part of our submit person function.

private function submitPerson():void
			{
	if (workflowState == "adding")
	{
		addPerson();
	}
	else if (workflowState == "editing")
	{
		editPerson();
	}
	else
	{
		//Err something really odd is happening here.
	}
}

And the actual edit function.

private function editPerson():void
{
	var obj:Object = peopleColl.getItemAt(people.selectedIndex);

	obj.firstName = firstName.text;
	obj.lastName = lastName.text;

	peopleColl[people.selectedIndex] = obj;

	people.selectedIndices = new Array();

	workflowState = "adding";
	buttonTitle = "Add Person";
}

So what’s happening here? First lets get the object from the array. Then change it’s properties of firstName and lastName to the text fields. Then put it back into the array where we got it from, effectively overwriting the item in the array. As the textFields are bound to the selected item of the people list we need to deselect the list, or we are going to be stuck in edit mode as the text fields will keep displaying the selected item. We cannot do firstName.text = “” as this would overwrite the binding we had set up and stop the app working as expected. If you set the selectedIndices of a list to a new Array this effectively deselects the list.

We are done editing so we set the workflow state to adding and the buttonTitle back to Add Person.

The final tweaks we need to make are in the delete function as you need to select the list before you can delete the person from it. This would then leave the application in edit mode and would stop it working as expected.

private function deletePerson():void
{
	if (people.selectedItem != null)
	{
		peopleColl.removeItemAt(people.selectedIndex);
		workflowState = "adding";
		buttonTitle = "Add Person";
	}
}

And finally, finally, lets put the validation code on to make sure that people at least enter something into the form.

private function addPerson():void
{
	if (firstName.text != "" || lastName.text != "")
	{
		var obj:Object = new Object();
		obj.firstName = firstName.text;
		obj.lastName = lastName.text;

		peopleColl.addItem(obj);

		firstName.text = "";
		lastName.text = "";
	}
	else
	{
		mx.controls.Alert.show("At least enter something, doofus.","No Details Submitted");
	}
}

You can see the finished app here.

Download the code from this link -> Simple Contact Form Complete MXML . The code is commented, so should be quite easy to read through.

Category:Basic Code, Flex, Tutorials | Comment (0) | Author: admin

Flex Dynamic Data Binding 101 – Part Three

Monday, 14. January 2008 7:32

We’ve covered basic data binding with Actionscript in part one and simply sticking components together in part two, now lets look at something a bit more interesting. As I’m working on a contact manager at the moment I’m going to use this as the basis for this little tutorial (hey, I’m lazy and the code is just sitting there….).

First things first lets create a panel with a list to display the contacts, a little form to get the contact information and some buttons for managing the data.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

	<mx:Panel title="Contacts" layout="horizontal">

		<mx:VBox>
			<mx:List id="people"/>
			<mx:Button label="Delete Person" enabled="false"/>
		</mx:VBox>

		<mx:Form>
			<mx:FormItem label="First Name">
				<mx:TextInput id="firstName"/>
			</mx:FormItem>
			<mx:FormItem label="Last Name">
				<mx:TextInput id="lastName"/>
			</mx:FormItem>
			<mx:Button label="Add Person"/>
		</mx:Form>
	</mx:Panel>

</mx:Application>

This creates a basic panel which should look something like this.

Contact Form

Note that I’ve set the delete button to disabled as initially we won’t have any contacts, so we won’t have anything to delete.

Now we need to create the code that are going to make the mini application work. First we need an array collection to act as the data provider for the list.

<mx:Script>
	<![CDATA[
		import mx.collections.ArrayCollection;
		[Bindable]
		private var peopleColl:ArrayCollection = new ArrayCollection();
	]]>
</mx:Script>

The peopleColl needs to be bindable as we are going to attach this to the list.

<mx:List id="people" dataProvider="{peopleColl}"/>

Like that.

Next we are going to need a function to add a person.

<mx:Script>
	<![CDATA[
		import mx.collections.ArrayCollection;
		[Bindable]
		private var peopleColl:ArrayCollection = new ArrayCollection();

		private function addPerson():void
		{
			var obj:Object = new Object();
			obj.firstName = firstName.text;
			obj.lastName = lastName.text;

			peopleColl.addItem(obj);
		}
	]]>
</mx:Script>

And get the button to call the function when it is clicked.

<mx:Button label="Add Person" click="addPerson()"/>

Cool. Now when we enter details into the form and click ‘Add Person’ this adds the person’s details to the array collection. But hang on – look at the list

Contact Form with no Label Renderer

Ah. The list is getting updated by the data binding, but doesn’t know how to display the items. It, by default, calls the toString() function which in the case of an Object returns [object Object] . Not good enough for a proper display. So we add a label function to the list so it knows how to display the item.

<mx:Script>
	<![CDATA[
		import mx.collections.ArrayCollection;
		[Bindable]
		private var peopleColl:ArrayCollection = new ArrayCollection();

		private function addPerson():void
		{
			var obj:Object = new Object();
			obj.firstName = firstName.text;
			obj.lastName = lastName.text;

			peopleColl.addItem(obj);
		}

		private function peopleLabelFunction(item:Object):String
		{
			return item.firstName + " " + item.lastName;
		}
	]]>
</mx:Script>

Then tell the list to use this function

<mx:List id="people" dataProvider="{peopleColl}" labelFunction="peopleLabelFunction"/>

Now the list will display correctly.

Contact Form wit Label Renderer

Nice. A couple of notes. Normally when assigning a function to a component such as a click event you would put the call to the function in the “” such as click = “doSomething()” and you could send an event to the function too, click = “doSomething(event)”. In the case of a list component you only need to put in the name of the function.

The label function only receives objects, so you do need to know what the structure of the object is in order to extract the correct string and return it.

OK lets get the delete button working now. First lets enable it. We need to change the enabled property.

<mx:Button label="Delete Person" enabled="{peopleColl.length > 0}"/>

OK, what’s going on here? We are using data binding to do a comparison, on the fly, with the length of the peopleColl. If it is empty the comparison will be false, if not the comparison with be true. And as we are using data binding this will do the hard work for us, we don’t need another function operating on the button enabled property.

Right, now the delete function.

<mx:Script>
	<![CDATA[
		import mx.collections.ArrayCollection;
		[Bindable]
		private var peopleColl:ArrayCollection = new ArrayCollection();

		private function addPerson():void
		{
			var obj:Object = new Object();
			obj.firstName = firstName.text;
			obj.lastName = lastName.text;

			peopleColl.addItem(obj);
		}

		private function peopleLabelFunction(item:Object):String
		{
			return item.firstName + " " + item.lastName;
		}

		private function deletePerson():void
		{
			if (people.selectedItem != null)
			{
				peopleColl.removeItemAt(people.selectedIndex);
			}
		}
	]]>
</mx:Script>

Again – all we need to do is operate on the peopleColl array collection, we don’t need to get anywhere near the list component as it is bound to peopleColl. I’ve also added a little test to make sure that the list is actually selected or we’d get an error. Lets add the function to the delete button.

<mx:Button label="Delete Person" enabled="{peopleColl.length > 0}" click="deletePerson()"/>

And if you try out the app here you can see we can add and remove people from the list, and the delete button will disable itself if you delete all the people from the list. Alright, I know there is no validation, so you can add empty objects into the list, sheesh! Give me a break, we haven’t finished yet! On to part four.

Category:Flex, Tutorials | Comments (2) | Author: admin

Flex Dynamic Data Binding 101 – Part Two

Sunday, 13. January 2008 20:26

OK, so we’ve covered the basics of data binding in part one. However you don’t have to use Actionscript to use data binding. This is a very quick example of how you can bind two components together without using Actionscript at all. Click here to see the example.

And this is the code :

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

	<mx:Label text="{input.text}"/>

	<mx:TextInput id="input" text="Type in here to change the label"/>

</mx:Application>

Simple you can get the code from this link -> Binding Components MXML Code.(Sorry, just moved the blog – examples back soon) Note that when binding components their properties are available for binding without using [Bindable] meta, this is only for Actionscript. This is a fairly useless example of data binding though. What may be useful would be to bind the enabled state of a button, for example a delete button, to the length of the array property of a list component. If the list component was empty, disable (or hide) the button. Or set the index of a view stack to the value of a radio group, or – er – OK this isn’t too useful. (Shorthand for – I’ve run out of good examples, lets get on and play with some more code.)

Next lets look at something that’s halfway towards a useful application of data binding.

Category:Basic Code, Flex, Tutorials | Comment (0) | Author: admin

Flex Dynamic Data Binding 101 – Part One

Sunday, 13. January 2008 19:56

One of the really cool things you can do with flex is binding, or dynamic data binding, but I’ll just call it binding for now. At it’s most basic you can directly associate data with a view object, eg text input, without having to write the code that did it.

Suppose in Actionscript 2, or 1 for that matter, you had a dynamic text field with the instance name of ‘output_txt’.

Dynamic Text Field

There, I took a picture so you’d believe me. (The more eagle eyed of you will notice that this is actually Flash CS3).

If you had some data, in this case a string you wanted to display in this text field you’d write something like this.

var copy:String = "This is the copy.";

output_txt.text = copy;

And you’d display the copy. Fine, not too much code – what’s the problem?

The problem is that what if the copy has to be dynamic and change? What if the variable copy changes from “This is the copy” to “Disregard this information?” or “A zone one single is how much?” (I had to make a trip to London and am still wondering how anyone can afford it). The text input is a dumb component. It’s been told what its text property is, thankyou very much. If you want to change it, you’ll have to tell it to change the property. So in the function that returns the data, or changes the variable you’ve got to then reassign the variable to the text field

var copy:String = "This is the copy";
output_txt.text = copy;
function resetCopy()
{
 	copy = "Its costs nearly a fiver, why not take a cab, it's more comfortable and you've got more chance of getting where you want to."
	output_txt.text = copy;
}

Which is really just repeating yourself. And can become a real bore when you’ve got half a dozen (normally more) view components that are displaying data. Yes, you could write a function that is triggered every time a variable is changed (a listener), but invariably you’ll be checking which one has changed and then identifying which component that relates to and applying the change to that. You could be even more clever and use classes to have static functions that check your value objects (more classes basically) and update the view that way. (I’ll be doing some stuff on OOP – Object Orientated Programing soon)

However you do it as some point you will be saying this property (wot I already set) is equal to this variable (wot I’ve already said it was in the first place).

This is the point where dynamic data binding in flex really comes into it’s own. The process is really simple : -

  1. Create the variable you want to assign.
  2. Use the [Bindable] meta tag to let the compiler know that this variable is bindable – this allows us to access the variable with script on the component.
  3. Tell the view component what variable it has to bind to.
  4. That’s it.

Once it’s bound whenever the variable changes the component bound to updates too.

A simple example

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"

 			creationComplete="resetString()">

 <mx:Script>

 	<![CDATA[

 		//Bindable metadata letting the compiler know the variable

 		//imediately afterwards is available for binding.  If you

 		//leave this off then you will get a compiler warning, but

 		//the code will still work...but just for me leave it in.

 		[Bindable]

 		public var copy:String = "This is the copy";

 		//Function called on Creation Complete.  This is triggered when

 		//the application has been launched, so after the copy variable

 		//was initially created.

 		public function resetString():void

 		{

 			//Reset the copy

 			copy = "I've changed."

 		}

 	]]>

 </mx:Script>

 <!--

 Here's the text input to display the variable.  The curly braces

 are required so the compiler knows to treat what is in them as Actionscript

  -->

 <mx:TextInput id="output" text="{copy}"/></mx:Application>

I’m not going to go through the code, there are comments and it should be quite self explanatory, you can down load the mxml from this link ->Simple Binding Example MXML File .(Sorry, just moved the blog – examples back soon EDIT : I lost it – I’ll get it back up ASAP – sorry!) The only things I will mention are :

Putting meta tags into Actionscript felt extremely alien to me when I first started and I didn’t really get them, however now I’m totally at ease with it so don’t worry if you start typing and think “What on earth is this all about?”

You HAVE to use the curly braces in the mxml or the compiler will not know it is supposed to be calling an Actionscript variable.

By the way if you run this you should get “I’ve changed.” in the text field. This proves that data binding is working as after reseting the variable we didn’t then go back to the text input component and reset the text property. Wow.
So? How was that? Totally underwhelmed? Don’t worry this is just the principles, next we’ll look at how you can bind components together with no code whatsoever.

Flex Dynamic Data Binding 101 – Part Two

Category:Basic Code, Flex, Tutorials | Comment (0) | Author: admin

TortoiseSVN, Subclipse, how’s it all work?

Thursday, 6. December 2007 8:33

I’m just going to quickly talk about how I use SVN. That doesn’t mean it’s the right way, or even remotely the way it’s supposed to be used, but I’ve noticed on some forums and mailing lists that the SVN ‘getting started’ step seems to have been left out.

What you’ll need for this is a computer (what a wag!), Eclipse downloaded and installed (basically unzip into a directory) and that should be it. Apologies to Mac users I don’t use a Mac and these steps are for a Windows PC. Also this is not going to be about connecting to remote repositories, this is about creating a local SVN repository and connecting to it. So this is for developers who are just starting out with SVN and source control and want to manage their projects locally.

OK, disclaimers out of the way, lets get going.

Then go and get Tortoise SVN from here.

Run the installer, this will probably require a reboot after it’s installed.

Once you’ve done that and the machine is back up if you right click you’ll see a few extra options.

Right Clicking with Tortoise SVN Installed

This is the nice thing about Tortoise, you don’t need to open another application, it’s there in the file menu.

Go to where ever you want to create the repository and create a folder. I’ve just called mine ‘myProject’.

Right click on myProject and select ‘Create Repository Here’.

Create Repository

Select ‘Native filesystem’ (Should be selected by default) and hit OK.

Repository Created

(Hopefully!)

Open Eclipse. Go to Help -> Software Updates -> Find and Install.

Select Search for new features to install and click next.

Click on New Remote site.

Give the site a name of Subclipse and in the URL field put the URL to the Subclipse update site, currently http://subclipse.tigris.org/update_1.2.x.

Subclipse Update

Hit OK and follow the install instructions. (If you’re anything like me just keep clicking on OK or I agree until its down and installed.) Eclipse will prompt to be restarted, let it do it. If there are any problems at this point close eclipse, go to the command prompt and navigate to your eclipse install directory. Type eclipse – clean and hit enter. This launches eclipse with a clean cache and also lets it know to look for the new plugins.

This is the bit where it is a bit Irish (and I’m half Irish, so I should know). For these purposes I’ve created a new project in Eclipse called – wait for it! – myProject. (But what about the repository? Hang on…) Just FYI, it’s a flex project, but that doesn’t matter.

Flex Project

Delete the project, making sure that you have selected not to delete the contents!

Do Not Delete Project!

Navigate through the file explorer to the project created by Eclipse (not the repositorty).

Right click -> TortoiseSVN -> Import.  (Import?  But…. Yes I know – that’s the Irish bit.  The best way I can get my head about it is to think in reverse a bit.  Forget about the fact that you’ve just clicked on your project, we are actually at the repository.  So we are pulling the project in,  not pushing the project out.  Yeah – that makes sense.  Sort of.)

SVN Import

If you don’t see the repository you created click on the drop down icon on the right and select it from there. As you can see Captain Clever (me) has smartly placed the repository in New Folder(3). No matter, probably better for a real application not to copy exactly what I’ve done. I think it’s a good idea to pop a message in, so I’ve just added ‘Initial Import’ to the message area. Hit OK and hopefully : -

SVN Imported

So now we’ve added the project to the repository. Now delete the myProject project folder (not the repository……). Just in case – make a copy first ;)

Now we need to make a note of the URL for the location of the repository. As it isn’t on a server per se, the repository location is a bit different from a normal URL, and this is the easiest way to find it. Right click anywhere select Tortoise -> Repo Browser. This then opens a dialog where you can select the repository you want to look at. We are not interested in looking at a repository through Tortoise, but clicking on the drop down lists the repositories,normally with the newsest at the top of the list.

Finding the repository

Write down, or copy the location of the repository.

Back to eclipse.

Open the SVN Repository Exploring Perspective. Do this either through the quick link on the right, or through Window -> Open perspective -> Other and select SVN repository exploring from the list.

Right click in the SVN Repository window and select New -> Repository Location.

Add Repository Location

This launches the add repository dialog box. Type or paste in the repository location.

Adding Repository Step 2

Hit OK. You will now be connected to your repository and can explore it in the SVN Repository window.

Viewing the Repository

Right click on the repository and select Checkout.

Checkout Step One

These setting should be fine, but just check, then DON’T HIT FINISH! It will create the project in your defined workspace. This my be OK for you, but I rather keep my projects saved somewhere else than the workspace as I flit back and forth in workspaces as is my wont. Click next.

Checkout Step Two

Uncheck use default and browse to where you want your project to be saved. Hit finish.

Navigate back to the programing perspective you use – in my case Flex – and you will see the gleaming project, now under SVN source control in the Navigator window.

Done!

The silos icon indicate the file/folder is up to date in the repository and numbers after the files represent the version the file is at, the name afterwards is the person wot done it.

To commit changes back to the repository right click on the project folder Team – > Commit.

Right – I’m going to stop here, the repository is created and now you can have fun playing with the extra functionality of SVN gives you.

P.S. If you are working to a local repository and your machine blows up – don’t blame me…

Category:Eclipse, SVN, Tutorials | Comments (2) | Author: admin