Natural traffic – Flex / Rails / ACL searchers

I have only really had a couple of personal sites in my fairly lengthy time using the web. I had a personal programming site from the tender age of 14 showcasing my (at the time questionable) skills as a C++ programmer. It also came with what I rather gloriously called a graphics library written in C using mode 13h, a DOS based 320×200 256 colour graphics mode. I called it dang.h (Dan graphics). It featured such oddities as hand written straight line drawing algorithms (Bresenham‘s if you’re interested). I also featured my favourite games of the week, notably Blood and Carmageddon.

Then came the ill-fated (although technically still running) thewatchblog. To be honest I should make more of that site, it explores very briefly one of my other passions, watch collecting. However I could never find the commitment to post regularly to it and lost interest.

But one of the best moments I remember as a web host was one day receiving an email from a chap using my dang.h library. He expressed his gratitude and asked for some pointers for some new development work he was considering. It was only a small, and possibly the only, piece of feedback I ever received from that website. However I remember being immensely pleased at the concept. Traffic has been relatively slow on this blog initially. I’ve had 6 comments … all spam so far (and one genuine from a friend). But, I was very pleased when looking at my natural traffic today I saw the following:

My first natural search traffic

My first natural search traffic

Promising, but what was even better were the search terms that led them here:

  • acl 9 rails
  • actionscript prevent focus out
  • adobe flex determine component focus
  • restful_authentication

I’ve still got a grin on my face looking at those. That encourages me to the fact that people might stumble across this site for knowledge and find what they are looking for. And it has certainly given me a boost to carry on publishing my tech findings. Now, just waiting for that elusive first comment… (no that’s not a plea)!

Adobe Flex – Controlling focus with ActionScript

For my up and coming project, very soon to be released, I’ve been using the client side Flash based technology Adobe Flex. The best way to describe Flex is probably Flash for programmers. It gives the programmer complete control over the application, using XML to define components and embedded ActionScript to specify the more complex interactions between them. It’s a fantastic technology, produces very slick interfaces very fast and best of all, is totally free. Well, free if you’re happy using the command line SDK to compile, otherwise their IDE is only about £150.

Having said all that, there are a couple of things that you think should be easy, and turn out not to be so obvious. This is particularly true when you want to tweak the built in UI functionality to do something different. The Flex developers have generally done a great job, but some of the form and error handling is not quite ideal and needs some tweaks to really work well.

The application I’m writing has lots of text boxes in a vertical column to fill in, one after the other. Straight out of the box the tab order works sensibly which is great, but I had a lot of feedback requesting that pressing enter should advance the form to the next field. Fortunately text fields have an “enter” event defined so I thought I could be clever and put something like:

    <mx:TextInput enter="focusOut" />

since focusOut is another event associated with TextInputs. I suppose practically speaking I shouldn’t expect that to work, but I thought there must be a built in function I could call on pressing enter to advance the form focus. Anyway, either there isn’t one or I couldn’t find it, so instead I defined a method called nextElement which will programmatically find the next component and set the focus on it, as so:

<mx:Script>
    <![CDATA[
        import mx.managers.IFocusManagerComponent;

        public function nextElement():void
        {
            var nextComponent:IFocusManagerComponent = focusManager.getNextFocusManagerComponent(true);
            nextComponent.setFocus();
        }
    ]]>

</mx:Script>

<mx:TextInput enter="nextElement()" />

The code should be pretty straight forward, the method simply finds the next component using the focusManager and sets the focus on that. Easy when you know how.

Ruby on Rails SMTP Mailer – sending mail

This is a topic that has been covered a few times but took me a while to pickup from a couple of different sources. A note about my tech posts, these are generally designed as references rather than tutorials so they will move fast and assume some basic knowledge.

Environment Settings

The first point of call is setting up your environment variables to tell Ruby your SMTP credentials. Add the following to the bottom of your conf/environment.rb file:


# SMTP configuration
config.action_mailer.delivery_method = :smtp

ActionMailer::Base.server_settings = {
:address => YOUR_MAIL_SERVER,
:port => 25,
:user_name => YOUR_USERNAME,
:password => YOUR_PASSWORD,
:authentication => :login
}

Replacing YOUR_MAIL_SERVER with the address of your mail server, typically mail.DOMAIN.com or smtp.DOMAIN.com. Replace YOUR_USERNAME and YOUR_PASSWORD with the username and password of a valid mail user on the server, the mails will appear to come from that person to your recipients.

Generate the mailer

