Monthly Archives: May 2009

Upgrading to Windows 7 RC

I’ve had Windows 7 Beta installed on my personal laptop since it became available for download back in January, and I’ve really enjoyed using it. However, since I found out that, starting July 1st, copies of Windows 7 Beta will shut down every 2 hours, I thought it might be time to go ahead and install the RC.  The thing that was holding me back was that there’s not an upgrade path from the Beta to the RC, so I would have to do a clean install of the OS.  My machine was probably not due for a Windows reinstall quite yet, but it never hurts.  😉

I also decided to take the plunge into 64-bit for the first time, and it hasn’t been too painful.  The only thing that I ran into was that shell extensions for 32-bit programs don’t show up.  Fortunately, the three programs that I want the shell extensions for (Tortoise SVN, 7-Zip, and Vim) all have some form of 64-bit version available, so I’m all good.

The most painful part of the rebuild process by far was installing SQL Server 2008.  There are several downloads on the download site, and the descriptions of each have been so marketing-ized that you’re not even sure what the difference is between them all.  Once you’ve got the right one (maybe, who can tell?) downloaded, the installer is so cluttered with options and “upgrade analyzers” that it’s difficult to tell how to actually install the product.  The install experience needs some serious rework.

The other thing I’m going to have to do is reinstall GRUB, because right now I can’t get to my Ubuntu install, but I think I’ve found a good guide to doing that here.  Wish me luck!

Fluent NHibernate Auto Persistence Model

I wrote the other day about how conventions in Fluent NHibernate can make your life easier by decreasing the amount of code you have to write to map your objects to their relational representations.  Well, if you’re willing to go along with even more convention, you can even do away with some of your mapping files entirely.

When setting up your NHibernate configuration via FNH, normally you specify where to find your mappings by using something similar to the following:

.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Entity>())

Notice the “FluentMappings” property being used here.  This will look for any mappings you have explicitly specified in classes that derive from ClassMap, a base class provided by FNH.  However, if we change that to use the “AutoMappings” property instead, like so:

.Mappings(m => m.AutoMappings.Add(AutoPersistenceModel.MapEntitiesFromAssemblyOf<Entity>()))

FNH will determine the mappings all by itself based on conventions, and you don’t have to write a single ClassMap class.

Used in conjunction with NHibernate’s SchemaUpdate feature, this becomes really powerful.  You can simply add a property to an entity class contained in an assembly for which you are using auto mapping.  When you run SchemaUpdate, either at the start of your application, or maybe in a separate console app, your database schema will be updated to include a new column to store that property value.  To illustrate, I’ll show you a simple example.  

I’ve got a small entity named “Course” that represents a college course.

    public class Course
    {
        public virtual int Id { get; private set; }
        public virtual string Name { get; set; }
        public virtual string CatalogNumber { get; set; }
    }

And the database table it maps to looks like this:

sql1

Say that I wanted to add a property to my Course entity to tell how many credits the course was worth.  I just add the property to the class:

    public class Course
    {
        public virtual int Id { get; private set; }
        public virtual string Name { get; set; }
        public virtual string CatalogNumber { get; set; }
        public virtual int NumberOfCredits { get; set; }
    }

And run SchemaUpdate through a simple console app that looks like this:

    class Program
    {
        static void Main(string[] args)
        {
            Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2005
                .ConnectionString(c =>
                    c.Is(ConfigurationManager.ConnectionStrings["SQLServerConnString"].ConnectionString)))
            .Mappings(m =>
                  m.AutoMappings.Add(AutoPersistenceModel.MapEntitiesFromAssemblyOf()))
            .ExposeConfiguration(BuildSchema)
            .BuildConfiguration();
        }

        private static void BuildSchema(Configuration config)
        {
            new SchemaUpdate(config).Execute(true, true);
        }
    }

I’ll see the script being used to update the schema in the console window:
console

And my database table will be updated with a new column for the new property:

sql2

