Categories
Other Programming

CoffeeScript with WebSQL and jQuery

Lately I’ve developed a distaste for Javascript.  I like what Javascript has done for the web, but I hate the syntax.  I hate that there are little “Gotch Ya!”‘s all over the language.  I don’t have to worry about that too much anymore though since I’ve started using CoffeeScript.  If you interested in learning more about it, check out the official web site, and then my “Getting Started” guide.

Now that I’ve had a chance to dive in to CoffeeScript a bit more, I’ve started to integrate what I’m doing with other features and libraries to see what I can create.  For work I’ve been using a lot of WebSQL and jQuery, so that was the first place I took my new found CoffeeScript powers to.

Using jQuery with CoffeeScript is really, really, easy.  For instance, let’s say we want to Ajax a page into an array:

$.get("mypage.html", (data) ->
    myArray.push data
)

The syntax changes just a hair, but overall it looks a lot cleaner.

As mentioned previously, the other thing I’ve been doing a lot at work recently was working with WebSQL.  It’s been dropped by the W3C, but Webkit has implemented it already so it’s here to stay.  Anyways, CoffeeScript makes WebSQL a little more palatable.

#Start a transaction
db.transaction( (tx) ->
    query = "SELECT * FROM table"
    tx.executeSql(query, [], (tx, results) ->
        rLength = results.rows.length
        for(i=0; i < rLength; i++)
            alert results.rows.item(i).someColName
    )
)

With WebSQL and CoffeeScript, the syntax doesn’t change a ton, but I like the look of it better without the braces.

Another feature that I wanted to share with out about CoffeeScript is it’s equivalent to PHP’s key, value loop construct.  In PHP, it would look like:

foreach($key => $value as $myArray) {
    //do stuff
}

In CoffeeScript, the equivalent is:

for own key, value of myArray
    #Do stuff.

The benefit of the CoffeeScript version is that it can loop over object properties as well, not just arrays.  If you have any other cool features or examples of CoffeeScript usage, drop a link (or example) into the comments.

Categories
Other Programming

Getting Started with CoffeeScript

Note: You may also be interested in “CoffeeScript with WebSQL and jQuery“, which gives more examples of CoffeeScript code.

Lately in web development circles there has been a movement to make Javascript easier for everyone. Well, easier is probably the wrong word.  Lets just say that they want to “modernize” it’s syntax.  A little language has been gaining a lot of attention lately that does just this, and it’s called CoffeeScript.  A quick example of assigned on a condition:

big = true
number = 100 if big

Instead of:

var big = true;
if(big) {
   number = 100;
}

Anyways, this tutorial is about getting the CoffeeScript compiler up and running. To do this, you’re going to need Node.js and the Node Package Manager(NPM).

Step 1: Node.js

Getting Node to install is pretty straight forward. All you need to do is download the latest stable version from here and then run:

./configure
make
make install (may need to run as super user)

Step 2: Node Package Manager

Node Package Manager is the equivalent of EasyInstall for Python. It allows a user to install pre-made programs, like CoffeeScript, easily without worrying about build dependencies or any annoying stuff like that.

If you have Curl installed (most Linux/Mac users will), the easiest way to make this happen is to do the following:

curl http://npmjs.org/install.sh | sh

I personally ran into problems with this because of some permissions errors. If you run into this, check https://github.com/isaacs/npm/blob/master/README.md out which has extensive documentation on how to get around it.

Step 3: Install Coffee

Now that we have all of Coffee’s dependencies solved, you can install CofeeScript by doing:

npm install coffee-script

Step 4: Brew Some Cofee

Let’s make a math object…

math =
	cube: (x) -> x * x * x
	square: (x) -> x * x
 
startNumber = 2
cubeStartNumber = math.cube(startNumber)
squareStartNumber = math.square(startNumber)
alert "Cube: " + cubeStartNumber
alert "Square: " + squareStartNumber

