# Saturday, October 21, 2006
Since I took the day off to prepare for our family cruise to Mexico tomorrow, I ran into an extra hour today to do with as I please.  Having wanted to play around with Atlas (now ASP.NET AJAX) and Castle ActiveRecord for a while, why not cram them both into my free hour today.  So I did exactly that, and I still have 10 minutes to spare to write this blog entry - and that includes the downloading of the software, installation, and reading some of the docs.  Although it has become painfully obvious to me that I need a new PC as I think I wasted a good 5 to 10 minutes waiting for my PC to do "stuff."

I was amazed at how dumb foundingly easy both these technologies make it to throw together a featureful web app.  First I created a database table:

CREATE TABLE GalleryUser (
    GalleryUserId            int IDENTITY(1, 1) PRIMARY KEY,
    FullName                varchar(50) NOT NULL,
    Login                    varchar(16) NOT NULL,
    CreatedDate                smalldatetime NOT NULL DEFAULT GETDATE()
)

then I went about creating a GalleryUser class marked up with ActiveRecord attributes.  The attributes mapped my class properties to the table I just created above.

using System;
using Castle.ActiveRecord;

namespace Sneal.Gallery.Core
{
    [ActiveRecord("GalleryUser")]
    public class GalleryUser : ActiveRecordBase
    {
        private int id;
        private string fullName;
        private string login;
        private DateTime createdDate;

        public GalleryUser() { }

        [PrimaryKey(PrimaryKeyType.Native, "GalleryUserId")]
        public int Id
        {
            get { return id; }
            set { id = value; }
        }

        [Property("FullName")]
        public string FullName
        {
            get { return fullName; }
            set { fullName = value; }
        }

        [Property("Login")]
        public string Login
        {
            get { return login; }
            set { login = value; }
        }

        [Property("CreatedDate")]
        public DateTime CreatedDate
        {
            get { return createdDate; }
            set { createdDate = value; }
        }

        public static GalleryUser[] FindAll()
        {
            return (GalleryUser[])FindAll(typeof(GalleryUser));
        }

        public static GalleryUser Find(int id)
        {
            return (GalleryUser)FindByPrimaryKey(typeof(GalleryUser), id);
        }
    }
}

Next I created a Global.asax to handle my ActiveRecord initialization and NHibernate session per request schtuff.  This particular part (including my web.config mods) is where I spent the bulk of my time with ActiveRecord.

using System;
using System.Web;
using System.Web.Security;
using System.Configuration;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework;
using Sneal.Gallery.Core;

namespace Sneal.Gallery.WebUI
{
    public class Global : System.Web.HttpApplication
    {
        public Global()
        {
            this.BeginRequest += new EventHandler(Global_BeginRequest);
            this.EndRequest += new EventHandler(Global_EndRequest);
        }

        protected void Application_Start(Object sender, EventArgs e)
        {
            IConfigurationSource source = ConfigurationSettings.GetConfig("activerecord") as                      IConfigurationSource;
            ActiveRecordStarter.Initialize(source, typeof(GalleryUser));
        }

        public void Global_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Items.Add("nh.sessionscope", new SessionScope());
        }

        public void Global_EndRequest(object sender, EventArgs e)
        {
            try
            {
                SessionScope scope = HttpContext.Current.Items["nh.sessionscope"] as SessionScope;
                if (scope != null)
                {
                    scope.Dispose();
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Trace.Warn("Error", "EndRequest: " + ex.Message, ex);
            }
        }

    }

}

Now for the fun ASP.NET AJAX hookup in my ASPX page.  This is where all of the AJAX magic happens, specially in the Update Panel.  I could have thrown all of the controls into the UpdatePanel and then I wouldn't have needed to add the explicit AsyncPostBackTrigger reference, but hey - I wanted to see how it works.  Having used Telerik's AJAX framework, which is quite good by they way, I found the ASP.NET AJAX framework even easier.  It's so well integrated now into ASP.NET and Visual Studio, I can't imagine anyone not using it going forward.  It won't be cool to use AJAX next year, it will just be the de facto standard.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ASP.NET AJAX Test Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:ListBox ID="lstUsers" runat="server" />
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="btnGetUsers" />
            </Triggers>
        </asp:UpdatePanel>
        <asp:Button ID="btnGetUsers" runat="server" Text="Get users from DB"
            OnClick="btnGetUsers_Click" />       
        <asp:TextBox ID="txtInfo" runat="server" EnableViewState="false" />           
    </form>
</body>
</html>

And the associated code behind, which looks just like it would without the AJAX magic.  The fun part to note here is the data fetching; just too easy!  So easy in fact I just skipped following any decent application patterns like MVP, but hey its just a tech spike.

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sneal.Gallery.Core;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
            txtInfo.Text = "IsPostback = true";
        else if (IsCallback) // doesn't work as hoped.
            txtInfo.Text = "IsCallback = true";
        else
            txtInfo.Text = "Initial page load = true";
    }

    protected void btnGetUsers_Click(object sender, EventArgs e)
    {
        GalleryUser[] users = GalleryUser.FindAll();

        foreach (GalleryUser user in users)
        {
            lstUsers.Items.Add(user.FullName);
        }
    }
}