Having not used this feature of Fluent NHibernate in anything close to a production capacity, I can’t speak to how well it scales.  However, I think this has a lot of potential for rapid prototyping, especially when you pair it with ASP.NET MVC and the templated controllers and views that you can generate.  A little alteration of the T4 templates used for the controllers could do some default persistence via NHibernate, and then we’d be quite a bit closer to the ease of protoyping provided by Rails.

Again, hats off to the Fluent NHibernate team!

Miguel Castro on .NET Rocks

I’m still not ready for the blog post on Fluent NHibernate’s Auto Persistence Model that I’ve wanted to write for a couple of days, so I thought I’d share a few of my impressions about Miguel Castro’s interview on DNR on Thursday.

First, no ORM proponent (to my knowledge) has ever said that using an ORM means that you don’t have to know anything about databases or SQL.  It’s still essential, when using an ORM, to understand how relational databases work.  At the end of the day, that’s how your data is being stored.  And you also need to understand SQL, not even so much to try to decide if your  ORM is producing sub-optimal queries so you can step in and write them manually yourself, but to clue you in that you may be using your ORM incorrectly.  I don’t know of anyone in the ORM camp, as I said, who has indicated otherwise.

Second, I may just not run in the right circles, but the whole OO-vs-SOA argument seemed kind of ridiculous.  Is anyone actually fighting about those things in an either-or way?  Maybe it was just a CSLA thing (which would explain why I’d never heard anything about it), because I don’t know of anyone who’s suggesting that service-oriented-architecture is even the same category of thing as object orientation.  I mean, unless you’re writing your services in F# or Erlang or something, chances are you’re going to be consuming them from a OO environment.  Sounds like a made-up fight to me.

And last, does anyone really need to drag out the C#-vs-VB thing again?  Is anyone really still arguing about which one is better?  Aside from a few notable exceptions (XML literals come to mind), there’s not a dime’s worth of difference between the two languages.  Again, sounds like more of a manufactured fight than anything.

There were several more things that he brought up that were in more or less the same vein.   He’s a smart guy, I think, but he probably could have made a better contribution to the .NET community by discussing a subject he was knowledgeable in and sharing some of that knowledge with us.  In the end, it just sounded like he was trying to find “controversial” subjects to “make some people mad” over, and it ended up falling kind of flat.

NHibernate ICriteria Queries – Way Too Many Strings

I hoped to have a lengthier blog post ready for tonight, but I just didn’t end up with enough time.  Instead, I’m just going to use this opportunity to say that I’m really looking forward to NHibernate.Linq being production ready.  The following block of code is more or less the query I have to build up to execute that search I talked about last post, not including the extra filters that are appended for each user-input value:

ICriteria query = session.CreateCriteria(typeof(Campaign));
query.CreateCriteria("CampaignStatus", "s");
query.CreateCriteria("CampaignType", "ct");
query.CreateCriteria("CampaignLocations", "cl")
    .CreateCriteria("Location", "l")
    .CreateCriteria("County", "c")
    .CreateCriteria("Territories", "t")
    .CreateCriteria("Company", "com")
        .Add(Restrictions.Eq("com.CompanyID", 1));
IList cams = query.SetProjection(Projections.ProjectionList()
                  .Add(Projections.Count("cl.DateResponseReceived"), "ProspectCount")
                  .Add(Projections.CountDistinct("l.LocationID"), "LocationCount")
                  .Add(Projections.GroupProperty("CampaignName"), "CampaignName")
                  .Add(Projections.GroupProperty("ct.Name"), "CampaignType")
                  .Add(Projections.GroupProperty("s.Message"), "CampaignStatus")
                  .Add(Projections.GroupProperty("StartDate"), "StartDate")
                  )
                  .SetResultTransformer(Transformers.AliasToEntityMap)
                  .AddOrder(new Order("StartDate", false))
                  .List<IDictionary>();

Waaaay too many strings for my taste.  Looking forward to completely strongly-typed queries.

