Dependency Injection; Ok but how?

More Robotlegs for you guys, but this time in is more conceptual.

One thing that bugged me with Robotlegs was the use of the expression Dependency Injection. Cool word, it must mean something huge. Well if you look at it quickly; not really. If you take time to think about it, it means more.

Half of it is injection

Well, how you implement dependency injection is actually pretty simple and is something that you are doing every day (well if you program). Dependency Injection is giving, by the mean of the contructor, a method or a property, dependency (data) to an object. As Joel Hooks said it in his InsideRIA article (read it, it’s a good intro): “When you pass a variable to the constructor of a class, you are using Dependency Injection. When you set a property on a class, you are using Dependency Injection.

Ain’t that just pleasing; I can just walk around the office and tell every one I am doing Dependency Injection.

The concept behind it

I first was reading about this on the Robotlegs best practices and I couldn’t understand anything (that’s mostly the case when I am first exposed to a design pattern, no offense to that document). After that I found Hooks article and I said to myself: “this ain’t complicated, why all the fuss”, but I wasn’t really understanding the concept (the why) behind it. It took me this article to really understand. The example is really simple and clearly expose why we should use dependency injection.

Why we should use dependency injection is mostly to create more flexible Classes. If a Class as settings that could change and that it depends on them to work, these settings should not be set inside the Class’ code but outside of it. That way every time the settings change, you don’t need to go in the Class’ code to change them.  You should really read Fabien Potentier’s article about it; he does a way better job at explaining this than me. Also this presentation by Jeff More is pretty good. The more you read about it the more you’ll understand what it is.

Fine but it still feels like magic in Robotlegs

When you read the wikipedia article on Dependency Injection, at one point they list some draw backs and one of them was that “Code that uses dependency injection can seem magical to some developers” and that is exactly how I felt about it in the context of Robotlegs. Mostly because of the use of the [Inject] metatag. That is not a mechanism I was used to in AS3. I was thinking that these meta where holy blessed keywords that only Adobe could create.

Well it turns out I was wrong. Well half wrong. The [Inject] meta is used at runtime while let’s say the [Embed] metatag is used at compile time, so it is not exactly the same beast. In Robotlegs, injection is handled by the SwiftSuspenders. What it does is that for all rules you create using the method mapValue, mapClass and mapSingleton it will inspect the classes it receive. It uses the function flash.utils.describeType on the Class to do so, this will return an XML that represent that Class. In this XML, there will be tags that represent the [Inject] metatag. That is what SwiftSuspenders is looking for when parsing the class representation XML, after that it can freely do the injection (passing the values) according to the rules.

Now you could go and create your own metatags, but it seems that the compiler would remove them at compilation. If you use the source for the SwiftSuspenders instead of the SWC they tell you to add this to the compiler arguments:

-keep-as3-metadata+=Inject

-keep-as3-metadata+=PostConstruct //This is another metatag that SwiftSuspenders makes use of

This will prevent the compiler from removing the metatags from the Classes, so you could basically change these lines to make the compiler keep your newly created metatags. I have no idea why you don’t have to do this when using the SWC.

That is kinda what I wanted to cover. I’m still not fully comfortable with dependency injection but at least I have a better idea of how it works underneath. I hope you feel the same.

, , , , , , , ,

No Comments


Recharge with milk and Robotlegs

I just wanted to show you what came out of my work with Robotlegs. Recharge with Milk is a hybrid site Html/Flash. We did the flash part because for the home section it would be faster to take care of the page resizing and to add some animations in the compare tool.

Only the home page was built using Robotlegs. It is pretty simple so it was a good fit to try a new framework, but there is way more going on than what it looks like. Everything on the home page is customizable from a xml and there are a lot of layers of views.

Recharge with Milk

At some point in the project I was finding real beauty in the code, but I was really sad because nobody other than developer could see that beauty…

, ,

No Comments


Using the ActionScript 3 YouTube Api

On October 14th YouTube released a new version of it’s API for Flash. This version would support ActionScript 3. Previously discussed on here was the library TubeLoc which was basically an AS3 wrapper around the ActionScript 2 API. Now the new API does all TubeLoc pertmitted us to do and even more.

Well loading a YouTube video in ActionScript 3 has never been easier and there is nothing to download (which has its downside in some way)to get started.

Here is all the code needed to load a YouTube movie:

package {
 import flash.display.DisplayObject;
 import flash.display.Loader;
 import flash.display.Sprite;
 import flash.events.Event;
 import flash.net.URLRequest;
 
 public class Main extends Sprite {
  private var _loader : Loader;
  private var _player : Object;
 
  public function Main() { 
  _loader = new Loader();
  _loader.contentLoaderInfo.addEventListener(Event.INIT, _onLoaderInit, false, 0, true);
  _loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
  }
 
  private function _onLoaderInit(event : Event) : void {
  _player = _loader.content; 
  _player.addEventListener("onReady", _onPlayerReady, false, 0, true);
  addChild (DisplayObject(_player));
 
  _loader.contentLoaderInfo.removeEventListener(Event.INIT, _onLoaderInit);
  _loader = null;
  }
 
  private function _onPlayerReady(event : Event) : void {
  _player.removeEventListener("onReady", _onPlayerReady);
  // Once this event has been dispatched by the player, we can use
  // cueVideoById, loadVideoById, cueVideoByUrl and loadVideoByUrl
  // to load a particular YouTube video.  
  _player.setSize(640, 360);
  _player.loadVideoById("D2gqThOfHu4");
  }
 }
}

You can compile this code as an ActionScript project or make it the Document class of an fla in the Flash IDE to make it work.

So you start by loading the player using a normal Loader. Once the player is loaded you have to wait for it to send the onReady event before you can interact with it. Once this is done you can call all of the function from the API.

The previous code would load the chromeless YouTube player; but if you wanted to use the controls from YouTube you would only have to replace one line:

//_loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));//replace this line with the following
_loader.load(new URLRequest("http://www.youtube.com/v/VIDEO_ID?version=3"));//replace VIDEO_ID with the id of the video you want to load in the previous case :"D2gqThOfHu4"
 
//also you can comment the following line if you don't want the video to start automatically:
_player.loadVideoById("D2gqThOfHu4");

All the functionalities that where accessible with TubeLoc are also accessible with the AS3 API and there are some more. Those are methods to control the quality setting of the loaded movie. You can set the quality to small, medium, large and hd720. To do so you have 3 methods on the player. getPlaybackQuality():String will return the quality of the video currently playing. setPlaybackQuality(suggestedQuality:String) enables you to set the quality. Finally, getAvailableQualityLevels():Array will return you all the possibilities of quality that you can set the current video to.

For more information on the topic, refer to the API : http://code.google.com/apis/youtube/flash_api_reference.html

, , , , ,

No Comments


Some tricks when switching to Robotlegs from PureMVC

From the past posts and a couple of tweets, you all know I have been playing around with Robotlegs. Also, up until now, my framework of choice has been PureMVC, so what I want to do in this post is inform you of the little road bumps I hit when trying to learn the new framework.

Public dependency injection

The first one is really small. Robotlegs makes use of dependency injection (more on that in a later post) and to do so you have to put a meta tag [Inject] before you variable declaration. That is all good, just remember to make your variable public or else you’ll get an error. I wasn’t accustomed with the error I got so it took me some time to find out why I got it.

[Inject]
public var view:Footer; //remember to make public injectable variables

Playing with models

First thing first, when creating my model I was looking to extend the Model class from the Robotlegs framework. Turns out there is no such class; models should extend the Actor class. Services also extends the Actor class.

The next gotcha was a little weird to me at first because it is different from PureMVC mindset. Robotlegs does lazy instantiation, so when you map a model using the injector.mapSingleton method the model will only be created the first time it is injected (that is how I understood it). For some models this is ok, but for others they need to be created before that. In order to do so you use injector.instantiate method and pass it the class you want to create. Here is the code for it and how you would pass data to your newly created model:

injector.mapSingleton(ApplicationModel);
var appModel:ApplicationModel = injector.instantiate(ApplicationModel);
appModel.init("whatever you want here");

Where do I list and handle framework events?

This is the big plus for Robotlegs, no more handling notifications but not listing them and then not figuring out why it doesn’t work. Robotlegs uses the same mechanism, in a mediator, to listen to view events than to listen to framework events which makes it easier to deal with.

So to listen to a view event I would do this:

eventMap.mapListener(view, StringEvent.HIT_ZONE_ROLL_OUT, _onRollOut, StringEvent);

and to listen to a framework event I would do this:

eventMap.mapListener(eventDispatcher, StringEvent.RESIZE, _onResize, Event);

Robotlegs basically wraps around the traditional addEventListener method and what does this give us as an additional bonus? We don’t ever have to set these listeners to weak reference because that is the way they are set by default. Oh, the joy!

Learning a new framework isn’t an easy task (at least when you don’t know any), but I found that learning Robotlegs from a PureMVC background was pretty easy. I hope you will take the time to check it out.

, , ,

5 Comments


A real portfolio and the sources to go with it

Well ya it’s kinda was crazy that I am a Flash dude and that I had an html portfolio. Well that time is over!

Go see my new portfolio here : http://www.zedia.net/portfolio2010/

Now I am not a designer, so I did my best in that domain and I think I managed pretty well but you know, a designer would still have done better. There are still some tweaks I want to do: add sounds, individual urls for projects, analytics, loading indicators, add dates to projects, etc. I will continue to work on it but I thought it was good enough to show.

