Browsing Posts published by james

To be honest, I usually ignore the Toolbox column in MSDN Magazine. Usually it features various vendors’ offerings around .NET. The December 2007 issue is typical in that it features .netLIVEHELP ($395), Instant C#/VB ($179), and UltraMon ($39.95). November 2007 featured Spread for Windows Forms ($899), Peter’s Date Package ($90), and WinMerge (free). Previous issues are similar. I’m not commenting about the quality of the software, but more about the focus on commercial offerings.

Today I received the January 2008 issue in the mail (it’s not yet online) and flipped it open. The word “mocking” in the Toolbox column caught my eye and I thought, yet another advertisement for TypeMock. Then I did a double-take. Toolbox was featuring Rhino Mocks by Oren Eini (aka Ayende Rahien). The other features were MbUnit (free), JetBrains’ dotTrace ($499), and Continuous Integration: Improving Software Quality and Reducing Risk. Both Rhino Mocks and MbUnit are open source tools. Although dotTrace is a commercial tool, it’s the best profiling tool that I’ve ever used – and I’ve tried a lot of them!* If you watched my MSDN webcast on tools, you’ll notice that I highly recommend all three tools. I hope that Toolbox’s new author, James Avery, keeps up the excellent work and continues to feature great open source frameworks alongside commercial offerings! Times, they are a-changing. Good open source software is starting to get the respect and recognition it deserves.

* To be honest, I’ve heard excellent things about Red Gate’s ANTS Profiler, but haven’t had a chance to try it and compare.

I know many developers still swear by Windows XP, but I actually like many of the improvements in Windows Vista. Yes, Vista still has some rough edges, but overall it’s a pleasant experience. That said, one of the best features of Vista is the new Start menu. Rather than clicking through a bunch of cascading menus to find the program you want, you press the Windows key and start typing the first few letters of the desired application. Unfortunately, by default, Vista also searches documents, emails, and myriad other places as well, which makes this feature really slow. To make it useable, you can have Vista only search your programs.

  1. Right-click the taskbar and select Properties.
  2. Go to the Start Menu tab.
  3. Select “Start Menu” (not “Classic Start Menu”) and click Customize…
  4. Near the bottom, unselect “Search communications”, “Search favorites and history”, and under “Search files”, select “Don’t search for files”. Make sure “Search programs” is selected.
  5. Click OK twice.

Vista Instant Search is now fast enough to be usable.

I know a few friends who are absolute keyboard junkies. They won’t even touch the mouse unless absolutely necessary. I tend to be more pragmatic about my keyboard use. If I use an application a lot, I learn the keyboard shortcuts. Otherwise I just reach for the mouse. That said, here are some keyboard shortcuts that I use regularly. I’ll skip the usual suspects like copy, cut, paste, undo, redo, … 🙂

Windows*

Close current application ALT-F4
Switch tasks ALT-TAB (2D)
Windows-TAB (3D)
Lock your computer Windows-L
Display task manager CTRL-SHIFT-Esc
Run Windows-R
Launch a program in Vista Windows and start typing
Show desktop Windows-D (toggles)
Windows-M (no toggle)
Go to System Tray (icons beside the clock) Windows-B
Launch Explorer Windows-E
Launch application on Quick Launch bar Windows-1 to Windows-0
Cycle through task bar Windows-T – space selects

* Most work on Windows XP/Server 2003 and above, though some were added in Vista. So your mileage may vary.

FireFox

Open a new tab CTRL-T
Close current tab CTRL-F4
Switch tabs CTRL-TAB (forward)
CTRL-SHIFT-TAB (backward)
Re-open last closed tab CTRL-SHIFT-T
Go to search box CTRL-K
Go to address bar CTRL-L
Find CTRL-F
Go back ALT-left arrow
Go forward ALT-right arrow

Visual Studio/ReSharper

