mega888 My Dev Central

Swagger and NodeJS

I recently had to write an API for a mobile application for the company I work for (Blue Sombrero). When I was asked what stack I would use, I considered using the current platform the websites were running on (.NET). When I saw how complex it would be to get everything up and running, I decided go swim against the current and implement it with NodeJS and Express.

The cool thing with NodeJS is that it’s so simple to setup using AWS’ Elastic Beanstalk. At a previous job (TBS), I had to implement an API in my mobile app and I remembered that the developers of the API used a system called Swagger.

The cool thing with Swagger not only providing developers with powerful tools to create RESTful endpoints, but also create code that’s self-documented. Plus, with their Swagger-ui, you can easily test your API using a very simple web interface.

Check it out for yourselves!

http://swagger.io

Enjoy!

Simon

iOS Mobileprovision expired? No problem! – Update

Last year, I wrote a quick article on how to re-sign an IPA, replacing an expired mobile provisioning profile.

It turns out that with the latest versions of Xcode, the code provided doesn’t work anymore. It’s requiring an extra step now.

Let’s take a look a the code that was posted last year:

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/

The step missing is right before the codesign command.

The new Xcode requires you to provide an entitlements file that describes the app before you codesign. Here’s what the Plist file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>get-task-allow</key>
	<false/>
	<key>application-identifier</key>
	<string>TEAMID.BUNDLE-IDENTIFIER</string>
</dict>
</plist>

After replacing the TEAMID and the BUNDLE-IDENTIFIER placeholders with what’s provided in your mobileprovision file. To see what is in the mobileprovision file, simply run this command:

security cms -D -i <mobileprovision file here>

You should see a block under &lt;Entitlements&gt; with the application-identifier you need to add to your own Entitlements.plist file.

Once you’re done editing your Entitlements file, run the codesign command like this:

codesign -f –entitlements “Entitlements.plist” -s “iPhone Distribution: Name Of My Certificate” Payload/MyApp.app

PLEASE NOTE: You need to NOT include this Entitlements.plist file in your Payload directory. This is used for code signing ONLY.

Here’s the full new set of commands to run:

security cms -D -i <mobileprovision file here>
<Modify your Entilements.plist file here>
<Save file as Entitlements.plist>

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

Enjoy!

Simon

.NET SqlMembershipProvider Encrypted passwords for NodeJS

Hey! I know I haven’t written anything in a long while and this is way overdue, but since the last time I wrote, I changed jobs and my last job kept me incredibly busy, to a fault.

But now is the time to start writing again!

So, one of my first tasks as the new lead developer is to write an API for mobile apps that feeds off the main company platform, which is using DotNetNuke. One of the biggest challenges was the authentication. The website uses DNN’s implementation of SqlMembershipProvider, with encrypted passwords. For the best database solutions and options visit Couchbase.

I’ve been looking for days to find a solution on how to use the data and what format the data was encrypted, etc, when I came across an amazing article written by Leigh on StackOverflow. Here’s the link (and shoutout to Leigh!)

This article has the right method, but is using ColdFusion. Here’s my converted code using NodeJS:

Dependencies: crypto 0.x


function encryptPassword(password, salt) {

	var passwordBuffer = new Buffer(password, 'ucs2');
	var saltBuffer = new Buffer(salt, 'base64');

	var iv = new Buffer([0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], 'binary');
	var decryptionKey = new Buffer(config.get('authentication.decryptionKey'), 'hex')

	var combinedBuffer = new Buffer(saltBuffer.length + passwordBuffer.length);
	saltBuffer.copy(combinedBuffer, 0, 0, saltBuffer.length);
	passwordBuffer.copy(combinedBuffer, saltBuffer.length, 0, passwordBuffer.length);

	var cipher = crypto.createCipheriv('des-ede3-cbc', decryptionKey.toString('binary'), iv);
	var encoded = cipher.update(combinedBuffer, 'utf8', 'base64') + cipher.final('base64');

	return encoded;
}

