Angry Monkeys

Angry Monkeys is a web dev team based in Melbourne. We build software for smarter simians.

There are 1001 guides out there for installing bits and pieces of Ruby, Linux or Rails. This is intended as an absolute beginners guide, specifically for Windows users who don’t know jack about Linux, Ruby OR Rails. I’m a complete n00b at this. I spent a day or two trying to get this setup, finally worked it out and have gone back and done it all again whilst writing this guide on how I did it. I’ve tried to find the easiest way with the least complications. Advanced users will laugh at me, but they can go #&^$ themselves. If this whole setup wasn’t so difficult to use, I wouldn’t have needed to spend so long working out half of this stuff in the first place.  I hope it helps other .NET Ruby hopefuls, but please keep in mind, I am FAR from an expert, so comments/improvements/suggestions are more than welcome!

I was issued something of a challenge last week: To write our next web app in Ruby.

Not such a big deal right? I mean, it’s just another language? Can’t be that hard? I read this quickstart guide, and whilst Ruby is rather odd little language, it didn’t appear to be anything that I couldn’t handle. So, I decided to give it a go..

The first thing I’d suggest as a .NET developer of nearly 10 years, is that if you’re seriously considering giving Ruby on Rails a go, I strongly suggest playing around with .NET MVC first. As a big fan of MVC, getting into Rails was a lot easier, as many of the concepts found in MVC were…well…stolen fromRails. If you’re familiar with Models, Views, Controllers, lambda expressions, partials and all that stuff, Rails will be a breeze. Ruby is still an ugly SOB in my opinion…but at least Rails will feel familiar to you.

Step 1. Installing Linux.

You could use Cygwin, or even Windows, but I’d really suggest not. I tried this, and it’s just a pain in the ass. Besides, you won’t be using either in our production environment, so you best get used to Linux sooner rather than later! I chose Ubuntu, just because that’s what came up in Google. If that statement doesn’t make it clear, I’m a complete Linux beginner. I used Linux about 10 years ago, and haven’t touched it since. So if lack of knowledge of Linux is what’s been stopping you, have no fear. If I can manage it, anyone can.

You have a couple of options to get up and running with Linux. Setup a new Linux box, or run a Virtual Machine. I didn’t have a spare box lying around, so I chose the latter. So, first thing you’ll need to do is go off and download Oracle VM VirtualBox and Ubuntu. Then mount the Ubuntu ISO as a virtual CD drive in Windows (there are plenty of apps to do this, google it).

Install VirtualBox and create a New Machine, Call it Linux, choose Linux/Ubuntu as your OS Type. You can pretty safely click next repeatedly during the rest of the install. Once it has installed the VM, go to settings > storage. Click the little empty CD controller and from the CD/DVD device on the right, choose the drive which has your Linux ISO. Click ok and start up the VM. If you’ve done everything right to this point, Ubuntu should start installing. If it crashes because it can’t find your ISO, go back and check your settings.

Assuming you have a fairly standard machine, it should all install easily enough. Skip the language packs if you don’t need them, they take forever to download and install. Once it has installed, you’ll need to “power off” the VM, and remove the ISO so that Linux can boot. When you first get into Linux, it’ll want to install a heap of updates…just let it.

Ok, so If you’re a Linux n00b like me, you wont even know where to start. In fact, you’re probably wondering why the damned VM window is so small. To fix this, go to the Devices menu in VirtualBox, click the Install Guest Additions. This will mount another ISO in Linux. Go to Applications>Accessories>Terminal. Welcome to Linux’s DOS prompt :P

cd /media
cd VBOXADDITIONS_3.2.0_61806/

(bit of a tip for the REAL n00bs…rather than typing the directory, just hit TAB and it will autocomplete)

sudo sh ./VBoxLinuxAdditions-x86.run

This will go off and install a heap of stuff to make Linux run nicer with your host environment….including allow you to have nicer screen resolutions. Once it is done, do a reboot. Couple of quick tips. Right Ctrl is your host key. Ctrl+F will give you fullscreen.

