iOS Mobileprovision expired? No problem!

I ran across an issue with an app I had distributed with an enterprise distribution certificate. The problem is, after a year, the certificate expired.

What to do? Download the code again, recompile the app, make sure everything works with the latest iOS SDK, etc. I ran into multiple issues doing so as the application I needed to update the embedded provisioning profile where, because of changes in the iOS SDK, some of my code was simply not compatible anymore. It’s a legacy app and nobody wants to update that stuff, no time, no budget, etc.

Then, I came across this brilliant website that explained how to extract the app, inject a new mobile provisioning profile, resign the app and repackage everything. Here’s the code for it:

unzip app.ipa
rm -rf Payload/MyApp.app/_CodeSignature/
cp ~/Downloads/MyProfile.mobileprovision Payload/MyApp.app/embedded.mobileprovision
codesign -f -s “iPhone Distribution: Name Of My Certificate” –resource-rules Payload/MyApp.app/ResourceRules.plist Payload/MyApp.app
zip -qr app-resigned.ipa Payload/

Genius! Worked like a charm and saved me the headache of re-compiling everything.

Enjoy!

Source: http://blog.favo.org/post/21905923260/how-to-manually-re-sign-an-ipa-with-a-new-provisioning

What have you tried?

If you’re a developer and you’re about to ask another developer a technical question (on a forum, via email, on a chat channel, or in person), you’d better be ready to answer the question “What have you tried?”

This of course isn’t specific to software developers, but that’s my field and it’s thus the area in which I’m most familiar with the issue which motivated me to write this. I’m (sadly) quite sure that it applies to your own industry too, whatever that might be.

The thing is, there’s a disease in the software development world; a sort of sickness. It’s an unusual sickness in that it’s often not something you acquire once you actually join the industry (like greying hair, caffeine addiction and an ulcer), but rather it’s something that new recruits already have when they arrive.

Now, a quick clarification before I continue: when I say “new recruits”, I don’t just mean graduates and other young people. There are those who will say that this sickness is a product of modern western education systems, and that things were perhaps better back in the day. Maybe that’s true and maybe it’s not, but I’m not qualified to say and that isn’t the position I’m putting forward here anyway. The illness I’m talking about seems to apply to both young and old alike.

The illness, of course, is a flawed approach to solving problems. Here’s an example, which is an actual quote from a web forum:

1) Can we establish http connection in application.

if so, i need that code.

I checked NSURLconnection. I cannot intergrate that code.

2) I want to display a image from the website

Can anybody please provide me the code?

If anybody having sample program please give me.

So where’s the problem? It’s not in the quality of English (it’s reasonably evident that English may not be this person’s first language, and that doesn’t matter as long as the intent is clear – which it is). It’s not in punctuation and grammar, because those things again aren’t particularly important in this context as long as they don’t become barriers to understanding what’s being asked.

The problem is that this person’s problem-solving technique is to ask for the solution. Not to seek advice on how to approach the task, or ask for the names of likely classes to look into, or a link to an example – but to just ask for the code, fully formed and ready to go. This is not problem solving, and software engineering is entirely about problem solving.

The interesting thing to note here is that the above example isn’t actually as bad as it could be; there’s one tiny glimmer of light to be found in the assertion that this person “checked NSURLConnection”. That inspires some small amount of confidence, since NSURLConnection is indeed a suitable class to learn about when wanting to make HTTP connections in Cocoa. However, it seems that “checking” it was pretty much the sum of our friend’s effort – they “cannot integrate that code”, and have thus given up.

This is an issue we all see constantly (and I don’t mean having trouble making HTTP connections). There’s an entire class of so-called developers whose first and final tactic when given a problem to solve is to simply ask for the completed solution elsewhere, commonly on web forums or other suitable help channels. Their goal is the same as ours – to have code which solves the problem, which can then be presumably delivered to the client. This goal is reasonable and quite normal.

What isn’t normal is the unwillingness (I hesitate to say inability - because after all, very few things are truly, fundamentally “hard” if you apply sufficient thought and effort) to achieve that goal by a process of self-education, honest attempts and the classic iterative process of refinement and improvement until something acceptable is created. This process in turn equips you better to handle the next challenge, and sooner or later you find that:

  • there are entire sets of familiar problems to which you already know the answer and can approach with confidence; and:
  • you’re quite capable of approaching unfamiliar problems by generalising your current knowledge and conducting some simple focused research.

This isn’t some trick of software engineering; this is the entire process of learning how to do anything at all.

It’s not a secret handed out at institutions of higher education, it’s just how things work: you begin with a lack of understanding about a topic, and a need to solve a problem in that topic area. The honest, sustainable means of doing so is to improve your understanding. This is achieved by:

  1. Formulating a question which, when correctly answered, will improve your understanding in some way; then:
  2. Attempting to answer it.

Note the second step above. To argue that grabbing the completed solution in some way satisfies this process is laziness and intellectual dishonesty, and probably renders you unworthy of being helped. For after all, why should someone else do your work for you?

I’ve had a lot of personal experience with people displaying this troubling unwillingness to learn or research or try. I’ve released a lot of code over the years, and I’m very visible in the open source community for the platforms I work with. Since open source contributors seem to be seen as freelance teachers, that means I get a lot of email asking for help with one thing or another. And I provide that help whenever I can.

I’ve helped literally hundreds of people looking to get started with Cocoa, since Mac OS X was first released. I don’t send boilerplate replies, either – I replied to each email individually. Everything from specific code issues (including but by no means limited to queries relating to my own code), book recommendations, right up to advice on how to get started with programming as a whole; I’ve done my duty in that regard, and I really do believe it is a duty. People who can do something to whatever extent ought to help others who wish to be able to do the same; surely that’s a fundamental truth and indeed a desire for all of us.

But this is real life, and no principle comes without the consideration of certain realities. Help may be free for the most part, but that doesn’t mean there isn’t a cost-benefit ratio to be considered. My benefit may come from a warm fuzzy feeling rather than cold hard cash, but if you’re wasting my time then you’re not going to seem as worthy as someone who genuinely wants to learn.

Here’s a secret: willingness and desire to learn are the true qualifications.

