November 11, 2008
@ 07:36 AM

Don't forget about Seattle Code Camp v4.0 this weekend in Redmond.  For all the details, go to the Seattle Code Camp website.  This is a free weekend of presentations on a wide variety of software development subjects.  This isn't a 'Microsoft' only event, check out the list of sessions if you don't believe me.

Two South Sound .NET User Group members will be presenting:

Chris Bilson is presenting 'Getting Git'

Git is a distributed version control system. It's a little different than other source control systems you may have used (Subversion, TFS, etc.), and a little more powerful too. In this session we'll talk a little bit about what the big deal is with distributed revision control systems, which ones exist, git, some tools related to git, web sites that work with git, and go through a typical git workflow.

Camey Combs is presenting "What's the Big EFing Deal? Even Newbies can do Entity Framework"

Have you done anything with Entity Framework yet? Have you heard of it? Curious about it? if you're new to EF and want to do some coding utilizing it, this is the session for you. Come and see what a newbie (you and your presenter) can do with EF after only a few short lessons. Bring your laptop loaded up and ready to go and follow along, building your own simple applications using EF.


 
Categories: Development | Events | Local

Please join us on Thursday, November 13th for a presentation on MVC by Chris Tavares.


Meeting Summary:
The ASP.NET Model-View-Controller (MVC) framework is a new web development framework that sits next to the existing ASP.NET WebForms framework. Rather than attempting to abstract away the Web, MVC embraces the web programming model. The result is a very different experience for writing web applications on the .NET platform. In this talk, we’ll look at what the MVC framework is, the basics of how to use it, why it exists, and how to decide whether to use it (or not).

Speaker Info:
Chris is a developer on the Microsoft patterns & practices team. He started his obsession with computers in third grade with an actual teletype taking to a mainframe. The job has gotten rather easier since. He’s worked in embedded systems, shrink wrap software, developer tools, consulting, and as a developer trainer before joining Microsoft. His current projects are as dev lead / architect for Microsoft’s Enterprise Library, and consulting software designer on the ASP.NET MVC framework.

Meeting Specifics:
November 13th, 7 - 9 PM
Olympia Center (222 Columbia NW)
All attendees are eligible for the prize drawings. Past prizes have included technical books, passes to Devscovery, copies of Visual Studio, Vista, Office 2007 and more.


Don't forget to let your friends and co-workers know about this meeting.  Feel free to forward this email and/or direct them to www.ssdotnet.org for more information.


 
Categories: Development | Events | Local

I have assembly A with class Z that inherits from class X in assembly B. Now in a completely different solution, I have assembly C, which uses class Z.

The compiler complains unless assembly C has a reference to both assembly A & B. Even though assembly C does not use class Z directly in anyway.

Is this expected?

It seems to me that if assembly B is missing at run time stuff blows up, but at compile time it shouldn't care.

What am I missing here?

My goal is that I can tell my clients to depend on class Z in assembly A, but I can completely reconfigure my assemblies on the other side and have no effect at all on the client when they upgrade.


 
Categories: Development

I have the following solution project structure:

  • Application.Core.Entities
  • Application.Xtend.CustomerName.Entities

In the Core project I have an entity Customer defiend. In the XTend project, I have an entity defined that subclasses Customer named xCustomer (for lack of a better name at this time...).

The idea here is that we have a Core domain model in our application. A customer can then create a new assembly that contains extensions to our core model. When the extension assembly is present a smart IRepository class will return a subclass of the core class instead.

I am attempting to map this relationship in NHibernate. Using Fluent NHibernate I was able to generate this mapping:

 

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   default-lazy="false"
                   assembly="NHibernate.Core.Entites"
                   namespace="NHibernate.Entites"
                   default-access="field.camelcase-underscore">
  <!-- Customer is located in assembly Application.Core.Entities -->
  <class name="Customer" table="Customers" 
        xmlns="urn:nhibernate-mapping-2.2">
    <id name="Id" column="Id" type="Int64">
      <generator class="native" />
    </id>
    <component name="Name" insert="true" update="true">
      <property name="LastName" column="LastName" length="255"
                type="String" not-null="true">
        <column name="LastName" />
      </property>
      <property name="FirstName" column="FirstName" length="255"
                type="String" not-null="true">
        <column name="FirstName" />
      </property>
    </component>
    <!-- xCustomer is located in assembly Application.XTend.CustomerName.Entities -->
    <joined-subclass name="xCustomer" table="xCustomer">
      <key column="CustomerId" />
      <property name="CustomerType" column="CustomerType"
                length="255" type="String" not-null="true">
        <column name="CustomerType" />
      </property>
    </joined-subclass>
  </class>
</hibernate-mapping>

But NHib throws the following error:

NHibernate.MappingException: persistent class Application.Entites.xCustomer, Application.Core.Entites not found ---> System.TypeLoadException: Could not load type 'Application.Entites.xCustomer' from assembly 'Application.Core.Entites, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'..

Which makes sense xCustomer is not defined in the Core library. I took my quandary to the NHibernate Users mailing list and StackOverflow. After some helpful suggestions and pointers, I discovered that the solution was so obvious that I am somewhat embarrassed that I couldn't see it.

The hibernate-mapping attributes assembly and namespace are convenient short cuts that allow you to not have to fully qualify your class names. This lets you have the nice mark up , but the name attribute of both class and joined-subclass elements can take a fully qualified assembly name as well.

