Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Fear and Loathing

Gonzo blogging from the Annie Leibovitz of the software development world.

  • Ready for the weekend

    Hi guys. I’m packaging up the Forums for release shortly and you’ll have it this weekend. I had it planned for release today but some security and performance issues creeped up that I need to take care of. Watch for a release with installation instructions this weekend (not sure when exactly) and a source release to follow. Thanks.

  • SharePoint Forums to be Open Source

    I’ve decided that I’m going to release the source code to my SharePoint forums web part. I think it’s a pretty nice piece of work and figure it can only benefit by having the source code out there and other people contributing to it (or learning from it). The source contains various patterns and techniques that I use such as:

    I won’t be releasing the source with the initial version of the web part (which I’m trying to get out for tommorow) as I need to clean things up and make it consumable by the public, but a couple of weeks or so after the initial release is when you’ll be able to download the source. The only thing I’ll ask is people to contribute back to the codebase if they make any enhancements so I don’t have 10 different forks out there all competing with each other.

    Unlike my Microsoft April Fools joke about Windows SharePoint Services being open sourced (which fooled a few more people than I expected) this announcement is real.

  • Using Calculated Fields in CAML to Display Conditional Images

    Came across a nice gem in the newsgroups that I thought I would share here. Someone had a choice field with three values: failed; pass; re-run; and wanted to display a red image for items in the list matching the failed value, green for pass, and yellow for re-run (oh yeah, can you see where this is going).

    I pointed them immediately to Ian Morrish’s article here on conditional formatting using a DataView Web Part which works nicely for this. However Colin Gardner came up with a nice solution that used the RenderPattern tag in CAML for a list to do the job. Here’s his solution:

    1. Edit the FieldTypes.xml file (make backups for safety) and look for the row definition for the calculated field type (search for <Field Name="TypeName" DisplayName="TypeName">Calculated</Field>).

    2. Modify the deafult render pattern in the <FieldSwitch> statement so that it handles the values returned by a calculated file in such a way that will return you an image/icon/traffic light.  You will see that the <FieldSwitch> statement handles Boolean, Number, Currency and DateTime field types but anything else falls through and is processed by the code in the <Default> tag which is: <Column HTMLEncode="TRUE" AutoHyperLink="TRUE" AutoNewLine="TRUE"/>

    You need to replace this default rendering with you're own custom logic.  In my implementation I replaced it with another complete switch statement like the one below:

    <Switch>
    <Expr>
    <GetFileExtension><Column/></GetFileExtension>
    </Expr>
    <Case Value="giF">
    <HTML><![CDATA[<IMG SRC="]]></HTML><Column HTMLEncode="TRUE"/><HTML>"</HTML>
    </Case>
    <Default>
    <Column HTMLEncode="TRUE" AutoHyperLink="TRUE"
    AutoNewLine="TRUE"/>
    </Default>
    </Switch>

    In this example the the Switch <Expr> calles the GetFileExtension function which processes the value in the calculated field and tries to extract a file extension.  You can then use a Case statement to render the value returned by the calculated field in a way that makes sense. In the example above - if the GetFileExtension returns the string "giF" then I process the value as an image and render it as an HTML <IMG> tag.

    Note that I chose to take advantage of the fact that the comparison is case sensitive but the source url for the image is not.  This means that if my calculated field returns a string that ends with ".gif" rather than ".giF" then it will slip through the case statement and be rendered as before i.e. not as an image.

    Of course you can modify the above to handle jpeg or any other graphics format that WSS can render.

    3.  Save the modified FieldTypes.xml file.

    4.  Create a Caluclated field in your list in the standard way with a formula that checks the value of your Choice field and returns a URL (relative will work) to the appropriate graphic file making sure that it is a format that will be handled by the newly modified render pattern.  Something like:

    =IF(Choice="A","/imagepath/red.giF", IF(Choice="B", "/imagepath/yellow.giF", "/imagepath/green.giF"))

    Now you can use the calculated field wherever you like.

    This is pretty elegant and nice to do since a) you don’t need to create a DVWP and therefore unghost a page b) it uses CAML which is always cool and c) you can set up a list with this in it so anyone creating a new list of this type will get the results. RenderPattern is a pretty powerful little thing because basically you can do anything in it, including conditional logic.

    NUnit test results stored in a SharePoint list anyone? Yeah, who needs Team Server Foundation when you do stuff like this.

  • An Architect is an Architect, is it?

    Arno Nel recently posted a question about what is Architecture on his blog and some people disagree with what he suggested it was (to be fair to Arno, he asked the question of what people thought about the questions he asked, but I don’t believe he thinks this way).  

    I came across this fairly elegant definition for architecture that tend I agree with and try to emulate in my work:

    "Architecture is the use of abstractions and models to simplify and communicate complex structures and processes to improve understanding and forecasting."

    It’s simple and gets right to the point covering the various aspects of solution or software architecture (at least IMHO).

    Robert Bogue followed up with his own views and the general result was he disagreed with a lot of points Arno made.

    I tend to agree with most of what Robert said where he disagreed with Arno's. We do care about methodologies (maybe not the extent a developer does, but we need to know about the process in order to facilitate communication about and around it). I think Robert hit home with his last point about Architecture being about translating the business problem into IT solutions, not translating IT into Business as Arno stated. I would rephrase this to be communicating business needs using IT solutions, but maybe that’s just mincing words.

    Architecture is about communication and collaboration. I think communication is the key cornerstone in what makes a good architect. Yes, you can draw pretty UML pictures and talk about the fantastic abstractions you did as a child but can you really communicate a business model to an IT guy so much so that he/she can go away and build something that meets the needs of the client? That’s the secret to success. You can build a system that, technically is architecturally perfect, but if it’s not what the customer wanted or explained to you they were looking for, you might as well have built them a pole digger (or insert witty but useless item of your own liking here).

    I used to be a building architect and now I'm a software architect. Is there a difference? From one perspective, lots. From others, not so much. I could probably blog for hours on that subject. Maybe a cup of coffee or a beer next time I’m out at a geek fest (hook up with me at TechEd for example). Now that would be an interesting discussion!

  • Identity and your Domain Model

    I’ve been struggling with a concept today that I wanted to flesh out. I may ramble on but I think there’s a point to be had deep down here (somewhere).

    How often do you see a class begin its life like this:

        5     public class Customer

        6     {

        7         private int id;

        8 

        9         public Customer()

       10         {

       11         }

       12 

       13         public int Id

       14         {

       15             get { return id; }

       16             set { id = value; }

       17         }

       18     }

    Looks innocent enough, but many times that Id value is there because

    • an object of this class has to eventually persist into a database and someone thought it would be easy to store it here
    • that database uses an identity column and thus, the value in your business entity has to be an integer to maintain a reference to it
    • someone wants to use it in a UI layer so they can retrieve details about the item (DisplayCustomer.aspx?Id=3) (or someone wants to show a “nice” number to a user)

    An identity column (more of a SQL Server term, Oracle can pull it off but it’s a little more involved) is a column that provides a counter for you. In it's simplest form an identity column creates a numeric sequence for you.

    More often than not though, it gets tied (directly or indirectly) to a class design. This is where the fun begins.

    What happens when I want to test this class? When I want to write a test checking that two objects have a unique identity I might write some tests that look like this:

       21     [TestFixture]

       22     public class CustomerFixture

       23     {

       24         [Test]

       25         public void TwoCustomersAreUnique()

       26         {

       27             Customer firstCustomer = new Customer();

       28             Customer secondCustomer = new Customer();

       29             Assert.IsFalse(firstCustomer.Id == secondCustomer.Id);

       30         }

       31     }

    With the above code, my test fails because I haven’t initialized Id to anything so they’re the same. However, in order to initialize them to something unique (each time) I need something to do this. Since Id was put there because someone knew this object was eventually going to be stored in a database it’s easy. Create the customer and when it’s saved (and loaded back into my object) a new Id is created. Voila. Test passes.

    This is great but it means I’m inherently tied to my data source layer (in order to get an identity) to create my business entity. That’s no good for testing.

    Maybe with a mock customer I can fix this, but again I would have to create some kind of mock system that generated id numbers on the fly. Not as easy as it sounds (especially when they have to be unique). In any case, it doesn’t model my business domain and at the end of the day, why do I need some number floating around that tells me what record # my object is in some database somewhere. That has nothing to do with the problem at hand.

    I’m not saying an object couldn’t/shouldn’t/wouldn’t have identity, but a domain objects identity is not it’s ordinal position in a database.

    Eric Evans makes a great statement about this:

    “When an object is distinguished by its identity, rather than its attributes, make this primary to its definition in the model.”

    I completely believe this and try to follow it as best as possible. Given an object (say a bank transaction) where each transaction has to be unique, identity is an important thing. However imagine if you tied bank transactions identities to an endless numbering system in SQL Server? How can I guarantee uniqueness when I have multiple data stores (say an active and passive one). Or a data warehouse. Or an internationally distributed system where I have to generate two unique transaction numbers on each side of the planet. What if someone resets/restarts the identity counter?

    Okay, maybe I’m getting carried away here but eventually, IMHO, the identity approach falls short and you need something better.

    Relying on infrastructure for your domain objects is a bit of a cheat and while even using something like a GUID isn’t perfect (and requires infrastructure as GUIDs are generated from things like hardware) it is pretty much guaranteed to be unique no matter what. Even creating one in Java and one in .NET, on the same machine, at the same time will get you a unique identifier (although I’m not sure if a dual-core system would never generate two GUIDs but I’ll leave that for the weary traveller to test out).

    So if we change our Customer class to use GUIDs for identity we get something like this:

        6 public class Customer

        7 {

        8     private Guid id = Guid.NewGuid();

        9 

       10     public Customer()

       11     {

       12     }

       13 

       14     public Guid Id

       15     {

       16         get { return id; }

       17         set { id = value; }

       18     }

       19 }

    Now the test we wrote before passes correctly because we have two unique identities for each object, no database required. Much better.

    So all I’m saying is (to quote Jimmy Nisson) “Get rid of those nasty IDENTITY/sequences…” and “let the model set the values, for example by calling a simple service at the right place/time”.

    Just something to consider when you’re building out your classes. Sure, what’s a system without storing it but it doesn’t mean you have to pollute your model with multiple numbers to keep track of something in a database system somewhere. Identity in a database is just that, and not something that you should rely on in your domain (especially if you’re doing TDD and don’t have one).

    Try using GUIDs (or some other method if you prefer, like a service) that will help you keep your domain model pure of what it needs to operate with, and leave the non-business stuff like tracking numbers to the infrastructure layer.

    Note: if you’re still hung up on using identity and SQL to generate ids for your business objects, check out Don Schlichtings article here on getting the right identity.

  • Quick note to start the week

    Just a quick note as I try to wake up and consume large quantities of bucks this morning. I’m still working on the forum web part today. Ran into some security snags (don’t you just love those descriptive error messages, “An error has occurred”) so need to rework some things. Watch for an update shortly.

  • Plumbers at Work - Episode #5 - Pan Galactic Gargle Blaster

    Okay, it’s a couple of weeks later after my other plumber dudes posted this but check out Episode 5 – Pan Galactic Gargle Blaster of the show on our Plumbers @ Work site. In it James, John, and I cover:

    • IronPython v1.0 Beta 4
    • The 73+ Languages in .NET 
    • Windows Workflow Foundation (WinWF) v2.2 CTP 
    • SQL Server 2005 SP1 CTP 
    • Visual Studio SDK CTP 
    • Matt Hawley’s eWorld Controls
    • Multi-Core CPUs and Moore's Law
    • on10.net and Leeroy Jenkins
    • Blackberry .NET Development with AppForge's Crossfire
    • Multi-Platform Frameworks
    • TestDriven.net
    • Scott Hanselman and DasBlog at Alberta .NET User Group
    • Calgary Code Camp - May 27, 2006
    • Vance Morrison - CLR Performance Dude
    • James on Locks and Lockless Programming
    • Double-Check Locking and CPU Architectures
    • MSDN Canada realDEVELOPMENT_06
    • Time Management with TimeSnapper.com
    • Halo and Aliens

    Podcast Link

    I’m only posting this as we just wrapped up taping Episode #6 tonight so we should have the new show out this week. It was a great show and (at least we) think we’re getting better with each podcast.

    At least let us believe that okay so we don’t crush our already fragile and delicate egos.

  • SharePoint Forums Web Part

    A lot of people have been asking me about my SharePoint Forums Web Part that I posted about at the middle of January. It’s been a busy time since then and I’m working furiously right now to finish it and get it out to you guys as soon as possible.

    It’s a self contained web part and generates all the lists it needs the first time it runs (if they’re not available). All editing operations are performed by the AppPool user so nobody has to have contributor access to the various lists. You define who has what access through the Web Part interface. Here are some more screenshots of the current build and feature set:

    Quoting of previous messages in a thread:

    forums_blog1

    Fonts and formatting:

    forums_blog2

    Threaded discussions with all the features:

    forums_blog3

    Expect a release by the end of the week as I’m just getting the final work done on it. I may have to release it with no documentation but I would rather do that to make it available this week rather than letting it go any longer. Hope you like it!

  • Back to basics, AreSame vs. AreEqual

    I thought I would do a little back to basics today as I was working with some people (new to unit testing) and had to explain the difference between calling Assert.AreEqual vs. Assert.AreSame.

    On the surface, they look identical. They both test expected and actual items and the test will fail if the items don’t match. So here's a simple test:

    [Test]
    public void TestAreSameStrings()
    {
      string expected = "MyString";
      string actual = "MyString";
      Assert.AreSame(expected, actual);
    }

    So this test fails if the strings are different. Obviously they are the same but imagine if we retrieved the string from a property, web service, etc. Then we might be testing the return value from a business entity against a known string value. This test written using Assert.AreEqual instead of Assert.AreSame will be the same result, pass (or green in the NUnit GUI).

    However what if we use integers instead of strings like so:

    [Test]
    public void TestAreSameIntegers()
    {
      int expected = 1;
      int actual = 1;
      Assert.AreSame(expected, actual);
    }

    This test actually fails. It looks like it should pass as it's no different than the string test above right? Let's take a look at this code in IL form using ILDASM:

    IL_0000: ldc.i4.0
    IL_0001: stloc.0
    IL_0002: ldc.i4.0
    IL_0003: stloc.0
    IL_0004: ldloc.0
    IL_0005: box                [mscorlib]System.Int32
    IL_000a: ldloc.1
    IL_000b: box                [mscorlib]System.Int32
    IL_0010: call               void [nunit.framework]NUnit.Framework.Assert::AreSame(object, object)
    IL_0015: ret

    Don't worry about some of the gobbly-gook here, but pay attention to IL_0005 where it calls box. This is known as boxing in .NET and basically converts value types to objects and vice-versa. For more information on boxing check out this article.

    So we know it's loading our integer values but then boxes them into Int32 object types. So when the compare is done, we're comparing two new Int32 objects against each other. While their values are the same, the objects are not (for example every object has a ReferenceEquals method which will return a unique reference). Since we have two different boxed objects here, they are not the same. Strings on the other hand are not boxed so that test works (more on this later).

    The obvious thing we might do is to change the test to use Int32 types instead of int. This will eliminate the boxing problem. Unfortuantely, again, this won't work because we're creating two different objects and the AreSame method is expecting to fail if the entire object is different, not just the value.

    So the rule of thumb here is use AreEqual if you're just comparing values, use AreSame if you really want to compare things at the object level (and you can create two objects that are the same).

    One thing that might be bugging you is the first test with the strings. Surely .NET boxed the strings into a native object so why didn't it fail? If you create this test (and look at the IL code generated) you'll see that strings are reference types already (plus the fact that they're immutable) and thus will produce duplicate items (at the object level). There's a good article here on strings in .NET that you may want to check out. Also you can use "String" and "string" interchangable, as one is just an alias for another. 

    I know this post is basic and it may boil down to NUnit documentation saying "use AreEqual for values, use AreSame for objects" which you can find here but this was a bit of a mystery to some people so I thought I would elaborate here.

  • Pay no attention to the man behind the curtain

    I’m a happy camper. Not only am I be going to be at TechEd and working for the man (read:Microsquishy) as a Technical Expert in the Office System Track at the Technical Learning Center (yeah, just ask me silly questions about SharePoint like you always do) but my Birds of a Feather session, “Getting Ready for the next generation of SharePoint” has been officially accepted by the powers that be.

    Way cool.

    The discussion is tentatively scheduled for Tuesday, June 13, 2006 at 1:00 PM so make sure you bring your popcorn and get your dialog caps on as we’ll be having a rockin’ time chatting it up about Microsoft Office SharePoint Server (MOSS) 2007. As BOFs are really discussions and not presentations, lectures, or sessions, you guys fill the content. I’m really just the goofy looking geek that might take notes and throw in some pithy observations from time to time. In any case, it’ll be a lot of fun. And if things get really boring, we’ll make SharePoint shadow puppets on the wall and balloon animals of your favorite Office assistant (I call dibs on Clippy!).

    See you there and thanks to everyone who voted!