Category Archives: Uncategorized

Migrations In SubSonic

A few weeks ago Rob Conery foolishly tapped me to help get migrations in SubSonic up to snuff and I’ve been working on them ever since trying to sneak them into the latest SubSonic beta. I’ve changed the way they’re implemented slightly from when Rob first talked about them so here’s a quick re-introduction to migrations.

Migrations are a way to create and version your database schema using code rather than having to rely on SQL scripts or compare and sync tools. They allow you to quickly rollback schema changes as well migrate schema changes from your development database to staging and then on to production. In a nutshell they rock when it comes to database maintaince, versioning and deployment.

Migration Breakdown

A migration is a class that descends from SubSonic.Migration and overrides both the Up() and Down() methods. Up() is used when going up a version and Down() is used to restore the database schema to the pre-Up() state. Anything you do in the Up() should be undone in your Down().

By convention they are put in a Migrations folder off the root of your project folder. While the actual name of the class isn’t important the name of the file is critical because this is how SubSonic determines which version the migration represents. The naming convention is 000_MigrationName.cs (or .vb) with the version number represented by leading three numerics, starting at ’001′ and working your way up. Currently it’s pretty particular about that naming convention so make sure it’s exactly three numerics, padded with zeros if needed. It’s convention to name your migration file something descriptive and to also not repeat names, such as:

001_AddExerciseTable.cs

An Example

Let’s start with a simple example and break it down:

using System;
using System.Collections.Generic;
using System.Text;
using SubSonic;
namespace SubSonic {
  public class Migration001:Migration {
    public override void Up() {
      TableSchema.Table t = CreateTable("Flights");
      t.AddColumn("Name", System.Data.DbType.String);
      t.AddColumn("FlightNumber", System.Data.DbType.String, 100);
      t.AddColumn("DateTraveling", System.Data.DbType.DateTime, 0, false, "getdate()");
      AddSubSonicStateColumns(t);
    }
    public override void Down() {
      DropTable("Flights");
    }
  }
}

In the example the ‘Flights’ table is created, then three columns are added to it, followed by the standard SubSonic state columns. If you don’t specify a primary key one will be created for you with the pattern of ‘TableNameID’, so that’s one less thing to worry about. The Down() method undoes everything we did in the Up() by dropping the ‘Flights’ table.

Available Methods

Currently the methods available from inside your migration are:

  • CreateTable(string tableName) - This creates and returns a table schema to which you can add your columns, as seen in the example.
  • DropTable(string tableName) - Does exactly what it says. If your Up() has a CreateTable() you’ll need a corresponding DropTable().
  • AddColumn(string tableName, string columnName, …) - Used to add a new column to an existing table. It has all the same overloads as TableSchema.Table.AddColumn() except the first parameter is the name of the table you’ll be adding columns to.
  • RemoveColumn(string tableName, string columnName) - You only get one guess that this does :)
  • AlterColumn(string tableName, string columnName, …) - Used to alter an existing column, again, the same overloads as AddColumn.
  • AddSubSonicStateColumns(TableSchema.Table table) - Adds the conventional SubSonic state columns to your table. I’ll be adding another overload that just takes a tableName if you want to add those columns to an existing table.

Running your Migrations

To run your migrations you’ll use SubCommander, the same tool used to generate your models but with the ‘migrate’ command. The simplest usage is:

sonic migrate

That’s it. It’ll use your default provider, look for your migrations in <project>Migrations and run every migration Up() starting at your database’s current migration up the last one found in the Migrations folder. You can also specify the provider, migration directory and version at the command line like this:

sonic migrate /provider “Northwind” /migrationDirectory “D:TestingMigrations” /version 4