Next we’ll generate the mailer class, using the very handy generate command. From the root directory of your project run:

script/generate mailer postoffice

This will generate a new class, postoffice.rb under the app/models directory containing the class called Postoffice. This class is responsible for building up email content and setting recipients. For each email you wish to send, you will typically create a method in this class. You can then automatically call Postoffice.deliver_METHOD_NAME and through some Ruby magic it will be sent. So, let’s say we want an email after someone has registered for your new game-changing site. We’ll create a register method which takes an email address and the name of the user in postoffice.rb:


class Postoffice < ActionMailer::Base

def register(email, username)
@recipients   = email
@from         = "mysender@mydomain.com"
headers         "Reply-to" => "mysender@mydomain.com"
@subject      = "Welcome to MyDomain"
@sent_on      = Time.now
@content_type = "text/html"

body[:username]  = username
body[:email] = email
end

end

Adding some templates

This method should self explanatory. The only point to make is the last two lines, they make the values username and email available in the email template files we are about to create. We create two files under app/views/postoffice, register.text.plain.erb and register.text.html.erb. Obviously one is for plain text email clients, the other for HTML. It is best practice to have both formats, there are still plenty of people who only read plain text (mainly sysadmins in my experience, I always though that was ironic). So as an example, register.text.html.erb could like like:


<p>
Welcome <%= @username %>,
You've just joined MyDomain.com, you must be significantly smarter than the average populous.
</p>

So, the final stage, how do we call the method to send the email. Well, in the main register method of your app (not the one we created above), at the point when you want to send the email place:

Postoffice.deliver_register(email, username)

where email and username are variables you have set up of course, referring to the email and username of the recipient of your email. One final note, you will need postfix running to test this locally. To start postfix on your machine (assuming you’re developing on a Mac), run:

sudo postfix start

at a terminal. Hope that helps.

Simplicity and Polish

I’ve recently bought a new 24″ iMac after many years using a PC as my main computer and occasionally begrudgingly using a “permanently borrowed” Mac laptop from my girlfriend. The new screen is certainly a sight to behold and has increased my productivity no end. I’m definitely not an avid gamer but one thing I am surprised is the lack of commercial games available for the Mac.

Before we take this tangent too far, the reason I mention it is because I’ve been trying out a few online Flash based games. Miniclip has tons of them, from flying a stunt plane to parking cars. But the place I always end up back at is WinterBells. The salient thought behind this post is that simplicity, or rather polished simplicity is an admirable target. While the games at miniclip are certainly impressive and flash (pun intended), the one I enjoy playing most is Winterbells. From a programmer’s perspective Winterbells looks simple, almost trivial, but there is literally nothing I can fault about it.

Let me explain. I think there is a tendency for application development to naturally descend into including everything and the kitchen sink. Business types are keen to include everything to see what shit sticks, development are probably thinking about showing off and working on fun technologies. Maybe taking a step back and focusing on what is important in your application; making that fantastic and giving sufficient time to polish it would be a better approach. That takes real work though, I have noticed recently that oftentimes over 50% of a project is taken up not in building something that works, but building something that is brilliant.

Take thepickuptruck as an example. I would say I wrote the bulk of the code, i.e. the database model, controllers and Twitter hashtag retrieval methods in a couple of nights maximum! Especially with some of the newer languages and frameworks, you can build something that works in a trivially small amout of time. It was tempting to think there wasn’t much left to do, but in fact the hardest bit was refining the app to feel finished and professional. The only word I can think of to truly describe this is polish. A good application should feel nice to use, smooth and polished. The chasm between something working and working well is huge, and truly separates the genius from the rest.

The lessons I have learnt (or am learning) are that focus is key, pick what you want to work and make sure you are totally happy with it. Approach suggestions for extra features with extreme skeptiscm, and if they are deemed important, plan for time not just to make them work but to make them shine.

restful_authentication and the Apache ACL

Wow, it didn’t take long after setting up this blog to find a coding issue that warranted blogging about. This is a real slap forehead WTF moment as well. I’ve been using the restful_authentication plugin for rails to handle my user registration and login. This is for a new site which will be announced shortly.

The site is currently sitting on a live server somewhere, so I decided to set up an Apache ACL while we have a closed beta test. An ACL is a way to get Apache to use basic authentication and log people in against a password file on the web server. It’s a quick way to lock down a site for a bit. See the bottom of the post for how to set up an ACL.

I sent around the ACL username / password to a few people, let’s say the username was pingu for argument’s sake. Well, the first person to use the site not only logs in to the ACL with pingu, but used it as a username to register on my rails app. Big deal you might think, I can’t imagine it would hurt. That would be your first (and my) mistake.