Now, save this file to test.cs and then run coffee -c test.cs on the file. You will get a new file called test.js that looks like:

(function() {
  var cubeStartNumber, math, squareStartNumber, startNumber;
  math = {
    cube: function(x) {
      return x * x * x;
    },
    square: function(x) {
      return x * x;
    }
  };
  startNumber = 2;
  cubeStartNumber = math.cube(startNumber);
  squareStartNumber = math.square(startNumber);
  alert("Cube: " + cubeStartNumber);
  alert("Square: " + squareStartNumber);
}).call(this);

That’s it!

If you run in to any problems during the install process, drop a line in the comments and I’d be happy to help.

Categories
Other Other Programming PHP Programming

SVN Merge Example (Trunk to Branch)

I’m often in the situation where I need to merge changes from the trunk development into a branch.  I can never, EVER, remember the command, so I’m putting in here in hopes that I can reference it again and that other people might find it useful.

svn merge -r x:y svn://repositoryURL/repo/trunk/ .

So, how does it work? X is the revision that you branched at. This can also be the revision that you last merged changes from. Y is the version that you want to merge up to.  In most instances, HEAD is probably what you’re looking for.

Note:  Using –dry-run if you want to see the changes that will be made before actually doing it.  It takes some of the “this is scary” out of merging.

Categories
Other Programming

Load Javascript Dynamically With Lazy Load

One of the blessings (or plagues) or the “Web 2.0” revolution is heavy use of Javascript.  Used properly, Javascript can enhance your user experience to nearly the level of a desktop application.  Used poorly, and you’re browser is going to crash and burn.  But this post isn’t about using Javascript, it’s about loading it.

You see, a large amount of web developers don’t think about how their web page is loaded.  They think that no matter where scripts are included, its going to take the same time to load.  Actually, this is true.  What we’re after is an apparent decrease in load time.  When you include Javascript files at the top of your HTML document, as soon as the browser encounters the Javascript it will load and execute it.  The problem here is that loading a Javascript file is a blocking call in most web browsers.  What does this mean to you?  It means that while the Javascript is loading, the rest of your page isn’t.  The apparent page load time has increased.

To get around this problem, some web developers have started including their scripts as the last element in the <body> tag.  Done this way, your entire page loads on to the screen before the Javascript starts to load.  The apparent page load time as decreased.  Yes, the script will still take the same time to download and execute, but now people will see content almost immediately.

But why should you include some Javascript files if you aren’t sure the user is going to make use of them?  Enter Lazy Load.  Lazy Load allows you to easily include Javascript or CSS files on the fly.  This is especially helpful when you have large files that need to be loaded.  For instance, a sweet new carousel for your site.  It’s probably pretty large, and the user is going to have to wait for it anyways.  Using Lazy Load you can decrease your site’s apparent and actual load time.  It’s also small (~800 bytes minified), so you won’t need to worry about the footprint.  Oh, it’s really easy too…

LazyLoad.js('http://example.com/foo.js', function () {
     alert('foo.js has been loaded');
});
Categories
Other Programming PHP Programming

Form Ajax : How to Create and Submit a Form Using Ajax

For the longest time, web developers were stuck submitting their forms in the normal way: Click a button, go to a processing page, redirect back.  However, now it is possible to submit a form without ever leaving the page with Ajax.  Ajax stands for Asynchronous JavaScript, which as stated before, basically means you can submit a form without ever leaving the page.

So how do you use form Ajax? First of all, we’re going use a JavaScript library called jQuery.  Don’t be scared of it though, jQuery makes JavaScript easy.  What jQuery allows us to do is use form Ajax without having to muck around with all the tedious JavaScript details (which trust me, is a GOOD thing).   Without further a due, here is how to submit a form with Ajax.

To download the full working code for this, click here.

