Going ASP.NET MVC (ALT.NET style)

Author: Rafael - Publish date: Mon, 16 Mar 2009 23:30:00 -0300 Mar 16

Everybody knows I’m far from a Micro$oft fanboy, but if you think about this under a pragmatic perspective, you’ll come to the conclusion that, even if they are a force of Evil, we must handle them and those who use their technology, some of them under coercion :). So, how can we go about it? Well, my short answer is ASP.NET MVC.

S#arp Architecture

ASP.NET MVC is a quite open-source (there are some limitations in the license) which breaks with the dreaded Webforms model and bring some MVC goodness to the M$ table. In the recent years we’ve seem many MVC web frameworks in the spotlight, my favorite being, of course, Ruby on Rails, but there are Django (Python), Joomla (PHP), Groovy on Grails (Java based – horrible name), Catalyst (Perl), and many more, so it was time to do the same with ASP.NET.

In fact, the .NET guys already had a MVC web framework, the Monorail (can you guess what inspired it?), a open-source project by the guys from the Castle Project that ported some of the ideas an practices from the Rails world. The problem is obvious: it’s not mothership certified and you can’t get a certification, so it never received the deserved attention when compared to the official choice. That sucks, but they were smart and hired Hammet, the founder of Castle, and I believe he is working on the MEF team. Back to ASP.NET MVC.

It’s a nice framework, quite well thought, much more adapted to the current best practices for web development and, the best part, stateless. For me this is its the best feature, no more ugly and heavy view state, no more magic, no more leaky abstractions. If you want to keep state in a stateless architecture be my guest and do it yourself. The “bad” side (not for me) is that you loose all the fancy webcontrol stuff and must learn some good practices and HTML, CSS, Javascript, Dependency Injection and ORM-techniques for real (at least for someone who’s interested in doing a good work).

My objection to ASP.NET MVC is that it’s not opinionated enough, but being a happy railer that’s just natural. Even though the framework gives you a pre-built structure and many of the tools you need to create a good app, you still need to make a lot of choices: which ORM? which Dependency Injection tool? how to create templates? and many more. It’s quite hard to start from scratch and choose all this, specially when we have so many options for each (which is very good).

Of course I wasn’t the only one, many people from the ALT.NET world embraced the ASP.NET MVC idea, complained about (more or less) the same stuff and decided to create a common infra-structure with all of these choices sorted out. Led by Billy McCafferty, they created the S#arp Architecture project.

As we’re approaching the official 1.0 version of ASP.NET MVC, these guys worked hard to sync their project up to the latest functionalities of the release candidate version, and they made a very good job. With S#arp Architecture it’s much easier to start developing the application, with many good default choices already made, some architecture guidelines to make it testable and maintainable, making it possible to capture all the value the framework can give us.

Most of the options (if not all) use open-source projects like Castle Windsor, NHibernate, Fluent NHibernate, NInject, etc. You can choose what to use, and reap the benefits of the many hours of tears and sweat it’s developer poured into it.

The downside (for some) is that you need to take sometime to study these choices to use it well, but I’m sure it would be much, much, much worse without it, and there are lots of documentation. Billy himself wrote an article about the project to InfoQ, and I recommend that you take a look at it, and after that go to the project’s page, download and take it for a spin.

And remember: it’s a open-source project. If you want to contribute go to their group, talk to them, discuss your ideas and see what you can do together.

Read more...

Comments: 2 Sections: altnet | Tags: alt_net,aspnet_mvc,csharp,sharp_architecture

Everybody hates Windows

Author: Rafael - Publish date: Mon, 16 Feb 2009 05:00:00 -0300 Feb 16

Hi,

I used to work under Windows everyday, for (at least) the last 10 years. When all we had was DOS, Windows came as a blessing, the one tool to deliver us all from misery, and so it was. After some years, Windows became too big, too slow, too clumsy, and the deeper you dig, the worse it gets, but by that time I couldn’t do much, my job was to create software to run under Windows, just like most people, so I’d better shut up and work.

Batux

Many years later I found Linux was unable to use it professionally, Windows was still paying my bills. Back then I was working with Delphi, and Borland released Kylix, the Delphi’s Linux version, promising we would be able to create cross-platform apps in no time, with usual VCL quality. Well, things didn’t work out that way. Kylix was a big flop, and now it’s dead, just like Delphi, who got lost into the transition of client-server development to Java and .NET.