Somehow, the ACL interacted with restful_authentication so that anyone logging in to the ACL was also logged in to pingu’s rails account. I clearly don’t know enough about http authentication or the restful_authentication plugin but that is definitely unintended circumstances. Changing the ACL username put everything back to normal. Let’s hope no-one registers with the new ACL username!


edit – Setting up an ACL

I notice a few people got here after searching for ACL details so here’s a quick guide to setting one up. I’ve assumed your Apache instance is installed under /usr/local/apache, if it’s not then please replace /usr/local/apache with the appropriate path in the commands below.

Create a password file using htpasswd

The first step is to create a password file which defines usernames and passwords. This is done using the Apache supplied tool htpasswd (typically this lives in /usr/local/apache/bin). A good place to put your password file is /usr/local/apache/passwd/, although it can go anywhere Apache is able to access. Note that although this file has basic tampering precautions, typically MD5 hashing, it is not entirely secure and should be kept very secret from the rest of the world. So, move into your desired password directory, in our case /usr/local/apache/passwd/ (create it if it does not exist), and run:

/usr/local/apache/bin/htpasswd -c passwords myusername

This will overwrite any existing password files called “passwords” so ensure it doesn’t already exist. The c switch means create, passwords is the name of the file and myusername is the username of a user to add. It will prompt you for a password twice which will be set on the user “username”. To add new users, just remove the c switch (forgetting to do this will overwrite all previous users), i.e. run

/usr/local/apache/bin/htpasswd passwords anotheruser

Configuring a Location with AuthType

Typically an ACL is applied against a Location under a VirtualHost element. So, let’s say you want to lockdown an entire site for beta testers only. In the Apache configuration file httpd.conf (typically under /usr/local/apache/conf), find your VirtualHost element for the site you want to lockdown and add:

<Location "/">
    AuthType Basic
    AuthName "Authorised beta testers only"
    AuthUserFile /usr/local/apache/passwd/passwords
    Require user myusername
</Location>

The “/” specified by location means everything under the root directory of the site is password protected. If you just had some content, e.g. under a directory called protected, you could specify “/protected”. AuthName is the title of the prompt that the browser will bring up, AuthUserFile is the password file we created earlier. Require user specifies which users are allowed through. If you would like to allow all users in the password file through, you can specify Require valid-user instead. Restart Apache and every time you try and access something under the Location specified, your browser will prompt you for your username and password.

Hello World

And yes I do mean that in the geeky sense.

Who?

Welcome, my name is Daniel and I’ll be your guide for this journey, please keep hands and feet within the vehicle at all times.

So, another blog added to the (ugh!) blogosphere. Could there be anything left to say out there, any unique sentences left to be uttered? I’m sure there are plenty of combinations of words left to be spewed forth. To rephrase, are there any worthwhile sentences left to utter? My inner cynic says no but my literary heart says yes so let’s go with that for now.

What?

I’m a programmer by trade and by passion. I found myself consuming lots of material from the web for years and thought maybe now was the time to give something back. Plus I love hearing (and second best reading) the sound of my own voice. So the best of both worlds really. My craft has until recently focused solely on Java based websites. Fairly complicated sites to be fair, I currently run the tech team for the best looking business directory out there bview, and worked for the insurance comparison website simplybusiness (Phil the SEO man made me give him a link I swear).

This was honestly the first pickup that came up

This was honestly the first pickup that came up

But for fun in my spare time I’ve been focusing on the newer languages out there, Ruby On Rails (hereby RoR) being the main one. For a man who wouldn’t touch a language without a compiler (and ideally a virtual machine to run it in) I’ve branched out into the wonderful world of scripted languages. And decided for some things, I like it. My first foray was the whimsical (and occasionally NSFW) the pickuptruck, an answer looking for a question. It’s actually a great Twitter powered, user generated Web 2.0 extravaganza for pickup lines. I’ve even branched further into Flex, the dark programmer’s Flash tool with XML and everything! I’ll shortly be reporting on the app for that, needless to say it’s pretty “flash”.

Why?

I’m hoping this site becomes a useful resource for people to pick up advice on whatever technology I happen to be using this week. And a place for me to vent my spleen, my doctor said I should get the hosting on prescription to reduce my blood pressure.

As to the name of this blog, there are deep seated psychological reasons for it and I will be using my posts to exorcise demons and hopefully one day reveal the truth.

« Newer Posts