Not ability; we all have differing innate and developed levels of ability to acquire certain skills. Some (probably most) of these can be improved with practice, and some can’t – and it’s wrong to pigeonhole or generalise a person’s ability in an entire discipline just because of their seeming difficulty in one particular aspect of that discipline. But if you want someone to spend time and effort (especially if it’s time they’re giving freely), then you’d better earn it.

Earning it isn’t about throwing a few units of currency at your teacher, and it’s not even about successfully completing your task – it’s about bloody trying. And trying is what so many of the type of developers I’m talking about seem bizarrely unwilling to do. So, of course, many of us ignore them. Problem solved, right? Wrong.

There’s a huge knock-on negative effect of the proliferation of this unwillingness to make the effort to solve problems yourself. People who are in a position to help stop frequenting the chatrooms, forums and mailing lists. “Bad signal to noise ratio”, they say, with some justification. The losers are the genuine (by which I mean well-meaning, willing-to-learn people who just happen to be new to a particular area) developers who naturally choose those places to ask their legitimate questions. These people have a reduced chance to get meaningful guidance because of the effort involved in working out who’s a lazy time-waster and who isn’t.

This is an awful thing, and it’s never been more relevant – since logically, platforms which are young and/or experiencing a surge in popularity are exposed to this phenomenon the most. There are fewer people who are genuinely experienced, the average level of experience is less, the amount of help being requested is higher, and there’s a far higher proportion of lazy, grab-the-money-and-run types mixed up in it all. This is the iPhone, Android and so on.

So, if you’re going to ask a technical question, I guess the first thing I have to say to you is: Great! You’re asking a question, and that means we have a better than even chance that you want to learn something. That’s usually awesome, and I stand ready to salute you.

But wait. Have you considered – really considered – what it is you’re about to ask? Is this the right time to ask, or can you take one more step first, which might either make your question clearer (good) or even unnecessary (probably better)?

Try taking a few minutes to run through these points:

  • Have you broken the question or problem down sufficiently to really ask something concrete? In software engineering, you can pretty much divide problems into the two categories of (1) things that can be broken down further, and (2) things you already know how to do or can look up trivially.
  • Is your problem the sort of standard question for which there’s definitely already some sample code and documentation available? There isn’t a GUI toolkit in the world that doesn’t have a section in the tutorial on how to put a window on screen. There’s no programming language that doesn’t tell you how to read the contents of a file. Skim the documentation, or do a quick search. If your problem is that simple, the answer is probably just moments away. You can find it!
  • Try searching the web. This is glib advice, I know, but stay with me. If you’re having trouble getting a decent result, you need to narrow things down. Don’t search for “if statement” if you’re just interested in an if-statement in ruby; instead, try “ruby if statement”. What might be even better is finding a site that’s specific to the language or technology you’re working with, and searching there. For Cocoa, this is the CocoaBuilder list archives. Someone else has probably asked your question – or maybe a hundred someones.
  • Whoever made your language or framework or API or whatever also created a bunch of sample code; really, they did. It’s designed to help you get on your feet with various common tasks, and there might be some code that does at least some of what you want to do. It’ll take you only a few minutes to check, and at the very least you can grab a load of code which will come in handy at some point in the future.
  • Use your IDE’s online reference or other built-in documentation. Xcode has a documentation browser. Eclipse etc will show you the Java class documentation. PHP.net has you covered for your PHP scripts. Find the canonical reference for what you’re working with, and search it. You’re going to find something that’s helpful almost every time.

OK, you’ve gone through those steps and tried at least a few of them. I can now finally say congratulations. Either you’ve solved your own problem (great), or you are now officially ready to be helped.

When I ask you “what have you tried?”, you can say with confidence that you’ve tried all that stuff above, and you can tell me anything promising you found, or you can say that you’ve at least come up empty honestly. I’m going to help you at this point, because I can see that you want to learn and that you’re willing to work for it, and so I want to teach you.

That’s the key realisation. When you’re asked “what have you tried?”, it doesn’t mean “show me the code you’ve written, or piss off”. What you have to do is at least try to help yourself – and the trying is the important thing.

Not just for avoiding pissing off someone who would otherwise be willing to give freely of their valuable time to help you, but actually for your own development. Do it enough times and the number of questions you’ll actually have to ask will start to go down. You’ll also be in the position to help others (including me), and that way everybody wins.

So next time you’re considering asking a question, you’d better be ready with a convincing answer when you’re asked “What have you tried?”

If your answer amounts to “not a lot”, take my word for it: the next question you get back will be “then why should I help you?”

 

Written by Matt Gemmell. Original post can be found at: http://www.whathaveyoutried.com

Double-buffering with ActionScript 3

Ever wondered why, when you create a Flash game or animation that requires a lot of movement, Flash’s performances aren’t so great? Ever wondered how come other people can make theirs behave correctly? The answer is simple: double buffering. If you are not familiar with the term, here’s a simple explanation:

The principle of double buffering is to create two separate buffers to render your graphics. The first buffer, called the “Frame Buffer” is used to build out your frame. The second buffer, called the “Render Buffer”, is used for display only. Let’s say, for example, that you have 10,000 objects on your stage, that are animating. Normally, Flash would freak out, even with a resolution of 550×400, giving you a very poor performance. Have you ever tried NOT displaying anything on the stage, but keep the simulation running? Yep! Flash runs at 30fps, like it was set to. Flash’s weak point is the rendering. Let’s set that heavy lifting aside and tell Flash to render differently. In a lot of scenarios, perfomance will be more important than graphics sharpness or scalability. Already, taking away the vector graphics and replacing it with bitmap graphics enhances Flash’s performance greatly. But, we’re not out of the woods yet. Flash still can’t animate 10,000 objects simulatneously and keep a good framerate. For Flash to render properly, you will need a “camera”. The camera is simply your field of view, the boundaries of the visible stage. Your main movie clip animating might be 40,000×40,000 pixels large, but your stage is 550×400, or 1024×768, or whatever size you decide to give it. Just not 40,000×40,000. By moving the “camera”, you simply move the X and Y coordinates of the animating movie clip in the opposite direction, so it looks like the user is actually moving the camera over a 2D plane.

The concept is to replace Flash’s timeline timer completely and make it do what you want. Even if you have animated movie clips on your stage, they will all need to be stopped. All the frames of all objects will need to be rendered once, at the beginning and stored somewhere, as bitmap data. So, the first thing we’ll do is loop through them all, loop through all their frames, and take a bitmap snapshot of each frame and store them into a mutli-dimensional array, like so:

private var renderedAssets:Array = new Array();
private var assets:Array = new Array();

// Cycling through the base assets and create the original objects, which will be used to populate the
// other arrays.
for (var i:int = 0; i < base_assets.length; i++) {
    // Creates a reference to the class reference contained in the array.
    var baseClass:Class = base_assets[i] as Class;
    // This creates the actual dynamic object.
    var baseObj:MovieClip = new baseClass();

    // Cycling through all the dynamic objects, extracting their frames.
    // Skipping the first frame, as it is the empty tile.
    for (var j:int = 0; j < (baseObj.totalFrames - 1); j++) {
        // Initializing the renderedAssets array.
        renderedAssets[assets.length] = new Array();
         // Moving to the correct frame before taking a bitmap snapshot
         baseObj.gotoAndStop(j+2);
         // Check if the child object in this frame is a movie clip. If it's not, we know there is no need
         // to cycle through its frames to extract the bitmap information. There's only 1 frame.
         if (baseObj.getChildAt(0) is MovieClip) {
             // Checking to see if there is more than one frame. If not, we know there is only one and can extract
             // that single frame without a loop.
             if ((baseObj.getChildAt(0) as MovieClip).totalFrames > 1) {
                // Looping through all the frames within the base object's child
                for (var k:int = 0; k < ((baseObj.getChildAt(0) as MovieClip).totalFrames - 1); k++) {
                    // Postioning the timeline to the right frame
                    (baseObj.getChildAt(0) as MovieClip).gotoAndStop(k+2);
                    renderedAssets[assets.length][k] = getAssetBitmap(baseObj.getChildAt(0) as MovieClip);
                }
            }
            // Only 1 frame
            else {
                // Adding the rendered snapshot to the rendered assets array.
                renderedAssets[assets.length].push(getAssetBitmap(baseObj.getChildAt(0)));
            }
        }
        // Not a MovieClip, only 1 frame
        else {
            // Adding the rendered snapshot to the rendered assets array.
            renderedAssets[assets.length].push(getAssetBitmap(baseObj.getChildAt(0)));
        }
        // Add the object to the assets repository array.
        assets.push(baseObj);
    }
    // Clear the baseObj object (free memory)
    baseObj = null;
}

// Populating the grid with 10000 objects.
for (i = 0; i < 10000; i++) {
    // If this is a new row, create a new array and put it in.
    if (grid[(i % 100)] == null) {
        grid[(i % 100)] = new Array(100);
    }
    var randNum:int = (Math.floor(Math.random() * assets.length));
    // Add a random number, associated with the index of the assets repository array.
    grid[(i % 100)][Math.floor(i / 100)] = randNum;
}

private function getAssetBitmap(baseObj:DisplayObject, secondObj:MovieClip = null):BitmapData
{
	// Creating an empty BitmapData, the size of the asset.
	var tmpBMData:BitmapData = new BitmapData(baseObj.width, baseObj.height);
	// Taking the bitmap snapshot of the current frame.
	tmpBMData.draw(baseObj);

	if (secondObj != null) {
   	tmpBMData.draw(secondObj, new Matrix(1, 0, 0, 1, (baseObj.width / 2 - secondObj.width / 2), (baseObj.height / 2 - secondObj.height / 2)));
	}
	// Returning the rendered snapshot.
	return tmpBMData;
}

Setup the stage to listen to the ENTER_FRAME event. The callback will become your application’s main loop.

addEventListener(Event.ENTER_FRAME, renderFrame);

In your main loop, you will determine which frame you are on by increasing a counter.

private function renderFrame(evt:Event):void
{
	frameCounter++;
}

Knowing where all our objects are supposed to be positioned, we can begin building our frame buffer. Looping through each individual objects that is supposed to be animating, or be present on the stage, determine if they should be visible, according to their X and Y coordinates, as well as their width and height. If you have determined that the object should NOT be visible at that time, skip it completely. One down! 9,999 to go!

Once we reach an object that needs to be shown (even 1 pixel of it!), we need render it. To do that, we’ll need a Bitmap data from that particular object, of its current state. We will then position the movie clip’s frame to (totalFrameCounter % mcNumFrames). That is, the total number of frames we went through in the application main loop and divide it by the number of total frames in the animating movie clip. Move to the rest of the division. Here is the function I wrote to determine that:

private function buildFrame(frameCounter:uint):BitmapData
{
    // Create a new BitmapData, the size of the stage.
    frameBuffer = new BitmapData(stage.stageWidth, stage.stageHeight);
    // Cycle through all the grid elements
    for (var i:int = 0; i < 10000; i++) {
        var gridValue:uint = grid[(i % 100)][Math.floor(i / 100)];
        // If the element we're on is supposed to be visible, according to the camera position, we need to render.
        if (
            (((i % 100) * (cellSize * (renderedAssets[gridValue][0].width / cellSize))) + cameraX) < stage.stageWidth &&
            ((Math.floor(i / 100) * (cellSize * (renderedAssets[gridValue][0].width / cellSize))) + cameraY) < stage.stageHeight &&
             ((i % 100) * (cellSize * (renderedAssets[gridValue][0].width / cellSize))) >= (-(cameraX) - (cellSize * (renderedAssets[gridValue][0].width / cellSize))) &&
            (Math.floor(i / 100) * (cellSize * (renderedAssets[gridValue][0].width / cellSize))) >= (-(cameraY) - (cellSize * (renderedAssets[gridValue][0].width / cellSize)))

        ) {
            // Positions the point to the right position in the frame buffer
            pt.x = (((i % 100) * (cellSize * (renderedAssets[gridValue][0].width / cellSize))) + cameraX);
            pt.y = ((Math.floor(i / 100) * (cellSize * (renderedAssets[gridValue][0].width / cellSize))) + cameraY);

            try {
                // Calculates which frame needs to be showing. Since the assets might not have the same amount of frames,
                // the modulo takes care of that by returning a relative position.
                var frame:uint = frameCounter % renderedAssets[gridValue].length;
                // Copies the actual pixels into the frame buffer.
                frameBuffer.copyPixels(renderedAssets[gridValue][frame], rect, new Point(pt.x, pt.y));
            }
            // Oh shit!
            catch (e:Error) {
            }
        }
    }
    // Return the frame buffer.
    return frameBuffer;
}