That’s it. Step 1 complete! The best part is that you haven’t completely committed to using Linux, it’s not too late to back out. You’re only ever a delete key away from being back in the safe hands of Uncle Bill and his crazy Cousin Steve.

Step 2. Installing Ruby.

Unfortunately, that was the easy part. The next part caused me a lot of grief. I eventually worked it out, but only after a lot of Googling, and a lot of swearing and it turns out I didn’t actually need to do most of it. Hopefully I can save you from the same fate. The first thing you need to know is, whenever Googling, resist the temptation to Cut and Paste helpful command line tips and tricks. These often include references to a specific version of a package, and can screw everything up real quick. If you need to install ANYTHING, make double sure that you’ve got the right version. The problem here is that so many versions of Ruby, Gems and Rails have come and gone, and the installation methods, requirements and problems are all different. This can be a major headache for Linux beginners! Even going through this the second time, I’m still running into issues!

So, crack open the terminal again. If you haven’t already guessed you’ll spend a lot of time here! First thing to note is a command called “sudo”. Sudo is the Linux verison of “run as administrator”. Most of the commands you run for installation will be prefixed with this. It will prompt you with your admin password and then carry on. Second thing to note is that for the most part, you won’t need to download anything from any third party website when doing installs.  Linux has a rather nifty package installer that gets and installs everything for you! If you’re keen you can download source packages and compile them yourself, but we won’t need to do any of that.

So theoretically, Ubuntu should have most of what you need already, but we do need to go get a few bits and pieces. Make sure that the updater has finished before trying this, as it won’t work if it is still running.

The first thing you need is ruby.

sudo apt-get install ruby-full build-essential

Run this to make sure it installed ok.

ruby -v

This will print the version you just downloaded (hopefully!)

This will go off and get the latest version of ruby and install it and a heap of other libraries for you.  Done! You’ve run your first Linux command and installed ruby!

To install gems :

sudo apt-get install rubygems

Run this to make sure it installed ok

gem -v

While you’re here, install the ruby-debug gem

gem install ruby-debug

Done and done.

Step 3. Installing Rails

Ok, so now we have ruby, and ruby gems. Now we need rails.

sudo apt-get install rails

Yeah…that’s it.

Now that all looks pretty simple, and you could’ve done most of it from the one line. But there are PLENTY of guides out there that will show you how wget your source packages, untar them, compile them, run them blah blah blah. Linux zealots want to know why people still use Windows over Linux? Have a read of your guides! You have to have a PhD in astrophysics just to learn how to run a web app!

Step 4.  Install your IDE

Given that you’re a .NET developer, you’re going to need an IDE. None of this command line editing BS. We’ll be using Aptana Studio.

Go here: http://www.aptana.org/studio/download

Download the archive. You’re most likely using Firefox, so you should be able to find the zip in the downloads folder. Extract the archive to your home directory. You can then run aptana directly from there. You can also create a shortcut in your Applications menu. In Ubuntu, go to Preferences > Main Menu > Programming. Click the New Item button. Fill in the details, navigate to Aptana executable and select it, and also click the icon to change it to the Aptana one. Click Ok, close. And check it out in your Applications menu!

Great, that was easy! Well…not so fast! This is Linux! You can’t install something so easily! You need to do some more command line hacking. Ubuntu doesn’t come with Sun Java, which appears to be a prerequisite for Aptana. So now we need to install that.

First we need to add the java repo:

sudo add-apt-repository "deb http://archive.canonical.com/ lucid partner"

Then get the updated list of files

sudo apt-get update

Then install Java

sudo apt-get install sun-java6-jre

You can now run Aptana. Once you open Aptana, you’ll also want to click on the Plugins button and install RadRails. It’s pretty self explantory.

That’s about all you need to get up and running.

If at this point, you’re wondering “why the hell am I doing this???”, I don’t blame you!  We’re nearly done…hang in there! At this point you should be able to run a pretty basic website. So this a good time to….

Step 5.  Watch a video

As you won’t have installed it, you’ll need to install curl before you get too far in the video, and mongrel (a webserver) too. Just run:

sudo apt-get install curl
sudo apt-get install mongrel

If you ever find yourself missing something, that’s usually a good way to try to install it.