In the end, I'm very happy with the results.  And to my surprise my spike app worked on the first run.

My only issue is that I'm not sure I like ActiveRecord and its static data access methods on the actual objects.  It seems like it's crossing the boundaries of separation of concern, but then again it didn't cost me any coding time...  I'll have to think about it.

Friday, October 20, 2006 11:23:08 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Friday, October 20, 2006
My ducked taped together photo site was causing me issues.  I finally fixed it...  I was getting a strange GDI+ exception, amongst others, when trying to use the site.  Apparently my NTFS permissions to the media folder got mucked up, so I ended up having to take ownership of all the files and then grant the NETWORK SERVICE account write permissions to the folder.

I think this happened before a long time ago.  I'm now thinking I don't like the thumbnails and xml files in each of the sub folders where the actual full size photos are stored.  It seems better to index these in a central location - heck maybe even use a database. 

Hmm...  Sounds like an excuse to play around with some new tech.

Friday, October 20, 2006 4:21:07 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, October 11, 2006
I came across this snippet of javascript in one of our apps...

if(i == 0 || i == 2 || i == 3 || dirty == ''){
//had to do this weird workaround as i!=0 was not working
}

WTF
Wednesday, October 11, 2006 6:00:44 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, October 10, 2006

OK, you’ve finally built up your beautiful platform agnostic and persistent ignorant business domain layer.  It solves all of your business requirements and is elegant and maintainable – too bad the model doesn’t fit nicely into your user interface!

This is about the time a non-domain driven developer says, “ha, I told ya that domain model was a waste of time!  You should have modeled your objects after the user interface!”  Was it really a waste of time?  Of course not!  Well then how do we slap a UI on top of a domain model?  Chapter 11 of Jimmy Nilson’s Applying Domain-Driven Design and Patterns to the rescue.

Basically you have three options when hooking up a user interface to your domain model:

  1. The domain model hooks up directly to the UI, and it just happens to be a good fit.
  2. You wrap the domain model with a presentation specific object.
  3. You map data from the domain model to a presentation specific object.

Of interest here are options 2 and 3.  To keep the domain model clean and pure, it may make sense to create a presentation specific object that transforms a domain specific object into a user interface friendly one.  The example given in Jimmy’s book is the one where the domain model represents a name, first and last, as separate fields.  In the UI, the first and last names are placed together in a single textbox. 

Below I’ve provided an example of option #2, wrapping.  In this example ResourceWrapper in the presentation layer wraps a domain model Resource object.  One thing that makes the UI easier to work with is to flatten out object graphs like in this ResourceWrapper example, specifically the resource’s manager.

 

public class ResourceWrapper
{
    private Resource resource;

    public ResourceWrapper(Resource resource)
    {
        this.resource = resource;
    }

    public string Name
    {
        get { return resource.FirstName + " " + resource.LastName; }
        set
        {
            string[] names = value.Split(" ".ToCharArray(), 2);
            resource.FirstName = names[0];
            resource.LastName = names[1];
        }
    }

    public string ManagerName
    {
        get { return new ResourceWrapper(resource.Manager).Name; }
        set { new ResourceWrapper(resource.Manager).Name = value; }
    }

    public decimal Salary
    {
        get { return resource.Salary; }
        set { resource.Salary = value; }
    }

    public Resource GetDomainObject()
    {
        return resource;
    }
}

I have to write more code?  Yes, but you may be able to get around a lot of this by creating a generic object to object framework that sets properties via reflection and/or code generation.  In the end, wrapping or mapping domain objects sounds like a good idea when they just won’t fit nicely into the UI.

Tuesday, October 10, 2006 4:57:09 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Saturday, October 07, 2006
Ayende posted about some IL wierdness he experienced while working on DynamicProxy2, which prompted me to go do some reading about IL.
  • The CLR is completely stack based, no registers.
  • st commands store things from the stack to memory.
  • ld commands load items from memory onto the stack.
A decent overview of IL (from 2001?!) is: http://msdn.microsoft.com/msdnmag/issues/01/05/bugslayer/

Saturday, October 07, 2006 2:53:36 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, October 05, 2006
Someone asked me today if there was a way to test the default statement in this piece of code:

public enum AEnum
{
    One,
    Two,
    Three
}

public void DoStuff(AEnum e)
{
    switch (e)
    {
        case AEnum.One:
            Console.WriteLine("AEnum.One");
            break;

        case AEnum.Two:
            Console.WriteLine("AEnum.Two");
            break;

        case AEnum.Three:
            Console.WriteLine("AEnum.Three");
            break;

        default:
            throw new Exception("Unhandled enumeration value");
            break;
    }
}