Heartbroken but still alive, I kept going. Had a fling with .NET, in fact with it’s hotter and hippier twin sister, ALT.NET, and then I found true love: Ruby. Elegant, beautiful, simple, powerful, intelligent, if it was a girl I’d be married. And with a bonus: was born to work with Linux-like systems.

Now I work 99% of time under Ubuntu, another blessing, and I’m very happy. Of course I have my issues with it, but can you point out one perfect relationship? To celebrate my new penguin life, I’d like to share with you two small videos that I like a lot. Hope you enjoy:

The Matrix runs on Windows

PC vs Mac

Cheers,
Rafael.

Read more...

Comments: 3 Sections: off-topic | Tags: linux

Localized parse with I18n

Author: Rafael - Publish date: Fri, 13 Feb 2009 19:40:00 -0300 Feb 13

Hi,

A few days ago I saw a post at Ruby on Br by Fernando Luizão asking about date conversions in Ruby using the (not so) new I18n from Rails, that was included in version 2.2.2. The thing is, if you try to do something like this with standard Ruby:

  >> I18n.locale = :'pt-br'
  => :'pt-br'
  >> "20/02/2008".to_date
  => ArgumentError: Invalid date....

You get a conversion error, but the reason is quite simple: Ruby don’t know that I18n exists, since it’s a Rails extension. But it’s a very nice tool for translations, I use it in this site and like it very much, even though it has its shortcomings.

So I took the challenge and developed some extensions so we can profit from the internationalization blessings. I baptized it i18n_localize_core.

I18n is very good to convert Date and Numeric objects to formated strings, but the inverse is not true. There’s no default support for String conversions and they can be really helpful when dealing with localized input data.

Even if it had some parsing system it wouldn’t help very much in operations like the creation of a new ActiveRecord object with it’s initial values passed as a hash, which is a very common construct in controller actions dealing with user input, since this process is already built into Rails and it doesn’t refers to I18n to parse the strings received, it uses pure Ruby conversions from String to the desired type.

But how can we add this support without interfering a lot with Rails and without changing code to add a intermediary class? The solution is use some more “meta-programming magic” to redefine the necessary methods.

The i18n_localize_core basically add some extensions to the I18n to make it easier to access it’s internals and then redefine the _parse behavior of the Date object and the to_f and to_i from the String object. That’s it.

With this functionalities you can do stuff like this:

  >> I18n.localize_core = true
  => true
  >> I18n.locale = :'pt-br'
  => :'pt-br'
  >> date_br = "20/02/2008"
  => "20/02/2008"
  >> date_br.to_date
  => Fri, 20 Feb 2009
  >> Date.parse date_br
  => Fri, 20 Feb 2009
  >> I18n.parse_date date_br
  => Fri, 20 Feb 2009

  >> date_en = "2009-02-20"
  => "2009-02-20"
  >> date_en.to_date
  => Fri, 20 Feb 2009
  >> Date.parse date_en
  => Fri, 20 Feb 2009
  >> I18n.parse_date date_en
  => nil

  >> float_br = "654.321,88"
  => "654.321,88"
  >> float_br.to_f
  => 654321.88
  >> float_br.to_i
  => 654321
  >> I18n.parse_number float_br
  => 654321.88
  >> float_br.as_delocalized_number
  => "654_321.88"

Now we can make Ruby parse dates as we configured I18n. If we try to explicitly convert them through I18n.parse_date we get nil if the date is not valid, but if we use the more basic methods, like Date.parse and String.to_date we still can make it work with default Ruby dates, formatted as “yyyy-mm-dd”. Why is that useful?

Let’s say we have a model Programmer with the following properties: name:string, birthday:date, commits:integer and salary:float. The code most create and edit actions use to initialize a new object in a controller, looking the params values, would look like this.

  params = {"name" => "José Pedro", "birthday" => "20/01/2009", "commits" => "132.323", "salary" => "534.231,23"}
  @programmer = Programmer.new(params)
  Programmer<#2323: name:"José Pedro", birthday:nil, commits:132, salary:534.231>

But now that the I18n formats are used by Ruby base classes during conversion, the same code will generate the following output:

  params = {"name" => "José Pedro", "birthday" => "20/01/2009", "commits" => "132.323", "salary" => "534.231,23"}
  @programmer = Programmer.new(params)
  Programmer<#2323: name:"José Pedro", birthday:2009-01-1980, commits:132323, salary:534231.23>