A few things to remember:

  • Migrations by convention are looked for in a Migrations folder off the root of your project, though this can be changed via the command line. (/migrationDirectory “D:Migrations”)
  • You run a migration against a single provider at a time, there is no support for specifying the provider inside the migration. The main reason is portability, often you’ll be running this migrations against different databases and hardcoding the provider name in the migration destroys their usefulness.
  • Migrations will run against the default provider unless otherwise specified via the command line (/provider “Northwind”)
  • By default migrations will try to go up to the latest version found in the migrations folder. To go up or down to a specific version use /version X to indicate which version.
  • To enable migration support a new table ‘SubSonicSchemaInfo’ will be created in your database, so don’t delete it and tell your DBA that it’s OK :)

TODO

These are things you *should* see before the next beta drop, but don’t hold me to it :)

  • Ability to generate your migration code skeleton using sonic.exe.
  • Add RenameTable()
  • Add RenameColumn()
  • Add ability to execute ad-hoc sql, for creating stored procs, views, creating roles, users, etc.
  • Add constraints
  • Add foreign keys

So You Want To Be a Web Developer

I just had a friend at work ask that most innocuous of questions, “So, what should I learn if I want to be web developer?” which led us into a pretty good discussion about all things web related and to give him (Hi Nat!) a place to reference my ramblings I thought I’d jot down what I suggested.

Define “Web Developer”

Web developer can pretty much mean anything these days so I find it best to ask yourself what it is you really want to do. I’ve been in shops where web developer meant just HTML/CSS while in others the dev does it all, from comps to HTML to database interaction. In my friend’s case it meant creating a dynamic database-driven website from nothing more than a designer’s comps and the napkin the business leaders scribbled on in between rounds of golf. Which was good because that’s how I define it.

Stage 1 - Learn HTML/CSS

You’ve gotta learn the basic currency of the web before you can get fancy pants on it so getting a solid understanding of good, standards-based semantic HTML and CSS (vs. table tag soup) is key. Regardless of which whiz-bang rocket framework you use in the end it all comes down to pushing HTML so you need to know how to craft good basic pages.

I also suggest forgetting about Dreamweaver, FrontPage or any other HTML editor, for now. In fact I’d suggest using just a really solid text editor like TextPad, InType or E. My current favorite is InType because it doesn’t require the cygwin install like E yet it has better syntax highlighting and snippet expansion than TextPad. When learning HTML you want to be as close to the metal as possible.

There are a ton of great books and websites out there teaching this stuff. Two of my favorites are “Bulletproof Web Design” and “Web Standards Solutions”, both by Dan Cederholm, who presents web design (as in the HTML, not Photoshop comp work) in a real-world, useful manner. Good stuff.

Stage 2 - Learn JavaScript

I’m still iffy on this one since you could argue that JavaScript could come later but I feel it’s best to at least get a rudimentary understanding of JavaScript to learn the basics like client-side validation, confirmation boxes and how to use one of the various JavaScript libraries out there like Prototype, jQuery, ExtJS. Most server-side frameworks try to color the basic way you use JavaScript which I feel can dilute a person’s understanding of just what client-side coding is all about.

Stage 3 - Pick Your Poison (Server-Side Framework)

Ahh, the golden ring, the big prize, what it’s all about, at least for me, the server-side framework that makes all the magic happen when it comes to dynamic page generation. This was probably the hardest thing to guide him on because I’ve worked with most of the major frameworks and they all have pros and cons. The big three to me are ASP.NET, Rails and PHP. They all have great support, vibrant communities and very active development. There is also Java, but I was badly scarred when I learned Java’s AWT and Swing frameworks so I’m going to completely ignore it since even thinking about it again makes me whimper :)

ASP.NET - I’m a little biased towards .NET because it offers a great springboard in terms further types of development. Want to do create a desktop application? No problem, you already know the IDE and C# (OK, or Visual Basic). Feel like being more creative and want to do something Flashy? .NET has you covered with Silverlight. It’s like a gateway drug of development, especially once you start factoring in things like IronPython, IronRuby and MVC. And despite what some people say ASP.NET isn’t just for corporate drones, there’s no Web 2.0 site out there that can’t be coded in .NET. Downsides are that it’s a little more complex to get started and that it’ll warp your fragile little mind when it comes to the bastard child that is WebForms.

