Chris Tankersley

  • Home
  • About
  • Portfolio
  • Projects
Twitter RSS

Building Facebook Apps – Let’s Get Started

Posted on August 4, 2011 by Chris
No Comments

Facebook apps are a part of society now. From fancy flash games to simple polls, almost everyone uses them. There will come a time in your development career where you will have to build something that interacts with Facebook. I’m on my second one this week, and a third one starting next week.

Facebook has tried to foster a developer community through SDKs and development wikis, but much of this information is spread out. Over the next few posts, I’ll take a look at building a basic Facebook app from end-to-end in an attempt to gather many of the answers I’ve found over the last week.

First we need to tell Facebook about our application…
Read more …

Categories: PHP, Programming, Tutorials | Tags: Facebook, PHP, Tutorial

Virtual RPG Tabletop Web Client

Posted on April 11, 2011 by Chris
No Comments

In my continued adventures playing around with Node.js, I decided to play with something else that caught my eye some time ago – Web Sockets. After a few hours of tinkering, I’ve got a pretty decent client that supports multiple games, dice rolling, and some very basic DM and roleplaying elements.

What I plan on adding is a DM interface, the ability to log/save/retrieve sessions, keep track of the player/NPC turns, maps, and more.

If you’d like to play around with this, I’ll be putting together a preview release by the middle of next week. Sign up here.

Ugly Screenshots

Login Screen
Basic Gameplay

Categories: JavaScript, Personal | Tags: node.js, websockets

Moving JavaScript Server-Side with node.js

Posted on April 4, 2011 by Chris
No Comments

When Twitter decided to basically tell developers ‘Stop Making Twitter Clients,’ that somewhat struck a cord with me. It wasn’t because I make Twitter clients but the attitude. I decided to start working on FlyAway to help people switch from Twitter to Identi.ca, which runs on StatusNet, an open source microblogging platform.

The announcement struck an even deeper cord with client developers like Ed Finkler, who runs the Spaz project. Since Spaz is an identi.ca client, I decided to switch back to it and started lurking around in the #spaz channel on freenode. Ed had an idea to create a Social Network proxy service to make it easier for clients to talk to all these different social networks. He called it Honeybadger.

To help out, I decided to create a server for the project. Since Honeybadger is being written in JavaScript I elected to build it in node.js, a server-side JavaScript interpreter that is built using Google’s V8 engine.

Server-Side Javascript?

JavaScript is generally considered a Client-Side language since it runs in the client’s browser. You do all your coding and then pray that the browser does what you want since each browser has its own JavaScript engine, just like how they have their own rendering engines for HTML and CSS. Your code might talk to external servers, but it doesn’t run on the server.

Recently an interest has been to use JavaScript on the server. According to Wikipedia, which has been proven to be infallible, there are many different options for running JavaScript on the server. I chose node.js mainly because its one of the most popular right now.

Setting up node.js

Installing node.js is pretty straight forward. Download and compile:

$ ./configure
$ make
$ make install

I cheated and used homebrew since I like using that as a package manager for OS X:

$ brew install node

Using JavaScript Outside the Browser

Server-Side JavaScript is pretty much like Client-Side, except you don’t have a DOM to deal with. The code is the same. What does ‘Hello World!’ look like? Put this one-liner in ‘hello-world.js’:

console.log('Hello World!');

To run this in node.js, just call node and pass it the name of the script to run:

$ node hello-world.js
Hello World!

Yes, I agree. That is totally awesome! OK, it doesn’t really show anything, but the idea is you can now use JavaScript to start working on things. node.js has a huge list of modules that can be used and its own package manager, npm.

CalcJS and WWWCalcJS- Two Functional Examples

Lets make two scripts – CalcJS, which is a command line calculator, and WWWCalcJS, which is the online version. We’ll pass them some numbers, add them together, and return the result.

CalcJS

We’ll invoke the calculator with ‘node calc.js 2 2′ and just have it spit out the results on the console.

1
2
3
var one = parseInt(process.argv[2]);
var two = parseInt(process.argv[3]);
console.log('The Answer is: '+(one + two));