So the above broken mapping file can be fixed like so:

 

<joined-subclass name="Application.XTend.CustomerName.Entities.xCustomer, 
                 Application.XTend.CustomerName.Entities, Version=1.0.0.0, 
                 Culture=neutral, PublicKeyToken=null" 
                 table="xCustomer">
  <key column="CustomerId" />
  <property name="CustomerType" column="CustomerType" length="255" 
            type="String" not-null="true">
    <column name="CustomerType" />
  </property>
</joined-subclass>

This works as I expected it to. So I then took a look at the Fluent-NHibernate source and created a patch complete with working unit tests to resolve the issue and submitted it to the project.

So at the end of the day, I learned something about NHibernate and the Fluent-NHibernate team got a patch to resolve and obscure bug.


 
Categories: Development | NHibernate

Yesterday, my team had a developer forum session to assist one our own get our latest release to build on our build server from a new branch. He had been working on it for a couple days and was getting nowhere. He would follow our documented process to create the new build and when he got to the end of it the build threw the following error:

The path C:\Build\ProductReleases\FullBuildv5.4.2x\Sources is already mapped to workspace BuildServer_23.

We used the Team Explorer IDE and attempted to identify this rogue workspace. Try as we might we couldn't locate it. We tried deleting all the source code on the file system. We tried nuking all the workspaces we could see through the IDE.

In the end we had seven developers in a room shouting out ideas to a frustrated developer sitting the keyboard. So we broke for lunch.

After lunch, I returned to my desk to troll the MSDN Team Foundation Server Developer Center. Using the tf workspaces command, you can get a list of all the workspaces you have created:

C:\>tf workspaces

Server: BuildServer
Workspace Owner          Computer Comment
--------- -------------- -------- --------
BOBBY     work\Bobby 	 BOBBY

But if you add the owner switch, you can get a list of all the workspaces on the server:

C:\>tf workspaces /owner:*

Server: BuildServer
Workspace      Owner      Computer  Comment
-----------    ---------- --------- -------------------------------
BuildServer    Shane      BuildServer
BuildServer    Craig      BuildServer
BuildServer    TFSSETUP   BuildServer
BuildServer    Keith      BuildServer
BuildServer_1  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_10 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_12 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_13 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_14 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_16 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_2  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_23 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_28 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_3  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_30 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_31 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_32 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_4  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_6  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_7  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_8  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_9  TFSSERVICE BuildServer  Workspace created by Team Build

From this output we can see that our build service user TFSSERVICE has a lot of workspaces defined. Considering we have 3 builds so far. Something is very wrong here.

Our original error message referenced a workspace named BuildServer_23 which does show up in our list. Using the tf workspace command, we can completely remove the workspace:

C:\>tf workspace /delete /server:BuildServer BuildServer_23;TFSSERVICE
A deleted workspace cannot be recovered.
Workspace 'BuildServer_23;TFSSERVICE' on server 'BuildServer' has 0 pending change(s).
Are you sure you want to delete the workspace? (Yes/No) Y

Our build now runs as expected. It's now time to verify what all those other workspaces are and remove them if they are not needed.

Hope this helps someone out there if you are desparately googling for away around this error.


 
Categories: Development | Tools

The application I am currently working on has a hand rolled implementation of Ajax that is somewhat awkward to work with. At the end of our last sprint, I was tasked with spiking what it would take to migrate to the .NET Ajax 1.0 extensions while everyone else was working on release week tasks.

It took a couple days to figure out all the installs, web.config modifications, component vendor compatibility and other various things. But in the end, I had a simple page with two sample Ajaxified controls that worked.

I then turned to the task of unraveling the way the current implementation was wired up and modifying a single page to use the Ajax framework instead. A few minor safe refactorings and quirks later, I had a semi-functional reference implementation with one giant problem.

The page contained a series of drop down lists that filter each other as you make selections. On initial page load, I could select an item any drop down and it would appropriately modify the others. The second selection always returned the following error:

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned was: 404

Reguardless of what list I selected from first, the second request would fail. My IIS logs revealed that my request was being sent to server, but for whatever reason the URL changed.

2008-10-17 14:52:14 W3SVC1 127.0.0.1 POST /Aware/Xtend/mParticipant/NewPlannedService.aspx  80 - 127.0.0.1 200 0 0

2008-10-17 14:52:20 W3SVC1 127.0.0.1 POST /Aware/mParticipant/NewPlannedService.aspx  80 - 127.0.0.1 404 0 0

Using Fiddler, I was able to see that a value for formAction was being sent back to the client that was invalid. You can also see that the second request is going to a non-existent page:

FiddlerOutPut

I was able to resolve the issue by explicitly setting the value of my forms action back to the correct path at the end of my call back method like so:

this.Form1.Action = Request.Url.PathAndQuery

But this seemed like a hack in the worst way and smelled somewhat like moldy cheese to me. And I still didn't understand what was causing the issue.

The application makes extensive use of Server.Transfer as a "performance enhancement". I noticed that the form I was working with was one of these cases where Page1.aspx transfers execution to my Ajaxified page.

I decided to try to isolate the behavior and reproduce it in a simple example project.

I fired up Visual Studio and created a new Ajax website. I added two pages; Default.aspx and AjaxPage.aspx. I implemented a simple ajax call back on my ajax page and the default page transfer execution in its Page_Load method.

