Simple layouts and views with Spark and MonoRail

Yesterday, I wrote about the coolness of The Spark view engine (and a brief history of web programming). As I explore more, I’ll share my experiences here in hope that it shortens other people’s learning curve.

Today’s topic is the basics: writing a simple layout.

Spark offers full support for layouts and views. As with any other view engine, the file extension (by default, .spark) of both your layout and view files must match.

A simple layout looks like this:

<title>A simple layout</title>
<h1>A simple layout</h1>
<use content="view" />

The only thing that isn’t HTML is the <use content="view" /> tag. This tag denotes where in the layout (master template) to embed the content from your view. In NVelocity, we used ${ChildContent} declaration in NVelocity, or the ${ChildOutput} declaration in Brail. Yes, it’s that simple.

Often times, we want to inject some view data into our layout, such as the page title. Let’s say our controller was sending a PageTitle to the view:

public void Simple()
PropertyBag["PageTitle"] = "Still a simple sample";

How would we get this injected into the title tag in our layout? The quick way is to reference your viewdata, as shown below.


The syntax is similar to that of NVelocity (even the use of the exclamation point to suppress the rendering of nulls), but we’ve got to explicitly reference the PropertyBag. Interestingly, you can also write $!{ViewData["PageTitle"]} — to Spark, both PropertyBag and ViewData are the same. There are two disadvantages with this method:

  1. It’s not as clean as $!{PageTitle}, which we can do in NVelocity.
  2. The result is not strongly-typed, which limits your ability to work easily with complex types.

The solution to these two problems is to specify a Spark viewdata tag and declare the name and type of the view data objects you want to expose. Note the changes in the code below.

<viewdata PageTitle="string" />

Much cleaner! The Spark web site has an example which shows the use of a strongly-typed collection that illustrates this further.

That’s it for now. It’s just a quick start, but there’s a lot more to Spark, and I highly recommend it to MonoRail users.

The Spark View Engine (and a brief history of web programming)

spark I should have gone to bed early last night (after all, I did wake up at 4:30AM yesterday morning). Unfortunately, a spark of inspiration quite literally kept me up later than normal sleep cycles dictate… but what a spark it was.

To understand the spark, you have to understand my history of server-side web programming.

In the beginning

My first experience with server-side web programming was with Allaire ColdFusion some ten years ago. What was great about ColdFusion is its use of a tag-based scripting language, CFML, as illustrated below.

<cfset value = "Hello" />
   #value# Bob!

After ColdFusion, I came across what is now known as “Classic ASP” – and my web code looked less and less like HTML.

<% value = "Hello" %>
<%= value %> Bob!

Classic ASP felt more like programming, less like web programming. Quite accurately, it was web programming via scripting. I missed the tag-based syntax of ColdFusion.

Then there was ASP.Net, which at first glance looked like it was a return to tag-based web programming! Well, almost… along came this weird codebehind model, and the entire stateless request/response nature of the web was bastardized.

<asp:label runat="server" id="greeting" /> Bob!
// and in the codebehind
greeting.Text = "Hello";

And so there I was until I found Castle Monorail, which returned web programming to its core, thanks to a fantastic MVC architecture. With MonoRail, you injected text into your web pages using a template engine. For me (and most other newcomers to MonoRail), that meant NVelocity.

${value} Bob!
// and in the controller
PropertyBag["value"] = "Hello";

Now assignments happened somewhere detached from the view (i.e. the controller), and my web page was looking rather clean. I still yearned for the tag-style days of ColdFusion.

Enter Spark, a tag-based view engine for MVC platforms (i.e. MonoRail!). Spark gives you almost all the power of C# and the .Net Framework within your view, but does it using a syntax that is entirely tag-based, as shown in the following example from the Spark web site.

<var names="new [] {'alpha', 'beta', 'gamma'}"/>
<for each="var name in names">
  <test if="name == 'beta'">
    <p>beta is my favorite.</p>
    <p>${name} is okay too I suppose.

With this, the presentation logic in your view looks like HTML. It makes the resulting view file much more semantic otherwise.

The Spark view engine is an impressive effort by Louis DeJardin, who deserves kudos for his efforts. Not only does the code work great, he’s got plenty of documentation on how to get it working with Castle MonoRail – even plenty of references to Windsor integration.

I’m switching a major project from NVelocity to Spark, and plan to blog more about this in the future. In the meantime, check out Spark – there’s lots to read and learn, and the examples available in the Subversion repository are fantastic.

I won’t get Alzheimer’s or diabetes (but I will have hallucinations)

Via Slashdot:

Amenacier writes:

“Recent studies by Finnish and Swedish researchers have shown that drinking moderate amounts of coffee can reduce the risk of Alzheimer’s disease in people. The reason for this is as yet unknown, although it has been hypothesized that the high levels of antioxidants found in coffee may play a role in preventing dementia and Alzheimer’s. Alternatively, some studies have shown that coffee can protect nerves, which may help prevent Alzheimer’s. Other studies have shown that coffee may also help to protect against diabetes, another disease which has been shown to have links to Alzheimer’s disease. However, researchers warn against drinking too much coffee, as 3 cups or more may cause hallucinations.”

Mixed blessing for me. I’m a more-than-three-cups-per-day coffee drinker (less on weekends), which means I’m getting all the Alzheimer’s and diabetes protection, with the occasional hallucination.

