Development Blog

 Thursday, January 10, 2008

stack-bar-chart

With Mingle 1.1 came several great new features, including date fields. Now you can track the date that you complete tickets by adding a Date Done field (along with a Complete transition that sets the Date Done field to today) and locking the Status field to be editable only by transition.

This works great for newly completed cards, but what about all the cards you already have in your system? Sure you could go without burn-up charts and date stats for those cards, but what's the fun in that? 


taskcomplete

Fortunately, Mingle tracks every card change in a history table. Each change in the history table has a date associated with it, so all we need to do is figure out how to extract the dates we care about. I must warn you, this is a little complicated, and I'm sure ThoughtWorks doesn't at all condone you mucking around in your Mingle database manually, so please please back up your database before attempting this and of course I'm not responsible for any damage you do. That said, here's how I was able to retroactively add dates for our two date fields: Date Done, and Date Published.

  1. Back up your Mingle DB. Really.
  2. You'll need to identify the field you use to track status. We use Status. We have Status of 'Not Done', 'Done', and 'Published'.
  3. Then connect to your Mingle database and find the name of your cards table and your card_versions table. Our project is called "eleutian_speakeng" so our tables are "eleutian_speakeng_cards" and "eleutian_speakeng_card_versions".
  4. Add the date fields you want to populate if you don't already have them. We have "Date Added", "Date Published" and "Date Done".
  5. Figure out which fields in the two tables you identified map to your status and dates (this is usually as easy as prepending cp_ and box_caring your names. For us we have cp_status, cp_date_published, cp_date_done, cp_date_added.
  6. Edit the following queries to add in your table/field names and values (these are the exact queries I ran, you'll need to change the red things):
    UPDATE eleutian_speakeng_cards SET cp_date_added = created_at
    
    UPDATE eleutian_speakeng_cards card SET card.cp_date_done = (
      SELECT MAX(b.updated_at) 
        FROM eleutian_speakeng_card_versions a
      INNER JOIN eleutian_speakeng_card_versions b ON a.number = b.number 
        AND b.version=a.version+1 
      WHERE card.number = a.number
      AND (a.cp_status='Not Done' OR a.cp_status IS NULL) AND b.cp_status='Done'
    ) WHERE card.cp_status = 'Done'
    
    
    UPDATE eleutian_speakeng_cards card SET card.cp_date_published = (
      SELECT MAX(b.updated_at) 
        FROM eleutian_speakeng_card_versions a
      INNER JOIN eleutian_speakeng_card_versions b ON a.number = b.number 
        AND b.version=a.version+1 
      WHERE card.number = a.number
        AND (a.cp_status IN ('Done', 'Not Done') OR a.cp_status IS NULL) 
        AND b.cp_status='Published'
    ) WHERE card.cp_status = 'Published'
    
  7. Once you've got that taken care of, go ahead and run the queries (you backed up right?) and you should be good to go.

So now that you've got your dates in your database, how do you get the cool burn up chart? Like this (mold to your project):

{{
   stack-bar-chart
   x-label-start: SELECT MIN('Date Added')
   x-label-end: Today
   x-label-step: 14
   chart-height: 600
   chart-width: 700
   plot-height: 500
   plot-width: 550
   conditions: Type IN (Bug, Story, Task)
   three-d: true
   cumulative: true
   series:
     - label: 'Not Done'
       color: #e6a800
       data: SELECT 'Date Added', COUNT(*)
       type: area
     - label: Done
       color: #1bcc00
       type: area
       data: SELECT 'Date Done', Count(*) WHERE 'Date Done' IS NOT NULL
     - label: Published
       color: #0079bf
       type: area
       data: SELECT 'Date Published', COUNT(*) WHERE 'Date Published' IS NOT NULL
}}
agile | development | mingle | tips | tools
by Aaron on Thursday, January 10, 2008 11:48:38 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Sunday, August 05, 2007

Jacob posted about the AutoMockingContainer several months ago. At that time we didn't really use it, it was just kind of an implementation of an idea. Well, we've finally started using it in some side projects (Resharper.TestDrive for example), and I must say... wow. It is most definitely the way to instantiate your subject under test most of the time. Why?

  1. It decouples your tests from your constructors. This means that if you have multiple TestFixtures for a class and you want to add a new service to your constructor, you don't have to change a thing in your tests.
  2. It simplifies your tests. Things are just cleaner when you're not having to create all your mock services to inject into your subject under test.
  3. It helps reinforce good mock usage. The default mock strategy is dynamic mocks. You can override that if you want to, but most tests should (in my opinion) be written with dynamic mocks. Like Dave talks about you only really want to set actual expectations on zero or one mock at a time. Everything else should be more stub-like.

I've started to use a base class for all my tests. Let's take a look at ReSharper.TestDrive's test base class:

  public abstract class AutoMockingTests 
  {
    private MockRepository _mocks;
    private AutoMockingContainer _container;

    protected MockRepository Mocks
    {
      get { return _mocks; }
    }

    protected AutoMockingContainer Container
    {
      get { return _container; }
    }

    [SetUp]
    public void BaseSetup()
    {
      _mocks = new MockRepository();
      _container = new AutoMockingContainer(_mocks);
      _container.Initialize();
      Setup();
    }

    public abstract void Setup();

    public T Create<T>()
    {
      return _container.Create<T>();
    }

    public T Mock<T>() where T : class
    {
      return _container.Get<T>();
    }

    public void Provide<TService, TImplementation>()
    {
      _container.AddComponent(typeof(TImplementation).FullName, typeof(TService), typeof(TImplementation));
    }

    public void Provide<TService>(object instance)
    {
      _container.Kernel.AddComponentInstance(instance.GetType().FullName, typeof(TService), instance);
    }
  }

So what's a test look like with this base class? Let's borrow Dave's example.

  public class SearchPresenterTests : AutoMockingTests
  {
    private SearchPresenter _presenter;
    private SearchResultDTO _fakeResults;

    public override void Setup()
    {
      this._fakeResults = new SearchResultDTO();
      this._presenter = Create<SearchPresenter>();
    }

    [Test]
    public void Can_search_for_customers_by_number_of_orders()
    {
      using (_mocks.Record())
      {
        Expect
         .Call(Mock<ISearchService>().GetCustomersByOrderCount(42))
         .Return(this._fakeResults);
      }

      using (_mocks.Playback())
      {
        _presenter.SearchByOrderCount(42);
      }
    }

    [Test]
    public void Search_results_are_displayed_to_the_user()
    {
      using (_mocks.Record())
      {
        mockView.SearchResults = _fakeResults;
        SetupResult
         .For(Mock<ISearchService>().GetCustomersByOrderCount(42))
         .Return(_fakeResults);
      }

      using (_mocks.Playback())
      {
        presenter.SearchByOrderCount(42);
      }
    }
  }

Not bad eh? You can do some more complicated things too. Let's say all your presenters take a hub service called PresenterServices. Rather than mocking it and its child services and setting up expectations for each of the children you can just use the real one and do this:

      Provide<IPresenterService>(Create<PresenterService>());
      this._presenter = Create<SearchPresenter>();

Now you can refer to all your hub's child services with the Mock<T>() method.

Ok, so if you made it this far you probably want to check it out for yourself. Thanks to Ayende, the AMC it is now part of Rhino.Tools so you can check it out (svn co https://rhino-tools.svn.sourceforge.net/svnroot/rhino-tools/trunk rhino-tools)  and build it yourself or just grab the current trunk build with all the dependencies here. Hope Oren doesn't mind me building and linking this... ;)

by Aaron on Sunday, August 05, 2007 11:47:22 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [7]  |  Trackback
 Monday, July 30, 2007

Writing ReSharper.TestDrive was kind of an exercise in tiny classes for me. I didn't TDD the whole thing because so much of it was just experimenting with ReSharper's mostly undocumented API and EnvDTE, though I did TDD a good portion of it after my initial spike. After I got a working prototype implemented I spent a lot of time refactoring it into tiny classes that for the most part follow the Single responsibility principle.

As this is the most code I've ever thrown out into the public at any one time and it was a bit of an experiment for me, I wanted to take this chance to ask the community to review my code. If you have the time, feel free to look over the code and tell me what you think. Likes/dislikes/hates/loves anything is fair game--feel free to rip on it. Maybe we'll get some interesting discussion out of it.

Source

by Aaron on Monday, July 30, 2007 9:54:52 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [2]  |  Trackback

Note: You must have ReSharper 3.0.1 in order for this to work.

When you're doing TDD you'll create two classes every time you need one. You'll create one for the class itself and you'll create one for the tests for that class. ReSharper makes it a little bit easier by allowing you to write your tests and then alt+enter on your class under test to create it. Unfortunately it will create the class in your test project and not your project under test. It may actually create it in that same file (I don't remember) which means you have to Move to File. Then you have to drag it over to the project under test and/or change the namespace. Pretty obnoxious for something we have to do so often.

So... I decided to write a ReSharper plugin to do just that. It'll also create tests from a class under test (just in case you cheated and created your class first). Heck, it'll even create all the folders you need to.

This current version makes a few assumptions about your structure and it's not configurable at all unless you actually hit the code. Here are the assumptions it makes:

  • The tests for Project.Foo live in Project.Foo.Tests.
  • Test classes have the "Tests" suffix.
  • Test classes live in the same namespace as the classes under test.
  • The tests for ClassFoo are in ClassFooTests.

I lied when I said it wasn't configurable at all. After you've used it for the first time it will have created ReSharper file templates that you can edit to customize what is generated when you create a test or a class under test. Just go to ReSharper>Options>Templates>FileTemplates>User Templates>TestDrive.

To install it just extract it somewhere and run install.cmd, or just copy the dll to your %APPDATA%\JetBrains\ReSharper\v3.0\vs8.0\Plugins\Resharper.TestDrive (obviously you'll need ReSharper installed).

To use it, just have the cursor somewhere within a class that doesn't have a test, or a test that doesn't have a class under test and hit Alt+Enter, select Create X Tests... or create X... and hit enter. In order for the light bulb/alt+enter to show up it will need to be able to find an associated project to the one you're in (Sample.Project.Tests<->Sample.Project).

I've got more plans for this but I wanted to get it out there to see what you all thought. Oh, and in case you're wondering, Bunker is just a really light nearly feature-free IoC container that Jacob wrote in a day for another project we're working on.

Binaries
Source

by Aaron on Monday, July 30, 2007 9:14:15 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Monday, April 09, 2007

We use a ton of Visual Studio plugins. CodeRush is one of them. Its templates are awesome, and its got a few nice refactorings that Resharper doesn't have. They're a little tricky to get working together, but not impossible. One thing I use a ton is GotoType under Resharper. One thing I find myself doing all the time is going between a class and it's fixture. Because I couldn't see anything else that would do it, I tossed together a CodeRush plugin for that very thing.

You just bind a key (I use Ctrl+Shift+X) to Eleutian Goto Fixture. All it does is do a regular expression search through type names in your solution. Say you're on HomeController. Because the class name doesn't end in "Tests" it will look for one that ends with "HomeControllerTests". If the class were HomeControllerTests, it would strip the suffix off and look for a class with a name that ends with "HomeController". It's missing a few things I still want. For example, for multiple matches I would like a menu, or the ability to cycle through them a la tab completion. I'm not sure of the best way to do the menu and haven't decided if I'll just do the cycling. If there's interest I'll think more about it.

There are a few optimizations, the first is that it will only look in projects ending with ".Tests" when looking for the test fixture. Also, it will keep a rolling queue of the last 10 types you jumped from and check those first. Both are handy when you have 40 projects and tons of classes. I started off with other loftier goals for the plugin, which might explain why there's so much other code.

In order to install this thing drop the binaries into your C:\Program Files\Developer Express Inc\DXCore for Visual Studio .NET\2.0\Bin\Plugins directory. Start Visual Studio and choose DevExpress | Options and then find the Shortcuts tab. In there, you can add a new shortcut (there's an icon in the lop left) and bind the keystroke you desire to the Eleutian Goto Fixture command.

It's my first CR plugin, so forgive me.

Source and Binaries

by Jacob on Monday, April 09, 2007 10:29:41 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Thursday, March 01, 2007

I needed the ability to execute a task from an MsBuild project and have MsBuild keep going and not wait around on the process to exit. I was hoping to find an option on the Exec task for this but that search turned up nothing. After scowering a bit I couldn't find one somebody else wrote, so here we go:

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;

using Microsoft.Build.Tasks;

namespace AsyncExec
{
  public class AsyncExec : Exec
  {
    #region Task Members
    protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
    {
      Process process = new Process();
      process.StartInfo = GetProcessStartInfo(pathToTool, commandLineCommands);
      process.Start();
      return 0;
    }
    #endregion

    #region Methods
    protected virtual ProcessStartInfo GetProcessStartInfo(string executable, string arguments)
    {
      if (arguments.Length > 0x7d00)
      {
        this.Log.LogWarningWithCodeFromResources("ToolTask.CommandTooLong", new object[] { base.GetType().Name });
      }
      ProcessStartInfo startInfo = new ProcessStartInfo(executable, arguments);
      startInfo.WindowStyle = ProcessWindowStyle.Hidden;
      startInfo.CreateNoWindow = true;
      startInfo.UseShellExecute = true;
      string workingDirectory = this.GetWorkingDirectory();
      if (workingDirectory != null)
      {
        startInfo.WorkingDirectory = workingDirectory;
      }
      StringDictionary environmentOverride = this.EnvironmentOverride;
      if (environmentOverride != null)
      {
        foreach (DictionaryEntry entry in environmentOverride)
        {
          startInfo.EnvironmentVariables.Remove(entry.Key.ToString());
          startInfo.EnvironmentVariables.Add(entry.Key.ToString(), entry.Value.ToString());
        }
      }
      return startInfo;
    }
    #endregion
  }
}

Don't fret over the WindowStyle and CreateNoWindow flags, Exec works by spawning cmd.exe with a batch file that it generates with our command. Without those flags, the command prompt window flashes by.

Obviously, very rough stuff and I make no promises of it's abilities. It worked for the simple example below and that's all I wanted. Ideally, the task would ensure the executable being started exists so we could at least fail if that's the case. But, for now this works for us. It's only used in interactive situations to spawn NCoverExplorer and things like thing. We can already easily spawn the HTML reports by using:

<Exec Command="$(ArtifactsDirectory)\mbunit-tests.html" />

But that just doesn't work when you need to run an application and not care about when it's closed:

<AsyncExec Command="$(ToolsDirectory)\NCoverExplorer\NCoverExplorer.exe $(ArtifactsDirectory)\coverage.xml" />

So here's the binaries in case somebody else is curious as well as the UsingTask.

<UsingTask AssemblyFile="AsyncExec.dll" TaskName="AsyncExec.AsyncExec" />

Obviously, if something like this is already easily possible and this was a half hour wasted, let me know. Especially if it's possible "out-of-the-box". I'm always glad to have one less dependency.

Source and Binaries

source | tools | msbuild
by Jacob on Thursday, March 01, 2007 12:52:18 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Thursday, February 22, 2007

I've been writing a lot of tests lately because our code coverage isn't up to where we'd like it. NCover+NCoverExplorer is a pretty awesome and while it does have its quirks it has been incredibly useful. A lot of my adventures in writing tests is creating tons of RhinoMocks so that I can pass them to constructors and that sort of thing. So I got a strange idea, and I'm not sure how I feel about it necessarily and figured I'd propose it to all of you out there and get your thoughts.

Basically, 99% of the time in a services unit test, all the interfaces passed to the service will be mocks, so we end up with lots of functions that look like this:

[SetUp]
public void Setup()
{
  _service1 = _mocks.CreateMock<IService1>();
  _service2 = _mocks.CreateMock<IService2>();
  _service3 = _mocks.CreateMock<IService3>();
  _serviceWeAreTesting = new DefaultServiceWeAreTesting(_service1, _service2, _service3);
}

If we do this a lot for DefaultServiceWeAreTesting, it's often refactored to a single location. All in all, it can be very repetitive to create all the mocks. So, as an experiment I decided to leverage the power of the IoC container, in our case Windsor, to take care of a lot of the mundane for me. In the end I end up with this code:

[SetUp]
public void Setup()
{
  _mocks = new MockRepository();
  _container = new AutoMockingContainer(_mocks);
  _service = _container.Create<DefaultServiceWeAreTesting>();
}

AutoMockingContainer is simply a WindsorContainer with a custom facility and dependency resolver that supplies a RhinoMock for any interface that is resolved. We've also moved the setup code into a base class AutoMockingTests that has the container and mock repository. We can then write code that uses the mocks from the container:

[Test]
public void DoWork_Always_AsksOtherServices()
{
  using (_mocks.Unordered())
  {
    _container.Get<Service1>().DoWork();
    _container.Get<Service2>().DoWork();
    _container.Get<Service3>().DoWork();
  }
  _mocks.ReplayAll();
  _service.DoWork();
  _mocks.VerifyAll();
}

Of course, you don't have to always do the Get call on the container, you can do that in the Setup and use member variables, etc... the point is, the mocked services are created for us. We can also mark other types so that they aren't tested, and take advantage of the IoC and injection that we use in our application to speed up writing and maintaining tests. The implementation I've uploaded allows you to associate a particular strategy with service dependencies. They are:

  • StubbedStrategy: A mock will be created, then for each property a GetValue expectation (with Repeat.Any) will be added to return a value for that property. The value will be retrieved like any other dependency (it's strategy will be gotten, and the value from that)
  • DynamicStrategy (default): A DynamicMock will be created for the dependency.
  • StandardStrategy: A standard mock from CreateMock.
  • NonMockedStrategy: Automatically set for any service that is registered normally with the container - a standard container resolve.

So, pros and cons? To get things started:

Pros

  1. Can be easier to maintain and write tests. Adding a dependency or changing the constructor breaks tests in ways that the production environment can usually handle just fine.
  2. Automatic testing the services construction via the IoC container.

Cons

  1. Speed/peformance? Does making the container such an integral part of the test fixtures hurt performance? Setup has to be longer when we're creating the container the way we are. Does this matter? Only as long as the time saved when writing tests is larger than the time it takes to run them, which I'm sure is the case...

What do you think? So far we really like the idea, or at least think it's interesting. Here are the sources:

Source and Binaries

by Jacob on Thursday, February 22, 2007 7:04:26 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [8]  |  Trackback
 Tuesday, February 20, 2007

I spent yesterday and today refactoring the code for the Controller Action/View map generator tool. I made some improvements, wrote some tests and I'm pleased to announce the first release. I saw Brian had implemented his as an MsBuild task and I liked that idea, so that's how ours runs now. First, things aren't as "drop in and go" as I would like because it's still evolving in and around our, already large, code base. It's my hope that over time the tool evolves as peoples needs change, etc... we can add some more configuration, that sort of thing. I'm more than willing to hear suggestions and such. Anway, here we go...

So in order to get yourself up and running, you'll need to do a few things. First, you'll need to add the task to your MsBuild. Simply open your csproj and add the following:

<UsingTask TaskName="Eleutian.Tools.CodeGenerator.MsBuild.GenerateMonoRailSiteTreeTask" AssemblyFile="Eleutian.Tools.CodeGenerator.dll" />
<ItemGroup>
  <ViewSources Include="../YourViewsDirectory/**/*.brail">
    <InProject>false</InProject>
  </ViewSources>
</ItemGroup>
<ItemGroup>
  <ControllerSources Include="Controllers/**/*.cs">
    <InProject>false</InProject>
  </ControllerSources>
</ItemGroup>
<Target Name="BeforeBuild" Inputs="@(Compile)" Outputs="$(ProjectDir)\SiteMap.generated.cs">
  <GenerateMonoRailSiteTreeTask File="SiteMap.generated.cs" Namespace="YourNamespace.SiteMap" ControllerSources="@(ControllerSources)" ViewSources="@(ViewSources)">
  </GenerateMonoRailSiteTreeTask>
</Target>

You'll notice a few things in here. ViewSources is just the collection of view files (be it .vm or .brail, etc..). It will use the paths of those files to add the View nodes into the map. ControllerSources is the C# source files for your controllers only, specifying this helps speed up parsing. I'll get to why in a bit. And for the Sources attribute on the task you should specify all the sources in the assembly, which @(Compile) works great for.

With the task added, you should be able to build and have a SiteMap.generated.cs file, now you'll need to tweak your "base" Controller class. If you're like us, you have a Controller class that you made yourself that all of your Controller's inherit from. In that class you'll need to add some code like the following:

private ICodeGeneratorServices _services;

public ICodeGeneratorServices CodeGeneratorServices
{
  get { return _services; }
}

public RootAreaNode Site
{
  get { return new RootAreaNode(this.ControllerServices); }
}

protected virtual void PerformGeneratedInitialize()
{
  _services = new DefaultCodeGeneratorServices(
    new DefaultControllerReferenceFactory(),
    new AspDotNetRedirectService()
  );
  _services.Controller = this;
}

First is the member variable, _services. You can do this however you like, but it's consumed by the ControllerAction/ViewReference classes to do various likes. CodeGeneratorServices is a property the partial controller code uses to create the MyActions and MyViews node instances. Site is just an easy way to get the top, root level node. PerformGeneratorInitialize is overridden in the partial controller classes to add the MyViews and MyActions nodes to the PropertyBag so they are available in the views. So there you go. If I'm not missing anything, that should do the trick. Let me know if I did and I'll append to this post.

Oh, the reason for specifying the ControllerSources is to cut down on the number of classes/types we visit when generating the internal "tree" that the source code is generated from. At first glance it seems like you should just be able to parse the ControllerSources only. We coudln't really do that because we needed to gather information on the other types in the assembly so we'd be able to use them in the arguments of our actions, etc... 

I have to stress that the code is relatively new, having undergone a major refactor to isolate it from the rest of our project. I make no promises that I won't have to upload a new copy, with a fix. :)

Source and Binaries

by Jacob on Tuesday, February 20, 2007 6:36:46 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [4]  |  Trackback
 Monday, February 12, 2007

So I was recently at a good friend's birthday gig. He's actually my old lead at Microsoft. Anyways, some of our friends that are still at Microsoft were at the party and I got a chance to talk to one of them for a while about various things... primarily open source, TDD, Inversion of Control and Mock objects. He was interested in Rhino Mocks and wanted me to email him about it. Instead of just doing that I threw together a good sized email. Here it is (slightly modified):

Good to see you again. As we talked about, there has been quite a shift in the way we write programs... that is a shift towards a much more testable, more maintainable type of programming. I know there are teams at Microsoft that have embraced recent changes... some have gone agile, most use some form of continuous integration, and some have written Inversion of Control containers (the Composite UI Application Block by the patterns & practices group has a container in it), but I'm sure most teams aren't employing all of these practices and could benefit from at least some of them.

In a number of teams, I think that there are a lot of improvements that can be made... even without shipping anything that's open source.

Firstly, you should take another serious look at Test Driven Development. I've attached an interesting study on TDD, and you may want to skim the MS Press book on the subject.

Also, the following blogs have some real good info on it:
Jeremy D. Miller's TDD Posts
Ayende's TDD Posts

A big part of TDD and Unit Testing in general is being able to remove not only your ephemeral dependencies, but also the rest of your dependencies. That way you know, when something fails, exactly what class caused the failure... it's the class being tested. In order to get rid of the dependencies, you need to replace them. In order to replace them, you need two things. The first is a replacement. The second is a method in which to inject the replacement. Mocks and stubs can handle the first task. I mentioned that we use Rhino Mocks:

Ayende's Rhino Mocks Posts

The library is great, it makes for very readable code and it's pretty darn flexible.

The second item can be a bit more complicated. The thing you usually see when class Foo depends on class Bar is this:

class Foo 
{
  private Bar _bar = new Bar(); 

  public string DoStuff()
  {
    return _bar.DoSomeOtherStuff() ? "yes" : "no"
  }
} 

Now if you're going to test Foo, you'll also be testing Bar. You can't avoid that the way it's written. Now, it's good to test Foo talking to Bar eventually, but that's what integration tests are for... not Unit tests. So what do you do? This:

interface IBar { bool DoSomeOtherStuff(); } 

class Foo
{
  private IBar _bar;
  public Foo(IBar bar) { _bar = bar; } 

  public string DoStuff()
  {
    return _bar.DoSomeOtherStuff() ? "yes" : "no"
  }
} 

Subtle difference, but this allows you to throw any implementation of IBar (including a mock) into Foo. That allows you to write a test like this:

[Test]
void DoStuff_WhenBarReturnsTrue_ReturnsYes()
{
  MockRepository mocks = new MockRepository();
  IBar bar = mocks.CreateMock<IBar>();
  Foo foo = new Foo(bar);
  Expect.Call(bar.DoSomeOtherStuff()).Returns(true);
  mocks.ReplayAll(); 

  Assert.Equals("yes", foo.DoStuff());
} 

Now even if Bar changes, or Bar doesn't even exist, this test will still pass.

Here's the definition from Martin Fowler of Dependency Injection/Inversion of Control

Unfortunately, real programs are a lot more complicated than just one class depending on another... dependency chains are generally pretty deep, and one class can depend on 5 classes, each of which depends on 2, each of which has a different lifetime... per web request, transient, singleton, etc. It would be quite a pain if you had to instantiate everything like this:
Foo foo = new Foo(new Bar(new Blah(), Yadda.Instance));

Fortunately, it's not terribly complicated to write a Container that can handle all of this for you... so all you do is something like:
Foo foo = container.Resolve<Foo>();

There are several:

And then I went on to mention how long this mail was getting and that I was going to post it to this blog.

by Aaron on Monday, February 12, 2007 1:33:16 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Sunday, February 11, 2007

It amazes me how often developers lack fundamental competencies. Things that every developer should at LEAST know about, somewhat understand and know the capabilities of (i.e. when they're presented with a problem that is easily solvable using something such as... oh, regular expressions, they can at least google the steps to a solution.) What I'm trying to say is:

Understand and make use of regular expressions whenever it is appropriate.

Unfortunately, if you're reading this blog, you probably read several other blogs, so you've already been exposed to regex's. If that's the case, the tip for you is:

Think of more ways you can use regular expressions, understand them even more, oh and tell a friend/coworker who doesn't subscribe to 30 dev blogs and doesn't understand/make use of regular expressions about them.

There are several resources for regular expressions.

Roy Osherove has come up with some pretty killer tools for regex:

What do you do with them? Well, there are tons of uses for them, but here's a quick list of some of the basic things they're used for:

  • Find things - Duh.
  • Replace things - tons of cool stuff you can do here with and without capture groups. Here's a naive example:
    Foo bar
    Blah yadda
    Etc etc
    // search: (\w*) (\w*) replace: \1 \2 = new \1();
    // becomes:
    Foo bar = new Foo();
    Blah yadda = new Blah();
    Etc etc = new Etc();
    
  • Parse things - obviously we love to parse things.
by Aaron on Sunday, February 11, 2007 10:33:10 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Friday, February 09, 2007

I've seen several people say the following when talking about TestDriven.NET: "It's so easy, just right click, and click run tests!" Maybe I'm just too lazy, but what's easy about moving my hand to the mouse, right clicking, finding the appropriate menu item and clicking it?

Bind a key to Run Test(s) and Run Test(s) with Debugger (I use Ctrl+Shift+R and Ctrl+Shift+D)

Just look for TestDriven.NET.RunTests and TestDriven.NET.Debugger in your keyboard settings. I personally use Resharper's Unit Testing feature (except in our 32bit apps on our x64 machines... they're still fixing that bug), but it's all the same. Bind a key to it. Real easy to finish up a test, hit Ctrl+Shift+R, and away you go. No arm movement required!

by Aaron on Friday, February 09, 2007 4:46:23 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [2]  |  Trackback

I've mentioned several tools that we use here, many of which cost money.  We're very lucky here that we can have most of the tools that we want, I know it pains the check writers--"What? Another $300s per dev?!?!" but thankfully they understand that it helps us immensely. I can't help but notice that occasionally people will mention on their blogs that they really like a tool, but that their company won't buy it for them. I think that usually, that shows a bit of shortsightedness in their management.

Developers are expensive and impatient. Good developers are often even more expensive and even more impatient. Tools help developers write more code faster, better, and with less distraction. We'll use ReSharper as an example to try and calculate true cost of the tool.

Let's say a developer's salary is $60,000 per year, that's about $240/day, or $30/hr. Say you build 10 times in an hour, half those times, you accidently typo'd something so you have to rebuild. We'll say fixing/rebuilding costs you 2 minutes per hour. That's 16 minutes per day or $8/day, $40/week, or about $2000/year. All for losing 2 minutes per hour. It's worse than that too, because 2 minutes is a gross exaageration, and that 2 minutes is during a developer's most productive time... the time they actually spend producing.

Now what if, for $300 you could have something that would warn you of impending build errors, so that you could fix them before you actually built? What if it had keybindings (I use Ctrl+Shift+N and Ctrl+Shift+P) to skip to the next error so you can quickly correct it? What if it saved you not only those 2 minutes per hour, but also gave you several other nifty features that saved you time with navigating, formatting, and several other things. Would you spend $300 to save $2000 per year? I would hope the answer is yes. Many other tools share this same productivity boost to cost ratio.

Does this mean developers should have carte blanche for tools? I don't think so. There still needs to be some filter in place, some time for evaluation, and someone who is in tune with both a developer's need for a tool and the company's need not to spend money senselessly, but please, managers, seriously consider requests for tools.

by Aaron on Friday, February 09, 2007 4:33:41 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [2]  |  Trackback
 Friday, February 02, 2007

As promised, here's the plugin I was talking about and the Rhino Mocks templates.

Rhino Mocks Templates - Import these in your Template config.

Plugin - Drop this in your "%PROGRAMFILES%\Developer Express Inc\DXCore for Visual Studio .NET\2.0\Bin\Plugins" Oh, and yeah I know it's named after only one of the commands in there, but I was too lazy after I added the other commands to rename the project. You'll see the new commands in the Template configuration in the Command dropdown.

Plugin Source - I know, not the source you want from us right now and it's pretty ugly, but it's a start, right?

by Aaron on Friday, February 02, 2007 6:00:18 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |  Trackback

I mentioned before that we love templates in CodeRush and that they're incredibly customizable. I wanted to give a few examples of that and share one of the plugins I wrote for it.

We use Ayende's Rhino Mocks quite a bit. We're also lazy, so I came up with a set of templates for it:

  • tfm - Expands to a TestFixture that includes a MockRepository already.
  • scm/sdm - Takes whatever is in your clipboard and expands to this:
    someClass = _mocks.CreateMock<SomeClass>();
  • =cm/=dm - Similar to scm/sdm, but for when you don't have anything in your clipboard
  • mu/mo - Creates a using(_mocks.[Un]ordered()) block
  • mra - ReplayAll
  • mv/mva - Verify or VerifyAll
  • ec - Expect.Call().Return();

One thing I noticed while I was using these is that sometimes I wanted to use them after I'd already written some code that would be in the expansion... for example, say I've already got a class called SomeClassTests but I want to add the TestFixture attribute, add the MockRepository instance variable, etc. Before I had to delete the class and do a tfm on a blank slate. Instead, I spent a few minutes writing a template command plugin that allows you to add an attribute to the class your cursor is in. That enabled me to do what you see in the video below.

Also, say I've already typed the method I was going to set a rhino expectation on. Normally, I'd just have to go to the beginning of the line, type Expect.Call(, go to the end of the line, type the rest. So to solve this, I wrote a few commands: DeleteSemicolon (this one seems a bit buggy w/ the latest CodeRush), GotoBeginningOfLine, and GotoEndOfLine. Now ec, ae, an, ann, etc can all be written to add code around code I've already written as you'll see in the video below.

Bear with me on this video, it's my first attempt at something like this. If anyone can suggest something better than YouTube and a screen recorder for stuff like this that's still free, I'd appreciate it. I don't like being limited to 320x240.

Also, the astute will notice that I'm not running Resharper on this machine. This is my home machine and once again I'm not quite sure about the stability of it (it likes to crash every time I close VS, it breaks some autocomplete scenarios, etc). There are some autocomplete issues in this video, but i think that's just because I had multiple classes named the same thing in this project.

I tried to go slowly so that you can see the templates before I expand them so that hopefully you can get a feel as to how easy it is to write code when you've got templates this powerful. I'm going to upload the source for the plugins as well as my Rhino Mocks templates a bit later today.

by Aaron on Friday, February 02, 2007 10:04:00 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Monday, January 29, 2007

I was trying to think of a way to introduce this post, and I realize that here at Eleutian, we hate strings. We don't hate all strings, it's mostly string literals that we hate. Not even all string literals. But most of them. A good portion of the work we do to make our code more solid involves removing string literals. Anybody familiar with MonoRail has seen lines similar to the following:

RenderView("Home", "Action");
<a href="${siteRoot}/Home/Action.rails">...</a>

${UrlHelper.LinkTo("Home", "Action")}

And so on, see all those string literals that refer to things that aren't really string literals? At first glance, we can get rid of the Controller string by doing something with typeof(HomeController).Name and chopping off the Controller suffix. That'd be an ugly static method call everywhere and still leaves "Action" to be dealt with. We want things to break if HomeController changes names and we want to know where HomeController is referenced.

One of our rules is to turn potential run-time errors into potential compile time errors if at all possible.

It's funny, but the compiler is our first test, and a good one at that. We found ourselves using those controller names, area names, and action names in a variety of situations - redirections, view rendering, generating url's in the views, etc... Anytime I see this I'm annoyed:

Redirect("AnotherAction.rails?parameter=34");

or even worse:

Dictionary query = new Dictionary();
query["parameter"] = 34;
Redirect("AnotherAction.rails", query);

You'll notice that our life would be much easier if methods were first-class objects. They aren't in C# 2.0... or even in 3.0 (without lambda functions) and so this is where we are.

Aaron and I talked things over, complaining on end about how frustrating things were. Our problem boiled down to turning the controller action's into something we could reference, so we decided to try a little code generation magic. We wanted to be able to write code like the following:

MyActions.Action().Render()

Site.AdministrativeArea.Home.Action(24, "Jacob").Redirect()

And so on. In order to do this we have a tool that runs as a pre-build step that does the following:

  • Walks the source tree, parsing *.cs files, looking for controllers. We have to parse source, we can't use reflection because the same source files we're parsing will be using this generated code.
  • Look for public methods (the actions) on the controller.
  • Generates a class (HomeControllerNode) that has a method, with the same prototype as the action, that returns a ControllerActionReference:
public partial class HomeControllerNode {        
  private IControllerServices _services;

  public HomeControllerNode(IControllerServices services) {
    this._services = services;
  }

  public virtual HomeControllerViewsNode Views {
    get {
      return new HomeControllerViewsNode(this._services);
    }
  }

  [System.Diagnostics.DebuggerNonUserCodeAttribute()]
  public virtual ControllerActionReference SomeAction() {
    return this._services.ControllerReferenceFactory.CreateActionReference(this._services.Controller, typeof(HomeController),
      "Home", "Administrative", "SomeAction", new ActionArgument[0]);
  }

  [System.Diagnostics.DebuggerNonUserCodeAttribute()]
  public virtual ControllerActionReference AnotherAction(string name) {
    return this._services.ControllerReferenceFactory.CreateActionReference(this._services.Controller, typeof(HomeController), 
      "Home", "Administrative", "AnotherAction", new ActionArgument[] {
        new ActionArgument("name", typeof(string), name)});    }
  }
}
  • Generates a stub class for area's with properties for each controller in that area (they return HomeControllerNode instances) We introduce a default root area that all top level controllers and other areas are children of:
public partial class AdministrativeAreaNode {        
  private IControllerServices _services;
        
  private HomeControllerNode _home;

  public AdministrativeAreaNode(IControllerServices services) {
    this._services = services;
    this._home = new HomeControllerNode(this._services);
  }
        
  public virtual HomeControllerNode Home {
    get {
      return this._home;
    }
  }
}
  • Walks the Views subdirectory looking for *.brail files mapping them onto their controllers.
  • Generates a class (HomeControllerViewsNode) with methods for each view that return a ControllerViewReference.
public partial class HomeControllerViewsNode {        
  private IControllerServices _services;

  public HomeControllerViewsNode(IControllerServices services) {
    this._services = services;
  }

  [System.Diagnostics.DebuggerNonUserCodeAttribute()]         
  public virtual ControllerViewReference SomeAction {
    get {
      return this._services.ControllerReferenceFactory.CreateViewReference(this._services.Controller, typeof(HomeController),
        "Home", "Administrative", "SomeAction");
    }
  }
}
  • Generates a partial class for the controller class itself with two properties - MyViews and MyActions that return the ControllerNode and ControllerViewsNode instances for that controller.
public partial class HomeController {
  public virtual HomeControllerNode MyActions {
    get {
      return new HomeControllerNode(this.ControllerServices);
    }
  }
        
  public virtual HomeControllerViewsNode MyViews {
    get {
      return new HomeControllerViewsNode(this.ControllerServices);
    }
  }
        
  protected override void PerformGeneratedInitialize() {
    base.PerformGeneratedInitialize();
    this.PropertyBag["MyViews"] = this.MyViews;
    this.PropertyBag["MyActions"] = this.MyActions;
  }
}

In the generated code, we pass a reference to an IControllerServices implementation down through the hierarchy, which provides the ControllerReferenceFactory that creates the ControllerActionReference and ControllerViewReference objects. Our EleutianController class has a property on it - Site, that returns the RootAreaNode so the top of the site can be reached from anywhere. This is also always placed into the controller's PropertyBag, along with MyActions and MyViews. The PerformGeneratedInitialize method, that's called in our base class so that each controller can add it's own MyViews and MyActions, which don't live in the base class.

Our ControllerActionReference class has Redirect and Transfer methods as well as a Url property. So now we can do the following:

<a href="${Site.HomeController.Action(200, true).Url}">...</a>

ControllerViewReference has a Render method that does the appropriate RenderView call on the controller. Now we've accomplished a lot of things:

  1. No more string literals. If we rename something, the build fails. Our views will fail when they're opened and not when links are followed, it is pretty easy to test that a view compiles.
  2. All URLs for redirections/transfers are always well formed and include necessary parameters with proper type checking.
  3. Provided ourselves with Intellisense when building URLs in tests and controllers. (Sexy? Yes.)

Speaking of testing, in our controller tests we have a custom IControllerReferenceFactory that returns mock ControllerActionReference instances (via RhinoMocks) So now redirections, transfers and view renderings are just mocked method calls:

using (_mocks.Unordered())
{
  _controller.MyViews.AnotherView.Render();
}

_mocks.ReplayAll();
_controller.SomeActionThatRendersAnotherView();
_mocks.VerifyAll();

Which is much cleaner than string comparisons on _controller.SelectedViewName, especially if a redirect with parameters is expected in an action. This has simplified our life and given us incredible peace of mind, well worth the time to implement - which was relatively simple. Whew.

by Jacob on Monday, January 29, 2007 6:45:08 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Sunday, January 28, 2007

My team and I are whores when it comes to productivity tools. At the moment I have and use so many in concer it's kind of amusing. I've actually spent a decent amount of time working with the various tool authors to get their tools to play more friendly so that I can use them together. Here's a rundown of some of the tools I use every day:

  • CodeRush with Refactor! Pro
    • I'm pretty sure I couldn't happily write code without this, and I even disable or neglect half the features.
    • I use and customize the templates heavily. They're so customizable its stupid. You can literrally do just about anything, and if you can't do it, you can write a plugin to help you do it and integrate it with any other template. I'll post the set of plugins I wrote for CodeRush later.
    • The refactorings are great and rank high on the visual appeal, discoverability and usability scales.
  • ViEmu (Visual Studio vi/vim emulation)
    • I almost took it upon myself to write this. When I worked at Microsoft, I submitted requests to the Visual Studio team to write this. Jon came to the rescue and implemented the now near-perfect ViEmu and he will forever be my hero.
    • Vim is really so much faster than regular text editing it makes transferring code from your mind to the screen much less of a barrier. If you haven't heard of it, used it, given it a good shot, or even if you haven't fallen in love with it, I'd strongly recommend doing all of those things. Here are some resources to get you started:
    • One quick tip: use Ctrl+[ instead of escape to get out of insert mode, it'll save you at least 15 seconds a day!
  • ReSharper
    • This one's new to me. I've tried it twice in the past and it's only done bad things--crashed, played badly with CodeRush or ViEmu, etc. The latest version however, seems to play fine with everything I have installed, so it's going to stay. Yes, I use CodeRush AND Resharper. I told you I was a productivity tool whore.
    • The biggest feature for me is the Error Highlighting and QuickFixes. Most of the refactorings CodeRush does (often better) but there are a few that are pretty slick.
    • The navigation features are great too. Real fast and real usable, much better than scrolling through our 40 project solution.
by Aaron on Sunday, January 28, 2007 10:54:23 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Saturday, January 27, 2007

Previously I mentioned that we switched to MonoRail for all of our new features. Well, MonoRail doesn't make page localization any easier than Web Forms does.  As a matter of fact, it actually breaks an important part of ASP.NET's localization (something I should probably submit a patch for, heh).  Basically, the DefaultResourceFactory in MonoRail creates IResources that wrap ResourceSets, which will not resolve resources to their parent resource. In other words, if you have Res.ko-KR.resx which defines String1 and Res.resx which defines String1 and String2, then calling GetString on a ResourceSet when your locale is ko-KR with String1 will work, but String2 will fail.  Calling GetString with any other locale, will return the String2 from Res.resx. To get around this, we created an IResourceFactory that returns IResources that wrap ResourceManagers instead of ResourceSets, which are capable of properly traversing the resource tree.  I'll probably submit this code soon. 

Anyways, in order to localize with MonoRail, you still need to create your resx file, add an attribute to your controller to map that resx file to something in your view's property bag, and create, name and initialize each string in your resx file.   

What we did was create a new generator like the one mentioned in my previous post that converts mybrail files to brail files.  All it does is convert this: 

${g.Test: Global Text} <br />
${v.ViewTest: View Text} <br />
${c.ControllerTest: Controller Text} <br />



To this: 

${g.Test} <br />
${c.Localization_ViewTest} <br />
${c.ControllerTest} <br /> 

Now a few things happened here:

  1. A file called Global.resx was created.
  2. A file called Test.resx was created (Test is the name of the controller)
  3. A resource called Test was added to Global.resx and initialized with the value "Global Text"
  4. A resource called ControllerTest was added to the Test.resx and initialized with the value "Controller Text"
  5. A resource called Localization_ViewTest (Localization is the name of the view) was added to Test.resx and initialized with the value "View Text"
  6. v.ViewTest was converted to c.Localization_ViewTest

Essentially, what you end up with, is one resx for your global strings, and one resx per controller, with view specific strings being stored in the controller resx with ViewName_ prefixed to them.  There's still one piece missing to the puzzle, which is how do the views know what g and c are? Do we attribute each controller with a g resource and a c resource? No... that would be too much work for us. Instead what we do is define a new IControllerDescriptorProvider that wraps a DefaultControllerDescriptorProvider and adds appropriate ResourceDescriptors to the Resources collection of the descriptor built by the DefaultControllerDescriptorProvider.   

There is some room for improvement, like gracefully handling the case where you define and give a value for a resource twice in the same file or two seperate files, e.g. ${g.Test: Hi} ${g.Test: Hello}.  In this case, g.Test will be Hello.  In the case where they're in seperate files, it'll depend on which one was saved last (ew).  A decent way around this would be to detect this happening and pop a message box if you try to do this.

by Aaron on Saturday, January 27, 2007 2:05:36 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |  Trackback
One of the things we love to do is remove tedium from code. That subject will probably be the topic of this post, and many of our posts in the future I'm sure, as we've done a lot of things in that department.  ASP.NET is lacking in a number of areas, as I'm sure most of you know.  It's "strong point" is supposed to be its declarative nature--but that often leads to very difficult to test pages.  Not only that, but it's declarative syntax leaves much to be desired.  My primary complaint is with its verbosity.  There's nothing simple about ASP.NET syntax.  Here's an example:

<asp:HyperLink runat="server" ID="_lnkForgot" NavigateUrl='~/ForgotPassword.aspx' Text='<%$ Resources: PageStrings, Login_lnkForgot_Text %>' />

Now, let's complain a little.  First, we've got that runat="server" tag.  Who's idea was that?  I mean, I understand why it's there, but how often are you going to want <asp:Anything> to be sent to the client in that form?  Wouldn't it make more sense to just ASSUME that <anything:Anything> was runat="server" and just allow us to specify runat="client" and strip that attribute when rendering if we really want to send that to the client?

Next, we've got the ID tag.  I don't really have a problem with that, it's implemented just fine.  Then there's the NavigateUrl.  Notice the ~.  I love that.  It's something that ASP.NET did right. It makes it a breeze to make pages location agnostic... unless of course you want to use a non-asp control.  Then you've got to use this lovely syntax:

<img src='<%= ResolveClientUrl("~/Images/img.gif") %>' />

Ah yes, that just screams beautiful.  Now would it have really been that difficult to replace ~ with ApplicationPath and let ~~ by as ~ in attributes? 

OK, let's move on to my favorite subject--Globalization/Localization.  ASP.NET 2.0 has come a long way on this front.  It's much easier to localize your pages the way ASP.NET 2.0 wants you to than the way ASP.NET 1.0 wanted you to, especially with the new meta:resourcekey attribute and automatic generation of resources.  Unfortunately, it's still not as simple and elegant as it could be.  If you don't want to use the meta:resource attribute (because you have a shared string) then you have to use the lovely Resources: syntax seen up above, and you have to manually create your resx file, and manually name and fill in your default locale value.  If you want to localize a literal, you get to use wonderfully verbose <asp:Localize> control. 

Another complaint that isn't demonstrated in the example is with Databinding.  The databinding syntax is pretty clean, I don't have any complaints about that, but its implementation is a bit poor, mainly because of its use of uncached reflection.  It's been a while since I benchmarked it, but if my memory serves me (and often it doesn't) then it took about 30% longer to databind using the reflexive <%# Field %> syntax than it did to use <%# ((Class)Container.DataItem).Field %>.  Who wants to write all of the latter, especially with autocomplete in aspx pages being flaky at best?

So how could ASP.NET be less verbose and more elegant? How could WE make it better without being able to extend the many internal and sealed classes that make up the webforms engine?

Preprocessing!

Here's an overview of what you do.
  1. Create a generator that extends Microsoft.CustomTool.BaseCodeGeneratorWithSite for .aspx files and do your preprocessing here.
  2. Create a wizard that extends Microsoft.VisualStudio.TemplateWizard.IWizard to set up a file hiearchy like this:
    • Page.myaspx
      • Page.aspx
        • Page.aspx.cs
        • Page.aspx.designer.cs
  3. Create an ItemTemplate for your item that contains these files and sets your custom tool to the generator you created in step one.
  4. Add a new myaspx to your project and make sure you don't ever modify the aspx directly (this takes some getting used to)
So what are some things you could filter/generate/preprocess?
  • Add runat="server" tags to all <anything:anything> nodes that don't have it.
  • Replace "~/blah" with an appropriate call to ResolveClientUrl
  • Do some localization magic

<asp:HyperLink ID="_lnkForgot" NavigateUrl='~/ForgotPassword.aspx' Text="$:Forgot your Username or Password?" />

          This is actually the markup that we wrote to generate the markup at the beginning of this post.  See the $:?  That tells the generator to create a resource in PageStrings.resx with the format Page_ID_Property that has the value that appears after the $:.  You never need to touch that resx file.  You can just write your markup, define your strings, and not be interrupted, or even have to name your strings.  If you want to name your strings, say something global.  Just do "$Name: This is a string" and if you want to use it later just use "$Name".
  • Make databinding strongly typed.  This requires a bit of help, as you can't easily infer the type being bound by just inspecting the source.  Our solution was to add a DataType="Class" attribute to whatever the repeating control was.  For example:


    <asp:Repeater ID="repeater" DataType="BoundClass">
      <ItemTemplate>
        <asp:Label ID="textBox" Text='<%#@Name%>' />
      </ItemTemplate>
    </asp:Repeater>

Notice the @ in the <%#%> tag.  That gets replaced with ((BoundClass)Container.DataItem), so you can do things like <%# String.Format("{0} {1}", @FirstName, @LastName) %>

So that's how we made ASP.NET more manageable.  Now, there are still several issues with ASP.NET WebForms that caused us to eventually switch to MonoRail, which also benefits from preprocessing, but I'll post on that later.

by Aaron on Saturday, January 27, 2007 8:47:03 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |  Trackback