To my surprise, it worked with no problems. I didn't see the nasty error at all. I verified with Fiddler. I was stumped.

I started thinking about the behavior in my application. The only difference I could think of was that the page that was being transferred to was in a different subdirectory than the original page. So I created a folder in my test project and moved AjaxPage.aspx into it. And this time I got the error. I confirmed with Fiddler that my "Folder" sub directory was being dropped off the second request and that it was missing from the response from the first request.

My smelly cheese hack worked as well for my test project. But I didn't want to solve this issue with a server side hack. So I created the following client side Javascript to hook into the client ajax framework and solve it there in a single place:

var orginalFormAction = null;

//capture the current form action value
function BeginRequestHandler() {
  orginalFormAction = theForm.action;
}

//set the form action value back to the
//correct value
function EndRequestHandler() {
  theForm.action = orginalFormAction;
  theForm._initialAction = orginalFormAction;
}

function RegisterRequestHandlers() {

  if (typeof (Sys) != "undefined") {
  
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
    Sys.Application.notifyScriptLoaded();
    
  }
}

//register request handlers after the application 
//has successfully loaded.
Sys.Application.add_load(RegisterRequestHandlers);

I can then add the script to any ajax page, by adding the following code to my Page_Load event handler:

protected void Page_Load(object sender, EventArgs e)
    {
      PageScriptManager.Scripts.Add(
        new ScriptReference("~/Script/Ajax.Server.Transfer.Fixer.js")
        );
    }

Problem solved and I didn't have to rewrite the entire application to get rid of Server.Transfer calls. On to other things.

Fiddler Tip: To get Fiddler to capture traffic when you are debugging on local host, after you hit F5 to begin degugging change the address so that localhost has a "." after it. For instance, you start debugging and the you have the following URL in the Address bar: http://localhost:49573/Default.aspx Change it to http://localhost.:49573/Default.aspx hit enter and Fidder will start picking up your traffic.


 
Categories: Development | Tools

The code base I am currently working with has a collection class that inherits from ArrayList. The purpose of this class is to offer a unique list of objects and to provide case insensitive comparisons when adding a unique item to the collection. The collection does not need to be unique, but we a way to add unique things to the list is required.

My task the last week was to become familiar with the code base and identify possible refactorings. Using NDepend, I was able to determine that this class is typically used with strings. One possible refactoring I suggested was to replace this custom class with List<string>(). An out of sprint hit squad was formed to tackle doing just that. We came in on Saturday morning bright and early and got started.

Doing a global search and replace to change this custom ArrayList class with List<string> turned up thousands of compiler warnings where the method AddUnique() was called.

Our first stab at tackling this problem was to create a helper method that added an item to a given list only if that list did not already contain the item. We wrote a macro to quickly turn the old references into the new helper references. The code looked something like this:

tableList.AddUnique("item_table")

ListHelper.AddUnique(tableList, "item_table")

This seemed to get us around the uniqueness hurdle. It was a bit verbose, but it got the job done and would eventually allow us to get rid of the custom collection class altogether. We started hacking away, taking turns at the keyboard with three sets of eyes making sure we were hitting the right items and evaluating between List<string> and ArrayList where appropriate.

After a few hours of locating problem areas and fixing them with a handy macro we created out of sheer boredom, the hit squad decided this was not working. I mentioned that if we were using Visual Studio 2008, we could write an extension method that would simply attach an AddUnique() method to the List<string> class. We knew that Visual Studio 2008 allowed you to target the 2.0 framework. So we could upgrade the solution to VS2k8, leave all our projects targeting 2.0 and be able to use extension methods.

I left the 8 hour marathon triple-programming session with the goal of playing around with implementing extension methods in Visual Studio 2008. Since I was not familiar with actually writing them, I fired up my IDE and wrote a couple tests for what I wanted to happen.

        [Test]
        public void Can_Add_Unique_String_To_List_Of_String()
        {
            var list = new List<String>();

            list.AddUnique("one");
            list.AddUnique("one");

            Assert.AreEqual(1, list.Count);
        }

        [Test]
        public void Can_Add_Case_Insensitive_Unique_String_To_List_Of_String()
        {
            var list = new List<string>();

            list.AddUnique("one");
            list.AddUnique("ONE");

            Assert.AreEqual(1, list.Count);
        }

I flipped over to my Extensions library and added a ListOfStringExtensions class. To get the code to compile I quickly stubbed out the method like this:

public static void AddUnique(this List<String> list, string item)  {   }

Using the ReSharper unit test runner, I verified that my test indeed fail. The moved on to implementing the method logic. My first attempt at implementing the method looked something like this:

public static void AddUnique(this List<string> list, string item)
        {
            foreach(var s in list)
            {
                if(s == item)
                    return;
            }

            list.Add(item);
        }

This allowed my first test to pass, but not the second. So I modified the implementation like so:

public static void AddUnique(this List<string> list, string item)
        {
            foreach(var s in list)
            {
                if(String.Compare(s,item,true) > 0)
                    return;
            }

            list.Add(item);
        }

Now both tests pass. I continued down this TDD path until I had a nice set of extension methods and unit tests that satisfied all the requirements to get rid of our custom collection class. In the end I created AddUnique, AddUniqueRange, CaseInsensitiveContains, IsUnique and ToUniqueList extension methods which all work nicely together with a full suit of unit tests.