Unfortunately I don't see any way to do it without changing the design to something very wrong and ugly like:

public void DoStuff(Enum e)
{
    AEnum ae = (AEnum)e;

    switch (ae)
    {
        case AEnum.One:
            Console.WriteLine("AEnum.One");
            break;

        case AEnum.Two:
            Console.WriteLine("AEnum.Two");
            break;

        case AEnum.Three:
            Console.WriteLine("AEnum.Three");
            break;

        default:
           
throw new Exception("Unhandled enumeration value");
            break;
    }
}




Thursday, October 05, 2006 4:50:25 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, October 04, 2006
Sometimes it's useful to debug third party libraries without actually building them locally.  For instance with NHibernate.  This may seem trivial, but I actually don't do it very often; hence I'm writing it down here.

Right click the Solution in Visual Studio's solution explorer, select property pages.  Under common properties select debug source files.  Add the root source code folder to the list (subfolders seem to be automatically included).  Ensure the PDB for the assembly your are debugging is in the bin folder you are running from.  Visual Studio should step right into the third party library now.

Wednesday, October 04, 2006 4:49:51 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, September 28, 2006
I'll have to add to this in the near future.  From Jeff Atwood: http://www.codinghorror.com/blog/archives/000666.html

  1. Every programmer shall have two monitors

    With the crashing prices of LCDs and the ubiquity of dual-output video cards, you'd be crazy to limit your developers to a single screen. The productivity benefits of doubling your desktop are well documented by now. If you want to maximize developer productivity, make sure each developer has two monitors.

  2. Every programmer shall have a fast PC

    Developers are required to run a lot of software to get their jobs done: development environments, database engines, web servers, virtual machines, and so forth. Running all this software requires a fast PC with lots of memory. The faster a developer's PC is, the faster they can cycle through debug and compile cycles. You'd be foolish to pay the extortionist prices for the extreme top of the current performance heap-- but always make sure you're buying near the top end. Outfit your developers with fast PCs that have lots of memory. Time spent staring at a progress bar is wasted time.

  3. Every programmer shall have their choice of mouse and keyboard

    In college, I ran a painting business. Every painter I hired had to buy their own brushes. This was one of the first things I learned. Throwing a standard brush at new painters didn't work. The "company" brushes were quickly neglected and degenerated into a state of disrepair. But painters who bought their own brushes took care of them. Painters who bought their own brushes learned to appreciate the difference between the professional $20 brush they owned and cheap disposable dollar store brushes. Having their own brush engendered a sense of enduring responsibility and craftsmanship. Programmers should have the same relationship with their mouse and keyboard-- they are the essential, workaday tools we use to practice our craft and should be treated as such.

  4. Every programmer shall have a comfortable chair

    Let's face it. We make our livings largely by sitting on our butts for 8 hours a day. Why not spend that 8 hours in a comfortable, well-designed chair? Give developers chairs that make sitting for 8 hours not just tolerable, but enjoyable. Sure, you hire developers primarily for their giant brains, but don't forget your developers' other assets.

  5. Every programmer shall have a fast internet connection

    Good programmers never write what they can steal. And the internet is the best conduit for stolen material ever invented. I'm all for books, but it's hard to imagine getting any work done without fast, responsive internet searches at my fingertips.

  6. Every programmer shall have quiet working conditions

    Programming requires focused mental concentration. Programmers cannot work effectively in an interrupt-driven environment. Make sure your working environment protects your programmers' flow state, otherwise they'll waste most of their time bouncing back and forth between distractions.


Thursday, September 28, 2006 5:24:01 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
Jeff Atwood pointed out a very interesting XP change diary by James Shore

"It was 2002. The .com bust was in full slump and work was hard to find. I had started my own small business as an independent consultant at the worst possible time: the end of 2000, right as the bubble popped. I had some noteworthy successes doing what I loved: coaching agile Extreme Programming (XP) teams in doing great work for a valuable purpose. And then the work dried up.

Eventually I admitted that I was going to have to find some "real" work to fill the gap. I took a contract job as a programmer on a team customizing some web software for a large institutional customer. This team was the opposite of agile. I was bored and frustrated. It didn't take me long to remember Martin Fowler's advice. As a peon, could I make the kinds of changes I made as a (damned good!) XP coach? Or would they kick me out, causing me to change organizations a little more abruptly?"


The full diary can be found here: http://www.jamesshore.com/Change-Diary/.  I highly recommend reading it, even if you aren't that interested in XP.

Thursday, September 28, 2006 5:20:14 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, September 27, 2006
After moving the CruiseControl.NET server to a virtual instance of Windows Server 2003, we've been having problems with NDoc hanging.  I've noticed previously that NDoc was apparently leaking memory thus forcing me to reboot the server every night.  I think it may be opportune time to swap out the alpha version of NDoc we've been using up to this point for Sandcastle, Microsoft's (beta) code documentation generator.

Wednesday, September 27, 2006 6:22:32 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  |