Setting Up AutoMapper For Use From A Container

I like getting all my service from the container and I like using AutoMapper. So I added the AutoMapper to the container, a WindsorContainer in this case.

The main interface is IMappingEngine, which is implemented by MappingEngine which also implements IMappingEngineRunner. This contains a getter to an IConfiguration interface which is also an IConfigurationExpression. So to replace Mapper you need an instance of IMappingEngine and then you can configure the engine as follows:

public CustomMapper(IMappingEngine engine)


    engine = engine;</p>


    var runner = </em>engine as IMappingEngineRunner;

    if (runner == null)



    var configuration = runner.Configuration as IConfigurationExpression;

    if (configuration == null)



    configuration.CreateMap<IApplication, B.Application>();



Next setting up the container, the MappingEngine needs an IConfiguration, the Configuration needs some IObjectMapper instances.

private static void RegisterMappingEngine()



                            .FromAssembly(typeof (IObjectMapper).Assembly)

                            .Configure(configurer => configurer.Named(configurer.ServiceType.Name))

                            .Configure(configurer => configurer.LifeStyle.Transient));




















These are all set as Transient because each CustomMapper can be Singleton and I don’t want the mappings to over lap between the CustomMappers.


Testing Log4Net Output

We have a custom logging framework setup which is using log4net under the covers. When doing that the ILogger should be used, not the ILog. The ILogger sets up the correct Class information.

Below is some code for testing the output from log4net, this code is just using log4net to write the message, which is not valuable as a test, but when the logging call is replaced with a custom framework you can make sure you’re getting what you expect in your log events.

private MemoryAppender appender;</p>

private LoggingEvent </em>event;



public void Context()



    // Using log4net here, but should be replace with a custom logging class

    // which calls ILogger.Log under it.

    LogManager.GetLogger(GetType()).Warn("my test desc.", new Exception("my test exception."));

    </em>event = appender.GetEvents()[0];</p>




public void SetupLog4NetMemoryAppender()


    </em>appender = new MemoryAppender();

    appender.Name = "Unit Testing Appender";</p>

    </em>appender.Layout = new log4net.Layout.PatternLayout("%date{dd-MM-yyyy HH:mm:ss,fff} %5level [%2thread] %message (%logger{1}:%line)%n");

    appender.Threshold = Level.All;</p>



    Logger root = ((Hierarchy) LogManager.GetRepository()).Root;


    root.Repository.Configured = true;




public void RemoveLog4NetMemoryAppender()


    Logger root = ((Hierarchy)LogManager.GetRepository()).Root;


    root.Repository.Configured = true;




public void Should_have_When_logging_type_in_log()


    var data = _event.GetLoggingEventData();

    var info = data.LocationInfo;





BTW, the code highlighting was done using the Copy As HTML plug in from here.


TDD Reduces Defects!

I just read Realizing quality improvement through test driven development. It’s a summary of 4 TDD teams at IBM and Microsoft compared to similar non TDD teams. With all the variables in any software project it’s hard to draw a hard conclusion, but this shows definite trends toward fewer defects minimal increased time, and I’d argue less time, because the reduced number of defects. I think the time measurement here is really subjective as it’s based on the judgment of the project managers. Regardless, I think these types of studies help prove the importance of good software practices. 

Open VS2005 Project Files in VS2008

Here’s an interesting tip from a co worker. If you need to work on a 2005 project in both 2005 and 2008 you can add the following to the Project element: ToolsVersion=”3.5” Resulting in:

Making Sure Your Container Contains Your Basic Services

I’m working on creating some of the base code for our systems. One of the things we’re doing is moving to using IoC containers for our projects. These projects are all internal and as such they will be sharing some base functionality, like logging and configuration. To that end I wanted to create an implementation of WindsorContainer which has these services and facilities already setup. What I found was the IWindsorInstaller class. Using that in the constructor of my NewWindsorContainer I can call Install with any number of these installers, like:

public class MyContainer : WindsorContainer

<span class="kwrd">public</span> MyContainer(<span class="kwrd">string</span> settingName)
    Install(<span class="kwrd">new</span> InstrumentationInstaller());