The next task at hand was to get the extension methods working in projects that were targeting the 2.0 framework. I set my unit test class to target 2.0 and verified that they still worked. I got an warning as soon as I set the framework target that I had references to projects targeting a different framework. The tests ran fine.

I then changed the target of my extension library to 2.0 and got this nasty error at compile time:

Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll?

Hrm.. ExtensionAttribute seems to be a 3.x feature. But I had started out this adventure reading ScottGu's blog where he says that extension methods are language syntactical sugar and should work fine with the 2.0 framework. So I fired up Chrome and hit google.

The first result for my query happened to be my good friend Nate Kohari's blog. Nate is the creator of Ninject the amazing Dependency Injection framework. He also recently release his new web site IdeaVine. He is an awesome guy  and as usual he already blazed the path I was walking down.

According to Nate, all I needed to do was add an attribute class in a specific namespace to get around the compiler issue.

 
//override the .net 3.5 compiler services for .net 2.0 compatibility
//see: http://kohari.org/2008/04/04/extension-methods-in-net-20/
namespace System.Runtime.CompilerServices  
 {  
   [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]  
   public class ExtensionAttribute : Attribute  
   {  
   }  
 } 

Everything compiles and test run fine targeting the 2.0 framework. In morning I plan to verify this by running sample code on a fresh box with only the 2.0 framework installed. As always you can get my full source code here.


 
Categories: Development | Unit Testing

I will be attending the Wintellect Devscovery conference this week, August 19th - 21st, on the Microsoft campus in Redmond. If any ALT.NET people want to get together for lunch or dinner while I am there feel free to contact me via the plethora of options to the right. I will be in full on geek out mode and happy to talk with you.

Here is my schedule while I am there:

 

Tuesday  
9:00 AM Keynote - I am ASP.NET 3.5 Extensions and So Can You! - Hanselman
10:45 AM Translating Architecture to Technologies - Dahlman
12:15 PM Lunch
1:30 PM An Overview of ASP.NET MVC - Haack
3:15 PM An Introduction to TDD - Haack
Wednesday  
9:00 AM Windows Communication Foundation: Rest with WCF - Mehner
10:45 AM Windows Communication Foundation: Debugging & Error Handling - Mehner
12:15 PM Lunch
1:30 PM Practical Workflow Foundation, Part 1 - Mehner
3:15 PM Practical Workflow Foundation, Part 2 - Mehner
Thursday  
9:00 AM An Introduction to LINQ to SQL - Demsak
10:45 AM An Introduction to LINQ to Entities - Demsak
12:15 PM Lunch
1:30 PM Unit Testing & Code Coverage Best Practices - Robbins
3:15 PM .NET Performance Tips & Tricks - Robbins

 
Categories: Development | Events | Local

 Taken in Blijdorp Michael Feathers, the amazing author of Working Effectively with Legacy Code, posted recently about technical debt.

What happens to code when you don’t refactor?  Anyone with any experience knows the answer.  It gets messy.  It becomes hard to change and the rate at which you can add features slows to a crawl.

I was on a project that inherited a tremendous amount of technical debt. The motivating force for the original team was meeting a hard deadline. As the deadline approached development process crumbled. Hero developers shot from the hip. Corners were cut. Non-critical bugs piled up. Quality was sacrificed to meet the deadline.

The technical debt was put on the American Express.

At the end of the project, the resulting application had a week long eventful launch full of rapid critical bug fix releases. The application was eventually brought up to an acceptable level of performance through Herculean effort of very skilled and talented people.

The technical debt bill was left ignored.

The following project cycle a new team was introduced to the application. A feature set to be added was defined. A deadline was set. A new requirement was added. All new features would have a emphasis on quality. No defects would be added to the already limping system.

The technical debt went into Universal Default and the APR was bumped up to 29%.

The team began moving forward except this time the business actively using the system kept running into critical issues that the team had to quickly deal with. The short cuts taken by the previous team became direct roadblocks to the new features slowing the implementation down. Each new line of code had to make sacrifices to work around quirks in the code base.

The 800 pound technical debt collection gorilla started calling demanding payment.

After a year of use the sheer size of the technical debt in the database caused leaks to spring which cascaded outward through out the application. New releases were viewed with dread by the entire organization. The DBA's were not happy. The help desk was not happy. The users were not happy. Morale on the project was through the floor.

The 800 pound technical debt collection gorilla had frozen all assets and put a lean on the house.

You can put that debt on the card. You can ignore it and buy some time. But eventually that gorilla is going to find you, climb on your back and beat you down.

Photo Credit:  Ruben Bos


 
Categories: Commentary | Development | Random

Introduction

As you may have noticed, I have become interested in the concept of Object Relational Mapping and the NHibernate framework. One of the more painful/tedious aspects of using NHibernate is hand writing the xml mapping files. That is why I got excited when I heard that Jeremy Miller was open sourcing his mapping generation libraries.

FHLogo The Fluent NHibernate project is an effort to create a set of APIs that generate NHibernate mapping files using a fluent interface. I downloaded the source code from the Google Code Repository and quickly found myself adding fluent methods. I submitted my changes to the project and was accepted as a contributor.

One of the tasks identified by the project owner, James Gregory, was to create a quick start guide that easily fit into the NHibernate Quick Start section 1.3 Mapping the cat. I assigned the task to myself and start hacking some code.

Creating the Mapping Class

