Thursday, May 29, 2008

SafeExecute: A Functional Pattern for Cross-cutting Exception Handling

In some cases, you may find yourself implementing the exact same exception handling logic in several methods within a class, and your brain screams DRY!  Here's way to use C# 3.0 to put that exception handling logic in one place:

        public string Foo(string name, string greeting)
{
return SafeExecute<string>(() =>
{
return greeting + " " + name;
});
}

public int Bar(int i)
{
return SafeExecute<int>(() =>
{
return i + 1;
});
}


protected T SafeExecute<T>(Func<T> funcToExecute)
{
try
{
return funcToExecute.Invoke();
}
catch (Exception)
{
throw;
}
//if your error handling does not throw an exception
//return default(T);
}



The details of proper exception handling are elided above to allow the reader to focus on the functional aspects of the pattern.  This pattern is really only useful when you are using exactly the same exception handling logic.  This is often the case in classes due to common implications of SRP.



Actually, this pattern is more generalized by the common functional pattern of wrapping the execution of another function, but this provides a useful concrete example.

Wednesday, May 28, 2008

Learning New Tools

I sometimes wonder which is more complex, in the information theory sense: the functioning of a given vital organ or the functioning of a modern IDE.  In the case of Emacs, I would tend to favor the the IDE.

I learned vi in college; because, truthfully, it was the default editor for elm, and I wanted to send email.  Most other folks used pine, but I didn't hear about that for a while.  Anyway, that was how it began, and I came to love vi and later vim.  This loved flowered even after I found out Bill Joy wrote it, probably because he hated Emacs.

Now, there are a few flawed attempts to bring syntax highlighting and indenting for Erlang to my favorite little editor, but they're far from perfect.  There's even an aborted attempt to bring Erlang to Eclipse.  Alas, it too is seriously flawed.  It would seem that most of the Erlang programming universe writes code in Emacs.

I've never been a joiner, and I wore my iconoclastic editor as a badge of honor.  Now, however, I've resolved to follow the pack and learn Emacs.  As a side benefit, it would appear that I'll be learning a little Lisp along the way, well elisp at least, more out of necessity than desire.

What bugs me is that I don't really want to learn Emacs, I'd rather spend that time exploring OTP. But, c'est la vie!  It will just take some time to become proficient.

At work these days I'm learning the ins-and-outs of BizTalk.  This, too, is less than ideal.  BizTalk is really powerful, very enterprise-y message-oriented middleware.  Truthfully, I wouldn't mind it so much if its development tools had any notion of refactoring.  The whole thing just seems to brittle, and could there be a more miserable way to spend ones time mapping messages types?

Getting Erlang Going on a Vanilla Ubuntu Install

Before you are able to configure and make Erlang OTP from source, you're going to need to be sure your have the right dependencies installed.  For a vanilla Ubuntu installation, this means:
sudo apt-get install libc6-dev
sudo apt-get install libncurses6-dev
sudo apt-get install m4
sudo apt-get install libssl-dev
sudo apt-get install sun-java6-jdk

The last two aren't strictly necessary, but libssl-dev is the source files the OTP system needs to utilize OpenSSL.  Now, that last dependency on the JDK may seem a bit odd, but the standard makefile for the OTP system tries to build jinterface, an OTP application that enables running an Erlang node in Java.  (As an aside, there is a similar package called twotp that does the same thing for Python.)

Assuming all goes well, you should be able to cd into the source directory (wherever it is you extracted it to when you downloaded it) and execute the following commands in order:
./configure
make
sudo make install