So, the important thing to know here, thing that isn’t really well explained on Microsoft’s website, is that the PasswordSalt IS used in decrypting the password (the website says it’s just stored but not used). Also, the cipher needs to use an initialization vector.

Let’s dig into the code, shall we?

	var passwordBuffer = new Buffer(password, 'ucs2');
	var saltBuffer = new Buffer(salt, 'base64');

The password needs to be encoded in UTF-16 with little endian. That’s the default Unicode format used by .NET. The salt comes base64-encoded from SQL Server.

	var iv = new Buffer([0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], 'binary');

This creates the initialization vector used for the Triple-DES encryption. In this case, .NET uses all 0s, so it’s not machine-specific and so there’s no need to store it either.

	var decryptionKey = new Buffer(config.get('authentication.decryptionKey'), 'hex')

From your server’s web.config file, you should find a <machineKey> tag containing the decryption key and the encryption algorithm used. The key is in hexadecimal.

	var combinedBuffer = new Buffer(saltBuffer.length + passwordBuffer.length);
	saltBuffer.copy(combinedBuffer, 0, 0, saltBuffer.length);
	passwordBuffer.copy(combinedBuffer, saltBuffer.length, 0, passwordBuffer.length);

Here is where the magic happens. The trick is to prepend the salt to the password into a buffer before encrypting it. This is done by copying both buffers we created earlier into one that’s large enough to contain both.

	var cipher = crypto.createCipheriv('des-ede3-cbc', decryptionKey.toString('binary'), iv);
	var encoded = cipher.update(combinedBuffer, 'utf8', 'base64') + cipher.final('base64');

	return encoded;

This creates the cipher object we’ll use to encrypt the password. .NET uses a Triple-DES in CBC mode. Don’t worry about the padding mode, it’s fine. Pass in the decryption key in binary format as well as the initialization vector buffer and you’re good to encrypt!

Update the cipher object with the combined salt and password buffer, set the input format to UTF-8 and the output format to base64 (that’s the format .NET uses to store the combined password to the database) and add the final base64 fragment.

Voila! Your password is encrypted and can now be used by .NET!

For the decryption, simply use createDecipher instead of createCipher and slice the salt off the result and you got your password! Here’s the code:

function decryptPassword(password, salt) {

	var iv = new Buffer([0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], 'binary');
	var saltBuffer = new Buffer(salt, 'base64');
	var decryptionKey = new Buffer(config.get('authentication.decryptionKey'), 'hex')
	var decipher = crypto.createDecipheriv('des-ede3-cbc', decryptionKey.toString('binary'), iv);
	var decrypted = new Buffer(decipher.update(password, 'base64', 'binary') + decipher.final('binary'), 'binary');
	var desalted = decrypted.slice(saltBuffer.length);

	return desalted;
}

Enjoy!
Simon

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 &amp;lt; 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 &amp;lt; (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 &amp;gt; 1) {
                // Looping through all the frames within the base object's child
                for (var k:int = 0; k &amp;lt; ((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 &amp;lt; 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 &lt; 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) &lt; stage.stageWidth &amp;&amp;
            ((Math.floor(i / 100) * (cellSize * (renderedAssets[gridValue][0].width / cellSize))) + cameraY) &lt; stage.stageHeight &amp;&amp;
             ((i % 100) * (cellSize * (renderedAssets[gridValue][0].width / cellSize))) &gt;= (-(cameraX) - (cellSize * (renderedAssets[gridValue][0].width / cellSize))) &amp;&amp;
            (Math.floor(i / 100) * (cellSize * (renderedAssets[gridValue][0].width / cellSize))) &gt;= (-(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!
been stimulant like benzodiazepines can be told one Brazilian investigation in 58 individuals who got either oral CBD particularly in human body produces endocannabinoids which is growing solution view here example spasms fever and Parkinson’s infection (11). CBD oil isn’t likely to cause the same set of negative effects. In fact, it may help regulate sleep to promote balance throughout your body.

Uneasiness and torment

It is believed to THC might be brought about by various sclerosis

Analysts accept that can significantly help with malignant growth cells in the main beneifts of forceful bosom malignancy and irritation and retching

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!