The best thing is that we don’t need to change anything on ActiveRecord or Rails, all the standard code should work as usual, but now we can parse the external strings according to our I18n configuration.

You can find the code at GitHub: i18n_localize_core home page

If you think this is useful for you, download it, take it for a spin and tell me what are your impressions. Hope you enjoy it.

Cheers,
Rafael.

Read more...

Comments: 2 Sections: rails, ruby | Tags: i18n, rails22, ruby18

Custom FormBuilder - automatically adding obligatory field marks

Author: Rafael - Publish date: Sun, 08 Feb 2009 14:39:01 -0300 Feb 8

Hi,

Rails form_for, and its associated FormBuilder, are very nice tools, they helps us create web forms without effort and easy to maintain, but they can be much better.

The basic problem with the default is that we can’t change the template used to create the fields, so we can’t easily add common features like automatic labels, obligatory field markings or even customize the display of errors.

To do so we need to create a custom FormBuilder and pass it to the form_for command. This is a quite common technique, mentioned in the Rails api documentation, but I’m writign this post to answer a question posted on RailsFrance.

The first thing we should know is that the “form_for” command uses the class FormBuilder to create the actual HTML output, and it has a optional parameter which we can use to inform it to use a different builder, like this:

<% form_for(@post, :builder => CustomBuilder) do |f| %>

And that’s what we’re going to do. We’ll add the following features to the custom FormBuilder:

  1. Create labels
  2. Add obligatory field markings
  3. Custom error template

Creating the CustomFormBuilder

We’ll use the default FormBuilder as the base for the custom one, redefining just the methods we need. For this example I’ll put the code into the “lib” directory, but you can change it to a plugin if you want. This is the final code for the form builder:

module Lib
  class CustomFormBuilder < ActionView::Helpers::FormBuilder
    helpers = field_helpers +
      %w(date_select datetime_select time_select collection_select) +
      %w(collection_select select country_select time_zone_select) -
      %w(hidden_field label fields_for)
    
    helpers.each do |name|
      define_method name do |field, *args|
        options = args.detect {|argument| argument.is_a?(Hash)} || {}
        build_shell(name, field, options) do
          super
        end
      end
    end

    def build_shell(method_name, field, options)
      @template.capture do
        locals = {
          :element => yield,
          :label   => translated_label(field, options[:label]),
          :required => object_class.required_fields.include?(field) || options[:required]
        }

        if has_errors_on?(field)
          locals.merge!(:error => error_message(field, options))
          @template.render :partial => 'lib/form/field_with_errors',
                           :locals => locals
        else
          locals.merge!(:error => nil)
          @template.render :partial => 'lib/form/field',
                           :locals => locals
        end
      end
    end
    
    private
      def object_class
        if @object.nil?
          @object_name.to_s.classify.constantize
        else
          @object.class
        end
      end
      
      def error_message(field, options)
        if has_errors_on?(field)
          errors = object.errors.on(field)
          errors.is_a?(Array) ? errors.to_sentence : errors
        else
          ''
        end
      end
      
      def has_errors_on?(field)
        !(object.nil? || object.errors.on(field).blank?)
      end

      def translated_label(field, label_options)
        result = object_class.human_attribute_name field.to_s
        result = label(field, label_options) if result.nil?
        result
      end
  end
end

This code is not what I’d call trivial, but after some Ruby you can get it easily. This code was inspired by a friend of mine, Yvon Cognard, which thought me a lot of Ruby, and by recipe 15 from Advanced Ruby Recipes.

In the first part we create a variable called helpers containing all the methods we should rewrite based on the base class field_helpers property, and excluding the ones we shouldn’t touch, like hidden_field.

After that we use some meta-programming magic to redefine these methods, encapsulating the old call into the new build_shell method, where the actual magic takes place. There we create a locals hash containing the information we need to use in the templates.

The yield in the :element key is where result of the base method will be put, the :label will have the humanized text for the field, that might be translated, and the :required will have a boolean value that indicates whether or not we should add the required field marking.

