Monday, February 21, 2011

FizzBuzz in AS3


I'm not sure why this didn't seem hard, but in 10 minutes I came up w/ this solution to fizzBuzz:

private function fizzBuzz():void{
  for (var i:int = 1; i <= 100; i++){
    var str:String = String(i) + " " ;
    if(i%3==0){
      str += "Fizz";
    }
    if(i%5==0){
      str += "Buzz";
    }
    trace(str);
  }
}

Was there an easier way to do this?  Could I refactor this down further in AS3?  I tried overcomplicating it for reuse, but then said, "why?"  I just need it to spit out Fizz, Buzz or FizzBuzz, and the value of i...so that's it for now...Go AS3, modulo, and procrastineering...

edit: After reviewing the code, I decided to expand it (yes, I wasted another 10 minutes on this), but now I can pass in to fizzBuzz any values so that I don't have to have my modulo hardcoded.  Here it is, eat your heart out :)


public function fizzBuzz(starter:int, ender:int, fizzer:int, buzzer:int):void{
for(var i:int = starter; i<=ender; i++){
var str:String = i + " ";
if(i % fizzer == 0){ str += "Fizz";}
if(i % buzzer == 0){ str += "Buzz";}
trace(str);
}
}

Wednesday, February 2, 2011

Hacking an iOS app from an existing Flex app


To make an iPhone application work from an existing Flex/AS3 app, you have to jump through a few hoops.  The first and foremost are getting a few certificates, png's and licenses out of the way.  Before going any further, you need the following:

1) Provisioning profile
2) PKCS12
3) icons
4) an app (not necessary before you start, but indeed necessary for the end result)
5) PFI (Packager For IPhone)
6) AIR SDK (2.0.2 or later)

Ok, the provisioning profile is the hardest bastard to deal with.  If you are like me, and just want to put together a proof of concept, you don't (nor shouldn't) have to pay a company $99 just to try it out.  However that's not how it works for iOS applications.  Apple wants your money any way they can get it, and even if you want to write just a simple app, they'll try and get it however they may.  After asking Lord Google the best way to get past paying money, I found this one link with a hacked provisioning profile...success!!!  Actually, I need to learn the mechanics of this profile to understand what's really in there.  But for my POC, I just grabbed one from here.