The Installer interface is just one method Install which takes a container and a configuration store. This makes these installer classes easy to implement and test. Below we just make sure the logging facility is registered.

public class InstrumentationInstaller :IWindsorInstaller
    public void Install(IWindsorContainer container, IConfigurationStore store)

And the test code:     

public void Install_Expect_Facility_Installed_Can_Resolve_Logger()
    var installer = new InstrumentationInstaller();
    var c = new WindsorContainer();
    installer.Install(c, null);
    var logger = c.Resolve<IMyLogger>();

I was initially going to create a facility to load our base services, but I like this approach more because it's simpler and the installer classes follow Single Responsibility Principle.

What Tools I&rsquo;m Currently Using

I setup a new machine this week, the machine was imaged with some of the obvious MS stuff, VS, Office, etc. I thought I’d note some of the apps I install right away. Things I know I’ll need, most development related, some system related, some others.

FireFox: web browser and associated plug-ins
Download Them All
Smart Bookmarks
No Script
SysInternals Suite: a ton of tools for windows to help see what’s going on in the OS.
7Zip: open source zip utility.
Powershell: upgraded command line for windows.

QueryExPlus: Light weight query analyzer.
Subversion: SCM used by a lot of projects.
Tortoise SVN: Explorer integration with Subversion.
NUnit: Unit testing framework.
MbUnit: A nother unit testing framework.
Fiddler: HTTP inspector.
ReSharper: Coding optimizer I guess, not sure what it’s called but I can’t really code without it.
Notepad++: Tabbed notepad with syntax highlighting and a bunch of other text tools.
Nant: Build tool.
RhinoMocks: My mocking framework of choice.
Patch for RhinoMocks: Need this if your using .net 3.5.
Reflector: .Net decompiler.

Pidgin: Multi-service instant messaging application.
Launchy: Application launcher. Apparently has problems on some x64 machines, including my new machine. I’m really missing this.
FARR: Find and Run Robot, trying this as a Launchy replacement.
Windows Live Writer, but it doesn’t install on Server 2003, WTF?

I’m sure I’ve missed some, but these are at least the essentials that I use almost daily.

Any others I should checkout?

More Effective C# Notes: Generics

I’ve been reading the More Effective C# book by Bill Wagner. I’m going to blog some of my notes and thoughts on the book. If you find some of this stuff useful you will want to pick up a copy of the book.

Use the least amount of constraints on type parameters as possible. I’ve run into this, and besides limiting the usefulness of your class, in many cases you need to implement an interface or add a default constructor to get classes to compile. And ultimately your generic class ends up not being very generic.

In order to help achieve the above, you can use methods or delegates to enforce a specific needed operation. Whatever constraint you were going to have you could create a delegate that needs to be passed in and remove the constraint.

If you need to create new instances of the type parameter, you need to make sure you dispose of it correctly if it implements IDisposable. If it’s created as an instance member your generic classes needs to implement IDisposable. This simple pattern can be used for method scoped instances.

T instance = new T();
using (instance as IDisposable)</p>

instance.MethodCall();<style type="text/css">.csharpcode, .csharpcode pre


font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/

.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt

background-color: #f4f4f4;
width: 100%;
margin: 0em;