Rails - I think learning Ruby (the language of Rails) is a great addition to any developer’s knowledge, regardless of what they code in by day. If someone is interested strictly in single focus, highly dynamic web sites and really has an aversion to Microsoft this is where I’d steer them. It’s a much better abstraction of the web than .NET’s WebForms and you can really get rocking quickly without having to understand much with Rails. The downside is finding jobs in your area looking for entry-level Rails devs.

PHP - This is sort of the monkey in the middle. There are a ton of great PHP jobs but it’s lost a little of it’s hipster sizzle, which isn’t exactly a bad thing. PHP is a great choice for the newbie consultant looking to work with small to medium-sized companies because there are a lot of CMS packages in PHP and you can get solid PHP hosting for a song.

In the end I suggested that he go through job descriptions he was interested in (shhh, don’t tell his boss) and see what they were asking for in terms of knowledge. This brings up another good point, why do you want to be a web developer? If it’s just for a better job then I stand by my suggestion. On the other hand if it’s because you want to do Website X or Project Y then that completely changes the game and makes it easier. You pick the technology and learning curve that will get you quickest to your goal. In the end users could care less if your site is in Rails, .NET or PHP.

New Blog Address

I decided to self-host my blog over on my own domain, blog.enginefour.com. I figured I’ve been paying for it I may as well put it to good use :) I decided to go with BlogEngine.NET, mostly because it was super simple to get setup and seemed to have pretty active development. I think I’ve ported most of the articles and comments over though a few stragglers may be around. I’ll be posting all my pearls and nuggets over there so update to the new RSS address.

I know some of the layout may seem funky, I’m currently porting a free CSS template from a fixed-width layout to a fluid one instead and I haven’t pushed everything yet. For the record I used Yahoo’s grid builder to come up with the CSS layout and it’s damn snazzy. Usually I build up my divs by hand or crib one of my prior fluid layouts but this time I tried something different and I’m impressed. Clean CSS/HTML, though I could use a little more verbose id and class selectors.

Cheat Sheet Needed for ASP.NET MVC

The cool kids over on the other side of the fence always make these really cool "cheat sheets" for whatever bit of tech kit they’re using and I fully expect someone with some good design skills to produce one for ASP.NET MVC.

You hear that Rob Conery?  Scott Hanselman?  How about you Phil Haack?  I fully expect Scott Guthrie, who is a Word among Bytes, to conscript some stylish hipster graphic designer to produce a masterful, stylish and yes, useful cheat sheet for the MVC masses at Mix ’08, an event I sadly won’t be attending because my company considers computers and those that make them work to be second class citizens.  I’m lucky if I get  to upgrade my IDE before the next one comes out much less attend an actual conference.  I’ve heard of conference swag but I’ve never actually received any of this mythical bounty.

Still, I desire, want and dare I say expect said cool cheat sheet.

Here are some examples for those that need some prompting and design ideas and to figure out just what in the hell I’m talking about:

CopySourceAsHtml for Visual Studio 2008

I ported the CopySourceAsHtml to work with Visual Studio 2008. There are some workarounds to get the existing addin to work with Visual Studio 2008 but they all assume you have 2005 installed, which I don’t. I recompiled from source, built against .NET 3.0, removed some crufty code thanks to FxCop and removed a call into olepro32.dll that wasn’t needed. I’ll provide the updated source if anyone cares, this is just a quick posting as I’m flying out the door :)

To Install

  1. Download the CopySourceAsHtml AddIn zip.
  2. Unzip to My DocumentsVisual Studio 2008Addins, if the Addins folder doesn’t exist just create it.
  3. Restart Visual Studio (you did close it first right?)
  4. Right-click some selected code and you’ll have a new Copy As HTML… menu item, that’s the gold, click it.
  5. Check the boxes in the dialog that comes up to your delight and then paste into your blog software or forum post.
  6. IMPORTANT: This Addin generates HTML code, so remember to switch into the HTML view in your blog software or forum edit box.
  7. Bob’s yer uncle