First, create a new class project QuickStart.Domain to hold  domain model objects that need to be mapped. To this assembly,  add the Cat class from the NHibernate quick start.

namespace QuickStart.Domain
{
    public class Cat
    {
        public virtual string Id { get; set; }

        public virtual string Name { get; set; }

        public virtual char Sex { get; set; }

        public virtual float Weight { get; set; }
    }
}

This is what the class looks like after a little ReSharper Code Clean Up loving.

Then add a second class project QuickStart.Domain.Mapping to hold  domain model mapping classes using the Fluent NHibernate library. Add references to both the FluentNHibernate.dll and the domain model library.

Create a new class in the mapping library called CatMap. This class will inherit from ClassMap<T> where T is the type you are creating the map for, in this case Cat. Create a constructor for the CatMap class. The constructor is where the mappings will be defined.

Because CatMap is an instance of ClassMap, you can begin using the fluent interface in the constructor right away.

public CatMap()
        {
            this.TableName = "Cat";
        }

The TableName property of the ClassMap object specifies the name of the table in the data store that stores the Cat class. This explicit setting of the table name is unnecessary. If one is not provided the API will assume the table has the same name as the class being mapped. So, for the rest of this example, it will be dropped.

The API offers several fluent methods for defining an identifier though the Id method of ClassMap. The Cat example uses the UUID generator which looks like this:

 

public CatMap()
        {           
            this.Id(x => x.Id)
                .GeneratedBy
                .UuidHex("B");
        }
 

An identity column in SQL server would be mapped like this:

public CatMap()
        {
            Id(x => x.Id);
        }

These two examples take advantage of the new C# 3.0 syntax sugar lambda expressions. An explanation of lambda expressions is outside the scope of this article, but  tons of information is available on the topic on the web.

The remainder of the CatMap constructor uses the Map method of ClassMap to define the remaining properties of the class.

public CatMap()
        {
            this.TableName = "Cat";
           
            this.Id(x => x.Id)
                .GeneratedBy
                .UuidHex("B");

            //non-nullable string with a length of 16
           this.Map(x => x.Name)
                .WithLengthOf(16)
                .CanNotBeNull();

            //simple properties
            this.Map(x => x.Sex);
            this.Map(x => x.Weight);
        }

Both the Sex and Weight properties of the Cat class are mapped quickly with a single call to them Map method. You do not need to explicitly specify the type of your properties, Fluent NHibernate will infer it based on the type being mapped. The Name property has an additional two fluent calls to limit the length of the property to sixteen characters and to disallow null values.

Usage of this mapping generates the following XML document:

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
  default-lazy="false" 
  assembly="QuickStart.Domain" namespace="QuickStart.Domain">
  <class name="Cat" table="Cat" xmlns="urn:nhibernate-mapping-2.2">
    <id name="Id" column="Id" type="String" unsaved-value="0">
      <generator class="uuid.hex">
        <param name="format">B</param>
      </generator>
    </id>
    <property name="Weight" column="Weight" type="Single">
      <column name="Weight" />
    </property>
    <property name="Sex" column="Sex" type="Char">
      <column name="Sex" />
    </property>
    <property name="Name" column="Name" length="16" type="String" not-null="true">
      <column name="Name" />
    </property>
  </class>
</hibernate-mapping>

This mapping xml is a bit more verbose than the original example from the NHibernate quick start, but this post is being written using an alpha version of the Fluent NHibernate library. There is a lot of clean up and work left to be done.

Hooking It All Up

So, how exactly did I go from CatMap to generated XML document? There is currently no recommended methodology that I am aware of, but I am happy to share how I accomplished it.

I started by adding an interface to the Mapping library called IMapGenerator that looks like this:

namespace QuickStart.Domain.Mapping
{
    public interface IMapGenerator
    {
        string FileName { get; }
        XmlDocument Generate();
    }
}

 

FileName is defined in the fluent interface on the ClassMap class, I know I added it while writing this code ;). It represents the conventional name for the NHibernate mapping files. For example, We are mapping the class Cat so FirstName would contain the string "Cat.hbm.xml". Generate on the other hand, will be a wrapper around the ClassMap's CreateMapping method.

I then added the interface to the CatMap class. The final CatMap looks like this:

namespace QuickStart.Domain.Mapping
{
    public class CatMap : ClassMap<Cat>, IMapGenerator
    {
        public CatMap()
        {
             Id(x => x.Id)
                .GeneratedBy
                .UuidHex("B");

            Id(x => x.Id);

            //non-nullable string with a length of 16
            Map(x => x.Name)
                .WithLengthOf(16)
                .CanNotBeNull();

            //simple properties
            Map(x => x.Sex);
            Map(x => x.Weight);
        }
        
        public XmlDocument Generate()
        {
            return CreateMapping(new MappingVisitor());
        }
    }
}

 

I now have a way to identify all my mapping classes using the interface. I wanted to be able to automatically get a list of all the classes that implement the IMapGenerator interface, so  created a helper class GeneratorHelper with a single static method GetMapGenerators. The class lives in the Mapping library and looks like this:

namespace QuickStart.Domain.Mapping
{
    public class GeneratorHelper
    {
        private const string GENERATOR_INTERFACE = "IMapGenerator";