This deserves a separate post and/or screencast, which I’ll get to eventually. For now, download the ReSharper keymap from here (ReSharper 2.x/IDEA scheme). Personally I wouldn’t bother with the “Visual Studio scheme” for ReSharper. Every ReSharper Jedi I know uses the IDEA scheme.

This is the must-see Web 2.0 parody video by The Richter Scales. The lyrics are superb and hit the proverbial nail on the head. The lead singer, Matt Hempey, is a high school friend of Scott Hanselman. More info can be found on Scott’s blog.

A few weeks ago I was merrily working away on an application that uses NHibernate to query data from an Oracle database. I didn’t feel like installing a local Oracle instance as typically I do more work against SQL Server. So I develop locally against a SQL Server database and switch to Oracle by changing a few NHibernate configuration settings. Very nice. I deploy the application into the test environment and it fails with:

ORA-12571: TNS:packet writer failure

Examining the stack trace, the error was happening in the guts of the Oracle driver. Looking up the documentation, this error typically indicates a faulty network cable or similar hardware cause. So I try another query. This time it works. I try my queries one at a time. Only one query is failing. What are the chances that the network cable only comes loose when executing a certain query? Not terribly likely, IMHO.

So I reproduced the error in a simple application and started pulling it apart. I’ll save you the blow-by-blow, but suffice it to say, the only difference between the working queries and broken query was the query parameters. (Also note that the identical code worked fine against SQL Server.) Working queries had integer parameters. The broken query had a string parameter. As soon as I realized this, I made an educated guess that it was a Unicode/ASCII conversion problem. I modified my mapping file to include the datatype in the property definition:

<property name=”InvoiceNumber” column=”invoice_num” type=”AnsiString” not-null=”true”/>

Now both Oracle and SQL Server were happy to execute the query. (N.B. Usually NHibernate can properly infer the datatype based on the property type on the class. So it is not required.)

Come on now, Oracle! Loose network cable??? Not “unable to convert Unicode to ASCII” or “unexpected datatype” or something vaguely useful. Loose network cable??? Hardware failure??? Oracle has a long way to go in improving their error messages. My database of choice is still SQL Server because, most of the time, it just works.

Thanks to everyone who came to my presentations during DevTeach. I’m going to try something different than zip files for distributing code samples. I’ve set up a public Subversion repository on Google Code here. If you’ve got a Subversion client (such as TortoiseSVN) installed, you can point it to:

http://jameskovacs.googlecode.com/svn/Presentations/

The slidedecks are available in the repository, but I’ll provide them here for those that don’t want to go spelunking through the repository…

The Persistence Ignorant Domain Model – PI and, more generally, anti-corruption layers between your code and frameworks, are incredibly important in creating maintainable software. I’ll definitely be talking about these issues in the future. Slidedeck can be found here. Demos can be found in the SVN repository.

Agile Panel with David Laribee and Friends – I qualified in the “Friends” category. The discussion panel was a lot of fun and David did a great job moving the topics along. No slides or demos to see here. Move it along…

Enterprise Version Control – Bil Simser and I did a presentation on best practices in version control. We discussed both Subversion and TFS, though all of our demos were done with Subversion. (The reason… Setup time for a Subversion server – 5 minutes. Setup time for TFS – longer than we cared to take. Yes, both Bil and I have set up TFS before. It’s just a lot more complex than Subversion, though it offers more out of the box.) Slidedeck can be found here (SVN) or here.

Queuing and Caching to Scalability – Other than the technical difficulties in getting my laptop to talk to the projector, I had a fun time with this presentation. (Thanks to the attendee who lent me his laptop so I wasn’t just talking in front of a blank backdrop.) After spending so much time making sure the demos ran flawlessly, I was disappointed that I didn’t get to show them. Slidedeck can be found here. Demos can be found in the SVN repository. The code should be fairly self-explanatory. To run the demos, you need to install MSMQ and create two private queues called messageboardqueue and newbabblesqueue. If you have any questions or problems with the demos, please email me. I’ll try to put together a screencast in the next few weeks for those who are interested, but don’t want to go to the trouble of installing MSMQ.