Modulo (the % sign) is a mathematical operator that will perform an integer division and return the rest. For example, 7 % 3 will return 1. 7 divided by 3 will obviously return a fraction so, we’ll take the “floor” value of that fraction, and multiply it by the divider (which is 3). The floor of 7 / 3 is 2. 2 multiplied by 3 is 6. 7 minus 6 = 1. It is a pretty complicated mathematical operation, but ActionScript takes care of all that for you.

Once all your visible assets are determined and rendered to the frame buffer, it’s time to take a big screenshot of that framebuffer and push that to the render buffer. Let’s add more code to our rendreFrame function:

private function renderFrame(evt:Event):void
{
	// Build the frame buffer.
    frameBuffer = buildFrame(frameCounter);
    // Clone the frame buffer into the render buffer.
    renderBuffer = frameBuffer.clone();
    // Destroy the frame buffer.
    frameBuffer.dispose();

    // Draw the render buffer into the document class' graphics using the BitmapFill.
    // Since we're already dealing with bitmap data, no need to create heavy objects such as flash.display.Bitmap.
    this.graphics.clear();
    this.graphics.beginBitmapFill(renderBuffer);
    this.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
    this.graphics.endFill();

 	frameCounter++;
}

Now, every time the application enters a frame, all those operations will be performed. Tada! We now have a double buffering application. As long as Flash can compute the coordinates of all the objects we need to animate, we should get a decent framerate.

To make a long story short, instead of making Flash “Render object -> Display object, Render object -> Display object” 10,000 times, we do “Render object, Render object, Render object, … , Display visibible objects”. Makes much more sense.

I attached a test project I wrote using that principle. The code is pretty detailed. It uses Simcity Classic assets (Micropolis). Some of them are animated, some of them are not. You’ll see!

DoubleBuffering.zip

Thanks for reading and please, feel free to leave comments!

They did it, again.

Once again, Apple did it. Breaking the record for awesomeness, previously held by… themselves! The new iPhone will incorporate tons of extremely cool features such as iPhone OS 4, supporting multi-tasking and tons of other smaller features.

One very noticeable feature is the front camera, giving access to video conference and many many ideas for new iPhone applications. High resolution screen (twice as much as the iPhone 3GS) will provide for extremely sharp and crisp images, HD video recording, etc.

All this, combined with a larger memory bank and a significantly faster processor makes me really ecstatic about finally retiring my iPhone 3G and upgrade to the latest puppy.

For more infos: http://www.apple.com/iphone/

Posted via web from Simon Germain’s posterous

How to create a jagged array in Objective-C

I don’t know if you ever ran into that kind of problem before, where you need to initialize a jagged array with Objective-C, but I did. I was disappointed to find out that Objective-C doesn’t have any easy way of recursively call a variadic method. I read several posts talking about using NSInvocation to achieve this, but as Apple stated, it’s not capable of doing so. Setting an argument on the NSInvocation object that is beyond the static arguments returned by the method signature will result in an out of bounds exception.

I found a way, it’s not super pretty, but it works just fine. Here’s a few examples of how simple this task is using other languages:

PHP:

<?php
    function createJaggedArray($length) {
        $args = func_get_args();
        array_shift($args); // We don't need the first parameter, it's already defined.
        
        $arr = array();
        while ($length--) {
            $arr[$length] = count($args) ? call_user_func_array('createJaggedArray', $args) : 0;
        }
        return $arr;
    }

    $jaggedArray = createJaggedArray(3, 3, 4, 4); // creates var[3][3][4][4]
    $jaggedArray2 = createJaggedArray(10, 3, 9); // creates var[10][3][9]

?>

ActionScript 3:

package {
    public class ArrayUtil {
        public static function createJaggedArray(len:int, ...args):Array {
            var arr:Array = new Array(len);
            
            while(len--) {
                arr[len] = args.length ? createJaggedArray.apply(null, args): 0;
            }

            return arr;
        }
    }
}

var myArray:Array = createJaggedArray(3, 3, 4, 4); // creates var[3][3][4][4]
var myArray2:Array = createJaggedArray(10, 3, 9); // creates var[10][3][9]

Here’s what I came up with for Objective-C. As you can tell, it’s quite convoluted. I’m sure there’s a better way of executing this, but at least, if you need something right away, that might answer *some* questions:

CreateJaggedLib.h:

@interface CreateJaggedArray : NSObject {
}

- (NSArray *)createJaggedArray:(NSNumber *)len, ...;
- (NSArray *)createJaggedArrayFromArray:(NSNumber *)len childrenLengths:(NSArray *)childrenLengths;

@end

CreateJaggedArray.m:

#import "CreateJaggedArray.h"

@implementation CreateJaggedArray