        public static IList<IMapGenerator> GetMapGenerators()
        {
            IList<IMapGenerator> generators = new List<IMapGenerator>();
            Assembly assembly = Assembly.GetAssembly(typeof(IMapGenerator));
            foreach (Type type in assembly.GetTypes())
            {
                if (null == type.GetInterface(GENERATOR_INTERFACE)) continue;
                var instance = Activator.CreateInstance(type) as IMapGenerator;
                if (instance != null)
                    generators.Add(instance);
            }
            return generators;
        }
    }
}

This method uses reflection to locate and load the assembly that contains the IMapGenerator interface. It then iterates over the types in the loaded assembly and checks to see if the type implements the IMapGenerator interface. If a match is found, an instance of that class is created and added to the generators list.

Finally, I created a console application, QuickStart.Domain.Mapping.Mapper, and added a reference to my Mapping library. The implementation of my console app is fairly straight forward.

 

namespace QuickStart.Domain.Mapping.Mapper
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            IList<IMapGenerator> generators =
                GeneratorHelper.GetMapGenerators();
            
            foreach (IMapGenerator generator in generators)
            {
                XmlDocument classMapXML = generator.Generate();
                classMapXML.Save(generator.FileName);
            }
        }
    }
}

 

The app calls the generator helper class to get a list of IMapGenerator objects which it then iterates over calling each objects Generate method and saves the result using the conventional name for mapping files. It works fairly well and I can add as many mapping classes as I need to the Mapping library and spin out xml any time I need.

Now where Fluent NHibernate becomes really interesting is when you decide to do away with xml mapping files all together. For a great example of this check out Zachariah Young's post, "Does the Fluent NHibernate create static XML mapping files?".


 
Categories: Development | Fluent Interface | NHibernate | Tools

In a recent post, I discovered a flaw in my world domination plot. I had written a Unit Test to test my expectation that the method GetByID() of the class UserRepository returned the expected User. When UserRepository.GetById() is called, it calls IDataProvider.GetById(), which returns an instance User to the UserRepository which in turn returns it to the caller.

My UserRepository class delegates database access to the interface IDataProvider. This allows me to substitute any implementation of IDataProvider to satisfy this responsibility. In non testing code I use Dependancy Injection to map UserDataProvier to IDataProvider. But in testing code I do not really want to hit a database as it slows the testing process down. So I use Rhino.Mocks instead.

Rhino.Mocks is a framework for creating mock objects for use in Unit Testing. Provide Rhino.Mocks with an Interface and it will give you back an object that implements that interface. You can also tell it to expect certain calls against the interface and how it should respond.

My Unit Test looked something like this:

      [Test]
        public void GetByIdTest()
        {
            MockRepository mock = new MockRepository();

            IDataProvider dataProvider = (IDataProvider)mock.CreateMock<IDataProvider>();
            UserRepository target = new UserRepository(dataProvider);

            Expect.Call(dataProvider.GetById(1)).Return(new User() { Id = 1 });

            mock.ReplayAll();
            User u = target.GetById(1);
            mock.VerifyAll();

            Assert.AreEqual(1, u.Id);
        }

As you can see this test, creates a MockRepository that is provided by the Rhino.Mocks framework. It then declares an instance of IDataProvider but delegates the creation of that instance to the MockRepository's CreateMock method. This tells Rhino.Mocks to create a dummy instance of the IDataProvider interface. Next we new up a UserRepository (the actual target of the unit test) and provide our mocked IDataProvider to it's constructor. Then we tell Rhino.Mocks to expect a call to our mock IDataProvider's GetById method and to return a new instance of User with it's Id property set to 1. Finally, we do our testing and validation.

This test fails to compile. The entity class User has read only properties. Id happens to be one of them. In the domain model for this particular application Id is a unique identifier and once a User instance is returned from the data access layer, it should never be modified.

So this presents a unique challenge, how do I test that UserRepository.GetById(1) returns an instance of User with an Id of 1?

I went down the path of trying to use Ninject (an Inversion of Control container), to inject the value in a newed up instance. But this had code smell for me. Why am I creating a dependency on Ninject to get my Unit Tests to work. That just seemed wrong to me. So I began digging in the Rhino.Mocks documentation wiki to see if it had a method for resolving this.

That was when Aiden Montgomery in the #ALT.NET IRC channel suggested that I use Reflection. He even went so far as to download my source from CodePlex and demonstrate what he was suggesting in my application.

The final test ended up looking something like this:

[Test]
        public void GetByIdTest()
        {
            MockRepository mock = new MockRepository();
            
            Type userType = typeof(User);
            PropertyInfo pi = userType.GetProperty("Id");
            User user = new User();
            pi.SetValue(user, 1, null);

            IDataProvider dataProvider = 
                (IDataProvider) mock.CreateMock<IDataProvider>();
            UserRepository target = new UserRepository(dataProvider);

            Expect.Call(dataProvider.GetById(1)).Return(user);

            mock.ReplayAll();
            User u = target.GetById(1);
            mock.VerifyAll();

            Assert.AreEqual(1, u.Id);
        }

 

This of course passed, didn't add a non-BCL dependency and maintained the original intent of the test and the domain model. With all the shiny new toys, I was forgetting to see the forest through the trees and return to the simplest solution. Thanks to Aiden for bringing me back down from the clouds.


 
Categories: Development | Tools | Unit Testing