Sample

This is how a chuck of code looks when pasted (you’ll notice it uses your exact color and font settings):

[Test]
public void Select_ColumnList_Specified()
{
   SqlQuery qry = new Select("productid", "productname").From(Northwind.Product.Schema);
   ANSISqlGenerator gen = new ANSISqlGenerator(qry);
 
   string selectList = gen.GenerateCommandLine();
 
   Assert.IsTrue(selectList == "SELECT [dbo].[Products].[ProductID], [dbo].[Products].[ProductName]rn");
}

The Source

UPDATE: I’ve finally zipped up the source and uploaded it by request. Remember, I’m not the original author so all the good credit goes to someone else, I’m just the monkey that made it work on Visual Studio 2008. Here it is for your enjoyment:

CopySourceAsHtml-2.1.0-Source.zip

What ASP.NET MVC Can Learn About REST from Rails

I'm starting to see more ASP.NET MVC samples and questions come out and I'm realizing that a large portion of the ASP.NET crowd doesn't even realize that a huge reason for the MVC movement is because of the Ruby on Rails framework. A lot of new .NET MVC developers are struggling with architectural questions that have already been debated and answered in the Rails community, which makes Rails a great resource for when you're first starting out or you're curious how to handle certain situations, like nested resources or how to structure your controllers.

Speaking of controllers one great thing from Rails that I hope more MVC developers embrace is REST. Instead of repeating everything just watch David Heinemeier Hansson's keynote speech from RailsConf back in 2006. Sure, it's almost two years but for ASP.NET developers it may as well be yesterday. I'd suggest starting from the second part since the first segment is just normal conference ra-ra-ra.

