Friday, August 29, 2008

Marshaling the Ruby Way

This post is for the .NET developer who is looking at IronRuby but is otherwise unfamiliar with Ruby. As you learn Ruby, keep in mind a question that Ruby programmers like to ask themselves a lot, "What is the Ruby Way of solving this problem?" Today the problem is marshaling an object and we're going to solve it the Ruby Way.

If you're like most other .NET developers, you're probably thinking about BinaryFormatters or perhaps you prefer XmlSerializers. Maybe you're thinking about DeserializationCallbacks or XmlIgnoreAttributes and where to put them. Stop right there! That's definitely not the Ruby Way.

Let's define a Ruby class:
class Person
attr_reader :first_name, :last_name, :hobbies

def initialize(first_name, last_name, *hobbies)
@first_name = first_name
@last_name = last_name
@hobbies = hobbies
end
end

This is just a simple class with three read-only attributes: first_name, last_name, and hobbies. How would we create an instance of our class and marshal it the Ruby Way?
ray = Person.new("Ray", "Vernagus", "programming", "walking")
yml = ray.to_yaml
puts yml

to_yaml, what's that? YAML stands for "YAML ain't markup language." Did that make you smile? Now that's the Ruby Way! ;) YAML is very simple but also very powerful. It's the kind of notation that you would write yourself if you were just jotting a class down on a piece of paper except that it's structured and standardized. Here's what our marshaled person looks like:
--- !ruby/object:Person
first_name: Ray
hobbies:
- programming
- walking
last_name: Vernagus

Not bad, aye? That's about as ugly as you're likely to see YAML get. I encourage you to learn more about YAML and to use it in place of XML every chance that you get.

We can get our person back just as easily:
p = YAML.load(yml)
puts p.inspect

and this prints:
#<Person:0x0000064 @first_name="Ray", @hobbies=["programming", "walking"], @last_name="Vernagus">


This is all running in IronRuby (batteries-included version).

Wednesday, August 27, 2008

Threading in IronRuby (Part 2)

In my last post I pointed out some issues with the Thread.new construct in IronRuby. One of the advantages of using IronRuby is that we have access to the .NET framework. In this post, we'll take a look at using the ThreadPool class in order to correct some of the issues that came up in the previous post.

The first issue that we saw with the Thread.new construct was that it launched the thread as soon as we declared it. When using the ThreadPool, we first declare a callback object:
require "mscorlib"
include System::Threading

callback = WaitCallback.new { puts "pool thread" }

We declare a callback in a similar manner to a Thread, by passing a block to the constructor. In this case, however, we get a WaitCallback object that we can hold on to until we are ready to execute the block. You can run the code block by queuing it up in the ThreadPool:
ThreadPool.queue_user_work_item callback

You may need to pause the main thread in order to see the line print to the console, giving us this as a full example:
require "mscorlib"
include System::Threading

callback = WaitCallback.new { puts "pool thread" }
ThreadPool.queue_user_work_item callback

Thread.sleep 100


The other issue that I mentioned concerning the Thread.new construct was that it defaulted to a foreground thread. This isn't a problem when using the ThreadPool since all ThreadPool threads are background threads.

A lot of this code is very un-Ruby-like. For instance, it would be nice to just write:
ThreadPool.queue_user_work_item { puts "pool thread" }

Hopefully future versions of IronRuby will make it easier to pass blocks in place of delegates. That would definitely make these tasks feel more like Ruby.

Monday, August 25, 2008

Threading in IronRuby (Part 1)

I couldn't find much at all on the Web about threading in IronRuby. Here's a little introduction to some basic threading in IronRuby.

In contrast to Ruby's less than ideal threading model (which is to change in 1.9), .NET has a rich threading model that we can tap into using IronRuby. We can create a new thread in IronRuby in the same way that we do in MRI Ruby:
Thread.new { puts "child thread" }

In IronRuby, however, we're not talking "green" threads. Instead, we get a real .NET thread as demonstrated in this example:
require "mscorlib"
include System::Threading

puts "##{Thread.current_thread.managed_thread_id} is the main thread."
# #1 is the main thread.

Thread.new { puts "##{Thread.current_thread.managed_thread_id} is a child thread." }
# #3 is a child thread.

You may have noticed that we didn't have to do anything to launch the thread. This is undesirable if you need to, for instance, start a thread as a background thread. Since the default value for the IsBackground property is false, the thread in the example above runs as a foreground thread. If your thread runs long enough, you can do this:
require "mscorlib"
include System::Threading

t = Thread.new { Thread.sleep 1000 }
puts "t.is_background = #{t.is_background}"
# t.is_background = false

t.is_background = true
puts "t.is_background = #{t.is_background}"
# t.is_background = true

Use of Thread.new will probably suffice in only the simplest situations. IronRuby supports more advanced threading scenarios and we'll get started on that in the next post in this series!