Fluent NHibernate Rocks

At work, we are preparing to institute an “Innovation Idea of the Quarter” program.  I say “Innovation Idea” and not “Innovator” because the idea doesn’t necessarily need to end up being implemented for the person who came up with it to win.  I think this is great, because it really encourages people to think outside of the box from the way we normally develop, and not to just propose things they know for sure would be “safe” enough to actually go into the product.

As you can probably tell from the title of this post, I’ve already decided what my initial submission is going to be.  A few months back, when we were first floating the idea of the innovation program, I started trying to prototype using NHibernate in one of our smaller systems as a proof-of-concept.  I eventually got one of search pages working, but it took a lot of trial and error with the “hbm.xml” mapping files, since I didn’t know until I ran the program when I had misspelled something.  Since the innovation program still in incubation when I finished, I set my proof-of-concept aside.

Fast forward a few months, and I had noticed that the Fluent NHibernate project had come a long way.  They’ve now got  a significant amount of documentation on their wiki site (http://fluentnhibernate.org/), pre-built binary packages, and a pretty active mailing list (http://groups.google.com/group/fluent-nhibernate).  After perusing the site a bit, and determining that, based on the amount of activity I saw, Fluent NHibernate probably did have some legs and wouldn’t just be a flash in the pan, I decided to convert proof-of-concept over to using Fluent NHibernate.

I was not disappointed.  One of the key benefits of using FNH is that you get compile-time checking of your object property names, since you use lambda expressions to specify your mappings.  You also don’t have to use the verbose type name syntax (e.g. “My.Really.Long.Chain.Of.Namespaces, ClassName”) when creating relationships between entities.  But the thing I liked the most was the ability to define conventions for just about everything.

The team I work on has an… ahem… interesting pattern for column naming:  basically, Hungarian notation for columns.  If a column is an integer column in the database, it will have an “int” prefix on the column name.  If it’s a char or varchar column, it will have a “str” prefix, and so on.  While I may not agree with this “coding standard”, the team has at least been consistent about it, so I was able to take advantage of conventions.  

In FNH, you define a convention by creating a class that implements one of the convention interfaces provided by FNH, such as IPropertyConvention (you can see the entire list of available interfaces here).  That interface requires you to implement two methods, Accept and Apply.  

The Accept method lets you define what kinds of properties or classes will be affected by the convention.  You get full access to all of the information about the property, such as the name, the data type, and so on, to let you determine if the convention ought to apply to the property.  For example, the Accept method for the string column convention I mentioned earlier looks like this:

public bool Accept(IProperty target)

    return target.PropertyType == typeof (string);
}

The Apply method lets you perform mapping actions on the property or class just as you would in a ClassMap<T> class, which is where mappings are defined in FNH (each one of those classes would correspond to a “hbm.xml” file used by NHibernate when not using FNH).  This is easier shown than explained, so here’s the Apply method for that string column convention:

public void Apply(IProperty target)
{
    target.ColumnNames.Add("str" + target.Property.Name);
}

So, with that convention in place, all I have to do to define a mapping between an entity property named Address and a column named strAddress is:

Map(x => x.Address);

You can, of course, override the conventions you define at any point that you system deviates, so you’re never painting youself into a corner by defining conventions. You’re just taking care of the majority case, and eliminating a lot of code (and magic strings) in the process.  

Since I had conventions and Intellisense working for me, I was able to convert all the hbm.xml mappings I had defined the first time to FNH mappings in a single evening.  If you’re using NHibernate in your application, you should take a serious look at Fluent NHibernate.  Not just for the reasons I’ve covered here, but also for the help it provides with refactoring (property names in mappings are affected by refactoring tools) and the ability to test your mappings.  Kudos to James Gregory,  Paul Batum, Andrew Stewart, Chad Myers, Jeremy Miller, et al. for providing a way for the rest of us to improve our NHibernate experience.

One Year at Praeses