Form Ajax Step 1:  The HTML Page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<html>
<head>
<title>Form Ajax Tutorial</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
//After the document has loaded, it adds the following handlers
//to the web page.
$(document).ready(function() {
//When the form with id="myform" is submitted...
$("#myform").submit(function() {
     //Send the serialized data to formProcessor.php.
     $.post("formProcessor.php", $("#myform").serialize(),
     //Take our repsonse, and replace whatever is in the "formResponse"
     //div with it.
    function(data) {
          $("#formResponse").html(data);
     }
);
return false;
});
});
</script>
<head>
<body>
<h2&gt;Form Ajax Tutorial</h2>
<p&gt; Fill out some information &lt;/p>
<form id="myform">
<input type="text" name="firstName" value="" /><br />
<input type="text" name="lastName" value="" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
<div id="formResponse">
</div>
</body>
</html>

For anyone who is used to HTML programming, this should all look very familiar.  The only confusing part is the JavaScript, but I’ll explain that here.  The first bit just includes the jQuery library.  This is crucial for form ajax to work.  The rest of the function is explained below:

  • $(document).ready() – This will add handlers to your web page only after the entire page has loaded.
  • $().submit() – This will catch the click of the submit button so that it doesn’t submit the form the normal way, but the Ajax way instead.
  • $().post() – This is the part that sends out data to the processing file.  It also has a callback function that will modify our page to contain data that the processing file sent back.
  • $().serialize() – Takes our form data and puts it into an easy to parse format.

Form Ajax Step 2:  The Processing Page

1
2
3
4
5
6
7
8
9
10
11
<?php
//Get the information that was sent from the form.
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
 
//Get the unix time stamp.
$unixTimeStamp = time();
 
//Print output for out web page to catch.
echo "Hello $firstName $lastName.  The local unix time is <b>$unixTimeStamp</b>";
?>

The processing page is very important for making form ajax work correctly.  What this file does is catch the data sent by the form, and then prints out some information.  The form is waiting for this information, and then will add it to your page.  Note:  This file is a .PHP file.  You need to be running a web server (or have access to one) that can process php files.

Form Ajax Step 3:  You’re Done!

Form Ajax used to be pretty difficult, but now that their are JavaScript libraries like jQuery, MooTools, and Scriptaculous, it’s easier than ever.  To download the full working code for this example, click here.

Categories
Other Programming

Javascript Net PDF Viewer

When trying to view PDF files on the internet, you have a very limited number of choices.  The obvious one is to let the user handle viewing PDFs with something like Adobe Acrobat Reader.  However, some users don’t have Acrobat installed.  Or the file gets downloaded instead.  If you want an easy way to view PDF files online though, look no further than Google Docs.

The Google Docs Javascript PDF Viewer will embed the same javascript pdf viewer that Google Docs uses right in to your page via an IFrame.  It’s really that easy.  It even allows for searching of documents (which is quite handy!).  If this sounds like what you’re looking for, the link is below.

Javascript Net PDF Viewer [Google Docs]

Categories
IPhone App Development

iPhone and iPod Touch Development: Starting Out

Beginning iPhone 3 Development Book CoverLast Christmas I graduated from college.  One of my graduation gifts was a 2nd generation iPod Touch!  At the time, the iPod Touch was one of the coolest things I had ever got.  I immediately started to play with it, and was impressed with it’s ability to know the orientation of the device.  It’s multi-touch support was also impressive.  Probably the coolest part of owning an iPod Touch was that “there’s an app for that” attitude.  The sheer volume of available apps was mind blowing.

After graduation I started grad school, so I didn’t have much time to play on the technical side of iPod Touch and iPhone development.  However, I now have the time, and what follows is my journey on the road to iPod Touch and iPhone development enlightenment.

Getting Started

iPod Touch on top of "Beginning iPhone 3 Development"
The iPod Touch. A little banged up, but still amazing.