Oddly, I don’t recall ever hallucinating, unless… this entire experience… of reality… is not real……

Anyone using Sprint mobile phone service?

I’ve used a Palm Treo 650 for about 2 1/2 years, and it’s served me well (especially when teamed up with ChatterEmail). That being said, my Verizon Wireless contract is up for renewal, which means I can get a severely discounted new phone… or I can switch to a new provider.

Palm Pre I was going to stick with the Treo until the announcement of the upcoming Palm Pre. I’m no iPhone junkie or gadget-hound, but I’m a fan of Palm, so this new device certainly caught my eye and created a small amount of drooling.

No surprise that the Pre will initially be available to a service provider other than Verizon Wireless – that service provider being Sprint. I’ve never used Sprint, but their rates seem much more competitive than Verizon, and they do have the phone I’m yearning for.

Does anyone have experience with Sprint, especially in the New York City area? How’s the service and wireless coverage? Is data access fast and reliable?

Unit testing an Activerecord domain model with NUnit

[Digression] This post has been sitting in a somewhat unfinished state for a long time. It feels good to finally post it!

In rewriting my baseball game, CSFBL, I made the decision to use Castle ActiveRecord (built on top of NHibernate) to handle the persistence of my domain model. As a result, I needed to find a simple but effective way to unit test this implementation.

The unit tests needed to accomplish the following:

  1. Test the initialization of ActiveRecord (which validates the database schema against the object mappings).
  2. Test object validation (since I am using Castle’s Validation component and the ActiveRecordValidationBase<T> base class).
  3. Ensure that a domain object can be persisted to the database.
  4. Ensure that a domain object can be retrieved from the database.
  5. Ensure that multiple instances of an object with the same persisted primary key are equal.

How, then, do we do this? Continue reading

Heaven has one hell of a baseball team

It’s hard to believe that, not so long ago, blacks were forbidden from playing Major League Baseball. For a person like myself, born in 1970 and never experiencing the true meaning of segregation, it’s hard to comprehend. Alas, it’s true. One can be disappointed by this tarnished past, or be proud of how we, as a people, have overcome it.

Regardless, being excluded from “professional” baseball didn’t stop many from playing professional baseball, thanks to the Negro Leagues. Without such a league, we’d never have the opportunity to know some of the most talented athletes and colorful sports personalities to ever play the game.

The Negro Leagues brought to fame folks such as Andrew “Rube” Foster (a great pitcher and the founder of the Negro League), Satchel Paige (one of the best pitchers of all time), Josh Gibson (a power-hitting catcher)… and Prince Joe Henry.

He wore shorts as part of his uniform, his hat bill turned around crooked and was animated at the plate.ref

Prince Joe has a special place for me and some friends, for a very special reason. A few years back, RedHawk (a player of my online baseball game, CSFBL) started a new league in our game: Negro League Tribute. After starting the league, RedHawk and TFM_Dale (another community member) got in touch with Negro League legend Prince Joe. Continue reading

Time to shut down the Office of Federal Housing Enterprise Oversight

The Office of Federal Housing Enterprise Oversight proudly proclaims the following on its web site:

Our Mission: To promote housing and a strong national housing finance system by ensuring the safety and soundness of Fannie Mae and Freddie Mac.

Just in case they take it down, here’s a screenshot, taken just a moment ago:

Office of Federal Housing Enterprise Oversight -- their mission

Still not convinced of their mission? From their Supervision & Regulations page: Continue reading

Next in line for their TARP bailout is…

Via CATO@Liberty

CNN reports:

Another major American industry is asking for assistance as the global financial crisis continues: Hustler publisher Larry Flynt and Girls Gone Wild CEO Joe Francis said Wednesday they will request that Congress allocate $5 billion for a bailout of the adult entertainment industry.

I’d bet they have real good lobbyists…

How much are your two cents worth?

I just wrote a message on the CSFBL forums where I said, “My two cents.” Which got me wondering… How long has the expression, “my two cents” (and its many variations) been around?

Like most Google searches, I quickly was brought to a Wikipedia article, My two cents (idiom). In it, we can review a speculative history of the phrase “my two cents”:

OK, so the “my two cents” phrase has origins going back some 500 years. How do we figure out how much two cents from the 16th century is worth today, considering inflation?

Turns out this isn’t easy to figure out. I was able to discern a few things in my research.

  1. The 16th century was in the heart of the Price Revolution, a period of great inflation.
  2. Wikipedia provides a fine graph of US inflation since around 1670. Unfortunately, raw data isn’t available before 1774.
  3. A study by Oregon State University helps us lets us calculate the value of money from 1774 to 2018 (estimated).

Using this, we can determine that two cents in 1774 is worth 51 cents in 2007.  Needless to say, the first person to coin the phrase, “my two cents,” even in today’s terms, wasn’t saying much.

C# 3.0’s syntatic sugar

In the old days, we’d write something like this:


With C# 3.0 we can do this:

new string[] { "Type", "Count", "Whatever" }
    .ForEach(str => view.Rows.Add(str));

That is very cool syntatic sugar. Sure, this is not new news, but when you think about C# in the context of the new features available in 3.0, it really starts to feel a lot more like coding with JavaScript (which is a good thing).