Design Patterns in Ruby
One of the cool things about working at Dotway is the Design Patterns study group that we have. We have been meeting weekly/biweekly/sometimes for a while now and each time we discuss one of the GoF patterns in detail. We like to find out how they are used, what variations there are of them and how they are used in the .NET Framework (which is what we normally work with). However I thought I would use this as an opportunity to get to know Ruby better. So, I will try and write up an example of a Ruby implementation of each of the patterns we discuss. We are already through more than half of them so maybe I will be thinking about the ones we have already done as well.
I am not saying that my implementation is optimal, in fact in many cases it will only be an example. Please chime in with comments about alternative implementations or anything else if you want. The first pattern I will write about will follow this post immediately.
Setting the contents of a WPF RichTextBox
In the project I am currently working on we are using Windows Presentation Foundation for building the GUI. This means there are a lot of new things to learn. Even the small things take some time when you do not know which of the new controls to use are what properties and methods to use on these. (Of course it does not help that Resharper 2.0 does not know anything about XAML).
One such problem that I just had was working with a RichTextBox. The application should contain a text box where the users can enter text, using all the standard functionality such as bold, italics etc, and this information (text and markup) should be stored in the database. This was not as straightforward as it used to be in .Net 2.0 (or earlier). Since I guess other people will likely want to do the same thing I am posting the code I wrote to do this.
public string InputText
{
get
{
string text = "";
using(Stream stream = new MemoryStream())
{
TextRange contents = new TextRange(
textBoxInputText.Document.ContentStart,
textBoxInputText.Document.ContentEnd);
contents.Save(stream, DataFormats.Xaml);
stream.Position = 0;
using(StreamReader reader = new StreamReader(stream))
{
text = reader.ReadToEnd();
}
}
return text;
}
set
{
textBoxInputText.Document.Blocks.Clear();
if(value != null && value.Length > 0)
{
using(Stream stream = new MemoryStream(
UTF8Encoding.Default.GetBytes(value)))
{
TextRange contents = new TextRange(
textBoxInputText.Document.ContentStart,
textBoxInputText.Document.ContentEnd);
contents.Load(stream, DataFormats.Xaml);
}
}
}
}
The property InputText is part of the view interface for this page in our Model-View-Presenter architecture. The presenter uses this property to show/collect the value in the model.
Active Record presentation at SNUG
Wednesday evening we had the last “SNUG”:http://www.snug.se/ meeting before summer. The meeting was hosted Dotway. We had a great turnout with around 30 people apart from us that arranged it, even though we informed about the meeting as late as two weeks earlier. First we had Jim Christensen from Commentor in Denmark tell us about the .NET Compact Framework and his experiences with mobile development. After that we had a break with Subway sandwiches and some great discussions. Finally I presented a session on the Active Record pattern that Martin Fowler describes in “P of EAA”:http://www.amazon.com/gp/product/0321127420/.
I have uploaded a zip file with the C# examples that I showed. They show how the Active Record pattern works in it’s most simple implementation and then how to use Castle project’s ActiveRecord framework to avoid having to do all the work yourself.
I also showed an example of how a dynamic language such as Ruby can take this even further for extreme productivity gains. The code below shows how to use the ActiveRecord implementation in Ruby on Rails by itself in a simple script.
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => 'sqlserver',
:host => '127.0.0.1\SQL2005',
:database => 'blogs',
:username => 'blog_user',
:password => 'secret')
class Blog < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :blog
end
blog = Blog.new
blog.name = 'Chris Hedgate'
blog.uri = 'http://www.hedgate.net/'
post = Post.new
post.title = 'Hello, SNUG!'
post.contents = 'TBW'
blog.posts << post
blog.save
blogs = Blog.find_all
blogs.each do |blog|
puts "#{blog.name} (#{blog.uri})"
puts 'Posts:'
blog.posts.each do |post|
puts " -- #{post.title}"
end
puts ''
end
Finally, I promised to post some links to various things I talked about in the session.
* “Active Record pattern in P of EAA”:http://www.martinfowler.com/eaaCatalog/activeRecord.html
* “Data Mapper pattern in P of EAA”:http://www.martinfowler.com/eaaCatalog/dataMapper.html
* “Castle ActiveRecord implementation”:http://www.castleproject.org/index.php/ActiveRecord
* “NHibernate”:http://www.nhibernate.org/ Object-Relational Mapper
* “NHibernate Generics”:http://www.ayende.com/projects/nhibernate-query-analyzer/generics.aspx, Ayende Rahien’s nice contrib for working with generics
* Mats Helanders tool “ObjectMapper”:http://www.objectmapper.com/Home/Default.aspx
Thanks to all the people who attended the meeting. Kim, Daniel, Henrik and I look forward to seeing you at new SNUG meetings after the summer.
Microsoft Certified Technology Specialist
I just noted in my MCP transcript that I passed the Beta Exam for 70-431 TS: Microsoft(r) SQL Server(tm) 2005 – Implementation and Maintenance. This means that I am now a Microsoft Certified Technology Specialist (MCTS) for SQL Server 2005. Curiuosly though, I do not feel any different. :)
It is nice to see some results from the busy months I have had behind me though. First a lot of reading for beta exams (next one coming up in March) and then a lot of writing, both an article for SQL Standard magazine and also the presentation on CLR Integration. I gave the second presentation last Thursday in Stockholm at the Swedish SQL Server User Group. It went quite well, although there were unfortunately not as many in the audience as I had hoped. So now it is two down, one to go, and the final one is the big one at PASS Europe in Barcelona. I have also spent a lot of time preparing a presentation of the Ruby programming language for my colleagues next weekend, but that is a different story.
PASS Europe 2006 over
I am back home after attending PASS Europe 2006 in Barcelona, where I also presented a session myself. I have uploaded a zip file with the presentation that I did (Understanding CLR Integration in SQL Server 2005). I will be posting a followup post about some of the things that I discussed with attendees to my presentation as soon as possible.
Overall I had a good time. The best part as always was spending time and talking with the other attendees and speakers. Me and “Andres”:http://www.taylor.se/blog/ spent a lot of time with “Haidong Ji”:http://www.haidongji.com/, Marin Mamic and “James Luetkehoelter”:http://sqlservercentral.com/cs/blogs/james_luetkehoelter/default.aspx. It was great meeting you guys. Talking with people such as Kevin Kline, Ken Henderson and Randy Dyess is always a great inspiration.
Unfortunately there are not that many people that attend PASS summits in Europe. The good thing about that is that it is easier to network with the ones that are there, but I was expecting more people to attend my session than what I normally get back home at Dotway. Andres and I are thinking of submitting an abstract for PASS in Seatlle later this year, so hopefully I will be at the bigger event as well. We discussed the reason there are so little interest for PASS Europe with Kevin. The things we specifically thought was part of the reason was that the cultural differences in Europe of course make it difficult to attract people outside the country the event is hosted in. I think many people are thinking they will not understand all of the information since the English might be bad, but I do not think that is a problem. All of the speakers I heard was great in English.
We spoke about perhaps running smaller shows, like one day maybe, in several countries would be a better idea. I think it is an interesting idea if PASS can pull it off. Like I said to Kevin, the PASS summits are still the best (and almost only) source for SQL Server-focused sessions so people should be interested in them. Another idea could be to team up with some other more developer-oriented conference, but I am not sure that would be an optimal solution. If you have any thoughts on these issues I am sure “Kevin”:http://www.sqlmag.com/Authors/AuthorID/718/718.html would be really interested in hearing them.
Getting things done with TDD and pair-programming