- (NSArray *)createJaggedArray:(NSNumber *)len, ... {
    NSMutableArray *argArray = [[NSMutableArray alloc] init];
    NSMutableArray *buildingArray = [[NSMutableArray alloc] init];

    NSNumber *eachArgument;
    if (len) {
        va_list argumentList;
        va_start(argumentList, len);
        while (eachArgument = va_arg(argumentList, NSNumber *) {
            [argArray addObject:eachArgument];
        }
        va_end(argumentList);
    }

    NSInteger length = [len intValue];

    while (length--) {
        NSMutableArray *nextArray = [[NSMutableArray alloc] init];
        for (NSInteger i = 1; i < [argArray count]; i++) {
            [nextArray addObject:[argArray objectAtIndex:i]];
        }
        
        NSNumber *value = [NSNumber numberWithInt:[[argArray objectAtIndex:0] intValue]];
        NSArray *resultArray = [self createJaggedArrayFromArray:value childrenLengths:nextArray];
        [buildingArray addObject:resultArray];
    }
    return buildingArray;
}

- (NSArray *)createJaggedArrayFromArray:(NSNumber *)len childrenLengths:(NSArray *)childrenLengths {
    NSInteger length = [len intValue];
    NSMutableArray *buildingArray = [[NSMutableArray alloc] init];

    while (length--) {
        if ([childrenLengths count] > 1) {
            NSMutableArray *nextArray = [[NSMutableArray alloc] initWithCapacity:([childrenLengths count] - 1)];
            for (NSInteger i = 1; i < [childrenLengths count]; i++) {
                [nextArray addObject:[childrenLengths objectAtIndex:i]];
            }
            NSNumber *value = [NSNumber numberWithInt:[[childrenLengths objectAtIndex:0] intValue];
            NSArray *resultArray = [self createJaggedArrayFromArray:value childrenLengths:nextArray];
            [buildingArray addObject:resultArray];
        }
        else {
            NSMutableArray *valueArray = [[NSMutableArray alloc] init];
            for (NSInteger i = 0; i < [[childrenLengths objectAtIndex:0] intValue]; i++) {
                [valueArray insertObject:[NSNumber numberWithInt:0] atIndex:i];
            }
            [buildingArray addObject:valueArray];
        }
    }
    return buildingArray;
}

@end

Call:

NSArray *jaggedArray = [<delegate> createJaggedArray:[NSNumber numberWithInt:3], [NSNumber numberWithInt:3], [NSNumber numberWithInt:4], [NSNumber numberWithInt:4], nil]; // Creates var[3][3][4][4]
NSArray *jaggedArray2 = [<delegate> createJaggedArray:[NSNumber numberWithInt:10], [NSNumber numberWithInt:3], [NSNumber numberWithInt:9], nil]; // Creates var[10][3][9]

As you can see, this can get pretty convoluted. I had to create a method that reacts differently for all the children parameters, since the recursive call of a variadic method isn’t supported with Objective-C. You could simply call the createJaggedArrayFromArray method using an array of lengths instead of using the nil-terminated list of arguments, but sometimes, it makes it easier for porting code from one language to another, to make sure it works the same way.

If someone has a better idea on how to fix this, please share! :)

New Website Launch!

After months and months of hard work, I’m proud to present our new website!

http://www.22squared.com

This site was made with Drupal 6. It uses A LOT of modules, as every other Drupal installations. The very cool thing is the search engine. We decided to implement Apache Solr to handle the site index for various reasons. One of them, is the powerful search engine and its auto-complete feature for the search form, but also for the related content.

The site only released the first phase of three. The second phase is in progress, which will add employee blogs and a blog aggregation engine. The site will be able to index all the blog contents and display related content throughout the site, as well as show existing content related to blog posts.

The third phase will include a public bookmarking engine, similar to del.icio.us. You will be able to share a set of pages, kinda like a portfolio of things you want people to see and share that via multiple social networking and/or directly through email.

Enjoy the site!

Handling beans with BlazeDS and Flex

I recently did a little bit of testing around some concepts with BlazeDS and Flex for a game I’m writing with a friend. The game needs to be multi-player and online. Since the game will have some synchronous (real-time) and asynchronous operations going on in the same session, I needed to have an efficient way of passing data from the messaging system to the remoting system. I decided to use a bean. Creating a singleton controller, I can put whatever data I want in my bean and keep it in memory, passing it back and forth between my controllers. Here’s a small example of how to use the classes:

Messaging Section

Let’s go ahead and create an adapter class, let’s call it JavaFlexAdapter.

package com.javaflex.adapters;

import java.util.logging.Logger;

import com.javaflex.objects.BeanController;

import flex.messaging.messages.AsyncMessage;
import flex.messaging.messages.Message;
import flex.messaging.services.MessageService;
import flex.messaging.services.ServiceAdapter;

public class JavaFlexAdapter extends ServiceAdapter
{
    private static final Logger log = Logger.getAnonymousLogger();

    @Override
    public Object invoke(Message arg0)
    {
        AsyncMessage message = (AsyncMessage) arg0;
        message.setBody("[Server] " + arg0.getBody()); // Just to say the server treated the message;
        BeanController instance = BeanController.getInstance();
        try {
            instance.populateBean("value1", "value2", "value3");
        }
        catch (Exception ex) {
            log.error(ex);
        }
        MessageService service = (MessageService) getDestination().getService();
        service.pushMessageToClients(message, false);
        return null;
    }
}

Next, comes the remoting class:

package com.javaflex.remoting;

import com.javaflex.objects.BeanController;
import com.javaflex.objects.MyBean;

public class BeanReader
{
    public MyBean returnBean()
    {
        BeanController instance = BeanController.getInstance();
        return instance.getBean();
}

Now that we got both our Java classes that Flex talk to, let’s write the glue. This is the controller:

package com.javaflex.objects;

public class BeanController
{
    private static BeanController instance = null;
    private MyBean bean = null;

    protected BeanController()
    {
        bean = new MyBean();
    }

    public static BeanController getInstance()
    {
        if (instance == null) {
            instance = new BeanController();
        }
        return instance;
    }

    public void populateBean(String val1, String val2, String val3)
    {
        bean.setValue1(val1);
        bean.setValue2(val2);
        bean.setValue3(val3);
    }

    public MyBean getBean()
    {
        return bean;
    }
}

And now, the bean itself:

package com.javaflex.objects;

public class MyBean
{
    private String value1;
    private String value2;
    private String value3;

    public String getValue1()
    {
        return value1;
    }
    public String getValue2()
    {
        return value2;
    }
    public String getValue3()
    {
        return value3;
    }
    public void setValue1(String value)
    {
        value1 = value;
    }
    public void setValue2(String value)
    {
        value2 = value;
    }
    public void setValue3(String value)
    {
        value3 = value;
    }
}

Now that everything for the backend is written, let’s take a look at the Flex application:

<?xml version="1.0" encoding="utf-8"?>
<mx:Applicataion xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init();">
    <mx:Script>
        <![CDATA[
            import mx.rpc.events.FaultEvent;
            import mx.rpc.events.ResultEvent;
            import mx.messaging.messages.AsyncMessage;
            import mx.messaging.events.MessageFaultEvent;
            import mx.messaging.events.MessageEvent;
            
            private var consumer:Consumer = null;
            private var producer:Producer = null;

            private function init():void
            {
                consumer = new Consumer();
                consumer.destination = "messaging";
                consumer.addEventListener(MessageEvent.MESSAGE, msgHandler);
                consumer.addEventListener(MessageFaultEvent.FAULT, faultHandler);
                consumer.subscribe();

                producer = new Producer();
                producer.destination = "messaging";
                producer.addEventListener(MessageFaultEvent, faultHandler);
                producer.send(new AsyncMessage("Test!"));
            }

            private function msgHandler(evt:MessageEvent):void
            {
                trace(evt.message);
                remoteObject.returnBean();
            }

            private function faultHandler(evt:MessageFaultEvent):void
            {
                trace(evt.message);
            }

            private function roMsgHandler(evt:ResultEvent):void
            {
                trace(evt.message);
            }

            private function roFaultHandler(evt:FaultEvent):void
            {
                trace(evt.message);
            }
        ]]>
    </mx:Script>
    <mx:RemoteObject id="remoteObject" destination="remoting" result="roMsgHandler(event)" fault="roFaultHandler(event)" />
</mx:Application>

When running this code, you should get the following output:

(mx.messaging.messages::AsyncMessageExt)#0
  body = "[Server] Test!"
  clientId = "746CE46E-AF0A-1EE4-804E-13FF83B3F9F0"
  correlationId = ""
  destination = "messaging"
  headers = (Object)#1
  messageId = "D2713439-8507-C778-C0D5-4771D314477C"
  timestamp = 1263919026976
  timeToLive = 0
(mx.messaging.messages::AcknowledgeMessageExt)#0
  body = (Object)#1
    value1 = "value1"
    value2 = "value2"
    value3 = "value3"
  clientId = "746CE55B-800A-EBDD-C77F-11E4902E2A4A"
  correlationId = "4082D4B5-8554-C76D-BD02-4771D34B5138"
  destination = ""
  headers = (Object)#2
  messageId = "746CE55B-801E-822C-6CF7-92A7C01FE758"
  timestamp = 1263919027072
  timeToLive = 0

Voilà! You set the bean values through the messaging system, and you’re fetching the values through the remoting system.

Please let me know if this article was useful.

Thanks for reading!

HTML in Flash/Flex

I was mandated at work to work on the company’s website. Since the site needs to incorporate a blog for several employees, the option of writing the whole site in Flash was out of the question, as people would embed whatever videos from YouTube, images from various places, etc. The support for HTML rendering with Flash Player is fairly limited.

Not anymore! Today, I decided to simply Google Flash HTML renderer and I come across this little marvel: http://code.google.com/p/htmlwrapper/. It’s a fairly advanced HTML renderer. It supports most of the features that one would need on a blog. I have yet to try this library, but I sure will as soon as I can. This puts the idea of writing the whole site with Flash and GAIA Framework back in the run!

Hope you enjoy this library!

Developing for Google Wave

Hi! I don’t know how many of you had the chance to play with Google Wave at all, but I had the opportunity to fool around with it a bit. I’m quite amazed of how things turned out, even though their interface needs quite a bit of work. The overall performance of the system is a little disappointing, but I try to keep in mind that this is only a preview version. As soon as it hits the beta stage, I think we’ll see some major improvement across the board.

Even though the system is only an alpha version (or preview, call it what you will), Google still released some information on how to develop for it. I will go over two different aspects of Google Wave development, which are gadgets and robots.

Gadgets

Google Wave gives you the possibility to add gadgets to  your waves. They’re used to display some custom data, for example, a Google Map gadget. You can pass it parameters and Google Wave will add an interactive Google Map within your Wave posts. The beautiful part? They all use shared states. That means that, whoever is participating in your wave has access to control your gadget and interact with it. Even pass in new parameters. They opened the API to developers so you can develop your own gadgets. They chose to use XML to deliver the gadget content. The gadget itself is HTML and JavaScript. Here is an example of a shared state gadget that simply increments a counter:

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="State Example" height="120">
  <Require feature="wave" />
</ModulePrefs>
<Content type="html">
<![CDATA[
<div id="content_div" style="height: 50px;"></div>
    <script type="text/javascript">

    var div = document.getElementById('content_div');

    function buttonClicked() {
      var value = parseInt(wave.getState().get('count', '0'));
      wave.getState().submitDelta({'count': value + 1});
    }

    function stateUpdated() {
      if(!wave.getState().get('count')) {
        div.innerHTML = "The count is 0."
      }
      else {
        div.innerHTML = "The count is " + wave.getState().get('count');
      }
    }

    function init() {
      if (wave && wave.isInWaveContainer()) {
        wave.setStateCallback(stateUpdated);
      }
    }
    gadgets.util.registerOnLoadHandler(init);

    // Reset value of "count" to 0
    function resetCounter(){
      wave.getState().submitDelta({'count': '0'});
    }

    </script>
    <input type=button value="Click Me!" id="butCount" onClick="buttonClicked()">
    <input type=button value="Reset" id="butReset" onClick="resetCounter()">
  ]]>
  </Content>
</Module>

Now, with this gadget, everyone participating in a wave can click on the button and increment the counter. But, that is only one part of the gadget. You need to host this code somewhere on a public web server in order for Google to be able to reach it. Now that you’re done writing the code, let’s save that file as “buttonShared.xml” and host it somewhere. Now, to insert this gadget into a Google Wave post, click on the Add Gadget by URL button and enter the full path to the “buttonShared.xml” file. You should see your button and the label next to it appear in your wave.

If you are a registered developer for Google, you can also install Extensions. Extensions are basically installers for gadgets. All you have to do is write a manifest XML file with the information about your gadget, where you want it to reside in Google Wave and the path to the gadget. Here’s an example manifest file for our button gadget:

<extension
    name="Button Gadget"
    thumbnailUrl="http://your.url.here/path/to/screenshot_buttongadget.png"
    description="Get everyone to click your button. See how high you can go!">
  <author name="Your name here"/>
  <menuHook location="toolbar" text="Add Button Gadget"
      iconUrl="https://your.url.here/path/to/icon_insertButton.png">
    <insertGadget url="http://your.url.here/path/to/buttonShared.xml"/>
  </menuHook>
</extension>

Google Wave will then insert your button to your interface toolbar and you can directly click on it to insert a button to your wave. There’s a whole series of actions you can do with those extensions that I will not post here. You can refer to the link section at the end of this post to get the full Google page about these examples.

Robots

Robots are an interesting concept in Google Wave. They are participants in a wave. They can be silent or they can be interactive. They have total control of the wave. If you want the robot to, for example, post certain things on Twitter, all you have to do is add it to the wave and it’ll start doing its thing. The way you register robots for Google Wave is through Google App Engine. Please refer to my post about Google App Engine and BlazeDS for how to setup the Google App Engine plugin for Eclipse and get started with a project.

You will need the Google Wave library. You can find it at http://code.google.com/p/wave-robot-java-client/downloads/list. You will need them all so go ahead and download all the JAR files.

Once you have your Google App Engine project setup, written, compiled and deployed to Google App Engine, simply add a new contact to your list. The contact will be <application-id>@appspot.com. For example, I’ll call mine “mytweetbot”, so the contact I will be adding to my list is mytweetbot@appspot.com.

For the sake of this example, I will simply use Google’s example for a simple bot called Parroty. Create a new Google project and call it Parroty. Go ahead and set the package to “parroty”. Once you created your project, copy the downloaded JAR files to your /war/WEB-INF/lib directory.

Create a new class in /src/parroty called ParrotyServlet. In the Create new class dialog, click on the “Browse” button next to the Superclass and search for AbstractRobotServlet. It should be in the com.google.wave.api package. Make sure you got the Inherited Abstract Methods and Generate Comments checked and click Finish.

By default, the superclass will add the processEvents method. That’s your entry point for your robot. Here, we’ll simply make the bot repeat everything said on the wave.

package com.google.wave.api.samples;

import com.google.wave.api.*;

public class ParrotyServlet extends AbstractRobotServlet {

    @Override
    public void processEvents(RobotMessageBundle bundle) {
        Wavelet wavelet = bundle.getWavelet();

        if (bundle.wasSelfAdded()) {
            Blip blip = wavelet.appendBlip();
            TextView textView = blip.getDocument();
            textView.append("I'm alive!");
        }

        for (Event e: bundle.getEvents()) {
            if (e.getType() == EventType.WAVELET_PARTICIPANTS_CHANGED) {
                Blip blip = wavelet.appendBlip();
                TextView textView = blip.getDocument();
                textView.append("Hi, everybody!");
            }
        }
    }
}

In Google’s terms, a Bundle is the whole wave information, the Wavelet is what contains the wave Blips, a Blip is an entry on a wave and the TextView is an object you put in a Blip to render text.

In order to make your robot react to certain events happening on the wave, you need to tell your robot what to listen to. To do that, create a new directory in your /war directory called “_wave”. In this new directory, create an XML file called “capabilities.xml”. This file should look like this:

<?xml version="1.0" encoding="utf-8"?>
<w:robot xmlns:w="http://wave.google.com/extensions/robots/1.0">
  <w:capabilities>
    <w:capability name="WAVELET_PARTICIPANTS_CHANGED" content="true" />
  </w:capabilities>
  <w:version>1</w:version>
</w:robot>

This tells your robot to be listening to the WAVELET_PARTICIPANTS_CHANGED event.

The only thing remaining is to map our servlet. By default, Google Wave will look for the /_wave/robot/jsonrpc servlet to interact with your robot. Let’s map our class to that servlet:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
    <servlet>
        <servlet-name>Parroty</servlet-name>
        <servlet-class>parroty.ParrotyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Parroty</servlet-name>
        <url-pattern>/_wave/robot/jsonrpc</url-pattern>
    </servlet-mapping>
</web-app>

This part is optional, but it’s also cool. You can provide a bean to your robot with its user profile. Here’s the code to the profile servlet for the Parroty robot:

import com.google.wave.api.ProfileServlet;

public class Profile extends ProfileServlet {
    @Override
    public String getRobotName() {
        return "My Robot Name";
    }

    @Override
    public String getRobotAvatarUrl() {
         return "http://My Robot Image URL";
    }

    @Override
        public String getRobotProfilePageUrl() {
        return "http://My Robot Profile URL";
    }
}

Since everything with the Google Wave robots are versioned, you need to increment your <w:version> tag in the “capabilities.xml” file to tell Google Wave that something changed. Otherwise, it’ll be cached and you’ll have to wait until the cache is refreshed to see your changes. Same thing if you want to change the set of events you want your application to listen to.

Now, all what’s left is to deploy your application to Google App Engine, and add your new contact as a participant TO A NEW WAVE. This is important. It won’t work properly if you just add the bot to an already existing wave.

Links

Wave Gadget Guide: http://code.google.com/apis/wave/extensions/gadgets/guide.html
Wave Gadget Reference: http://code.google.com/apis/wave/extensions/gadgets/reference.html
Extensions Guide: http://code.google.com/apis/wave/extensions/installers/index.html.
Java Client API Tutorial: http://code.google.com/apis/wave/extensions/robots/java-tutorial.html
Java Client API Reference: http://wave-robot-java-client.googlecode.com/svn/trunk/doc/index.html

I hope you find that information useful! Please feel free to comment and/or ask questions, I’ll try to answer as quickly as possible.

For those who are interested in developing for Google Wave but don’t have an invite yet, I have a limited amount of them. Please reply to this post with your email address and I’ll send you an invite. I have to add that you need to have a Gmail account to register to Google Wave.

Thanks for reading!

Simon

Zend Framework 2.0

Zend announced back in November of 2009 that the next major release of Zend Framework was on the way. They published the new framework’s roadmap and some of the new features. The upcoming release of Zend Framework has PHP 5.3 as a requirement, as it relies on namespace support. The main changes to Zend Framework is the MVC implementation, but there are many architectural and design changes as well. Here’s a summary of the new features.

The goal of Zend Framework is to improve the overall consistency, more consistent APIs relating to constructors, options and exceptions.

  • Unified constructor. All constructors will (optionally) accept an array for options or Zend_Config object as the first argument. This allows for more flexibility to add new arguments to the constructor, have a variable number of arguments and allow “named” arguments. Additionally, it’s a good technique for allowing Dependency Injection. As part of the initiative, most components will also have a “setOptions()” method to which the options array will be passed  (and which may be used later to reset object state). Typically, this will proxy to other setters. Many components in Zend Framework 1.x already do this: Zend_Application, Zend_Form, Zend_Validate, Zend_Layout, etc. We are simply extending this paradigm to cover all components. In order to reduce code duplication, we will likely introduce a zend\Options class, which will work roughly as follows:
    namespace zend;
    class Options
    {
        public static function setOptions($object, array $options)
        {
            if (!is_object($object)) {
                return;
            }
            foreach ($options as $key => $value) {
                $method = "set" . self::_normalizeKey($key);
                if (method_exists($object, $method)) {
                    $object->$method($value);
                }
            }
        }
    
        public static function setConstructorOptions($object, $options)
        {
            if ($options instanceof Zend_Config) {
                $options = $options->toArray();
            }
            if (is_array($options)) {
                self::setOptions($object, $options);
            }
        }
    
        protected static function _normalizeKey($key)
        {
            $option = str_replace('_', ' ', strtolower($key));
            $option = str_replace(' ', '', ucwords($option));
            return $option;
        }
    }
    
    use zend\Options as Options;
    class Foo
    {
        public $bar = '';
        public $baz = '';
    
        public function __construct($options = null)
        {
            Options::setConstructorOptions($this, $options);
        }
    
        public function setOptions(array $options)
        {
            Options::setOptions($this, $options);
        }
    
        public function setBar($value)
        {
            $this->var = $value;
        }
    
        public function setBaz($value)
        {
            $this->baz = $value;
        }
    }
    
    $foo = new Foo(array('bar' => 'baz'));
    echo $foo->bar; // "baz";
    
    $foo->setOptions(array('bar' => 'boo', 'baz' => 'bat'));
    echo $foo->bar . $foo->baz; // "boobat";
    
  • Options. In Zend Framework 1.x, the various components which accept options accept a variety of formats: some expect underscore_separated keys, other expect camelCasedKeys, others expect UPPERCASEDKEYS, and some expect lowercasedkeys. This leads to confusion for many, and also leads to difficulties debugging. The goal in Zend Framework 2.0 is to standardize option keys to correct this situation. Currently, they are leaning towards all_lowercase_underscode_keys. These are human-readable, contain only valid PHP variable characters, and make for a simplified option parsing implementation. Additionally, it is trivial to translate keys to camelCase (“str_replace(‘ ‘, ”, ucwords(str_replace(‘_’, ‘ ‘, $value)))”) for purposes of overloading – and this makes it easy to document option key => class property affiliations.
  • Exceptions. Each component will have an Exception marker interface, with exceptions defined for discrete exception types thrown by the component. The concrete exceptions will either extend the global Exception class or an SPL Exception, and also implement the component Exception interface. This allows to throw appropriate SPL exceptions while retaining a common Exception type (via the marker interface). As an example:
    namespace \Foo\Bar;
    interface Exception
    {
    }
    
    class InvalidArgumentException extends \InvalidArgumentException implements Exception
    {
    }
    
    try {
        throw new InvalidArgumentException();
    }
    catch (\Foo\Bar\Exception $e) {
    }
    
  • Design By Contract. They will be altering portions of the framework to follow the concept of design by contract, and new development will follow this paradigm. At first, this will take the form of refactoring to add interfaces/refactoring interfaces to reflect actual usage.
    Interfaces make creating alternate implementation of standard classes easier, while assuring that these implementations will continue to work with the classes that consume them. In many cases currently, they offer only abstract classes, with no equivalent interfaces; in other cases, the consuming classes use methods that are not part of the interface.
    In addition to this initiative, they will be eliminating some functionality intended to add flexibility to some of the standard classes. They have found that oftentimes this functionality leads to performance overhead as well as consumes maintenance time that could be used better elsewhere in the framework. As an example, the Dispatcher has a number of methods for adding custom class -> file mappings that are largely used and which use an unnecessary number of CPU cycles; refactoring this to follow only the standard use cases would ease maintenance, while having a good, simple interface would make creating alternate implementations for custom use cases easier.
  • Elimination of most singletons. Zend Framework has often been accused of “singletonitis”. While they’re not sure if they completely agree, in most cases, the singletons they have have presented a number of problems and led to difficult test cases. Additionally, in most cases, the singletons is unwarranted. They will be refactoring to eliminate these, including in Zend_Controller_Front. In exceptional cases, they will keep them; these include global operations such as autoloading and database connections.
  • Creation of components for general-purpose, cross-functional actions. A Number of components duplicate code, and they want to push the duplication areas into discrete components that the original components may then consume. Some of these include:
    • Plugins/Helpers/Strategies (seen currently in Zend_Controller_Front, Zend_Controller_Action_Helper, Zend_View (helpers and filters), Zend_Form (validators, filters and decorators), etc). Plugin discovery and loading could benefit from a common API.
    • Decorators (seen in Zend_Form; other areas could benefit from the pattern)
    • Factories (seen currently in Zend_Db, Zend_Navigation_Page, Zend_Auth, Zend_Translate, Zend_Cache, etc)
    • Caching (seen currently in Zend_Translate, Zend_Locale, Zend_Queue, Zend_Paginator, Zend_Feed_Reader, Zend_Db_Table, etc.)
  • Usage of new language features within plugin architectures. Currently, most plugins rely on the strategy pattern, but the mechanism differs between plugins. PHP 5.3 offers some compelling alternatives that they want to explore: __invoke() and closures. Closures are less compelling as we cannot do simple type-hinting on them. __invoke() offers perhaps the simplest solution, and could become a standard API for plugins.
  • Autoload-only. They will move to using autoloading throughout the framework. This solves a number of performance issues, as well as simplifies coding dependencies (particularily exceptions).
  • Namespaces. PHP namespaces benefit frameworks and libraries more than any other code bases, and Zend Framework can benefit from it greatly, particularily with components such as Zend_Search_Lucene and Zend_Controller. However, adopting namespaces does not come without a cost: all code will need to be rewritten to define and use namespaces. This will be the single biggest BC break they introduce.
    They also plan to introduce a separate namespace for unit testing, and are currently looking at either \test\zend, \zend\test, or \testzend. This, along with per-component namespaces, will help prevent naming collisions within the test suite.
  • goto. Goto is often considered “evil”, but is invaluable when creating Finite State Machines (FSM) and parsers; usage of goto will be evaluated on a case-by-case basis. Some examples of components that could potentially benefit from such an implementation include Zend_Search_Lucene (which already implements a FSM), the MVC (more below), Zend_Ical, and Zend_Markup (though not all of these may make use of it).
  • Specifics on Plugin architecture changes

For the MVC changes, there is a great article on Pádraic Brady’s Blog.

You can also find all the information about this new version of Zend Framework on Zend’s website at http://framework.zend.com/wiki/display/ZFDEV2/Zend+Framework+2.0+Roadmap.