This 15 minute video will take you about 2 hours to get through. With a bit of luck, everything you’ve done till now will see you through the video. Use Aptana as your text editor for the examples. You’ll be pausing every ten seconds, but stick with it. By the end of it you’ll understand why so many developers love RoR….even if you still think Ruby is a pile of poo (like me), you’ll see how quick it is to get something up and running in Rails.

Before watching the video, make sure you create yourself a code directory.

cd ~
mkdir code
cd code

And now enjoy the video!

http://media.rubyonrails.org/video/rails_blog_2.mov

Step 6. What next?

The good news is, that if you got through the video and everything worked, then you have everything you need to create your first web app. One good thing about Ruby is that there is a plethora of resources out there to get you moving from here. The one major pitfall is that there are HEAPS of tutorials that are hopelessly out of date, and can not only lead you astray but cause you some serious headaches if you mess up your installation!

There is a lot still to learn about RoR, especially for me, but I hope this is a good starting point. My goal was to write something that got ME up and running. I figure there are plenty of Windows developers out there (like me) that wouldn’t have the foggiest idea where to start, so if that is you, I hope this has helped!

Cheers,

Alan

Using plupload with ASP.NET

posted February 26th 2010

I hate file uploaders. The simplest way is always the ugliest, and having anything “nice” requires days of backbreaking labour, and even then you’re not even close to being sure it will work across all browsers. It’s frustrating to do so much work and then have some users receive seemingly random errors for no apparent reason!

Matt pointed this neat file uploader out to me the other day, plupload. It is very simple and has about a half dozen “fallbacks” for supporting different technologies from Google Gears, Flash and HTML5.

For the most part implementing plupload is a matter of downloading the zip, unzipping and whacking in some sample code. But there IS a catch. Plupload uses BINAY STREAMING, not your bog standard multipart upload. So if you’re hoping for a simple drag and drop replacement for your existing code, sorry to disappoint. But it’s not that hard to convert your existing app into a binary stream app!

Of course, there is an easy PHP implementation from the folks that wrote plupload, but I really struggled to find an ASP.NET one. So here’s one I wrote based loosely on the PHP version! This is not complete by any stretch (you’d want to handle caching, I/O errors, folder creation etc), but this is the guts of it to save you some research.

Two main things you’ll want to take note of.

1. Plupload supports chunks – this is a way to get around upload file size restrictions. Basically, the file can be chopped up and sent as multiple parts, and then put back together again when it arrives. If you look at the requests going to the server, you will see there are actually multiple requests PER FILE. This means we need to stitch the files together when we’re done at the other end.

2. Data handling – plupload stores the file name, and chunk info into the querystring, and all the file data is in Request.InputStream…so don’t bother trying to work out why Request.Files is empty!

Here is the basics of what you need to implement plupload in asp.net! Easy as! If you’re using any other file uploader, change it NOW!


int chunk = Request.QueryString["chunk"] != null ? int.Parse(Request.QueryString["chunk"]) : 0;
string fileName = Request.QueryString["name"] != null ? Request.QueryString["name"] : "";

//open a file, if our chunk is 1 or more, we should be appending to an existing file, otherwise create a new file
FileStream fs = new FileStream(Server.MapPath("/files/" + fileName), chunk == 0 ? FileMode.OpenOrCreate : FileMode.Append);

//write our input stream to a buffer
Byte[] buffer = new Byte[Request.InputStream.Length];
Request.InputStream.Read(buffer, 0, buffer.Length);

//write the buffer to a file.
fs.Write(buffer, 0, buffer.Length);
fs.Close();

Of course, if you’re REALLY lazy, they’ve just recently updated plupload to support multipart uploads…but that’s just boring!

ExtJS and .NET MVC

posted August 27th 2009

I’ve been using JQuery with .NET MVC for a while now, and it works wonderfully. I’ve made a couple of post previously on the subject. In my most recent project I’ve been using ExtJS with .NET MVC and it works wonderfully well (for the most part!).

Since the latest version of ExtJS (v3) came out, it has gotten a whole lot easier with full REST support for data stores.