May 7 marked one year since I started my current job here at Praeses, back home in Louisiana.  It’s been a pretty good year, and I’ve come away with some valuable experiences.

Apart from some playing around (and I realize now that that’s what it was) with ASP.NET at Data-Tronics, my first real-world experience with the platform came when I started here.  At my previous job, all web work was done with classic ASP, and I was anxious to start using a more modern technology.  I still have nightmares about the awful spaghetti-code reporting system that I worked on when I started at DTC.  When I got to Praeses, I discovered that ASP.NET had its own set of anti-patterns and pitfalls; no technology is a panacea (no matter what the Rails guys try to tell you).  That said, I do definitely enjoy developing on this platform more.  WebForms may be full of cruft, but writing in C# beats the pants off of writing in VBScript any day.

I also got my first three Microsoft certifications during my first year here.  I wasn’t sure what to think about the prospect of getting these certs before I started, but now my opinion is pretty well formed.  Like a BS in computer science, certifications prove that you can take tests, mostly.  You may learn a thing or two during the process, but most of your learning is really going to take place on the job and through personal study.  At the end of the day, it’s mostly just a line on your resume, but a line that may open up opportunities for you, and so one that may be worth pursuing.  I had a very interesting discussion with our CEO via email when he asked me if I thought that studying for the exam I had just passed had made me a better developer.  That entire story is probably worth a post of its own, but suffice it to say that I’ve done my best to influence the way our company thinks about developer education.

A couple months after my arrival in Louisiana, I decided to take advantage of an interesting opportunity.  I had just started attending the Fort Smith DNUG when I left, and I had greatly enjoyed the additional learning and networking opportunities it provided.  However, there was no .NET user group closer to Shreveport than Dallas, so I decided to start one.  It has been an interesting experience, but one which I in no way regret undertaking.  I think the Shreveport .NET community needs this resouce, whether I was the one who got the ball rolling or not, but I’m glad that it was me.  It’s been a great way to improve my organizational skills, and I think it will serve me well in the future.

In addition to all the professional stuff that I accomplished this year, my personal life has also been quite busy.  We sold a house, bought a house, and lived through staying at my in-laws for 5 months.  Our baby went from a cooing, screaming infant to a walking, talking, singing, dancing little person.  My wife Rachel became a tutor with a substantial client-base, and I became much more adept at taking care of Molly by myself in the evening, at least for a couple of hours at a time.  We found a good chruch home in River Valley Church, and a pastor that we can really look up to as a spiritual guide and mentor in Lowell Kenyan.

All in all, it’s been a pretty good year.  We still miss our friends from Fort Smith (Josh and Jen, our LTD friends, all my buddies from work), but Bossier City is really starting to feel like home again.  And it’s good to be home.

 

P.S. – Yeah, I know, I forgot to post yesterday.  Two days into it and I already goofed.  Not exactly the picture of good follow-through, am I?  Well, it was the spirit of the exercise, anyway, so I’ll just extend the timeline by one day.

May SDNUG Meeting

Tonight my friend Zac Kleinpeter gave a great presentation CouchDB, a schema-less document-oriented database from the Apache Software Foundation.  I have to admit that I don’t completely grok it yet, but the schema-less model does seem to be catching on in platforms designed for high scalability, such as Google’s BigTable, Amazon’s SimpleDB, and Microsoft’s SQL Data Services (at least the first available incarnation of it).  

Since it’s mostly popular with the Ruby and Python crowds, there isn’t a whole lot of effort being put into .NET libraries, but they do exist.  The SharpCouch library, part of the couchbrowse project on Google Code, is the main one that I’m aware of, but I believe there are others.

Definitely something that merits more investigation.  I’ll just squeeze it in alongside my experimentation with Mono, NHibernate, Rails, and the myriad of other goofy things that I continue to fill my free time with. 😛

Catching Mono