I built it using FlashDevelop and compiled using the Flex compiler version 4. I used Flash to make the visuals and exported those as swc to import them in my ActionScript project. I used PureMVC as my framework.

Since this is my project I can do what I always wanted to do and share the sources for it. I tried to comment it a bit and I am not saying that this is how one should code, but I have found that you can learn a great deal by looking at someone else’s code. That is what I am offering to you. You can reuse my code for whatever you want I don’t care, just don’t reuse my logo.

Here are the files:

Portfolio.rar

, ,

2 Comments


And now an AS3 Project – Robotlegs project template for FlashDevelop

So yesterday I gave you files templates for Robotlegs. I now give you a project template. File templates are used when you want to add a new file to a project, project templates are used at the creation of a project. It will create the folder structure, add libraries and create the basic files you will need in most projects of that type.

In this Robotlegs project template I added 7 files : Preload.fla, Main.as, IMain.as, MainContext.as, CreateModelsCommand.as, CreateMediatorsCommand.as and ApplicationModel.as.

I added the Preload.fla because has explained in this post, I pass the loaderInfo(I do this to pass the flashvars) from the preloader to the loaded Main so I thought it would make understanding why I did that in the Main easier. This is a template preloader so there is no graphics in it, just the basic code to make a preloader work.

In the Main.as I also do some weird things, namely this:

if (Capabilities.playerType == "StandAlone"){
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
init(this.loaderInfo);
}
 
//and this in the init method
if (Capabilities.playerType == "StandAlone"){
local = true;
}

I do this to test locally without having to compile the preloader every time. Also, I might need to know if I am local if I use AMF. In that case, the url for my gateway will be different.

For the rest, it is pretty straight forward, a MainContext for the application that will start it, a command to create the models, a command to create the mediators and finally an ApplicationModel. I don’t create the ApplicationModel in the CreateModelsCommand because I want to parse the data(parameters) inside of the LoaderInfo I passed in the constructor of the MainContext.

If you use this project template along with the files templates, you’re in for major time saving while enjoying Robotlegs!

Here are the files:
000 ActionScript 3 – AS3 Project with Robotlegs.rar

So when you downloaded the files, go in FlashDevelop, in the top menu select Tools and then Application Files… This will open the application files folder of FlashDevelop. Now go in the Projects Folder and add the files that you downloaded (copy the “000 ActionScript 3 – AS3 Project with Robotlegs” folder there). Now the next time you create a new project in FlashDevelop, scroll down and you will see it.

You may not agree with everything that is in those templates, then there is two things you can do. Either discuss about it in the comments or modify my project template. It is very easy to do so; I never even looked at documentation to learn how to do it.

, , ,

3 Comments


Robotlegs templates for FlashDevelop

I just finished my first project using Robotlegs and I can say I really like it. Way less code to write. The only thing that bothers me is that you have to create new Events when you want to pass around complex data but I think AS3Signals might fix that so I will look into that later on.

Since I have all my templates for PureMVC done in FlashDevelop, I thought I would do the same for Robotlegs. So I have built a template for a Command, a Context, a Mediator, an Actor and I also put in a ResizeModel (I know some people do this in a mediator but if you want to change this go ahead). Now, I don’t think these will be perfect, but it is a good starting point.

I am also working on a AS3 Project – Robotlegs template, but I want to try it out before I give it out. When I am pleased with it, I’ll post it along with an update of the other templates.

Here is the files with the templates:

RobotlegsTemplates.rar

To add them in FlashDevelop, in the Tools menu click in Application Files. This will open the folder where the applications files for FlashDevelop are. In there open the Templates folder, then the ProjectFiles folder, then the AS3Project folder. Now copy the Robotlegs folder you downloaded there. To use them, in the project view in FlashDevelop, right click on a folder, click “Add” and then Robotlegs. At that point you will see the five templates you just added.

Robotlegs Templates for Flash Develop

, , , , , , , , ,

3 Comments


Skinning the ComboBox Flash component

This post is more for me because I keep forgetting how to do this. For my defense I have to say that it is not exactly the first thing that comes to mind when you are trying to change the font in the ComboBox component, but at least I won’t have to remember in which project I did it; I’ll just turn to my friend Google and type : comboBox + zedia.

Editing the visual is mostly easy inside of flash but my main problem is always the fonts. In a previous post I talked about fonts in Flash in general, this one will use that as a base and apply it to the ComboBox. Here is the code to change the font in the textfield and the dropping list:

var myFormatWhite:TextFormat = new TextFormat();
myFormatWhite.font = "DFC GillSansLight";
myFormatWhite.size = 15;
myFormatWhite.color = 0xffffff;
 