.csharpcode .lnum { color: #606060; }

Remember that the type parameter is always going to be the best match in an overloaded method search. As, such you can use run-time type checking to optimize for performance. I would not bother doing this until you know that it’s a performance issue. Or unless your making a closed source framework.

Use generic methods unless the type parameter is going to be an instance field. This makes the generic class easier to use as you don’t need a new class for each different type parameter being used. Also these types of methods lend themselves to becoming extension methods.

Again these are just some of my notes, the book, like the previous one, is worth a full read.

Intro To Unit Testing: 2 of n

Where do tests fit into my project and process?

There are a few ways to structure unit tests. Two of the most common seem to be one to one assemblies and same assembly. One to one assemblies meaning one test assembly for each assembly being tested. This approach has the benefit of easily removing the test assemblies before releasing code to production. It also allows testing release built code with out an extra build cycle like the following method requires. One drawback is that internal classes are harder to test.

The second structure, same assembly, has the TestFixtures in the assembly being tested. The main challenge with this is creating builds without the tests. I’ve seen this handled two way, first by the build script excluding all files under a Tests directory. And secondly, using compiler directives like #if TEST around the test code. Both have draws backs but the main one being two complies one to test and one to release. The main advantages are access to internal classes and fewer assemblies in a solution.

Which is right? As with many things, it depends.

Unit tests generally fit into the development in two key places, three for TDD. The first is before any code check-in the unit tests should be run and pass. Secondly, the continuous integration system should run the tests and fail the build if the tests fail. Third, if developing using TDD you would run the tests almost constantly while developing and refactoring.

Intro To Unit Testing: 1 of n

What is UnitTesting? What are UnitTests?

UnitTesting is testing a unit of functionality with other code.

UnitTests, in the context of c#, are simply classes with attributes. Usually they are called test fixtures which contain test cases. Test cases are just methods with a Test attribute on them. UnitTests are mostly concerned with testing interaction between classes or logical outcomes. Interaction tests test for the correct interaction between classes, usually with Stub or Mock objects. An interaction test might test for a web service call with a specific message. Logical tests test that the given business logic is working was expected. For example making sure a filter on insurance applications actually filters out applications. Both of these test types will use Assertions to make sure what was expected to happen did happen. An Assertion is really just a logical check that throws an exception if it’s false. If a test has Assert.AreEqual(expected, actual) and expected does not equal actual it will throw an exception, with details, to fail the test.
Here is a super simple test to make sure the test framework is working correctly.

using MbUnit.Framework;
namespace IntroToUnitTests.Tests

<span class="kwrd">public</span> <span class="kwrd">class</span> TestFixture
    <span class="kwrd">public</span> <span class="kwrd">void</span> Is_The_Test_Framework_Working()
        Assert.IsTrue(<span class="kwrd">true</span>);


Why would I want to write tests? What are the advantages?

  • Unit tests allow code to be changed and refactored without worrying about breaking the expected functionality.
  • Unit tests promote better design and cleaner, simpler code.
  • Unit tests help document the intent of code.
  • Unit tests help make sure bugs do not come back to life.
  • Unit tests help reduce time in the debugger.

Why wouldn't I want to write tests? What are the challenges?

Unit testing the UI is typically a very challenging. WebForms usually make unit testing really hard or impossible. This is partly because recreating the ASP.Net life cycle is not possible. And partly because it's really easy to mix business concerns with UI concerns.

Unit testing databases is challenging on two fronts. First having a way to create a clean DB for testing. Secondly, keeping the test time reasonable.

Legacy Code, which is often considered code without tests, is challenging because before you change legacy code it needs tests, but often you need to change the code to be more testable.

Who writes and maintains these tests?

Developers are responsible for writing, maintaining, and running unit tests. The build/release process should also be responsible for running and failing if any of the unit tests fail.

I hope this provides basic high level overview of unit testing, and idea of what value they might add and what challenges they might present. More detailed posts will be coming soon.

Monitor Twitter and Respond with!

babblewatch-logo-final-med-whiteI’m looking to get some early feedback on a side project of mine, It’s a tool for monitoring Twitter and Responding. It’s main goal is to help build and maintain your companies brand reputation. It’s in very early stage development, but I wanted to get some feedback so please give it a try;

Tips for using Silverlight with Monorail (or embedded)

Today I worked on getting a Silverlight chart embedded in my monorail application. I learned a few things.

You need to have a Silverlight application project someplace in order to create the XAP file. This is what will ultimately get used in your view.

Since it’s really running client side, the XAP files are included in your other projects like other client site stuff, that is just manually copied into a directory there.

Databinding to XML doesn’t seem to work, I think I must be doing something wrong, but I finally ended up using Linq to transfer the data into objects and bind to those. Like this:

series.ItemsSource = from n in descendants</p>

                 select <span class="kwrd">new</span> Data
                                Date = n.Attribute(<span class="str">"Date"</span>).Value,
                                Count = <span class="kwrd">int</span>.Parse(n.Attribute(<span class="str">"Responded"</span>).Value)

series.IndependentValueBinding = new Binding(“Date”) { Mode = BindingMode.OneWay };
series.DependentValueBinding = new Binding(“Count”) { Mode = BindingMode.OneWay };

public class Data

<span class="kwrd">public</span> <span class="kwrd">string</span> Date { get; set; }
<span class="kwrd">public</span> <span class="kwrd">int</span> Count { get; set; }


In your View you use embed the XAP file using the object tag like:

<object data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%">
    <param name="source" value="/assets/Charts.xap"/>
    <param name="background" value="white" />
    <param name="minRuntimeVersion" value="2.0.31005.0" />
    <param name="autoUpgrade" value="true" />
    <a href="" style="text-decoration: none;">
    <img src="" alt="Get Microsoft Silverlight" style="border-style: none"/>

This is really my first time checking out Silverlight, so I'm sure I'm missing a lot and have a ton left to learn. There is a bunch of great info on the Silverlight site.

Selecting Aggregate Data With Castle.ActiveRecord

Lets say your using Castle’s ActiveRecord and you have a complex query to aggregate some data, but you want that query to return the data in a typed class, just not one that NHibernate or ActiveRecord know about…

Here’s what I ended up doing. Creating the SQL query then using the HqlBasedQuery class. There are two important details regarding this, first the query needs to name the columns using the SQL as keyword and setting the Scalar definition. Second, you need to set a transformer using the SetResultTransformer method. Luckily, NHibernate includes a class that will map named scalars to matching properties or fields. More about that here, in section 14.1.5.

Here’s the code:

var sql = @“
select convert(varchar, published, 101) as [Date],
count(state) as [Total],
sum(case when state = 2 then 1 else 0 end) as [Responded]
from notices n
inner join sources s on n.sourceid = and s.userid = :userid
where published >= dateadd(day, -7, getdate())
group by convert(varchar, published, 101)”;</p>

HqlBasedQuery q = new HqlBasedQuery(typeof (Notice), QueryLanguage.Sql, sql); q.AddSqlScalarDefinition(NHibernateUtil.String, “Date”); q.AddSqlScalarDefinition(NHibernateUtil.Int32, “Total”); q.AddSqlScalarDefinition(NHibernateUtil.Int32, “Responded”); q.SetParameter(“userid”, Id); q.SetResultTransformer(Transformers.AliasToBean(typeof(NoticeCount)));

var results = ActiveRecordMediator.ExecuteQuery(q) as ArrayList; if (results == null)

<span class="kwrd">return</span> <span class="kwrd">new</span> NoticeCounts();

var counts = results.ToArray(typeof (NoticeCount)) as NoticeCount[];
return new NoticeCounts { Counts = counts };

IDictionary and the Brail View Engine

I spent a lot of time trying to figure out that the brail engine assumes IList on indexed properties. If you have a IDictionary you need to use the get_Item method like:





Changes Needed for Castle.MonoRail to use jQuery

To get jQuery as the JS library for monorail I need to do the following:

  1. Get the JS files from jQuery and jQuery.Validation, save those to /Content/Js/ (or where ever).

  2. Implement the IMonoRailContainerEvents and IMonoRailConfigurationEvents interfaces on my GlobalApplication.cs file.

  3. In the Initialized method add:

IAjaxProxyGenerator ajaxProxyGenerator = new JQueryAjaxProxyGenerator();
container.ServiceInitializer.Initialize(ajaxProxyGenerator, container);
container.AjaxProxyGenerator = ajaxProxyGenerator;
  1. In the Configure method add:
configuration.JSGeneratorConfiguration.AddLibrary("jquery-1.2.1", typeof(JQueryGenerator))
  1. In the layout file reference the JS files like:
<script language="javascript" type="text/javascript" src="${siteRoot}/Content/Js/jquery-1.2.6.min.js"></script>
<script language="javascript" type="text/javascript" src="${siteRoot}/Content/Js/jquery.validate.min.js"></script>


  1. Use the Castle trunk source.


Publishing video as FLV using a SWF Player

This task turned out to be much more complicated then I would have expected. First just creating the video took a fair amount of time, trial, and error. I used CamStudio to capture the screen video and then the trial of Video Editor 8.

After that was done I ended up using Any Video Converter to convert the file to FLV. Then I needed a SWF player to embed in the web page. I looked at a couple of options, but ended up with OS Flv. Once that was done and working, I ran into one last issue, resolved here. IIS doesn’t serve FLV files by default, so I needed to add the mime type.

Awesome Child Bike Seat – iBert [off topic]

This is off topic. We recently started using an iBert child seat to take our son on bike rides with us. It’s a front mounted seat, which makes it really easy to control the bike, plus the child gets a better view. Our son loves it and even puts up with a helmet on it.  You need to make sure it will mount on your bike, mountain and road bikes may not work. It requires an inch or two of open stem space on the neck of the bike. I think most hybrid bikes will work, but make sure you double check. We bought it from amazon and so far we’re all loving it!

Get the selected radio button value using prototype

Assuming you have a set of radio buttons with the same id, you can use the following to get the value of the selected/checked button.

var value = null;
$$(‘#plan_plan’).each( function(i) {</p>

<span class="kwrd">if</span> ($F(i)) { value = $F(i); }

} );