Next, I needed a PKCS12 (or more short-handedly known as a .p12) certficate.  This wasn't easy because I've never created one before.  After much searching and trying, I came across Flat Mountain's awesome posts on how to do it.  Always looking to improve my shell skills, I followed his post and finally got some certs built.  I could've used Apple's developer site, but that seemed to obtuse.  and this is for OSX.4, so it might not be relevant, but it's also a start.  On a Mac you can even use Keychain Access, but I didn't go the "easy" route until Flex Builder started complaining that my cert wasn't a "code-signing" cert...  I spent another few minutes trying (However, now that I'd gone through the process of making the cert manually, I understood a lot more about what keychain access wanted to do).  In less than 3 minutes I had created a CA and a cert…but dangit! I couldn't export those as code signing certs (at least not right off the bat, even though I had created them as code signing certs).  About 2 minutes later, i figured I had to evaluate the cert.  I changed the viewing and evaluation to Code signing and voila! I could export the cert as a .p12!  WOOT!

OK, fine, I should also post that exporting the final release will also give you the option of creating your own .p12 right there on the spot, but I felt like that is just way too easy to do, and you don't actually have a clue what's going on in the black magic voodoo of Flex Builder's sneaky background (maybe a post is required about how FB builds keys…but not right now).

Armed with my cert and profile, I just needed a quick default icon, so I used some Photoshop (which isn't necessary, but can help), then Apple's Icon Composer (part of the xCode package: /Developer/Applications/Utilities/Icon Composer).  This guy's blog post helped, but I wasn't interested in paying for CandyBar, so I skipped that step .  It's also about 4 years old, so unless you're still running just Leopard or Tiger, and CS3 or CS4, then you have to use a little imagination.

Ok, icons and certs down, now to getting my AIR app to work.  I used FB4's converter to change the project from Flex to AIR.  A few errors (read: Flex 3.5 SDK custom preloader doesn't like AIR applications because of the addedToStage event.  With a workaround in my custom preloader, I have a functioning AIR app that works on my desktop.)

Now, command line is cool, but sometimes we just need functional.  I got the steps from Kevin Cantrell's post to start with, but I didn't like figuring out all the paths, tabbing through and hopefully not messing up the spelling of anything (I'm lazy, not a hipster).  Even after making it all, putting it into a text editor so I could copy and paste for later use seemed trite.  So I used FB's export tool with my custom signed certs to at least build my app's swf (it exports as a .air, but that's just code for .zip/.tar/.air/.whatever).  I un-tarred it to have the swf, but there's also a copy in my bin folder by default.  I also want to be lazy, so I used this post from Ivan to update the ant build process so I could remain lazy.  Now I have everything in place, so let's let it run, and tada!!!

I've got a functioning Flex app converted from Flex 3.5 to iOS (with some hefty mods). and it runs!  Ok, it isn't native, but as a POC, it doesn't matter.  The point is the point.

This was for me a POC as well as an aggregation of different user's experiences.  If you have any questions, please ping me or the other guys who put this together.

Tuesday, February 1, 2011

Debugging Flex and Java on Glassfish on OSX6

Just a short post about debugging apps.  If you are using OSX and Glassfish, if you want to debug a remote java application, you need to do the following on the glassfish (there are 2 ways to do this)

The first is going through the admin screen -> application server -> JVM Settings -> JVM Options -> and add the following to JVM Option:


-XX:+UseParallelGC




Save your options and you'll need to restart your server.

Make sure you only add that here, otherwise your server won't start up correctly and you'll be forced to do what I learned the hard way (proceed to step two if you added it to the General tab's Debug Options)

Open the following file:

~/glassfish/domains/domain1/config/domain.xml

Add a child to the with the same parameters:


-XX:+UseParallelGC



Then restart your server and you're all set!  I hope this helps anyone else trying to get eclipse breakpoints to actually catch on debug mode using glassfish!

Friday, January 7, 2011

Sending an email from your Flex app just got easier (short post)

I want to send an email from my Flex app.  Well, if I don't have a backend mailserver setup, and I want my user to send me a message about, say, the app's service crashing, the easiest way to do this is through URLRequest!

Quick demonstration - 

1) Create the url request: 

var u:URLRequest = new URLRequest("mailto:"+EMAIL_ADDRESS);

2) Create a variable for the subject and body:

var v:URLVariables = new URLVariables(); //interestingly, you can put all the variables into a string and pass that in, but here we're just going to append them as properties to the object

3) Assign those properties:

v.subject = "Application crashed";
v.body = TEXT_OF_CRASH_MESSAGE;

4) Pass those variable properties into the URLRequest:

u.data = v;

5) Navigate to the URL:

navigateToURL(u, "_self"); //the _self is .js and not required

This is an easy way to pass any valuable info from your flex app into your user's default email program (Entourage/Outlook, Thunderbird, Mail, etc.)

Thursday, January 6, 2011

Error #2173: Unable to read object in stream


I've been working on building up async tests (which I should have a different post for shortly), and came across this annoying error:

ArgumentError: Error #2173: Unable to read object in stream.  The class com.lordB8r.model.Control does not implement flash.utils.IExternalizable but is aliased to an externalizable class.
at ObjectInput/readObject()
at mx.collections::ArrayList/readExternal()
at mx.collections::ArrayCollection/readExternal()


Finding FlashSecret's comment helped, but didn't get me all the way there.  While I could put the path inside an array, I wasn't assigning the return value to an array, or Control.  Instead, I needed to import a/the class(es) needed by IExternalizable in my test.  So, simply putting this in my test class made it work:

import com.lordB8r.model.Control;


Is this correct for testing?  I'm not sure, but it helped me get my async test to retrieve data from a Spring RESTful service.  Test passed because I got data, but only once I told my test what data type it should be expecting.

I've dealt with this when bootstrapping an application, also when requesting data back from the server.  Often times, my service class (or service recipient) doesn't know the type I just asked for, so I need to import it into that class.

Tuesday, December 21, 2010

To Cuddle or not to Cuddle :} setting curly brace defaults in my IDE