When I first sat down to write my data components for this particular project, I made my subclass of the Store class (or JSONStore depending on what I was doing), and implemented my own REST-style interface. This basically involved providing a URL and then appending _get, _set, _delete etc to get the appropriate URL. It was messy and ugly and didn’t work like REST should.

Fortunately, around this time version 3 of ExtJS came out and solved all my issues in one go.

Now by including the property “restful:true” into your Store, the store will automatically wire up the get, set, update and delete methods for you.

var store = new Ext.data.Store({
restful: true,
...

In my case, I am using a datagrid with a row editor. This means that when I click add, delete, update or load, the data store will take care of everything. All I need to do is provide a URL. Now, most ASP.NET developers will have never come across this, but it’s definitely something you should be aware of.

All 4 actions use the same URL (and hence the same method name in the controller) but with varying HttpVerbs.


        [AcceptVerbs(HttpVerbs.Delete)]

        [AcceptVerbs(HttpVerbs.Post)]

        [AcceptVerbs(HttpVerbs.Put)]

        [AcceptVerbs(HttpVerbs.Get)]

What this means is that in your controller you can have ONE method name (but 4 separate methods) to handle all requests for this data type. Not only is it a lot neater, it’s a lot easier to understand.

Managing Databases in .NET

posted May 17th 2009

Migrating databases has always been a pain the ass.

In the past, I’ve used tools like RedGate SQL Compare to get the job done. The last major project I worked on (with a team of a dozen developers) we used a custom solution of managing sql updates and change scripts. Nasty business.

The main issue with updating databases is not only making sure that your test database matches your staging database which matches your live database, BUT that the database of each instance matches the code running alongside that database. Regardless of which method you use the code-sql versioning has always been a pain. I can’t count the number of times an SQL update has been applied when the relevant code patch hasn’t!

This problem is magnified when you are working in an “Agile” environment. When you’re making frequent code updates and with a scope that is constantly changing, databases changes unfortunately are a necessary evil. The Ruby crowd have been using database migrations for some time now, and it’s only recently that the .NET community is catching up.

I’ve recently begun using MigratorDotNet. It’s not perfect, and is still fairly immature, but it makes managing databases a lot easier than keeping track of change scripts! My particular implementation probably isn’t the most recommended method…but it works for me and it saves a lot of messing around with build targets and project configurations. If you haven’t already, take a look at the wiki and have a read of the “getting started” page…cos I’m going to assume you know what this code does…..

    [Migration(1)]
    public class _001_Init : Migration
    {
        public override void Up()
        {
              Database.AddTable("dbo.tbl_Tokens",
              new Column("TokenId", DbType.Guid, ColumnProperty.PrimaryKey),
              new Column("UserId", DbType.Guid, ColumnProperty.NotNull),
              new Column("DatePurchased", DbType.DateTime),
              new Column("DateUsed", DbType.DateTime)
          );
         }
     }

Where I change my process is how I set up my projects and how I run my migration. This is for a web application obviously btw.

Do this much (taken from the getting started Wiki):

1. Add a new class library project. In this example it’s called Called DBMigration.
2. Create a lib directory in your DBMigration project, and extract all the dotnetmigrator DLLs into it. You can exclude database-specific DLLs that you don’t need. e.g. If you’re not using Oracle, you don’t need Oracle.DataAccess.dll.
3. In your DBMigration project, add a reference to the Migrator.Framework.dll. That’s the only additional reference you need in the project.

Now….Ignore the rest of the steps, and do this instead :)

4. Create your first migration class (like the one above).
5. In your web application, add a reference to Migrator, Migrator.Framework and your DBMigration project.

Here’s the trick for the lazy peeps that can’t be bothered messing with MSBuild and build targets!

In your Global.asax file… you want something like this:

 protected void Application_Start()
 {
            string strConnString = ConfigurationManager.ConnectionStrings["AspNetSqlProvider"].ConnectionString;
            Assembly a = System.Reflection.Assembly.Load("DBMigration");

            Migrator.Migrator m = new Migrator.Migrator("SqlServer", strConnString, a);
            m.MigrateToLastVersion();
}

Whenever you update the code for your application, on first run the application will automagically update the database using your migration scripts! Nifty!

A few important things to take note of here!

The first thing to understand is the connection string. I set up my connection strings using an external XML which is referenced from web.config….like this

<connectionStrings configSource="connections.config"/>


And in my connections.config file I have the connection string for the Live OR test OR staging server. There is different version of this file on each respective server (thus make sure it’s not in your solution if you use VS deployment!).

Why? So that when I deploy my application to the test server, or to staging, it will be updating the database for THAT server only. This means I have a seamless means of updating my database at the same time as updating my code. No batch files, no configuration, no build targets! Just run it, and it updates the right database!

Now, obviously this is NOT ideal for all situations. You’d really need to be sure that this approach is suitable for what you need. For us, we do infrequent updates to the live server, but are constantly updating our staging server. This approach means that whenever we deploy and run the website, we know the database is going to be update and correct!

AJAX with JQuery and MVC

posted March 09th 2009

I love JQuery. I used to hate it. But now I love it. I especially love it when working with .NET MVC.

I’m building an app at the moment which allows a user to upload a file, and during the process they can choose to have a link to the file sent to them. It’s an optional thing, just to save them having to cut and paste a link. It’s a nothing feature… a bit of a freebie, and I didn’t want to spend a lot of time on it.

More importantly, I didn’t want to stop the user in their tracks to do this particular task. The email field just sits there in the Nav, and if you want to use it you can and if you don’t want to you don’t have to. Most importantly, however, if they user did choose to fill in the email box at some point, I didn’t want to take them away from what they were doing by doing a full post of the page. Enter AJAX!

Ajax is nothing new, and neither is MVC. But in the world of .NET they’re both still kinda fresh. So here is how I went about creating a neat little emailer in the middle of a page.

First of all, some HTML. The simpler the better!

<form id="EmailForm" action="/test/email" method="post">
    <input id="emailAddress" type="text" value="email address" />
    <input type="submit" value="go" />
</form>

Then some JQuery….

$("#EmailForm").submit(function() {                                    //capture the submit event of our form
    $.ajax({                                                           //create an AJAX request
        type: "POST",                                                  //use POST (we could also load this from the form if wanted to)
	url: $("#EmailForm").attr("action"),                           //get the URL from the form
	data: $("#EmailForm").serialize(),			       // this one line turns our whole form into tasty AJAX snacks!
	success: function() {
	    alert("win!!!1!1!")                                        //we got a 200 back...it worked!
	},
	error: function(XMLHttpRequest, textStatus, errorThrown) {
	    alert("epic fail!")                                         //something went HORRIBLY wrong!
	}
    });
    return false;                            //don't forget to cancel the event so we don't submit the page!
});

OK, so far so good. All pretty straight forward. That, of course, would work with any server side technology…not just .NET MVC. BUT, the reason I like this so much is because with MVC we don’t even have to bother with a responding page. Previously in .NET you’d have to create an ASPX page or web service just to handle this AJAX request (or a library of them perhaps). If you have a route setup already, all we need is a method in our controller class to handle the AJAX request!

[AcceptVerbs(HttpVerbs.Post)]
public void Email(FormCollection form)
{
    string emailAddress = form["emailAddress"];
    // validate the email address
    .....
    //create the email message
    MailMessage msgMail = new MailMessage("info@angrymonkeys.com.au", emailAddress);

    // do some email content stuff
    .......

    // send the email!
    smtp.Send(msgMail);
}

That’s all there is to it! Of course, this particular method doesn’t return anything to the AJAX callback (except an error if something breaks!)….. so you’d probably want to return something if the address is invalid and show a nice error to the user. But I’m keeping it simple here.

The crux of what is cool about this, however, is the separation between HTML and code. Because MVC doesn’t have tightly coupled Pages/Classes/Code behind, you can not only reduce the amount of code you write (by doing away with superfluous aspx pages and reusing existing functions), but you increase the number of ways you can use the code you have already written. Doing an AJAX request becomes nothing other than another type of View…. the Controller doesn’t have to care where the request is coming from and it means neither do you!