Not using Linq to it’s fullest can produce the worst of both worlds

I’m parsing some XML and need to do one thing if there are a group of XML elements with the same name and another thing if just one element with a given name.

Here my first attempt, yuck!

XElement on = null;
foreach (XElement element in elements.OrderBy(x => x.Name.LocalName))

var current = element;
<span class="kwrd">if</span> (elements.Count(x => current.Name.LocalName.Equals(x.Name.LocalName)) > 1)
    <span class="kwrd">if</span> (on == <span class="kwrd">null</span> || !current.Name.LocalName.Equals(on.Name.LocalName))
        <span class="kwrd">yield</span> <span class="kwrd">return</span> <span class="kwrd">new</span> JProperty(current.Name.LocalName,
                                   <span class="kwrd">new</span> JArray(
                                    elements.Where(x => current.Name.LocalName.Equals(x.Name.LocalName)).Select(
                                        x => <span class="kwrd">new</span> JValue(x.Value))));
        on = current;
<span class="kwrd">else</span>
    <span class="kwrd">yield</span> <span class="kwrd">return</span> FromElement(element);


That's really bad, Linq is probably making the code worse. After some refactoring...

foreach (var group in from e in elements group e by e.Name.LocalName)
    if (group.Count() > 1)
        yield return new JProperty(group.First().Name.LocalName,
            new JArray(from x in @group select new JValue(x.Value)));
        yield return FromElement(group.First());