var myFormatBeige:TextFormat = new TextFormat();
myFormatBeige.font = "DFC GillSansLight";
myFormatBeige.size = 14;
myFormatBeige.color = 0xa18c52;
 
comboBox.textField.setStyle("embedFonts", true);
comboBox.textField.setStyle("textFormat", myFormatWhite);<
 
comboBox.dropdown.setRendererStyle("embedFonts", true);
comboBox.dropdown.setRendererStyle("textFormat", myFormatBeige);
 
comboBox.prompt = "Province"; //default value that won't show in the dropdown
comboBox.addItem( { label:"New Brunswick", data:"New Brunswick" } );
comboBox.addItem( { label:"Nova Scotia", data:"Nova Scotia" } );
comboBox.addItem( { label:"Ontario", data:"Ontario" } );
comboBox.addItem( { label:"Prince Edward Island", data:"Prince Edward Island" } );

My problem was mostly with the setRendererStyle method; not that obvious. I also put the code for adding items in the ComboBox and to have a default text in it that doesn’t show in the dropdown. Now the next bit of code if to check, when you used ComboBox.prompt, if something was selected:

if (comboBox.selectedIndex == -1) {
//show error message because comboBox wasn't changed
}

P.S. all this code assumes that I have dragged the component to the stage in the Flash IDE

, , ,

No Comments


Log, trace, log, release, log?

Ok, this title doesn’t make sense if you haven’t read the article which goes against the concept of title, but I find it funny!

So here I was looking for a solution to the problem I think every Flash Developer most have had: I can trace fine when I am in the Flash IDE but sometimes I need to test in the browser and then I loose my traces…

Easy solution: use a logger tool like Alcon or MonsterDebugger.

Problem: it’s annoying. When you are at the point where you need the extra logger you need to find the ActionScript classes to make it work blabla.

What I want is an elegant solution that when I test locally it uses the trace and when I test in the browser it uses the logger. I was already using the snippet for trace in FlashDevelop so I thought I could make a snippet that would have this if statement and do just that. My first bump in the road was the fact that I didn’t know how to add an import statement when using a snippet at a different place in the code.

So while looking in the FlashDevelop forums I came upon FDTracer. Well it doesn’t exist anymore, it was a pluggin before but it is now an integral part of FlashDevelop. Turns out I always had it under my nose but I never knew about it. It would be nice if in the interface they actually tell what it is and how to use it.

So here are a couple of pictures to show you where that logger is. In FlashDevelop, under View it is called Flash Log Viewer and is by default one of the tab at the bottom of the program:

What this thing does is that it reads the logs that the Flash Player writes on the computer. You see, when you put the final swf on the server and the user plays it in his browser, all of your trace statements are written in the log file. That is why leaving trace statement in your final release is not that good for performance. Anyway one last thing to know is that you actually have to start it before it works. So press the little play button and start seeing your trace.

What is cool with this little thing is that it will work locally and in the browser, you don’t have do to anything(execpt press play) to make it work. Also if you feel spyish you can check the trace from Flash website made by others.

So yeah, please clean your traces…

, , , , , ,

8 Comments


Analytics for Mobile Applications : a good idea, six months too late

So yesterday I was talking with my friend that does iPhone applications about what data he gets from Apple about the applications he builds. It turns out that aside from the number of sales, he doesn’t have any data. I found this weird and we started talking about how it wouldn’t be that hard to build a kind of Google Analytics for Mobile Applications. In a sense, it would be very similar to the library GA for Flash except that you build a library for every Mobile SDK plus you have a webserver where the data is analysed.

It took so much time for a library of analytics to be made for Flash, I thought there might be a chance that nobody did anything like this for mobiles. So we got all excited (like so many other time), we started thinking how we would build this. But today I searched on the web and found Flurry a company that has an analytics division that does exactly this. Well not exactly how I would do it but about 85% the same. So my bubbles is a bit busted.

Flurry does it mostly right but their interface is a bit complicated and they didn’t make their analytics that specific to mobiles. There are plenty of concepts that exist in the mobile world that are new: what people do in their first and last run of the application, the number of tap (click with fingers) by session, the accelerometer, etc. And they don’t track that, yet. Also they provide an  API for events, but not for navigation (pageViews in the GA world). I think navigation still has an important role in the analytics of an application than in the analytics of a website. You want to know what the users did in a certain section of your app (how many taps in the help section for example).

So all of that could be implemented and would give a better service than what Flurry is offering. The problem is that their platform is already built and even if there is not much competition (they seem to be the only ones doing this), it would still be hard to beat their momentum.

So what do you think? Should I invest time in this project knowing these risks, or should I let this go and wait for another idea?

, , , , ,

1 Comment