Karl Seguin of CodeBetter.com released a 79 page ebook called Foundations of Programming yesterday. Browsing the table of contents, I found a ton of good information is covered here. Some highlights include: YAGNI & DRY principals, Explicitness, Cohesion & Coupling, Domain Driven Design... The list just goes on and on and on.

If you want to read about the stuff that a giant Wrox tomb will never mention, grab this ebook as a great launching point.


 
Categories: Development | Events | Fundamentals

Stephen Bohlen of Microdesk recently posted to the ALT.NET mailing list that he plans to release his internal training material on NHibernate to the world at large. The first two, of a planned  5, are online and ready for consumption.


I have been doing some noodling with NHibernate recently, so I downloaded the screen casts and watched them this morning. The quality is excellent, the material is comprehensive and Stephen's teaching style is top notch.

If you are interested in learning what NHibernate is all about and what you can do with it, I cannot recommend these enough. Grab them here:


 
Categories: Development | Fundamentals | Tools

I have been reading a ton of the ALT.NET bloggers and mailing list lately. They are constantly talking about the methodology of software development and the tools they use. On the concept front Domain Driven Design, Inversion of Control, Separation of Concerns and Test Driven Development are all popular topics that have been stewing in my mind. I also wanted to give some of the tools like Nhibernate, Rhino.Mocks and Ninject a try. I was also itching to get into the new Microsoft ASP.NET MVC code.

For the last couple months, I have been festering in the swamp of legacy VB.NET spaghetti code and haven't had the time or motivation to write something fresh just for the sheer joy of creation. Friday, I kind of snapped, fired up Visual Studio 2008, downloaded the tool stack and started hacking away.

Things seemed to just click on all of the topics I had been reading about. I started out with NHibernate and getting a simple User entity to persist to a SQL Sever 2005 database. I then moved on to implementing the Repository Pattern for my User entity abstracting away the actual persistence to a DataProvider class wrapping NHibernate. By this time I had Factory Patterns all over the place, so I added a reference to Ninject.Core and got rid of those too. I then whipped out a MVC site to consume my new repository.

After an evening of furious experimentation, I had a complete database to web page end to end implementation of my User entity. I was stoked, still am. I am currently working on getting unit tests in place using Rhino.Mocks, integration tests on my data access layer and fully implementing CRUD in the MVC site. It is a hell of a lot of fun.

If anyone is interested in seeing what I am working on or want a simple example of using all these things together in an easily understandable way, I posted my work to CodePlex. If you are new to this stuff like I am, download it and check it out. If you are an old hat and want to give me some pointers or tips, please download it and fill me in.

If you work with me and happen to read my blog and are interested, I would love to talk to you about the project and what I learned and discovered. Hit me up.


 
Categories: Development | Fundamentals | Tools | Unit Testing

I came across an interesting issue tonight exploring the use of Rhino.Mocks in unit tests. I have a class UserRepository that implements my current understanding of the Repository Pattern. My repository uses the interface IDataProvider to persist my User entity. The concrete class UserDataProvider wraps NHibernate.

My goal was to write unit tests that cover the methods of UserRepository. I used Rhino.Mocks to mock away UserDataProvider to prevent actually needing a database.

Things were going fine:

public void SaveTest(){
            MockRepository mock = new MockRepository();

            IDataProvider dataProvider = 
                  (IDataProvider) mock.CreateMock<IDataProvider>();
            UserRepository target = new UserRepository(dataProvider);
            User u = new User();
            
            Expect.Call(dataProvider.Save(u)).Return(1);
            Expect.Call(dataProvider.GetById(1)).Return(u);
            
            mock.ReplayAll();
            User x = target.Save(u);
            mock.VerifyAll();

            Assert.AreEqual(x, u);
        }
 
public void GetListTest(){
            MockRepository mock = new MockRepository();
            IDataProvider dataProvider = 
                 (IDataProvider)mock.CreateMock<IDataProvider>();
            UserRepository target = new UserRepository(dataProvider);

            Expect.Call(dataProvider.GetList()).Return(
                new List<object> { new User(), new User()});

            mock.ReplayAll();
            IList<User> users = target.GetList();
            mock.VerifyAll();
            Assert.AreEqual(2, users.Count);  
        }

Then I hit a snag. My User entity has a property Id that is read only. The users Id comes form the database and should not be able to be modified. So my next test has a bit of a problem and fails to compile.

public void GetByIdTest() {
            MockRepository mock = new MockRepository();

            IDataProvider dataProvider = (IDataProvider)mock.CreateMock<IDataProvider>();
            UserRepository target = new UserRepository(dataProvider);

            //TODO: Interesting Problem here. My actual dataProvider uses NHib
            //and would be able to meet this expectation. But my mock
            //cannot set the read only id property so this test will not
            //even compile.
            Expect.Call(dataProvider.GetById(1)).Return(new User() { Id = 1 });

            mock.ReplayAll();
            User u = target.GetById(1);
            mock.VerifyAll();

            Assert.AreEqual(1, u.Id);
        }

 

NHibernate has no problem injecting the value when I fetch the object from it, but my simple little expectation above chokes on it. I am not sure how to get around this one with out violating the intent of the test. I'll have to dig into the Rhino.Mocks documentation and see what tools it offers to get around this situation.

So far Rhino.Mocks is a great time saver. If I actually had to generate a fake for IDataProvider it would take quite a bit of time. I'll have to work it into my regular work life and see how it fairs there.

I'll update this post when I find a resolution to the issue at hand.


 
Categories: Development | Tools | Unit Testing