The code here is easier to read shorter and clearer. Much better.

What’s Needed for Castle Validation To Work

Make sure the view knows what to validate

The object or object type to be validated must be sent to the view.

PropertyBag["signuptype"] = typeof(SignupInfo);
// or
PropertyBag["signup"] = new SignupInfo;

Remember to use Flash if redirecting, like in the case of a validation error on the server side.

Make sure the JS files are included

Either just include the files with a script tags:

<script type="text/javascript" src="${siteroot}/Content/js/prototype.js"></script>
<script type="text/javascript" src="${siteroot}/Content/js/scriptaculous.js"></script>
<script type="text/javascript" src="${siteroot}/Content/js/formhelper.js"></script>
<script type="text/javascript" src="${siteroot}/Content/js/behaviour.js"></script>

Or using the InstallScripts method of the respective helpers. With the brail view engine it would be:


Make sure to use the FormHelper

Make sure you use the FormHelper for at least the start and end form tags, but it should be used for the fields too if you want the values auto populated on an exception.

${Form.FormTag({@area:'', @controller:'WaitingList', @action:'AddToList', @immediate:'true', @useLabels:'true'})}
<?brail OutputSubView('/shared/errorsummary') ?>
<div class="formrow">
${Form.LabelFor("signup.Name", "Name:")}
${Form.TextField("signup.Name", {@style: 'width: 300px;'})} <br/>
<div class="formrow">
${Form.LabelFor("signup.Email", "Email Address:")}
${Form.TextField("signup.Email", {@style: 'width: 300px;'})} <br/>
<div class="formrow">
${Form.Submit("Add Me")}

The immediate and useLabels are optional arguments for the validation JS.