I appreciate all the feedback I received, both the positive and negative. As a speaker, the best way to improve one’s craft is to critically examine the past presentations by accepting attendee feedback. I think about what went well (and should continue doing) as well as what didn’t go so well and how to improve. Very much like an iteration retrospective in agile development. So keep the feedback coming!

I spent last week hanging out at DevTeach in Vancouver. Awesome conference. Although heavily Canadian, people from around the world showed up. (I finally got a chance to meet Oren Eini (aka Ayende Rahien) in person after emailing/IMing/etc. for a long time.) The Agile track was particularly well-attended, often with standing room only available. Of all the presentations, the ones that stand out in my mind are:

Jeremy Miller’s Creating a Maintainable Software Ecosystem – Jeremy echoes so many of my thoughts on good software design, but does it much more eloquently. If you haven’t subscribed to Jeremy’s blog, go do so right now. I’ll wait… Oh good, you’re back. One of the most amusing moments in Jeremy’s talk when he demonstrated environmental testing in StructureMap. (StructureMap is the first .NET inversion of control container built by Jeremy himself before Castle Windsor or Sprint.NET.) Jeremy turns to Oren and says, “Here’s something that Windsor doesn’t have. Environmental testing.” The basic idea is you can mark certain methods with an attribute to indicate that they validate your IoC configuration. Oren agrees that Windsor does not have such functionality. At the end of Jeremy’s presentation, Oren calls me over and shows me some code on his laptop. Not to be one to turn down a challenge, Oren implemented the feature in Windsor while Jeremy finished his talk! You can check out the code on Oren’s blog and I can attest that he did code this start-to-finish during Jeremy’s talk.

David Laribee‘s Domain Driven Design – David has style like no other developer I know and he has the technical chops to match. He did an admirable job explaining the fundamental concepts of DDD and re-affirming my own understanding. I particularly liked his very visual slide design focused around a picture and short statement to convey the overall meaning. I’ve tried this in a few talks and been pleased with how it works. I was taking mental notes during David’s talk and figuring out how to better incorporate visual imagery into my own presentations. Great stuff.

But neither of those matched…

Justice Gray‘s Microsoft MVC Architecture…what side are YOU on? – Oh my gosh! This was the presentation to end all other presentations. Just read his abstract:

Everybody who is anybody is talking about the new MVC. And when you’ve heard it mentioned, you’ve *also* heard the standard “We can all play nice together”, “there’s still room for choice”, “this is just an alternative” and all those other phrases that likely also involve group hugs and the Care Bear Stare. FORGET THAT. The world is waiting for a man to take a stand – a name that people trust to start the next great religious war in software! So at DevTeach, North America’s Metrosexual Development Hero is going to break his silence and show you why the Microsoft MVC is the *only* Microsoft web architecture you should be developing with. Sure, Justice *doesn’t* have the advance betas, lines of cocaine at every table, and free entry to shady massage parlors that Microsoft gives their MVPs, but he *does* have the ability to incite a full-scale *RIOT*!! Why is this the most important piece of MS web architecture in ten thousand years? What’s the problem with traditional WebForms development? How do the mysterious Page Controller and Front Controller patterns figure into this? Why do Datasets suck? Will Justice even get a beta in time? Will you get laid tonight? Who hit you over the head with that beer bottle? The answers to these and *many* other questions can only be found in THIS PRESENTATION, so make sure you’re there for the session that neither you or the local authorities will *ever* forget!!

