Archive for July, 2008

Why Plain Old LINQ is so powerful

July 31st, 2008

Ian Griffiths posted a great example of how powerful and cool LINQ is when used in everyday code (it’s not all about databases people).

If you haven’t started to learn how to incorporate this awesome toolset into your daily coding life, you’re killing yourself.  No excuses.

Roadblock to Mocking Unit Tests

July 15th, 2008

I’ve been a faithful unit tester for a few years now.  I may not do everything by the book (I think end-to-end unit tests are helpful), but I do get good coverage most of the time.  That said, I’ve found myself unable to use any of the Mock frameworks out there, because I don’t use your typical Dependency Injection pattern.  That is, I don’t like “building up” very freaking instance with all the “Provider” or “Service” interfaces I’m might need in the possible life of a business object.  Yes, if your Customer class is only going to create or save an Order, it feels OK, but my objects are busy dude, so I’d need the longest constructor of all time.

I prefer Dependency Resolution.  I don’t use any fancy framework, I just use a good old, DI.Resolve<IBusyBee>() and go about my business.  It works wonderfully, it’s light-weight (cause I don’t use configuration based DI frameworks), and it’s my baby.

That said, it’s also been the roadblock to my mocking foray.  That was, until I “got it” today.  Long story short, here’s how I roll:

Create a Mock DI Container…

Mock<IDIContainer> mockContainer = new Mock<IDIContainer>();

Create the Injected Mock instances…

Mock<INotificationManager> mockNotifMgr = newMock<INotificationManager>();
Mock<IRepository> mockRepository = newMock<IRepository>();

Tell the mock IDIContainer to return the mock instances when asked…

mockContainer.Expect(c => c.Resolve<INotificationManager>(null)).Returns(mockNotifMgr.Object);
mockContainer.Expect(c => c.Resolve<IRepository>(null)).Returns(mockRepository.Object);

Mock your heart out…

mockNotifMgr.Expect(mgr => mgr.NotifyEmailConfirmation(It.IsAny<Member>())).AtMostOnce();
Member.Register("username", "firstname", "lastname", "ryan@myus.com");

mockContainer.VerifyAll();
mockNotifMgr.VerifyAll();

I’m very happy to have finally jumped on the Moq bandwagon as it will certainly make some unit tests much easier to write.  Maybe I’ll even do the test first part more faithfully now. 

FYI, I use my own DI framework which is just a glorified HashTable.  It works for me and it is quick.  Moq has also become my Mock framework of choice for no good reason other than I downloaded it first.

Video Conferencing Code of Conduct

July 7th, 2008

My team uses ooVoo for video conferencing our Daily Scrum.  It’s been great and very reliable.  My only complaint is a lack of whiteboard or desktop sharing, but we’ve overcome these obstacles with other tools (see SharedView).  Over the months, I’ve come to acquire an expectation of what the experience should be like and, from that, a Code of Conduct.  Here it is:

Don’t Be a Slob – Just cause you’re in your bedroom or PJ’s doesn’t mean I want to know about it.  Put a decent shirt on and brush your hair.  Same goes for yawning, coughing, and every other table manner.  Cover your mouth, mute the Mic, whatever.

Have a Headset – I’m sure some guy out there is ecstatic about the next step in the evolution of the speaker phone, but they still suck in comparison to a headset and Mic that are placed against their corresponding body part.  You’re laptop’s built in speaker and Mic are no better, so fork out the 10 bucks and get a cheap headset you cheap-arse.

Go Full or Go Home – I’m glad your torrents are racing, but your video looks like the corner of your head just entered the Atari zone.  Stop downloading the latest SUSE iso for a few minutes and give me your full bandwidth attention.

Setting up a Virtual PC Domain

July 7th, 2008

I do a lot of demos and Virtual PC 2007 is a mainstay in my arsenal for those demos.  I’ve used VMWare Server (the free one) and it is very nice, but I run an x64 OS and VMWare had neglected to sign certain emulation drives which caused me enough headache that I ditched it for the easy of VPC. 

I mentioned using Syspreping for my VPC library prior which saves me a ton of time, but one of the things I’ve always started but never finished was setting up a Virtual Domain.  Well this weekend, I finished things up and I’m happy to say, it wasn’t that bad. 

Here’s what I did:

Create My Domain Controller Machine by copying a Syspreped Window 2008 Server harddrive image and creating a new Virtual PC using an existing hard drive.  About 120 seconds later I have a free standing vanilla server ready to roll.

imageConfigure Network Adapter(s) by specifying Local Only in the VPC’s Network Settings. 

At this point you’ll want to log into VPC if you haven’t already.  We’ll want to isolate our domain and let each of the workstation VPC’s communicate with the domain controller by going into the Network Adapter’s properties.  Our little domain network is going to be rather isolated.  To accomplish this, we will specify a specific Subnet and IP address range.  Here is what I’ve used for mine:

IP Range: 192.168.8.1 – 254 (where 192.168.8.1 is my domain controller IP)
Subnet Mask: 255.255.248.0
Gateway: 192.168.8.1 (DC/DNS server)
Primary DNS: 192.168.8.1 (DC/DNS server)