process is a global object that holds information about the process that is running. In our case, we pull the arguments that are passed in (which start counting at 0, with 0 being node, 1 being the script name) and store them. Since they get passed in as strings, I cast them to Integers so that we don’t get string concatenation. Lets change this to take an arbitrary number of… numbers:

1
2
3
4
5
6
7
8
9
var numbers = [];
for(var i = 2; i < process.argv.length; i++) {
        numbers.push(parseInt(process.argv[i]));
}
var total = 0;
for(var j in numbers) {
        total += numbers[j];
}
console.log('The Answer is: '+total);

Yes, this can be done with one loop but that’s not the point. Since this is JavaScript, we can use arrays and loops just like on the client side. With the new addition, we can do this:

$ node calc.js 1 2 3 4
The Answer is 10

WWWCalcJS

node.js can also be run as an HTTP server by invoking the correct modules. For the next example, we’ll start a server on port 9000 and pass it two GET parameters: one and two. The URL and command line invocation will look this:

URL: http://localhost:9000/add?one=2&two=2
CLI: node wwwcalc.js localhost 9000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var http        = require('http');
var url         = require('url');
var querystring = require('querystring');
 
http.createServer(function (req, res) {
        switch(url.parse(req.url).pathname) {
                case '/add':
                        dispatch_add(req, res);
                        break;
        }
}).listen(process.argv[3], process.argv[2]);
console.log('Server running at http://'+process.argv[2]+':'+process.argv[3]+'/');
 
function dispatch_add(req, res) {
        var req_query = querystring.parse(url.parse(req.url).query);
        var one = parseInt(req_query.one);
        var two = parseInt(req_query.two);
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.write('The Answer Is '+(one + two));
        res.end();
}

Lines 1-3 pull in some modules that come with node.js. We’ll use these to start the server and do some manipulation of the URL to find out what we need to do. Line 5 creates the server object, and we pass in an anonymous function that will handle the logic for the server itself. We go dead simple and just respond to a URL that starts with ‘/add’ (everything else is just ignored).

If the URL starts with ‘/add’, we call the ‘dispatch_add’ function (line 14). It takes the request and response objects that get passed into the server so that we can get the query string and output a response. Line 15 separates out the query parameters into a JavaScript object.

Since this HTTP server is bare-bones, we need to output the headers to the client. We throw out an HTTP Code 200 and let it know we’re going to send it plain text (line 18). On the next line we write out to the client, and then close out the response. Line 20 is needed so that the client knows we’re finished sending a response.

Wrapping all the way back up to line 11, we actually start the server. We spit out a line to the console letting us know that the server is started as well as the address and port we should use.

JavaScript is Now a Viable Server-Side Technology

Servers like node.js allow users to create scripts and even services in a language that they already know. JavaScript is an easy way to write event-driven software and is a widely-accepted language. Will it supplant languages like PHP or Ruby for web technologies? No, but like everything else you should use the right tool for the job. Using available modules, you can create a node.js-based web server to render static websites, dynamic websites, APIs, interact with external libraries, and all sorts of things.

Browse through the modules that are available in npm, and just google. There are many different articles on ways to use node.js. You can also hit up the IRC channel on freenode under #node.js for support and questions. Take your knowledge of JavaScript, or begin expanding it, but moving it out of the browser and onto the server.

Categories: JavaScript, Programming | Tags: JavaScript, node.js, Tutorial

PHP 5.2 and MySQL 5 vs SQLQUERY and IBM DBU on V5R4

Posted on December 19, 2010 by Chris
No Comments

This is completely not at all scientific, but at work we needed to do what amounted to a giant SQL query to generate a stats file. The query itself was against two tables – one was 200,000 rows long and the other was 4.6 million rows long. We needed to add up many of the columns to get a row-by-row analysis on the individual pieces of a product, per customer.