Make sure your controller class inherits  SmartDispatchController

This will already be the case most of the time, but SmartDispatchController knows to validate the bound objects.

public class WaitingListController : SmartDispatcherController

Make sure you have validation attributes on your Model

There are a lot of build in validation attributes and a way to add custom attributes. There is also a way to bind the validation to a model without attributes, but I’m not going to cover that here.

public class EmailInfo
    public string Name { get; set; }

    [ValidateNonEmpty, ValidateEmail]
    public string Email { get; set; }

The Validation Attributes are in the Castle.Components.Validator namespace.

Make sure you check validation on your Action

You will most likely already have a DataBind attribute on your model parameter, but you will need to add Validate = true. Within you action, check if you have validation errors and redirect to the form if you do. Be sure to Flash the model instance and the error summary. This is important as the client might have disabled javascript and because some validators are server side only.

public void AddToList([DataBind("signup", Validate=true)] EmailInfo emailInfo)
    if (HasValidationError(emailInfo))
        Flash["signup"] = emailInfo;
        Flash["summary"] = GetErrorSummary(emailInfo);

    EmailAddress address = new EmailAddress(emailInfo.Name, emailInfo.Email);

    Redirect("waitinglist", "onlist");

Unit Testing

Unit testing is obviously not required for this to work. If you are testing and using the TestSupport classes with BaseControllerTest you will need to add the following before calling your action to test an invalid model instance. There may be a better way to test this, but here’s what I did.

public void Add_To_List_Expect_Validate_Fail_Redirect()
    EmailInfo info = new EmailInfo();

    if (!_controller.Validator.IsValid(info))
        _controller.PopulateValidatorErrorSummary(info, _controller.Validator.GetErrorSummary(info));
    Assert.That(Response.RedirectedTo, Is.EqualTo("/Controller/index.castle"));

There’s a lot covered here, but really it’s not much more code then what you’d have without validation and you get a robust validation framework with both client and server side validation.

Getting dasBlog and Castle.MonoRail to work together

Ok, it’s not really about getting dasBlog to work with MonoRail, but really remembering that web.config has a cascading effect on sub applications in IIS. I had two bugs today the first of which took a long time to find, but both related to the root web.config having entries that caused problems in the sub application (dasBlog in this case).

The first issue, for some reason I had the domain attribute in the forms authentication section set to / in the root web.config. Not sure why it was set like that, but apparently MonoRail overrides the domain value when setting cookies, while dasBlog doesn’t. This has the effect of not being able to log in to dasBlog, but not producing any errors, and in fact it says the login was a success. However, no cookie is issued. Removing the domain attribute fixed this problem.

The second issue was regarding httpModules, in this case MonoRail’s routing module. This caused problems by requiring Castle dll’s be copied to the blogs bin directory, but more importantly it caused the FreeTextBox control to break and the blogging.aspx page to break because in these cases the files didn’t exists on disk and so (I think) the routing engine kicked in, though not setup on this application and missing dependencies, it failed. The fix for this, also easy and strait forward, is to remove the routing module from the blog application. To do that, you can just add a remove tag to the httpModules config like:

  <remove name="routingEx"/></httpModules>

Both issues were simple enough, but not very obvious at the time.

Thoughts about 3rd party libraries and a projects build

One thing I’m going start doing when starting a new project is to initially create a directory for compiled 3rd party libraries in the new projects root. Maybe one for debug builds and one for release builds. Doing this will save a lot of time later, one is always created later in the projects lifecycle, but then it requires resetting all the references in the build system and the project files. This is important for building the project on a different box anyway (like for continuous integration). I think this gets really important when working off an OSS projects trunk source code so the working build always has the correct OSS build.

My Startup Life [Review]


I just finished reading My Startup Life by Ben Casnocha. It an interesting and enjoyable read. It’s a mix of his story and insights and learnings from along the way. The insights and learnings are in side bars, which I found distracting. I might have enjoyed the story first and then then insights second. But I think a little more detail in the story and less or no sidebars would have been better. Anyway, I’d recommend it for anyone with an entrepreneurial streak. I’d give it 3/5 for a great story, good content and an okay mixing of the two.

Brutalist Framework