Over the course of the last couple months I have been working diligently to migrate the application I inherited from the wild wild west of unmanaged corner cutting contractor land to the happy kingdom of semi-intelligent source control.

I have successfully migrated what we have come to know as "what we think production is built with" source in to Team Foundation Server source control, cleaning up along the way. Why exactly this particular batch of contractors felt it was necessary to include references to both the 2.0 and 3.0 Enterprise Application Blocks, I may never know. I suspect they felt it was 2x more "Enterprise-y".

Next up on my path to Agile Nirvana, I whipped up a set of build scripts that produce a consistent build every time. Imagine that! My server support people are so happy with me.

The system I am working on is somewhat interesting. The application went live last summer and was officially handed over to a group of maintenance developers. A new project was immediately started to add new functionality while the maintenance guys fixed up bugs. I currently work with the New Development group.

The maintenance guys decided they wanted in on all this awesome TFS goodness. So I spun them off a branch and let them go on their merry way. That was until they decided they were ready to start rolling forward into production.

That is when I realized that all of my build scripts no longer worked. I would fire up a build using Team Builds in Team Explorer, it would do it's thing pulling down source code and firing off MSBuild to compile and then throw errors.

I checked on the build server in the location where source is downloaded and Team Build was no longer pulling down the source for my Main branch. The only thing be retrieved from Source Control was my Branches directory. Obviously the dirty maintenance branch hosed by lovely build process.

I checked my build definitions and mapping files. My source tree looks something like this:

$/PROJECT
..Branches
    ..2.0.1.0-APPLICATION-branch
..Main
   ..Framework
   ..APPLICATION
   ..Samples
   ..Utilites
..TeamBuildTypes
The 2.0.1.0 node is a branch of $/PROJECT/Main/APPLICATION. My workspace mapping pretty much looks like so:

<InternalMapping ServerItem="$/APPLICATION" LocalItem="flibbityjibits" Type="Map" />

I have a few cloaked paths as well all related to $/PROJECT/Main/Something. When I execute my Team Builds Branches and TeamBuildTypes are retrieved from source control and Main is ignored.

My buildlog shows that CoreGet is retrieving the latest:

Get Version="T" Recursive=True Force=True Workspace="NinjaWarrior"

There was something I was missing here. I shot off an email to the Seattle ALT.NET mailing list, more in a effort to articulate the issue well than expecting them to solve my issues or anything. Kinda just getting it all out as I understand the issue for the eventual call to tech support.

I went home that night utterly devastated that my painstakingly lovingly crafted system had failed so spectacularly.

At home I was playing some Lego Indy with the wife on the Xbox and letting the subconscious work on it. And finally the light bulb went off.

I have other branches in the Branches folder that caused no problem when they were created. I thought to myself, "Self, it's not the branch that did it.. It must be something that you did at the same time you created the branch."

My assumption about the branch breaking my build came directly from my Jump To Conclusions Mat.
I created this branch for an external group who is adding functionality. In an effort to keep my main pristine, I locked it down so that only members of the group "Tech Leads" could check in to Main.

This had to be the cause.. when I realized it last night I almost went back in to work... but come on its Lego Indy!

So I get to work this morning and checked the membership of "Tech Members" and surprise, surprise... TFSService is a member... The build service uses this account to access TFS...

So I quickly added it to the leads group and verified that my builds worked again and went to repair the dent I put in the wall from beating my head against it.

So Lessons Learned here:
1. Respect the build user, he can make you a very sad panda.
2. I've automated the build, its time to get a nightly build going so these changes are fresh in my mind when stuff breaks.
3. While I am at it might as well look into setting up CI to the Dev environment with the nightly.
4. Indy really can accomplish anything.

So in the end, I created my own problem. Thanks to all the ALT.NET mailing list readers for silently laughing at me while I verbalized (textualized?) the issue on the mailing list and worked through it.

I'll be here all week.


 
Categories: Development | MSBuild | Random

Please join us on Thursday, June 12th for a presentation on Silverlight 2.0 by Erik Mork.

Meeting Specifics:

Erik Mork will be returning to Olympia in June to present Silverlight 2.0 to the South Sound .NET User Group. Our last visit from Erik was in July 2007, when he told us about Silverlight 1.0 and looked forward to what might be in version 2.0. Now, with Silverlight 2.0 released in Beta, he can come back and give us the next chapter in this ongoing story.

Erik was with Tranxition last year and looking toward self-employment. He's made that leap now, founding Silver Bay Labs. In addition, he and with his wife is producing a Silverlight podcast called Sparkling Client. Recent shows featured interviews with Adam Kinney aka The Silverlight Surfer and Jesse Liberty aka Captain Silverlight.

If you're into Silverlight, definitely check out what the Morks are up to and plan to attend the South Sound .NET meeting on June 12th with Erik and Silverlight 2.0.

 

Meeting Specifics:
June 12th, 7 - 9 pm
Olympia Center (222 Columbia NW)
All attendees are eligible for the prize drawings. Past prizes have included t-shirts, technical books, passes to Devscovery, copies of Visual Studio, Vista, Office 2007 and more.

Don't forget to let your friends and co-workers know about this meeting.  Feel free to forward this email and/or direct them to www.ssdotnet.org for more information.


 
Categories: Development | Events | Local

April 25, 2008
@ 12:35 PM

Based on my