The iSeries is a single CPU Power5 CPU running at 2.7ghz (I think), with 8gb of RAM and about 100gb of free harddrive space. We first ran the query on the iSeries using SQL. Within about 20 minutes we had eaten up 50gigs worth of hard drive space on the black box and had capitalized the CPU. That posed a problem as that meant we had used about 95% of the available harddrive space on the box, and the iSeries tends to shut down when that happens. The query was eventually killed.

Since the analysis was just a giant SQL query, I suggested moving it to one of the MySQL servers. It was an Ubuntu 8.04 box with half a gig of ram, 34gig of free hard drive, and a dual-core Xeon at 2.5ghz, all inside VMWare ESXi that is also running about 7 other VMs. Its actually one of our smaller virtual servers, but I figured we could sacrifice raw power for time.

We copied the tables to CSV, created the tables on the MySQL server, and then ran a PHP script to import the CSV files. All-in-all it took about 6 hours between beginning and end as giant 7gig files were shunted around the network and imported. I took the original query and modified it a bit for the joins, added an outfile to save the results, and set it to run.

I watched it for a bit. The CPU on the box never went about 75% on the query, though we had hit 100% during the import of the 4.6 million row database, and memory usage was never really above 20%. For the size of the tables, I was actually surprised. I let it just run.

In total, the first run took about 3.5 hours to run. I then learned that outfiles need an absolute path, not relative. Oh well. I ran it again and this time it ran in 2 hours, 48 minutes, which included actually generating the file. The file itself was almost 3gigs and 10 million lines long.

Not too shabby I’d say. The younger DB server on a small virtual machine did much better on resources than the more mature OS and hardware.

Categories: IBM i, MySQL, PHP | Tags: Coding, ibm, Linux, MySQL, Performance, PHP

Playing with Lithium

Posted on November 25, 2010 by Chris
4 Comments

Since my day job was generous enough to give me the entire week off (as a reward, thankfully not a “Don’t bother coming into work next week, or ever” kind of thing), I decided that I would spend some time looking at a new framework. I haven’t looked hard a new framework since I really started working with Zend Framework a few years ago. I decided to take a look at Lithium, an up-and-coming 5.3 only PHP framework.

Why Lithium (li3)?

li3 was designed from the ground up to take advantage of PHP 5.3′s new features and, at least coming from Zend Framework, has a much different workflow. It represented the biggest change in working with code compared to what I looked at as mostly syntax changes that frameworks like Kohana or CodeIgniter presented.

Filtering System

The filtering system allows for code to be modified on the fly without having to go in and modify the base class. The example on the Filters example page illustrates this: (modified below to what I ended up using):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Dispatcher::applyFilter('run', function($self, $params, $chain) {
    // First, define our list of protected actions
    $blacklist = array(
        '/lithium/users',
        '/lithium/users/add',
        '/lithium/home',
    );
 
    // Inspect the request to get the URL for the route the request matches
    $matches = in_array(Router::match($params['request']->url, $params['request']), $blacklist);
 
    // If this is a match, check it against an Auth configuration.
    if($matches && !Auth::check('user', $params['request'])) {
        // If the Auth check can't verify the user, redirect.
        Session::write('LoginRedirect', $params['request']->url);
        return new Response(array('location' => '/lithium/auth/login'));
    }
 
    // Important: return the results of the next filter in the chain.
    return $chain->next($self, $params, $chain);
});

The idea is that you have a base class, you apply an additional function to a method, and let the system handle it from there. The above filter will run when the Dispatcher::run() function gets called. It will take the current URL, compare it to a blacklist, and either redirect to the login page or allow the user through. Most of the core code is filterable so extending it to fit a developer’s need is easy.

It Really is a rad Framework

li3 is designed as a rad (Rapid Application Development) framework that just gets out of the way. For the most part, it did. The MVC structure is easy to pick up and there is a lot of magic that happens under the covers. Initially I had more trouble getting li3 and MongoDB to talk to each other (which ended up being a problem with the pecl extension), but once I did it was pretty easy from there. It wasn’t much more complicated than Zend Framework and Zend_Application.

5.3 Makes it Nice