Last week me and Andres where in Barcelona for three days. The main reason we where there was that I was presenting a session at the PASS Europe 2006 conference, and we of course wanted to see as much as possible of the other sessions at the conference as well. However, being the geeks we are, we also wanted to find some time to work on an as-of-yet unnamed project we started a couple of weeks ago. We have had trouble finding time to get anything done, especially since it does not feel good for the one of just us working singlehanded an evening.
So, now that we where not tied with client projects or had any private obligations we used every minute we could find to work on the project. A half hour after breakfast before the conference started, what was left of lunch break when we where finished eating, even timeslices as small as 5-10 minutes between sessions where used. And we managed to get quite a lot done, especially counting all the refactoring and design changes we made.
Now this is only speculation of course, but I cannot see how we would have gotten nearly as far (or probably anywhere at all) if we had not used test-driven development while doing this. We also did everything on a single computer pair-programming all the time. TDD really helped us stay focused and to get right into the action whenever we had a break. Even if we only had 10 minutes over we could simply continue right where we left off earlier. If it was not as simple as where the cursor was currently positioned it was at least never further away than running the tests and finding the red one. Pairing helped us stay disciplined enough to stick to writing good tests, small enough that we could often get them done in these 10 min coding sessions.
I am of course not saying that TDD and pairing is only useful in this kind of “extreme” situation, it is always helpful and the right way to go. But it was really interesting to see how we really got a lot done in this situation.
Getting FeedTools to work with SQL Server
I have been trying for a few days (hey, I’m on vacation and have been spending time with my girlfriend, son and dog so I have not spent a lot of time with this) to get “FeedTools “:http://rubyforge.org/projects/feedtools/ to work with a Rails application I am working on. I had a couple of problems getting up and running, despite following “tutorials”:http://sporkmonger.com/articles/2005/08/11/tutorial/ that I found online and starting with a “really simple example”:http://sporkmonger.com/articles/2005/08/11/tutorial/. First I encountered some problems with example code that did not work with the current version of FeedTools, but that was easy enough to fix. However, even with that fixed I could not seem to get the database cache to function, which meant I could not use FeedTools at all (I want to cache of course).
Whatever I tried I always got stuck at FeedTools saying that the cache was not initialized properly, even though I knew it was there in my database. I was puzzled for a while until I finally took a peek in the log file. There seemed to be a SQL query failing with an error message saying @”Incorrect syntax near ‘1′”@. At first I thought it was strange since I had not yet tried to retrieve a feed. But looking through the code I found the problem. When FeedTools initializes the database cache it calls @DatabaseFeedCache.table_exists?@. What this method does is try to retrieve the first row from the table where FeedTools stores the cached feeds. However, it does this by calling the execute method and sending it a specific SQL query to execute. This query uses the MySQL syntax @LIMIT 1@ to restrict the result set to one row. But I am using SQL Server 2005 as my DBMS, and the @LIMIT@ keyword is not included in T-SQL (SQL Server’s SQL dialect). So I get the incorrect syntax error.
To fix this I just needed to make a small change in the @DatabaseFeedCache.table_exists?@ method. This is what the old code was:
def DatabaseFeedCache.table_exists?
begin
ActiveRecord::Base.connection.execute("select id, href, title, " +
"link, feed_data, feed_data_type, http_headers, last_retrieved " +
"from #{self.table_name()} LIMIT 1")
rescue ActiveRecord::StatementInvalid
return false
rescue
return false
end
return true
end
And my modified version is this:
def DatabaseFeedCache.table_exists?
begin
ActiveRecord::Base.connection.select_one("select id, href, title, " +
"link, feed_data, feed_data_type, http_headers, last_retrieved " +
"from #{self.table_name()}")
rescue ActiveRecord::StatementInvalid
return false
rescue
return false
end
return true
end
I have created a patch and have -been trying to submit- submitted it to the FeedTools project at RubyForge , -but I keep getting timeouts-. You can get “the patch here”:http://rubyforge.org/tracker/index.php?func=detail&aid=4871&group_id=775&atid=3063 (or from my site), or simply update your DatabaseFeedCache.rb file manually with the code above.