Check it out here (don't forget to download the slides that he refers to here).

Note

He talks about using a semi-colon in the URL to denote an aspect/action of a controller, like this:

/people/1;edit

Well, you can ignore that and just assume he *really* meant to say:

/people/1/edit

They dropped that semi-colon silliness in Rails 2.0 and it feels much cleaner.

Nested Resources In ASP.NET MVC

Often you'll need to represent some hierarchical or parent-child relationship in your application and one thing you'll struggle with is how to cleanly mesh both the parent and child controllers yet keep them nice and RESTful. The secret is in good routing.

The problem

A popular example is tickets belonging to events (event as in Burning Man, not OnClick) and you want to get all the tickets for a certain event, as well as be able to work with just tickets or events. You want nice and pretty urls as well, so you're hoping for something like this:

/events/1/tickets all tickets for event 1
/events/1/tickets/new add a new ticket for event 1
/tickets/list all tickets for all events

The Messy Way

My first idea was to add a Tickets action to my Events controller so I could call EventsController.Tickets(int eventId) but that didn't really help when I wanted to view all the tickets for all the events. Plus it broke the whole REST idea and that's bad for maintainability.

My second idea was a butt-ugly url along the lines of /tickets/list?event_id=1 but that just kicks the whole MVC, SEO-friendly url philosophy in the nuts. Repeatedly.

The Routes Way

A Big Thanks goes to Adam Wiggins whose post about nested resources finally set off the lightbulb in my brain. Instead of trying to make my controllers do all the work why not take advantage of the actual mechanism that's there to handle these sorts of things and put it to use. That would be the routing mechanism that makes all your urls pretty and dictates which controller does what. Here is the way to keep your urls pretty and to have both a separate Events and Tickets controller yet still maintain the cool parent/child relationship:

[code=csharp]RouteTable.Routes.Add(new Route { Url = "events/[eventId]/tickets/[action]/[id]", Defaults = new { controller = "Tickets", action = "List", id = (string)null }, RouteHandler = typeof(MvcRouteHandler) });[/code]

(yes, I know, my code formatting sucks, I'll update it this weekend)

Once I discovered this I smacked myself on the forehead for not realizing just how simple this whole thing was.

Microsoft Shareholder Value

I just saw a quote from Joe Rosenberg via the MSFTextrememakeover that included one of the most asinine and scary things I’ve ever heard about Microsoft:

Rosenberg said. “The company has lost sight of its principal focus, which is to produce value for shareholders.”

What’s scary is that this is from a “Chief Equity Strategist” yet after this quote I wouldn’t trust anything this guy has to say about money or investing because if there is one common theme among the most successful companies and individuals it’s that their primary focus is to do what they love and to be the best at doing it. Once you start chasing money for moneys sake the game is over and you’re done ever making any type of substantial financial gains. Rosenberg should know this and if he doesn’t perhaps he needs to pick up a BusinessWeek and read this article, “The Secret Behind Trump’s Success“.

So if you ever find yourself starting a venture simply because you think it’ll net you millions or because you’re secretly hoping you’ll be bought out then stop, take a breath and get a grip on reality. If you really want to make money find your passion and be the best at it, do everything you can with it, surround yourself with others who share the passion and push that passion, be uncompromising with it and don’t change your vision to fit into a committee or shareholder view.

Getting SubSonic Setup in Visual Studio

I’m a big fan of SubSonic, a ORM/DAL generator slash utility belt of goodness. Like any tool there is a little configuration and setup you need to do to get everything rolling and while Rob Conery has some great podcasts on doing just this sometimes you just need to remember that one little option vs. wanting to watch a 10 minute podcast again, regardless of how melodic and sweet are the dulcet tones of Mr. Conery’s voice.

1. Download and Install SubSonic.

Seems simple but hey, some people need to be told everything :)

2. Create SubSonic DAL as an external tool

Even though SubSonic supports Rails-style auto-gen of your DAL via build providers I like putting my model/DAL in a separate class library and sadly build providers don’t play well with class libraries.

Go to Tools | Externals Tools… click “Add” and make it look like this:

External Tools

  • That command is your path to sonic.exe
  • If you’re working with the MVC Toolkit (and why aren’t you?) then change “App_CodeGenerated” to “ModelsGenerated”

3. Create SubSonic DB as an external tool

SubSonic can also version and script your database, very useful for source control and distributing your application. Same as above but make it look like this:

External Tools (2)

4. Install SubSonic Schema

I dislike any warnings during a build and one you’ll get with SubSonic is it not knowing about the SubSonic config sections. I did a blog post on how to fix this awhile back but I’m repeating here for the lazy (like myself):

  1. Download SubSonicSchema.xsd (if you right-click to download make sure you save it with an xsd extension)
  2. Put it in C:Program FilesMicrosoft Visual Studio 8.0XmlSchemas (adjust accordingly for VS2008)
  3. Edit DotNetConfig.xsd in the same folder and add the following line:

    (I added it right underneath the <xs:schema> opening tag, seems to work. Also, if you’re using Vista you’ll need to edit DotNetConfig.xsd in an editor that was started with right-click, Admin, otherwise it’ll write a copy of the xsd into the Virutal Store and your changes will never take effect. Trust me, I learned this the hard way.)

  4. Close Visual Studio if it’s running, re-open, ta-da you now have IntelliSense as well as no more annoying “Could not find schema information for…” messages.

5. Install SubSonic code snippets

You add various sections into your web.config to wire up the magic and nothing is more boring than typing the same poop over and over again. I created some snippets that provide the various bits that you can download here (actually not quite yet since the bits are at work and my VPN is broken right now).

And Bob’s your Uncle, you have all the boring schtuff out of the way and now you’re ready to start genning ya some code. If you don’t actually know how to start genning your code then I’d suggest watching some of those screencasts I mentioned above.

Software I Use Everyday

I’m one of those people that enjoy rebuilding their machines every so often, either for performance reasons or just because I like to tidy things up.  I rarely keep software installs around since there are usually newer versions by the time I re-pave my machine so this is my "must have" list of software I reinstall every time, in one easy place for my future self to grab the downloads from.

General/Misc

  • CCleaner - My favorite registry/file cleaner.  I run it at least a few times a week.
  • Trillian - Pretty much the one and only IM client.  It supports all major IM networks and the 4.0 beta version eve handles GTalk and MySpace so there really is no need for anything else.
  • Virtual CloneDrive - It’s what I use to mount ISO’s on anything from XP to Vista, though I hear MagicDisc does a great job as well.
  • Windows Live Writer - It’s what I use to write my blog and it rocks, seriously easy.
  • Windows Live Photo Gallery - Great for tagging photos and includes built-in flickr.com uploading support.  Really polished looking.
  • FeedDemon - My RSS reader of choice, if you only use Google Reader you’re missing out on some really great features.  Awesome support for offline feeds and they just made it free!
  • ClipX - Great clipboard history manager.
  • Window Clippings - I’m always taking screenshots for various things, either blogs or product help or just to send off to a client to show them what they should be seeing.  Free, easy and awesome.
  • Password Agent - New - There are a slew of password vaults out there but for some reason I keep coming back to this one.  It doesn’t try to offer every feature under the sun, just the ones I need.

General Development

  • TortoiseSVN - Best subversion client I’ve used so far.
  • Intype - A TextMate-like clone text editor that I’ve started using more and more.
  • TextPad - Until Intype matures some more I still need a lot of the great features in this text editor.
  • Sysinternals Suite - When you need to know exactly what’s going on in your system these tools will help you explore the plumbing.
  • Ruby - A beautiful scripting language that I find myself using more and more for little tasks that I used to write applications for.
  • Virtual PC 2007 - Because sometimes you just need to test on a different or clean OS and this is even better than a lab full of machines.

.NET Development

  • mbUnit - I find myself preferring mbUnit to NUnit to unit testing.
  • NCover - Ever wonder just how much of your application is actually being tested?  Here you go.
  • TestDriven.NET - Best way to run mbUnit, NCover, NUnit, etc. from inside of Visual Studio.
  • FxCop - Because it’s always nice to know what the framework team would think of your code.

Delphi Development

  • GExperts - Best add-in for Delphi ever in my opinion.  Just the Ctrl-G makes it a must-have.
  • QC Plus - When you want to submit Delphi bugs or just browse the current issues the CodeGear provided QC client app sucks.  QC Plus pretty much blows it out of the water.

Web

  • Chrome - New - This used to say Firefox but honestly I haven’t installed Firefox during my last three machine reinstalls.
  • Fiddler - When you need to debug HTTP traffic this is the tool I reach for.
  • SmartFTP -  I used to use Filezilla but honestly I’m a sucker for a good looking UI.
  • Gmail Notifier - Notifications of new Gmail messages in your tray.  Simple and useful.

LAMP

I still do a lot of PHP work for a few clients so these are my "must have" tools for working with the LAMP stack.

  • PuTTY - For telnet/SSH access into a site’s shell
  • SQLyog - GUI for managing MySql databases
  • LAMP Virtual Appliance - A LAMP stack in a virtual machine, with images for VMware and Virtual PC/Virtual Server.  Great for testing

Media

  • Zune Software - Because I have a Zune and I love UI.
  • Mp3tag - My favorite metadata tag editor.
  • Winamp - Still the most powerful media player out there, plus it rips better MP3′s than the Zune software since it uses the LAME encoder.
  • EncodeHD – There are a dozen if not hundreds of tools used to re-encode video out there yet oddly enough they either look like a boom box from the 80’s, are super complicated or are expensive.  This is free, open-source, requires a single installer and frankly rocks.  Highly recommended.

Uh, now I realize why it takes me so long to reinstall my machine :)

UPDATE: Okay, so I’ve updated my list for 2010, look for  - New – for the items I’ve added since I last made this list.