li3 uses many of the new 5.3 features that were introduced to PHP. Closures, lambdas, and namespaces are a bit part of li3. This will make it somewhat hard for new programmers to pick up, but li3 doesn’t look like its targeting newbie developers (that’s not a bad thing). You really have to know what you are doing and what the code is doing. That said, if a developer understands the new 5.3 features, they are all set.

MongoDB is Easy to Work With

Once I got my pecl problem worked out, interacting with MongoDB was a breeze. A quick read-up on how MongoDB works, and a download of MongoHub really helped to work with MongoDB. I had more issues understanding how MongoDB worked than how to get it to work with li3. They did an excellent job lowering the entry bar to work with non-SQL databases.

Downsides

As with everything, there are some downsides. These aren’t enough to get me to not want to use li3, but it makes it hard for me to want to use in day-in-and-day-out.

It’s Evolving Rapidly

My biggest complaint is the lack of tutorials. The Blog Tutorial is nice, but leaves out of a lot of what goes on under the hood. The overall Drafts project will attempt to cover all the aspects of li3, but I did find some of the code already out of date. A good example is the Dispatcher filter example that I highlighted above; as it turns out, the example code doesn’t even work with the last release (0.9.9). @gwoo did have a point that IRC is always up to date, but getting answers on IRC isn’t always the quickest.

Technical documentation is helpful, but tutorials really help speed up the learning process. This is a big thing that the Zend Framework guys are striving to fix with Zend Framework 2, so it’s not just li3. This leads too…

Lack of Community Documentation (Or Maybe It’s Hard To Find)

The website lacks in tutorials, so the next logical thing is to move to Google. Finding user generated tutorials or example code was very hard. Lithium is a pretty common term on the web, and searching for things like ‘Lithium authentication tutorial’ brought up things not related to li3 at all. I found some code, but there was still an overall lack of community chatter. li3 is young, but it is still discouraging.

Relational Databases are a Second Class Citizen

I got working with MongoDB very quickly, but my sample application (a basic Twitter clone) fell apart with the database structure pretty quickly. I decided to switch to MySQL. That switch was easy (changed a config file and created the database), but then found out there was no support for table joins natively in li3 (though it is coming soon).

@jperras pointed me to the li3_doctrine project. That worked pretty well… until I tried to authenticate to my test website. li3_doctrine doesn’t seem to have code that supports the built in Form authentication in li3, and the one tutorial I found for using Doctrine 2 and li3 was out of date. That was discouraging.

Conclusion – li3 Has Its Place

If you want to use a NoSQL database like MongoDB, li3 gets you up and running very quickly. The overall code structure easy to use and a breath of fresh air. The IRC channel is helpful (they got me past the pecl problem) and is easy to talk to. The technical documentation is top notch as far as I’m concerned. Its actively developed and well designed.

If the relational database support was better and there were more code examples, I’d be more apt to use it more often. I’ll probably pick it up again when the next release comes out, but for right now li3 will be regulated to just the times I need a NoSQL database.

Categories: PHP, Programming | Tags: li3, lithium, PHP
Previous Entries
Next Entries
  • Search

  • Archives

    • February 2012
    • January 2012
    • September 2011
    • August 2011
    • April 2011
    • December 2010
    • November 2010
    • September 2010
    • August 2010
    • May 2010
    • April 2010
    • February 2010
    • January 2010
    • November 2009
    • October 2009
    • September 2009
    • June 2009
    • May 2009
    • February 2009
    • January 2009
    • November 2008
    • October 2008
    • July 2008
    • May 2008
    • February 2008
    • December 2007
    • October 2007
    • August 2007
    • July 2007
    • June 2007
    • May 2007
  • Categories

    • Code Releases
    • Doing Development
    • Hardware
    • IBM i
    • JavaScript
    • Joomla!
    • MySQL
    • Non-Programming
    • Operating Systems
    • Personal
    • PHP
    • Programming
    • Project Management
    • Reviews
    • Servers
    • Software
    • This Site
    • Tutorials
    • TWS Software
    • Uncategorized
    • ZendCon 2010
© Chris Tankersley. Proudly Powered by WordPress | Nest Theme by YChong