Depending on the permissions to /usr/local/* you may not need elevated privileges, but again this is for a vanilla install.  Now, you should be able to run Erlang.  Next time, I'll have some notes on setting up vim and Emacs for Erlang.

Saturday, May 24, 2008

The ALT.NET Times for May 24th, 2008

A bit of a quiet week on the list this week.  In the U.S. this coming Monday is Memorial Day, and we get the day off--a fact that compels many to plan their vacations around it.  Whatever the reason, there wasn't much traffic, and so there's not much to report.

Probably the most interesting messages of the week revolved around ALT programming languages.  The Boo programming language--which is a full-on CLR language in the style of Python--seemed to be a favorite of many on the list.  Oren Eini is a primary contributor and uses Boo for his Windsor configuration tool, Binsor.  There's a healthy community around the language, one which created VS2008 integration for it.

There was also some discussion of F#, a language that is something like a CLR implementation of OCaml, with some changes required to behave well with the runtime and other CLR languages.  Additionally, it is missing one quintessential OCaml feature: functors.  Nevertheless, F# delivers many of the familiar mainstays of a dynamic functional language--like currying, first-class functions, pattern matching, and tuples/records--while integrating with all the .NET libraries and providing strong typing through type inference.  It also works seamlessly when installed over Visual Studio 2008.  To learn more, a good place to start would be to RTM, or Ted Neward's F# Primer.  The place where the F# community gathers is called hubFS.

So, that's the short version (or at least the thematically relevant version) of what I learned from the alt.netters this week.  Have a great one!

Wednesday, May 21, 2008

VMWare Blues

image

I suspect it's my fault.  I let Vista update to SP1 while I had the VM paused then tried resuming.  I got this BSOD while VMWare was restoring the virtual machine's state.  Since Vista now shows 4GB of RAM instead of 3.5GB after the update, I'm guessing the memory manager changed, and that caused VMWare to choke on its old memory map.

Saturday, May 17, 2008

The ALT.NET Times for May 17th, 2008

They say if you do something three times, it becomes a habit.  This is the second post in a series highlighting what I gleaned from the sharp minds in the ALT.NET scene over last week.

Early in the week, Harry McIntyre from London shared his process and custom code for managing change to DBML files, the XML that defines your classes in Linq to SQL.  Folks using Linq to SQL know the pain of managing change to these files.  You cannot regenerate them from your database without wiping out any customizations that you made.  The Linq to SQL designer is pretty good about capturing most of the idiosyncrasies of your tables, but you inevitably have to customize the generated DBML to cover the corner cases, such as having a default value on a non-nullable CreatedOn column.

Harry's project is called Linq to DBML Runner, and he has a post about the process he uses.  It's dependent on a couple of other projects, including Linq to XSD and in yet another case of trickle-down technology from Ruby: Migrator.NET.  If you're committed to effectively managing change to your DBML files, and you will be if you use it on greenfield projects involving more than a couple of developers, check out Linq to DBML Runner.

There was a lot of talk about MVC and MVP, along with specializations formalized by Fowler including Passive View.  A few astute alt.netters shared some exposition on the venerable MVC pattern as it was first conceived and developed in Smalltalk.  Among these posts, Derek Greer's extensive exposition of these patterns was linked up.  This is a fantastic, thorough, and cogent examination of the patterns and the origin, highly recommended.

You can also add another implementation to your MVP list: MVC#.  This looks very interesting, but I haven't had a chance to delve into it.

Also in the rich-client/WPF world, I heard the first rumblings about Prism this week.  Glenn Block has been a frequent poster to the mailing list in the past.  He's the Technical Product Planner for the Client User Experience (UX) program in Microsoft's Patterns & Practices (PnP) team.  Glenn posted about a code drop of a Prism reference implementation.  This is essentially an application that will bake-in all the concepts that will eventually be extracted, formalized, and generalized into the Prism framework for composite applications.  This is cool stuff, and it will be good to see a lot of the disparate PnP frameworks rolled up.

One ActionScript developer (now that is ALT) asked about dealing with nested asynchronous web service calls.  Two suggestions were given: Flow-based programming and continuation passing style.  The latter is familiar, I would imagine, to most developers, at least those with some exposure to functional programming, and it is now very easy to accomplish with C# and lambda expressions.  The former, Flow-based programming, is an unfamiliar programming style to me, but at first blush it appears to fit in very well with the current interest in SOA.

Our final topic is an appropriate one to this column, namely, how do we process all the technology out there? Asked by J.P. Hamilton on the list, the most interesting response was from Oren:

I don't.  I read some interesting blogs, but I don't go into technology unless I have a need for it.  I try to keep an eye for new ideas, but technology itself is not something that I even try to keep up.  I find that knowing he fundamentals helps immensely when you learn new stuff, so focusing on that is never a bad idea.

Have a great week!

Monday, May 12, 2008

Hpricot Ruby Script to Digest ISO Currency Codes

UPDATE: I fixed a couple of bugs in this and changed the XML Schema DataType namespace alias to “xs”.  You will likely want to remove some enumeration items because they aren’t particular useful for e-commerce applications, e.g. palladium troy ounce.

require 'hpricot'
require 'open-uri'
doc = Hpricot(open("http://en.wikipedia.org/wiki/ISO_4217"))
codetable = doc.search("//table[@class='wikitable sortable']")[0]
rows = codetable.search("//tr")
for i in 1..rows.length
    tds = rows[i].search("//td")
    unless rows[i] == nil
        puts '<xs:enumeration id="' + tds[3].search("//a[@title]").inner_html.inner_html.gsub(/\s/, '_') + '"  value="' + tds[0].inner_html + '" />'
    end
end

Also, here's a Powershell script to process the ISO 3166 country code list (semi-colon delimited):

gc countrycodes.txt | ? {$_ -match ';'} | % { $s0 = $_.split(';')[0]; $s1 = $_.split(';')[1]; "<xsd:enumeration id=`"$s0`" value=`"$s1`" />" }  | out-file codes.txt

Saturday, May 10, 2008

The ALT.NET Times for May 10th, 2008

This is the inaugural post of a series I propose to do over Saturday morning coffee.  I hope to cherry-pick the posts on the ALT.NET mailing list, and record here for posterity (and my feeble, fallible brain) the best information of the week.  Think of it as an ALT.NET Lazy Web distilled.

So, what did we learn this week?  Well, if you're writing, thinking about writing, or desperately need an HTML parser, you should check out Hpricot.  Incidentally, if you're not a fan of Ruby, beware!  The usage syntax of this library might make you a convert.  If you're looking for a .NET library, SgmlReader is a great place to start.

Speaking of Ruby, Dave Newman let us know about his VS plug-in for syntax highlighting of Haml.  Haml is a templating language for creating views in RoR.

A topic that frequently comes up made another appearance this week: "TDD: Where to Start?"  Ah, a fine question and one the ALT.NET crowd answers rather well.  A resounding chorus of alt.netters always seem to respond with one book title in particular: Working Effectively with Legacy Code by Michael Feathers.  Starting out with TDD is hard work, says the crowd, and starting out with TDD on a brownfield project that doesn't utilize inversion of control is considerably harder.  Another popular suggestion is to see TDD in action.

The Managed Extensibility Framework got some pixels towards the beginning of the week.  To quote Krzysztof Cwalina, contributing author of ".NET Framework Design Guidelines" and PM of the Application Framework Core team at Microsoft:

MEF is a set of features referred in the academic community and in the industry as a Naming and Activation Service (returns an object given a “name”), Dependency Injection (DI) framework, and a Structural Type System (duck typing). These technologies (and other like System.AddIn) together are intended to enable the world of what we call Open and Dynamic Applications, i.e. make it easier and cheaper to build extensible applications and extensions.

This is exciting news for .NET developers.  Incorporating these features into the BCL means we don't have to get permission from our clients and project managers to use them.  We won't have to take dependencies on Unity, Windsor, Structure Map, AutoFac, or Spring.NET to get inversion of control goodness into our applications.

One classically "ALT" exchange about distributing configuration changes mentioned some technologies with which I was unfamiliar.  ActiveMQ is a huge, mature Apache project for Message Brokering and Enterprise Integration Patterns.  Under its umbrella are projects such as the .NET Messaging API which provides a common API for interacting with messaging providers (ActiveMQ, STOMP, MSMQ, and EMS).  IKVM is, to put it succinctly, Java running on Mono.  The OP was keen on using custom WCF extensions to make distributed configuration caching with Memcached transparent.  Oren Eini posted some time ago about using Memcached with .NET, and it is definitely something you should check out, should the need for a distributed object cache arise.

That's all I have to report this week.  Have a great weekend and to quote Joe Krutulis of Appirio, "Think & Enjoy!"

Monday, May 5, 2008

Using LINQ from .NET 2.0

A few months back when I was migrating a project to VS 2008, the PM was very concerned that .NET 3.5 would cause problems on our servers, interfering with existing applications or creating new bugs in the existing codebase.  I did my best to educate my PM on the nature of .NET 3.5, that it still ran on the .NET 2.0 CLR, that it was a bunch of new libraries, that it include SDK tools that compiled the new C# 3.0 language, that it wouldn't affect existing applications.  Ever the pragmatic fellow, he insisted on late night installs and system testing, nevertheless.

Now, I don't mind pragmatism, in fact, I applaud it; however, a different situation can arise than the one I just described.  A non-technical PM or a draconian operations manager might insist that you don't "use .NET 3.5" and stick with ".NET 2.0".  If you take this at face value, it means you can't use C# 3.0, LINQ, etc.  Well, first you must get them into a Slammer worm recovery group.  Next, you can still use some .NET 3.5 goodness without having to install it on the production server.

Here's a minimalist approach: include System.Core.dll in your .NET 2.0 project.  You may already know that you can build strictly for .NET 2.0 from VS 2008, so just set the reference, set it to copy local, and roll. You'll have to convince them to let you install .NET 2.0 SP1, though.  Another thing you could try is LINQBridge, a .NET 2.0 re-implementation of LINQ to Objects along with Action<T> and Func<T>.

At the end of the day, you should probably just stay within the environment's strictures.  If you can make the case that .NET 3.5 will save time and money, you'll be much more successful in changing minds than if you just think it is cool.