The abstract pales in comparison to actual presentation though. I don’t think anyone else could have carried this off. He mixed humour with excellent technical content and insight. Explaining the model-view-controller (MVC) concept using Steven Rockarts’ drug habits* was brilliant. (I know Steven Rockarts personally and I can attest that he is very anti-drug. It made Justice’s presentation all the more funny to see Steve in the back of the room muttering to everyone who would listen, “I don’t do drugs. I don’t have a meth addiction. I don’t do coke. Ah, come-on, Justice!!!”) After demonstrating a MVC app to cure Steve of his various addictions, Justice went on to demonstrate another MVC app in an effort to assist Donald Belcham, The Igloo Coder. Enter The Igloo of Love – A Dating Website for Donald Belcham. On Donald’s list of potential paramours was The Mad Mexican, Martin Fowler, and Scott Bellware. (Showing off the MVC routing engine using the search-engine optimized (SEO) URL http://igloooflove.com/paramours/thatare/slutty/ and having Scott Bellware’s name appear was a riot.) I’ve never seen Donald turn such a brilliant shade of red. Justice had a rollicking good time roasting his fellow EDMUG directors. He was over-the-top and showed that you could have fun while being highly technical. Justice’s presentation style isn’t for everyone, but I for one found it incredibly refreshing and entertaining. Well done, Justice!

Most of the fun at the conference was just hanging out with the other presenters and attendees. There is no line drawn between the two at this conference and everything is set up to encourage interactions between presenters and attendees. (For instance, there is no presenter room. If you really need to prepare, go to your hotel room. Otherwise hang out and talk to everyone.) One dinner was at a Thai place. When we got there, we had to split over two tables. I was at the smaller table with six people. Half the people at the table were presenters. Where else does this happen?

Other fun happenings… I talked to some attendees at the JetBrains booth. While talking, I said to Jeff (JetBrains), it’ll be easier if I just show them. I took over the booth for about 10 minutes demonstrating everything I love about ReSharper. How many of your customers will do that for your product? 🙂

Thanks to everyone I talked to at the conference for making it such a fun time. If you’re thinking of going to a conference in 2008, I would encourage you to make DevTeach one of your choices. I know I’ll be at the next one… How can I be so certain? Because the organizing committee asked me to be the Agile Tech Chair. I’ll be organizing the agile track for DevTeach Toronto coming up May 12 to 16, 2008. If you’re interested in speaking, submissions are due by January 15, 2008. I would also welcome any feedback from attendees regarding topics that they’d like to hear about.

For those looking for slides and demos from my presentations, I’ll be posting those later today. So stay tuned.

Thanks to everyone who attended my Ignite Your Coding webcast. I enjoyed sharing a small sampling of the wealth of tools available for the Windows and .NET developer. For those of you who missed the webcast (or would like to watch it again), it’s available on-demand here.

Below you will find a list of links that I mentioned during the webcast as well as a few attendee-contributed suggestions:

Resources

Community-Contributed Resources (During the Webcast)

Be sure to check out the rest of the Ignite Your Coding webcast series as there are some other great sessions there.

In a domain model, you will sometimes encounter immutable data – objects that can only be read from a database, but never modified. The question is how to test your persistence layer to ensure that you can read them. One way is to hard code values into your tests and assume that the appropriate rows are in the database. This is rather fragile as you are counting on your database being in a known good state. This also prevents you (or another developer) from getting latest from source control onto a clean developer workstation and being able to run the unit tests immediately. You must populate a test database with known good data first. Here’s a little trick you can play with NHibernate. Let’s say you have the following class:

namespace JamesKovacs.Examples.ImmutableData {
    public class Invoice {
        private readonly int m_Id = 0;
        private readonly string m_InvoiceNumber;
        private readonly decimal m_Amount;
        private readonly DateTime m_InvoiceDate;

        public Invoice() {
        }

        public Invoice(string invoiceNumber, decimal amount, DateTime invoiceDate) {
            m_Amount = amount;
            m_InvoiceDate = invoiceDate;
            m_InvoiceNumber = invoiceNumber;
        }

        public int Id {
            get { return m_Id; }
        }

        public string InvoiceNumber {
            get { return m_InvoiceNumber; }
        }

        public DateTime InvoiceDate {
            get { return m_InvoiceDate; }
        }

        public decimal Amount {
            get { return m_Amount; }
        }
    }
}

And its corresponding NHibernate mapping file:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   namespace="JamesKovacs.Examples.ImmutableData"
                   assembly="JamesKovacs.Examples.ImmutableData"
                   default-access="field.pascalcase-m-underscore">
  <class name="Invoice" mutable="false">
    <id name="Id">
      <generator class="native" />
    </id>
    <property name="InvoiceNumber"/>
    <property name="Amount"/>
    <property name="InvoiceDate"/>
  </class>
</hibernate-mapping>

Note that the Invoice is lookup data only. So it is declared as immutable in the mapping file (mutable=”false”). NHibernate will not permit INSERT, UPDATE, or DELETE operations against the entity. The question is how do we test this? We could circumvent NHibernate and directly insert test data into the table via ADO.NET. The downside is that you’re coupling your test data generation code to a particular database schema. If the database schema changes, you must not only update the NHibernate mapping, but you must also modify your SQL statements for creating test data. A definite violation of DRY (Don’t Repeat Yourself) Principle. Let’s see if there is a better way…

NHibernate can generate the database schema from mapping files using NHibernate.Tool.hbm2ddl.SchemaExport. The problem is that you can’t insert data into the Invoice table since the type is mapped as immutable. However, you can read the NHibernate configuration and mapping files and modify the mapping at runtime. This is done by cfg.GetClassMapping(typeof(Invoice)).IsMutable = true. We’re switching our immutable entity to a mutable one on the fly for the purposes of populating test data! Note that you have to modify the mapping before creating your SessionFactory.

using System;
using JamesKovacs.Examples.ImmutableData;
using MbUnit.Framework;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace JamesKovacs.Examples.ImmutableData.Tests {
    [TestFixture]
    public class InvoiceRepositoryTests {
        private const string InvoiceNumber = "ABCD1234";
        // N.B. You should do this once before all your repository tests
        //      as creating a SessionFactory and executing DDL is time-consuming.
       [SetUp]
        public void Setup() {
            Configuration cfg = new Configuration().Configure();
            SchemaExport exporter = new SchemaExport(cfg);
            exporter.Execute(false, true, false, false);
            cfg.GetClassMapping(typeof(Invoice)).IsMutable = true;
            ISessionFactory sessionFactory = cfg.BuildSessionFactory();
            using(ISession session = sessionFactory.OpenSession()) {
                session.BeginTransaction();
                Invoice invoice = new Invoice(InvoiceNumber, 42m, DateTime.Today);
                session.Save(invoice);
                session.Transaction.Commit();
            }
        }

        [Test]
        public void CanRetrieveInvoice() {
            using(UnitOfWork.Start()) {
                IInvoiceRepository repo = new InvoiceRepository();
                Invoice invoice = repo.FindByInvoiceNumber(InvoiceNumber);
                Assert.IsNotNull(invoice);
                Assert.AreEqual(InvoiceNumber, invoice.InvoiceNumber);
            }
        }
    }
}

So we now have an elegant solution for populating immutable test data in a clean database without resorting to hand-coded SQL.

N.B. UnitOfWork.Start() sets up an NHibernate session that is used internally by the repositories. It is based on Oren Eini’s UnitOfWork implementation in Rhino Commons.

MSDN Canada is presenting a weekly webcast series called Ignite Your Coding starting Tuesday, November 6, 2007. I will be presenting the second webcast in the series on Tuesday, November 13, 2007 from :

Frameworks and Tools for the Windows Developer

Numerous frameworks and tools exist to help developers be more productive when building applications on Windows. In this session, you’ll discover some indispensable tools that will enable you to be a more effective developer of Windows. Expand your toolset by learning what’s available today!

Register now!

Here is the full line-up of webcasts. Further details and registration for the other webcasts can be found on the Ignite Your Coding website.

November 6 Understanding the Windows – Based Development Platform
November 13 Frameworks and Tools for the Windows Developer
November 20 Security Essentials for Windows
November 27 The Art of Debugging in Windows
December 4 Application Deployment on Windows
December 11 Developing as a Non-Admin