After a short stint of not understanding what the heck people were moaning about on twitter (re @jesterxl's comments about cuddling), and thanks to him, I came across Grant Skinner's post about curly braces.

I am personally a cuddler.  I find the code easier to read, and I am of the school of thought that less lines of code is better.  Also, to me logic dictates that if you are starting a block of code, you would emphasize that by showing me on the line that you are declaring the opening of that code, that the code block begins with the curly.  In Ruby, there are no curly's for code blocks, so it doesn't bother me there.

But what bothers me, and Grant mentioned it, is how Flashbuilder autogenerates non-cuddled code blocks. And he griped about it, asking that anyone who knows how to fix the problem please let him know.  Well, here's my quick fix, using Flashbuilder 4 on Eclipse 3.6 on OSX6.5:

-> Preferences (cmd + ,) -> Flash Builder -> Editors -> Code Templates -> ActionScript

For each of these classes, I manually updated the templates so that the curly braces all were at the end of the opening line for package, class and constructor, i.e.

package com.lordB8r.controller{
  public class TestClass{
    public function TestClass():{
    }
  }
}

and methods did the same thing:

private function runTestClass():void{
}

ahhh, breathe deeply, knowing that all auto-magically generated code in AS3 will now conform to my preferences.

And yes, I can export these settings, in case I don't want to manually change all of them for each instance of Eclipse (and then reimport them).

Now, I obviously am not smart enough to be the first person to have come up with this.  There is the following resources I found:

InsideRia's article by Greg Owen
FlexFormatter
ActiveTuts by Jesse Freeman
and the best example so far is someone who actually made real templates of what they use in their workflow:
FBB blogpost by Maxim Kachurovskiy

And you can quickly find your own by using lord google.

Monday, December 6, 2010

Resizing Dynamically Loaded swfs using swfloader

In my current project, I am using RobotLegs and a parent application to load in "modules".  However, I don't use modules, because frankly, I don't quite get why I should.  Instead, I have separate swfs that I can load, and pass information to them, if necessary.  The biggest frustration that I have is that when I resize the parent application, my child, which is a loaded swf, doesn't know it's stage has been resized, and thus doesn't resize itself.  To fix that, I tried a few different options, including resizing the loader, the system manager, the loaded application, the screen, everything!!!

The problem I was running into is that my loaded swf was getting it's size clipped.  This was unacceptable.

For example, if I loaded my swf into my app, if the window was sized at 700x400 (w x h), if I resized my window to something smaller, the controls inside the loaded swf would follow accordingly. However when I resized the window larger than 700x400, the controls would get clipped by an auto-assumed max size of the loaded swf's stage.

GRRRRRRR!!!!!!

So I have lost countless hours of sleep, including the time it's taking me to post this incoherent message.  But I feel I must share about resizing a loaded swf without scaling.   Right now I have some jerkiness in the movement, but it forces a scale and resize of the loaded swf's width and height.

I avoid using the _loadedSwf.scaleContent and _loadedSwf.maintainAspectRatio.  These together were fun to figure out, but the end result was that my controls were scaling, and I didn't want that.  If I turned off scaleContent, then nothing would resize.  If I turned off aspect ration, then things started looking wonky.

because I had added my _loadedSwf to a SkinnableContainer, and that container was getting resized, I wanted my _loadedSwf to update to that container's size.  On initialization I do use a method inside _loadedSwf.  And to use that, I have something like the following:

var loadedSM:SystemManager = SystemManager(_loadedSwf.content)
loadedSM.application["updateDimensions"](container.width, container.height);

This worked great for the initial setup, but resizing still didn't work.  I won't recount the countless hours I've tried to make it work.  Needless to say, and the reward for reading this post is to see that to make this work, I did the following on the resizeMyApp(), called by the parent application whenever an EVENT.RESIZE_EVENT is dispatched:

_loadedSwf.content.width = container.width;
_loadedSwf.content.height = container.height;
Object(_loadedSwf.content).setActualSize(container.width, container.height);
loadedSM.application["updateDimensions"] (container.width, container.height);

I got the idea on page 48 of this manual (Thank you Matt Horn!!!)

http://livedocs.adobe.com/flex/3/loading_applications.pdf 


These last 2 lines seem a bit hazy to me, but if I remove one of them, then the resizing doesn't work.  I do have some jerkiness that I need to work out, but the overall resizing now commits correctly.  I think there is something in the updateDisplayList() that I've missed, but somehow this makes the call work.