Saturday, August 9, 2008

Get Going Quickly with F# and ASP.NET MVC

Want a quick way to get going with F# and ASP.NET MVC?
  1. Start a new MVC project.
  2. Add an F# project to your solution with a source file in it.
  3. Set the project type for your F# project to dll.
  4. Set the output path to the bin folder of your MVC project.
  5. Add a namespace declaration to your F# source file. The namespace must match your MVC project's namespace, for example, MvcApplication1.Controllers.
  6. Write a controller in F# and compile your F# project.
  7. Reference your F# output in your MVC project.
If everything's wired up correctly, you can visit the appropriate URL in your browser and your F# controller will get called!

Wednesday, August 6, 2008

ASP.NET MVC & REST

Make that 4 too many acronyms...my apologies.

I'm crazy about REST. It appeals to me in a number of ways and it's the primary reason behind my interest in ASP.NET MVC. I didn't know a thing about REST prior to Ruby on Rails v2.0 but then again I wasn't a web programmer prior to that. Now that I'm building web applications on a regular basis, I've been drawn to REST and Rails concepts.

Which brings me to the topic of this post: REST on ASP.NET MVC (MSMVC)! It turns out that the MSMVC framework is very capable of following REST principles. The routing engine supports constraints based on HTTP methods and it's a no-brainer to also support overloaded POST. Here's a simple constraint to support a hidden _method form input:
public class FormMethodConstraint : IRouteConstraint {
string _method;

public FormMethodConstraint(string method) {
if (String.IsNullOrEmpty(method))
throw new ArgumentException("method cannot be null or empty.", "method");
_method = String.Format("^{0}$", method);
}

public bool Match(System.Web.HttpContextBase httpContext,
Route route, string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection) {
var vals = httpContext.Request.Form.GetValues("_method");
if (vals == null) return false;

foreach (var val in vals)
if (Regex.IsMatch(val, _method, RegexOptions.IgnoreCase)) return true;
return false;
}
}


With this class, you can write routes that support overloaded POST:
source.MapRoute(
"FormDestroy",
"{controller}/{id}",
new { action = "Destroy" },
new { httpMethod = new HttpMethodConstraint("POST"),
formMethod = new FormMethodConstraint("DELETE") }
);


Now, you can put a hidden input in your form with the name _method and the value DELETE and when the form is sent back the server, it will route to the Destroy() action on your controller!

There's more RESTful goodness to come from me, I'm just getting started! :)

Friday, July 25, 2008

GIS Server REST and Quirks Mode

ESRI recently released their REST API for GIS Server. I finally got a chance to put the REST API to use today and I have to say that I love it thus far! This really changes the picture for developing web apps using GIS Server.

I did, however, notice that the javascript examples produced by the REST services aren't XHTML. This has the side effect of forcing the browser into quirks mode. You can see why this was likely intended by adding a DOCTYPE declaration to the top of one of the sample pages:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

When you do this, the map disappears! The sample pages use a table layout with style="height: 99%;" to expand the table row to fill the page. The problem with this approach is that it is only supported in quirks mode.

I'm not an expert on CSS but I am able to get a map to fill the page without using a table layout or quirks mode. You should be able to just add this style declaration in the <head> section of your page:
<style>
html, body, div#map {
height: 99%;
}
body {
margin: 0px; /* Used here for IE & Mozilla */
padding: 0px; /* Used here for Opera */
}
div#map {
width: 99%;
}
</style>


Using this approach, you don't have to embed your maps in a table layout and you can write true XHTML.

Thursday, July 24, 2008

FsUnit 0.5.0!

I'd like to announce the release of FsUnit 0.5.0! What began as a stabilization release ended up as a complete rewrite. The core syntax is still the same, in fact, it got even better. One of the primary goals of FsUnit is to remain as clean as possible, from language constructs that is.

This latest release actually removed the need for a pair of parens in many cases. So instead of:
1 |> should (equal 1)

you can now write:
1 |> should equal 1

Getting rid of parens at this level is pretty important to me so it's pleasure to bid them adieu!

One of the other major changes was perhaps more for my sake than for the user's but then maybe not. Prior releases incorporated negation into the assertion bit itself. So if you wanted to say "1 should not equal 2" you had to write:
1 |> should (notEqual 2)

The not' keyword makes it possible to negate any assertion in FsUnit:
1 |> should not' (equal 2)
This removed a lot of duplicate code and it also just about cut the number of specs for FsUnit itself in half.

Finally, the last major change is the spec keyword. This keyword is a shortcut for labeling and executing your specs. It also stores the result in a ResultStore object. With the spec keyword, specs look like this:
spec "A number should equal itself."
(1 |> should equal 1)


I like the way that this looks very much and I'm going to try to keep this syntax stable between releases.

Let me know what you think of the new release!