Note that the actual HTML code isn’t coded anywhere in here, we’ll delegate this part to two different views: “_field.html.erb” and “_field_with_erros.html.erb”, that should be stored in the directory “app/views/lib/form/”. This way we can customize the template without changing any code, making it easier to maintain and less prone to errors. Here is some example of how these templates could be:

#app/views/lib/form/_field.html.erb
<p>
  <span class="field_label">
    <%= label %><%= "<em>*</em>" if required %>
  </span>
  <span class="form_field">
     <%= element %>
  </span>
</p>


#app/views/lib/form/_field_with_errors.html.erb
<p>
  <span class="field_label">
    <%= label %><%= "<em>*</em>" if required %>
  </span>
  <span class="form_field">
     <%= element %>
     <span class="form_error_message">
       <%= error %>
     </span>
  </span>
</p>

Finding out which properties are required

You’ll notice that we’re calling a required_fields property from the ActiveRecord class to find out when we should pass the required variable as true to the view, but it doesn’t exist on the Rails core. In fact, there’s no easy way to get the information about which properties are required or not, so we need to create our own. The following code can be put just bellow the CustomFormBuilder, just make sure to put it outside the module.

module ActiveRecord
  class Base
    def self.validates_presence_of *args
      @@required_fields ||= Array.new
      @@required_fields |= args.select { |e| e.class == Symbol }
      super(*args)
    end
    
    def self.required_fields
      @@required_fields ||= Array.new
    end
  end
end

This piece of code adds a class variable to the ActiveRecord::Base class called @@required_fields which is filled up when the class methods validates_presence_of is called upon, but in order to do this we need to override the default method. This kind of change on the base classes is possible thanks to the principle of open classes over which Ruby is build, and this is one of the most important reasons why Ruby is so flexible and Rails is possible. This technique is called monkeypatching, but I’m not a big fan of this title, I’d prefer to call it rubypatching, even though this isn’t a exclusive Ruby feature, but it sounds nicer :)

Making it work

I’m having some problems initializing the code I put into the lib directory, I’m not sure if I’m doing something wrong or not, but the solution is very simple, just create a new file into “config/initializers/” called lib_init.rb and add the following code:

#config/initializers/lib_init.rb
require 'custom_form_builder'

Now, in the form view we can just pass the builder and see its magic:

#app/views/posts/new.html.erb
<% form_for(@post, :builder => Lib::CustomFormBuilder) do |f| %>
  <%= f.error_messages %>
  <%= f.hidden_field :secret_id %>
  <%= f.text_field :published_at %>
  <%= f.text_field :title %>
  <%= f.text_area :body %>

    <%= f.submit "Create" %>
  </p>
<% end %>

This code will create all the humanized labels, including the available translations, the fields and will not change the way a hidden_field is created. The code is cleaner and to change the way it’s generated we just need to change the partials. There’s only one thing we can do to make it easier: create a helper so we don’t need to explicitly pass the :builder parameter:

#app/helpers/application_helper.rb
  def custom_form_for(record_or_name_or_array, *args, &proc)
    options = args.extract_options!
    form_for(record_or_name_or_array, *(args << options.merge(:builder => Lib::CustomFormBuilder)), &proc)
  end

Now, our view code can be simplified to:

#app/views/posts/new.html.erb
<% custom_form_for(@post) do |f| %>
.....

That’s it. We can extend this code to extract and pass more information to the view, but I really don’t recommend expanding the code more than necessary, always remember: YAGNI :)

There are other custom FormBuilders out there, one that seems to be quite interesting is Justin French’s Formtastic, but I didn’t have time to look it up very carefully.

I hope this code helps somebody. Stay tuned for more Rails code soon.

Cheers,
Rafael.

Read more...

Comments: 2 Sections: rails | Tags: form, rails22

First post

Author: Rafael - Publish date: Fri, 06 Feb 2009 01:31:26 -0300 Feb 6

Hi to all,

This is my first blog entry, and I hope to write many others. I’ve being studying Ruby and Rails for quite some time now, but this site is the first production project I’ve ever wrote.

I have a lot of things to learn, and I’ll write about my journey to Ruby and Rails mastering.

I’ll write about other things too, like ALT.NET, the closest we can get to the Ruby Way using Microsoft stuff. There are lots of good developers working with .NET and much more trying to get better, so I think it’s important to help up the community.

Commentaries and critiques are welcome :)

Cheers,
Rafael

Read more...

Comments: 2 Sections: | Tags: