September, 2009


29
Sep 09

Ruby On Rails for .NET Developers (Part 1)

In this short series of posts I will document some of the steps required for an experienced .NET developer to get the most out Ruby On Rails.

Getting used to life without Visual Studio

Visual Studio really is a great IDE, in fact it is probably the best IDE I have ever used. And as a .NET developer moving from C# ASP.NET (or ASP.NET MVC) you are really going to miss the Visual Studio IDE, in fact you will at some point during your first few days without it, you will question question your decision to try another toolset.

In my experience of seeing .NET developers use Rails those that get past those first few days without the IDE make really good rails developers.

The Rails Way, Saves the Day!

Initially the lack of a great IDE can seem a real down point however, once you appreciate the mind set of a rails developer you will see that life does indeed go on without Visual Studio.

Life as a Rails developer is about designing beautiful interfaces with simple and intuitive user experiences, less of your time will be spent on heavy lifting

NOTE: At this point I should say that many “Good” IDE’s are available for Rails development, and I will mention some of them in a second ;-)

Getting Started

For the remainder of this series I will assume that you are going to continue developing on Windows, and as such will only mention tools that are available on Windows, but i strongly recommend that if you get chance to develop software using a Mac you do so, its very liberating….

To Develop Ruby on Rails apps you are going to need:

  • A Ruby Environment
  • Rails (as in Ruby on Rails)
  • A Database
  • A way to edit files (An IDE Maybe ;-)
  • An open mind (optional, but recommended)

Ruby Environment

This is really easy, go to Google and search for the Ruby One Click Installer, this simple installer will give you all you need to get started with Ruby.

One thing you will notice when developing in Ruby is the amount of time you spend in a Console Window, so lets start right now… Open a Command Prompt (Start->Run->CMD) and type the following:

  ruby -v

If your Ruby One Click installation was successful you should see something like:

ruby 1.8.6 (2007-08-11 patchlevel 111)

Don’t worry if the numbers on your system are slightly different, we are just confirming that you have a Ruby environment and it looks like you do ;-)

Rails

Ruby has a nice packaging mechanism called GEMs which is similar to package management systems on linux operating systems (apt-get) but for many .NET developers who are not exposed to Linux, its a pretty new concept, one that might even seem like a step backwards but don’t let the simplicity of it fool you, its a great system and will make you take a second look at that ‘Add/Remove programs’ dialog that you are used to using.

The One Click Installer was good enough to instal Gem for you, all you need to do is update it using the following command (command prompt again):

  gem update --system

This command (when complete) will have updated your Gem version to something equal to or greater than 1.5.3 (Depending on how old this article is when you read it), you can test this with the following command:

  gem -v

Your now ready to install rails with the following command:

gem install rails

This command will take a few minutes to complete but once it has you have almost all you need to build your first Rails app! Remember how long it took to install Visual Studio?

A Database

Rails will change the way you think about Database’s, which may or may not be a good thing but to fully embrace rails you may need to leave some of your old database habits at the door.

For this series of posts i’m going to use Mysql, and you should too (if your following along at home), but Rails works with SQLite, Mysql, PostgreSQL, SQL Server, Oracle, and more (i guess)
Go to the Mysql site and download Mysql Community Server (i’m currently using version 5.0) and while you are there get the GUI tools.

A Way to Edit Files (And IDE Maybe ;-)

I told you i would mention some Rails IDE’s… well you have a few options ranging from a simple Text editor like Notepad++ or Scintilla (this comes with the One Click Installer) to a “fully fledged” IDE like Netbeans (FREE) or RubyMine (by JetBrains, PAID).
The final choice on IDE’s is one that you have to make alone, but many of the rails guides that you come across on the WEB will assume that you are using a simple Text Editor and the Command Prompt, once you get experienced you will of course learn to love the refactoring and code completion features of IDE’s like RubyMine, but until then i recommend that you try to use your choice of IDE as a text editor and leave the “integrated” features alone.

For example I’m going to use Netbeans for these posts, but i’m not going to use any of the built in features, because they overlap many of the Command Prompt based commands that you will see referenced in this and other tutorials, once you are comfortable with them the choice is yours.

So go to www.netbeans.com and get the latest version of NetBeans

An Open Mind

Ruby (and Rails) will introduce you to a somewhat different approach to software design, you will at first find it hard to let go, particularly if you are the type of developer who thinks in terms of Interfaces and Object Orientation, Rails simply takes a lot of this out of the equation, within a few days you will think of your project in terms of User Interactions and models, which is great because it’s a nice “Agile” way to work.

Part 2

OK! Thats enough for Part 1, you now have the tools, next time I will go though the process of building and running a Rails app.

My aim with these posts is to create an app that you would have created in .NET, therefor i’m going to create a Rails version of the Time Tracking ASP.NET Starter Kit. You may have already come across this on the APS.NET Starter Kit site Time Track Web Site Starter Kit Does. Now it’s important to that i’m not going to look at the code, i’m simply going to look at the app and build in Rails using a nice Agile approach.

See you in part 2 ;-)

My name is Floyd Price, I’m a software developer (and MD an Tea boy) at Component Workshop a small software company in the UK, if you have any questions please let me know at floyd[at]componentworkshop[dot]com.


28
Sep 09

Tidy up your Java logging

The logging libraries provided with Java 5 and above are pretty good, except they produce output that is almost unreadable. For example, consider the simplest example:

Logger logger = Logger.getLogger("PushServer");

logger.log(Level.SEVERE, "This is a sample message");

That produces the following log entry, on your screen and/or in a file:

Sep 28, 2009 9:30:48 PM javaloggersample.Main main
SEVERE: This is a sample message

Individually, that’s OK, but 20 messages? Messy. 1000 messages? Pretty nasty. 100 threads each generating a stream of FINE messages? Yikes.

We recently wrote a Java server application that was massively threaded, and because of the nature of the systems we were communicating with, we needed solid logging output that we could easily scan to get an idea of the health of the software. The default logging format was not it.

While you can get some degree of flexibility by changing configuration options, we found that the best solution, for us, was writing a new Formatter that the logger client could use to generate output. Here’s the above sample, using our formatter:

28/09/2009 21:41:44 SEVERE: This is a sample message

That is vastly more readable when the log file starts filling up, because each message is on a single line and each component of the message is formatted in columns. Here’s our logger class — you should add this class to your own project:

public class SingleLineFormatter extends Formatter
{
    public SingleLineFormatter()
    {
    }

    private SimpleDateFormat dateFormat;

    static final String lineSep = System.getProperty("line.separator");

    public String format(LogRecord record)
    {
        StringBuilder buf = new StringBuilder(180);

        if (dateFormat == null)
            dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

        buf.append(dateFormat.format(new Date(record.getMillis())));
        buf.append(' ');
        buf.append(record.getLevel());
        buf.append(": ");
        buf.append(formatMessage(record));
        buf.append(lineSep);

        Throwable throwable = record.getThrown();

        if (throwable != null) {
            StringWriter sink = new StringWriter();
            throwable.printStackTrace(new PrintWriter(sink, true));
            buf.append(sink.toString());
        }

        return buf.toString();
    }
}

When you create your logger, you need to tell it not to use the default formatter, and to use this formatter instead. Since the original Apache Log4j, loggers have been hierarchical — you can set parent/child relationships between logger objects and the child will do as its parent does, plus any configuration of its own. Therefore, to disable the default logger we set UseParentHandler to false. Then, we create a handler and initialize it with our formatter:

Logger logger = Logger.getLogger("PushServer");

logger.setUseParentHandlers(false);

ConsoleHandler h = new ConsoleHandler();
h.setFormatter(new SingleLineFormatter());
h.setLevel(Level.ALL);
logger.addHandler(h);

logger.log(Level.SEVERE, "This is a sample message");

Hopefully this will be useful to somebody. We’re trying out something different here — posting coding tips to the CodeSpaces blog (rather than our company blog — Component Workshop). Also, we don’t often post Java tips, so on both of these points your feedback is most welcomed! Also, let us know if there are any topics you’d like us to cover — I think the next post might be about Middleware-Oriented-Messaging in .NET. — Adrian

This advice and any code samples are provided as-is, and without any warranty. You are free to use them as you wish. If you require professional services, or support on your own projects, get in touch with us and we’ll see if we can help. Note that we are UK based.