Before I even got started with iPhone development, I already ran into a problem:  I don’t own a Mac, nor do I want to own one.  It’s not that I don’t like them.  They’re beautiful machines with top of the line hardware and software, it’s just they’re a little outside my

price range.  So, how does one go about developing for the iPod Touch and iPhone on a Windows machine?  Well, there are a few different options.  Some revolve around Cygwin, while others around VMWare.  There is a good thread going on over at Stack Overflow (here) about it.  Depending on your situation, you may want to just pony up the cash for a Mac Mini, but to each their own.  In my case, I went with one of the methods listed above.

About the Book

The book I’ll be using for this adventure is “Beginning iPhone 3 Development:  Exploring the iPhone SDK” by Dave Mark and Jeff LaMarche.  It was reasonably priced, well reviewed, and had a grapefruit on the cover.  How could I possibly go wrong with this?  While I’ve only read the back cover at this point, the only problem I have with it is that it fails to mention the need for a Mac.  Some people might say “Duh!  Of course you need a Mac for iPhone and iPod Touch development!”, but it’s not always obvious to everyone.

Requirements

As with most development projects, there are a few things you need before you get started.  In the case of iPhone & iPod Touch development, you need the iPhone SDK (also, from this point forward I’m going to start referring to “iPhone & iPod Touch development” as “iPhone development”).  To get at the iPhone SDK, you need to visit http://developer.apple.com/iphone/ and sign up to be an iPhone developer.  It’s free (or has free options), so that’s a relief.

The sign up process seemed fairly painless.  While I’m not a huge fan of having to register and give out personal information, they control the SDK, so I suppose I must do as they say.  Nothing too suprising once you’re through the registration though, except the download is 2.5 GB!!! The worst part is that I have no idea why.  I always thought Netbeans with the JDK/JRE was huge, but this thing blows it out of the water.

Hello World

It’s a programming tradition to learn any new programming language with a simple “Hello World” program.  Even when not programming, some programmers still use “Hello World” to break the ice.  Hardly one to break with tradition, I’m going to be starting with a “Hello World” too, except this time for an entire platform, instead of just a programming language.

After much fumbling around, here are the steps to getting a “Hello World” program started.

  1. Open XCode and select New Project… from the File menu.
  2. Select View-based Application.
  3. Name your project Hello World.
  4. In the Groups and Files window, open the Resources group.
  5. Double Click the file Hello_WorldViewController.xib
  6. With the view now open, browse down the library until you find Label.
  7. Drag the label to the view.
  8. Double Click the label, and type “Hello world!”.
  9. Now go to File, then Save.
  10. Go back to Xcode and select Build, then Build and Run.

Honestly, I expected it to be a bit harder than this.  Next time I’m hoping to make it though chapter 3, where I get to learn how to handle basic user interaction!  As always, any feedback is welcome.

Categories
Other Programming

Using HTTPService to get XML results from a server

I’m not a Flex developer, but I’m quickly becoming one.  Recently I was tasked with creating a Flex form, sending it to the server, waiting for a response, and handling things accordingly.  My problem was that I couldn’t figure out how to use my result set that I received from the server.  Turns out, I needed to import a EventResult library, which was the turning point.

The Actionscript

import mx.rpc.events.ResultEvent;

private function thanks(evt:ResultEvent):void{
var dataFromServer:XML = XML(evt.result);
mx.controls.Alert.show(dataFromServer.toXMLString());
}

The Flex

<mx:HTTPService
id=”srv” useProxy=”false”
url=”http://localhost/form.php” method=”POST”
contentType=”application/x-www-form-urlencoded”
resultFormat=”xml” result=”thanks(event); “>
<mx:request>
<name>
{ bname.text }
</name>
<address>
{ baddress.text }

</address>
</mx:request>
</mx:HTTPService>

What happens here is that the HTTPService sends my data to the server, then some new data is returned in XML format.  Important things to remember are the ResultEvent that is passed to the event handler.  Just passing a normal event didn’t do much for me.