When I was up in Bentonville, AR speaking at the Northwest Arkansas Code Camp, I came across an issue of ASP.NET Pro magazine with the title “The LAMA Stack” (short for Linux, Apache, MySQL, and ASP.NET).  The article inside turned out not to be that interesting, but the idea of using ASP.NET with an otherwise completely open-source stack certainly is.  

One of the things that is said to deter many startups or other small shops from using the Microsoft platform is the licensing cost of its products, particularly SQL Server.  But since Mono allows us to run .NET code on Linux, all of those costs can be eliminated.  Also, since the ASP.NET MVC framework was released as MS-PL (Microsoft’s most permissive open-source license), the Mono team was able to quickly integrate that into their framework as well.  

Since I want to start my own business one day, it ocurred to me that this could be a great way to leverage my existing skills, but use a modern web framework (MVC) and not have to put up a huge upfront investment.  And yes, I know about BizSpark, the program that gives startups free Microsoft software, but that deal “expires” after 3 years.  And if your business isn’t exactly booming at that point, then you may be stuck with an application that you can’t afford the licenses for.

So I decided to start experimenting with Mono to see if it was easy enough to work with that it would even be a viable option for me.  I’m not the most Linux-savvy guy in the world (as you may already be aware from reading some of my previous posts), and there was a distinct possibility that it would simply be too much of a headache for it to be worth it.  

I started out with the  VMWare image that’s available on the Mono project site (www.mono-project.com), and tried some basic “Hello, World” stuff, and that worked just fine.  Even getting an app running under Apache rather than the MonoDevelop IDE was really easy with the AutoConfiguration feature they’ve implemented.  The problem started when I tried to run an MVC app under Apache.  Because AutoConfiguration depends on the ASP.NET file extensions (“.aspx” et al.) to work, and MVC apps avoid those extensions, they can’t be used together, so I had to delve into defining an Apache virtual host for the MVC app.  Thankfully, the Mono team has provided a great tool for generating most of the boilerplate configuration for a Mono ASP.NET app on the project site (http://go-mono.com/config-mod-mono/).  

The next problem was that the version of Mono that supports MVC (v. 2.4) wasn’t available yet on the Linux distribution that I run, Ubuntu, which only has a package published for version 2.2.  That meant that I would need to compile Mono and several other tools from source, which is a somewhat daunting proposition for someone not very experienced with compilation on a Linux system.  I found a great resource for this, though, on the blog of a BlogEngine.NET team member named Russell (couldn’t find his last name) here: http://blog.ruski.co.za/page/Install-Mono-on-Ubuntu.aspx.  This post gives step-by-step instructions on getting Mono 2.4 running on Ubuntu, and without it, I would probably still be banging my head against the wall.

After much trial and error, I finally achieved my desired result.  I was able to run an ASP.NET application that was created and compiled in Visual Studio on Windows, copied over to a Linux machine and executed under Mono.  It wasn’t the most frictionless experience in the world, by any means, but after having done it once, I think subsequent apps will be easy enough to set up.  I’ll be doing the setup process at least one more time in the near future; I’d like to get Mono apps running on the servers we have set up for the new open-source shared interest group that I’ve recently joined with several other Praeses employees, which we’ve decided to call Samurai Delicatessen 😉 .  If I can manage to do the setup remotely over SSH, I think I can safely say it’s a stack that I’ll be able to handle using in the future.

Back From the Dead

I just realized that it’s been four months since I’ve last posted a blog entry, which is just dumb.  Like most bloggers, I started out with good intentions, but other things (work, family, sleep) just got in the way.  There’s also kind of a snowball effect.  Once you’ve not posted in awhile, you feel more compelled to make your next post really great to make up for the lost time, which just makes you even more hesitant to post.

Well, it’s time to end the cycle.  I hereby publicly declare that I will post at least something every day this week, just to get the juices flowing again.  It may not be technical in nature, and it may be utterly useless, but I think I just need to muscle past this block to get going again.  I apologize in advance for any time you may waste reading the ramblings that may result from this push.  😉