image Setting up Active Directory is a breeze if you do it the easy way.  Of course, I did it the easy way the last time.  (Note to self: when just learning, take the defaults).  Windows Server 2003 and 2008 have this concept of Roles.  A server can fill one or more roles which are the conglomeration of settings, services, etc to do something more abstract… like be a DC.  We are going to add the role Active Directory Domain Services.  

After the Add Role wizard does it’s thing, you actually “promote” the machine to a DC by running dcpromo.exe (Start, dcpromo, Enter).  This is where you make your selections, which in this case, I’ve chosen:

Create a new domain in a new forest
FQDN: vpc.com

You’ll want to let the machine also be a DNS server.  This is where I screwed up the first time.  Don’t get scared here, with our networking settings this domain we’re setting up won’t touch your corporate domain or anything crazy like that.

Let the Wizard do it’s thing and reboot when it is complete.

Your Active Directory Domain Controller is ready to roll.  Great job.

Adding Workstations is a matter of adding a Computer entry into the Active Directory Users and Computers console and then actually adding the computer to the domain.  You’ll find the AD Users and Computers MMC console in Administrative Tools.  Once you’ve added a computer entry, log into another VPC instance which has the same Network Adapter settings as above (different IP of course .2, .3, etc) and add the machine to the domain (vpc.com) in my case. 

imageHere’s a quick screen capture of my Network Adapter on the Workstation I added to the domain.

It’s great being able to demo Enterprise software this way or test things like integrated authentication for intranet applications.

Did you know? Screenshots of Virtual PC Instances

July 7th, 2008

If you are running a VPC instance and you’d like to take a screenshot of something on the VPC, did you know you can do that without any photo editing hassle?

Simply make sure you aren’t “in” the VPC (hit the right Alt key if you are).  Now click and drag a square around the portion of the VM you want to capture.  CTRL+C or Edit -> Copy will capture the section to the clipboard and you can paste it wherever. 

Nice touch.

Why WPF? This is why…

July 2nd, 2008

http://dnrtv.com/default.aspx?showID=115

Just awesome!  I didn’t see anything far fetched other than they must have a great designer on staff.  I wonder if the designer was doing the Blend work?

Visitor Pattern with Anonymous Methods

July 2nd, 2008

I don’t often have the need to implement the Visitor Pattern, but today I was that day.  I looked around really quick for an example of how to do this with Lambda Expressions and Anonymous Methods, which seemed like they were the way to go.  It may be that my search skills have deteriorated right along with my sense of style, but I didn’t find much.

I played around for a few minutes and here is what I came up with:

public abstract class CarBase
{
    public void Visit(Action<CarBase> action)
    {
        if (action != null)
            action(this);
    }
}

public class BigCar : CarBase
{
    public void RunOverLittleCar()
    {
        Console.WriteLine("Me smash little car!");
    }
}

public class LittleCar : CarBase
{
    public virtual void RunAwayFromBigCar()
    {
        Console.WriteLine("Go Faster!");
    }
}

public class EcoCar : LittleCar
{
    public override void RunAwayFromBigCar()
    {
        Console.WriteLine("Ouch.");
    }
}
class Program
{
    static void Main(string[] args)
    {
        IList<CarBase> cars = new List<CarBase>(new CarBase[] {
                                                                new BigCar(),
                                                                new LittleCar(),
                                                                new EcoCar()
                                                              });
        foreach (CarBase car in cars)
        {
            car.Visit(delegate(CarBase c)
            {
                if (c is BigCar)
                    ((BigCar)c).RunOverLittleCar();
                else if (c is LittleCar)
                    ((LittleCar)c).RunAwayFromBigCar();
                else if (c is EcoCar)
                    ((EcoCar)c).RunAwayFromBigCar();
            });
        }

        if (Debugger.IsAttached)
            Console.ReadLine();
    }
}

In many implementations of the visitor pattern there is an adapter or actual Visitor interface and implementation class which is passed into the Visit() method.  This is just smooth.

My visit method above is a little big to look good as a lambda expression, though maybe I just don’t have the eye for it. 

Virtual Property C# Code Snippet

July 2nd, 2008

For those of you who use NHibernate you may find this convenient, if you don’t already have your own.  Below is a C# code snippet for creating a public virtual property (code and file are both there).  Just put it in your <Visual Studio 2005/2008>\Code Snippets\Visual C#\My Code Snippets folder and you’re off and running.  No restart required.

File

Code

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>propv</Title>
            <Shortcut>propv</Shortcut>
            <Description>Code snippet for an automatically implemented virtual property</Description>
            <Author>Microsoft Corporation</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>Property type</ToolTip>
                    <Default>int</Default>
                </Literal>
                <Literal>
                    <ID>property</ID>
                    <ToolTip>Property name</ToolTip>
                    <Default>MyProperty</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[public virtual $type$ $property$ { get; set; }$end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>
 
 

Backup Your Site

July 1st, 2008

So last night I was restructuring my hosting infrastructure (read: moving folders around) and managed to delete the folder that hosts most of my sites.  I got that nasty sinking feeling in the pit of my stomach.  I was able to get things back up, but my hosting provider, which is normally pretty responsive and helpful, took FOREVER to respond to my restore request. 

Immediately after that I set up a scheduled job on my home machine to pull down a rar of the site each night.  It’s hard to get good help these days.

Jing

July 1st, 2008

http://jing.cromwellhaus.com/2008-07-01_1427.swf