markhneedham/blog huggingface dataset:
ASP.NET MVC: Reducing duplication for partial models
Date: 2009-03-03 23:55:36

One of the problems we can encounter when using http://www.markhneedham.com/blog/2009/02/21/aspnet-mvc-driving-partials-by-convention/[partials] throughout our views is how we should create the model needed for those partials.

The approach that we have been following is to have the partial/child model on the parent model and then just call the appropriate method where we create the partial.

e.g.

[source,csharp]
----

public class ParentModel
{
	public string Property1 {get;set;}
	public ChildModel ChildModel { get;set; }
}

public class ChildModel
{
	public string Property1 {get;set;}
}
----

We have sometimes run into the problem where the data in the ChildModel is being populated from the ParentModel (due to it also being needed there) leading to data duplication.

[source,csharp]
----

ParentModel parentModel = new ParentModel();
parentModel.Property1 = "value1"
parentModel.ChildModel = new ChildModel
						{	
							Property1 = parentModel.Property1;
					  	}
----

Now the other problem with this is that we are relying on line 2 being executed before line 3 - we have created an order dependency in our code for no gain!

We are following a convention of having minimal logic in our views which means that we want to avoid creating the ChildModel in our view, meaning that we now have a problem to solve.

A cool approach which http://twitter.com/davcamer[Dave] introduced me to makes use of the http://www.dotnetheaven.com/Uploadfile/rajeshvs/AdapterPatternInCS02012006034414AM/AdapterPatternInCS.aspx[Adaptor pattern] to solve the problem.

We would adjust the ParentModel like so:

[source,csharp]
----

public class ParentModel
{
	public IChildModel { get { return new ChildModelAdaptor(this); }}
}
----

We then just delegate the calls to the ParentModel and drive the ChildModel to become an interface since it no longer needs to be a class.

[source,csharp]
----

public interface ChildModel
{
	string Property1 {get;set;}
}
----

[source,csharp]
----

public class ChildModelAdaptor : IChildModel
{
	private ParentModel parentModel;

	public ChildModelAdaptor(ParentModel parentModel)
	{
		this.parentModel = parentModel;
	}

	public string Property1
	{		
		get { return parentModel.Property1; }
	}
}
----

If the data on the ChildModel is completely independent of the ParentModel then I would probably just create the model like before.

If the data on the ChildModel is a combination of data from the ParentModel and other classes then I would pass in those other classes in the constructor of the adaptor.
Coding: Good Citizens
Date: 2009-03-04 23:58:48

I was recently reading Brad Cross' recent post about creating objects which are http://bradfordcross.blogspot.com/2009/02/good-citizens.html[Good Citizens] in code and he certainly nails one aspect of this with regards to ensuring that our *objects are in a usable state post construction*.

____
In OO design, an object is considered to be a good citizen if it is in a fully composed and usable state post-construction. This means that once the constructor exits, the class is ready to use - without the need to call additional setters or init() methods.
____

This is the main reason I find the http://www.markhneedham.com/blog/2009/02/16/c-object-initializer-and-the-horse-shoe/[C# object initializer syntax] such a nightmare - it gets blatantly abused and you end up with half constructed objects all around the code base and you're never sure where your next Null Object Exception is going to come from so you pepper the code with null checks to try and avoid them.

Apart from this though I think another important aspect of an object being a good citizen is that *when it makes use of other objects it does so in the way that object would expect it to*.

For example I wouldn't expect object A to call object B and pass in null as one of its parameters. When we're not on the edges of our http://domaindrivendesign.org/discussion/messageboardarchive/BoundedContext.html[bounded context] then I think it's reasonable for objects to trust each other and assume that they will call each other in a non-evil way.

In a brief discussion with http://twitter.com/davcamer[Dave] about this he suggested that we might have different expectations of what makes a good citizen *depending on the context* in which we are using them.

For example, in our production code a good citizen wouldn't try to break encapsulation of another object by using reflection - it should tell the object what to do rather than taking data our of it.

In test code though it may be perfectly acceptable for us to make use of reflection to check the state of an object after we have performed an operation on it.

Dan North and Aslak Hellesoy have written up http://docs.codehaus.org/display/PICO/Good+Citizen[a more stringent list of what makes a good citizen] on the Pico Container website - I agree with the majority of them although I'd question whether every object should have an equals method on it unless its' actually used and I'm still undecided about whether objects should fail on construction if passed bad data.

Either way, it's definitely good to consider these types of things when writing code.
F#: Forcing type to unit for Assert.ShouldThrow in XUnit.NET
Date: 2009-03-28 02:35:27

I've started playing around with F# again and decided to try and create some unit tests around the examples I'm following from http://manning.com/petricek/[Real World Functional Programming]. After reading http://weblogs.asp.net/podwysocki/archive/2008/06/04/language-oriented-programming-and-functional-unit-testing-in-f.aspx[Matt Podwysocki's blog post about XUnit.NET] I decided that would probably be the best framework for me to use.

The example I'm writing tests around is:

[source,ocaml]
----

let convertDataRow(str:string) =
    let cells = List.of_seq(str.Split([|','|]))
    match cells with
    | label::value::_ ->
        let numericValue = Int32.Parse(value)
        (label, numericValue)
    | _ -> failwith "Incorrect data format!"
----

I started driving that out from scratch but ran into a problem trying to assert the error case when an invalid data format is passed in.

The method to use for the assertion is 'Assert.ShouldThrow' which takes in an Assert.ThrowsDelegate which takes in an argument of type unit\->unit.

The code that I really want to write is this:

[source,ocaml]
----

[<Fact>]
let should_throw_exception_given_invalid_data () =
    let methodCall = convertDataRow "blah"
    Assert.Throws<FailureException>(Assert.ThrowsDelegate(methodCall))
----

which doesn't compile giving the error 'This expression has type string*int but is used here with type unit\->unit'.

I got around the first unit by wrapping the convertDateRow in a function which takes in no arguments but the output was proving tricky. I realised that putting a call to printfn would solve that problem, leaving me with this truly hacky solution:

[source,ocaml]
----

[<Fact>]
let should_throw_exception_given_invalid_data () =
    let methodCall = fun () -> (convertDataRow "blah";printfn "")
    Assert.Throws<FailureException>(Assert.ThrowsDelegate(methodCall))
----

Truly horrible and luckily there is a way to http://cs.hubfs.net/forums/thread/3157.aspx[not do that printfn which I came across on the hubfs forum]:

[source,ocaml]
----

[<Fact>]
let should_throw_exception_given_invalid_data () =
    let methodCall = (fun () -> convertDataRow "blah" |> ignore)
    Assert.Throws<FailureException>(Assert.ThrowsDelegate(methodCall))
----

The ignore function provides a neat way of ignoring the passed value i.e. it throws away the result of computations.
DDD: Repository pattern
Date: 2009-03-10 10:31:27

The http://domaindrivendesign.org/discussion/messageboardarchive/Repositories.html[Repository] pattern from Domain Driven Design is one of the cleanest ways I have come across for separating our domain objects from their persistence mechanism.

Until recently every single implementation I had seen of this pattern involved directly using a database as the persistence mechanism with the repository acting as a wrapper around the Object Relational Mapper (Hibernate/NHibernate).

Now I consider there to be two parts to the repository pattern:

. The abstraction of the persistence mechanism away from our other code by virtue of the creation of repositories which can be interacted with to save, update and load domain objects.
. The need for these repositories to only be available for http://domaindrivendesign.org/discussion/messageboardarchive/Aggregates.html[aggregate] roots in our domain and not for every single domain object. Access to other objects would be via the aggregate root which we could retrieve from one of the repositories.

This pattern can also be useful when we retrieve and store data via services which we have been doing recently. Of course eventually the data is stored in a database but much further up stream.

To start with we were doing that directly from our controllers but it became clear that although we weren't interacting directly with a database the repository pattern would still probably be applicable.

The way we use it is pretty much the same as you would if it was abstracting an ORM:

image::{{<siteurl>}}/uploads/2009/03/repository.gif[repository.gif,448]

I think with an ORM the mapping would be done before you got the data back so that's an implementation detail that is slightly different but as far as I can see the concept is the same.
NUnit: Tests with Context/Spec style assertions
Date: 2009-03-01 16:43:46

I recently started playing around with http://twitter.com/bellware[Scott Bellware's] http://code.google.com/p/specunit-net/[Spec-Unit] and http://twitter.com/aaronjensen[Aaron's Jensen's] http://codebetter.com/blogs/aaron.jensen/archive/2008/05/08/introducing-machine-specifications-or-mspec-for-short.aspx[MSpec], two frameworks which both provide a way of writing Context/Spec style tests/specifications.

What I particularly like about this approach to writing tests is that we can divide assertions into specific blocks and have them all evaluated even if an earlier one fails.

http://www.nunit.org/index.php[NUnit] is our testing tool of choice at the moment and we wanted to try and find a way to test the mapping between the domain and service layers of the application.

Testing in the normal way was resulting in a test that was absolutely massive and a bit of a nightmare to debug when something changed.

Luckily http://twitter.com/davcamer[Dave] came up with the idea of using the TestFixtureSetUp attribute on a method which would setup the test data and then call the appropriate method on the object under test.

We could then have smaller tests which asserted various parts of the mapping.

[source,csharp]
----

[TestFixture]
public class FooAdaptorTest
{
	private Foo foo;
	private FooMessage fooMessage;

	[TestFixtureSetUp]
	public void GivenWeTransformAFoo()
	{
		foo = new Foo { Bar = "bar", Baz = "baz" };
		fooMessage = new FooAdaptor().MapFrom(foo);	
	}

	[Test]
	public void ShouldMapBar()
	{
		Assert.AreEqual(foo.Bar, fooMessage.Bar);	
	}

	[Test]
	public void ShouldMapBaz()
	{
		Assert.AreEqual(foo.Baz, fooMessage.Baz);		
	}
}
----

Of course this is a very simple example, and in a real example we would test more than just one property per test.

The Setup method does get pretty big depending on how much mapping needs to be done but it seems a reasonable trade off for the increased readability we get in the smaller size of each of the tests.

I know this isn't the normal way of using NUnit but I think it's cool to try and think outside the normal approach to find something that works better for us.
ASP.NET MVC: Pre-compiling views when using SafeEncodingCSharpCodeProvider
Date: 2009-03-24 22:55:41

We've been doing some work to get our views in ASP.NET MVC to be pre-compiled which allows us to see any errors in them at compilation rather than at run time.

It's relatively simple to do. You just need to add the following code into your .csproj file anywhere below the +++<Project>+++element:+++</Project>+++

[source,text]
----

<Target Name="AfterBuild">
    <AspNetCompiler VirtualPath="/" PhysicalPath="$(ProjectDir)\..\$(ProjectName)"/>
</Target>
----

where VirtualPath refers to the virtual path defined inside your project file and PhysicalPath is the path to the folder which contains the project with the views in.

As I http://www.markhneedham.com/blog/2009/02/12/aspnet-mvc-preventing-xss-attacks/[previously mentioned] we're using http://blog.codeville.net/2007/12/19/aspnet-mvc-prevent-xss-with-automatic-html-encoding/[Steve Sanderson's SafeEncodingHelper] to protect our website from cross scripting attacks.

A problem we ran into when trying to pre-compile these views is that when the AfterBuild target gets run it tries to compile our views using the SafeEncodingCSharpCodeProvider, leading to this error:

[source,text]
----

 [msbuild] /global.asax(1): error ASPPARSE: The CodeDom provider type "SafeEncodingHelper.SafeEncodingCSharpCodeProvider, SafeEncodingHelper" could not belocated. (\path\to\web.config line 143)
----

From what we could tell it looked like the AspNetCompiler was expecting the dll containing SafeEncodingCSharpCodeProvider to be within the directory we specified for the PhysicalPath but we were actually compiling it to another directory instead.

[source,text]
----

	<target name="compile">
		<msbuild project="solutionFile.sln">
			<property name="OutputPath" value="/some/output/path" />
		</msbuild>
	</target>
----

We only noticed this on our build machine because when Visual Studio builds the solution it builds each project into ProjectName/bin which meant that locally we always had the dll available since we rarely do 'Project Clean' from the IDE.

The solution/hack to our problem was to build just that project in Nant without specifying an OutputPath - by default msbuild builds into the /bin directory of the project which is exactly what we need! Our compile target now looks like this:

[source,text]
----

	<target name="compile">
		<msbuild project="projectWithViewsIn.csproj">
		</msbuild>
		<msbuild project="solutionFile.sln">
			<property name="OutputPath" value="/some/output/path" />
		</msbuild>
	</target>
----

It's not the greatest solution ever but it's an easier one than changing how we use the compilation path throughout the build file.
Coding: Isolate the data not just the endpoint
Date: 2009-03-25 23:28:42

One of the fairly standard ways of shielding our applications when integrating with other systems is to create a wrapper around it so that all interaction with it is in one place.

As I mentioned in a previous post http://www.markhneedham.com/blog/2009/03/10/ddd-repository-not-only-for-databases/[we have been using the repository pattern] to achieve this in our code.

One service which we needed to integrate lately provided data for populating data on drop downs on our UI so the service provided two pieces of data - a Value (which needed to be sent to another service when a certain option was selected) and a Label (which was the value for us to display on the screen).

Our original approach was to pass both bits of the data through the system and we populated the dropdowns such that the value being passed back to the service would be the Value but the value shown to the user would be the Label.

The option part of the drop down list would therefore look like this:

[source,text]
----

<select>
...
<option value="Value">Label</option>
</select>
----

With the data flowing through our application like so:

image::{{<siteurl>}}/uploads/2009/03/isolatedata-before1.gif[isolatedata_before.gif,487]

Although this approach worked it made our code really complicated and we were actually passing Value around the code even though our application didn't care about it at all, only the service did.

A neat re-design idea a couple of my colleagues came up with to was to only pass the Label through the application and then just do a mapping in the Repository from the Label \-> Value so we could send the correct value to the service.

The code then became much simpler:

image::{{<siteurl>}}/uploads/2009/03/isolatedata-after1.gif[isolatedata_after.gif,487]

And we had isolated the bit of code that led to the complexity in the first place.

The lesson here for me is that it's not enough merely to isolate the endpoint, we also need to think about which data our application actually needs and only pass through the data we actually use.
Functional C#: The hole in the middle pattern
Date: 2009-04-04 11:41:23

While reading http://manning.com/petricek/[Real World Functional Programming] I came across an interesting pattern that I have noticed in some code bases recently which I liked but didn't know had been given a name!

The http://enfranchisedmind.com/blog/posts/the-hole-in-the-middle-pattern/[hole in the middle pattern], coined by Brian Hurt, shows a cool way of using higher order functions in order to reuse code in cases where the code typically looks something like this:

[source,csharp]
----

public void SomeServiceCall()
{
	var serviceClient = CreateServiceClient();

	try
	{
		serviceClient.MakeMethodCall();
	}
	catch(SomeServiceException someServiceException)
	{
		// Handle exception
	}
	finally
	{
		serviceClient.Close();
	}
}
----

The first and the third lines (initialisation and finalisation) are always the same but the service.MakeMethodCall() varies depending on which service we are using. The more services we have the more boring it gets writing out the same code over and over again.

In C# 3.0 we could reuse code in this situation by passing in a lambda expression which calls that method, allowing us to vary the important part of the method call while keeping the scaffolding the same.

[source,csharp]
----

public void SomeServiceCall(Action<TServiceClient> callService)
{
	var serviceClient = CreateServiceClient();

	try
	{
		callService(serviceClient);
	}
	catch(SomeServiceException someServiceException)
	{
		// Handle exception
	}
	finally
	{
		serviceClient.Close();
	}
}
----

[source,csharp]
----

SomeServiceCall(service => service.SomeMethodCall())
----

One of the things I've noticed with the ability to pass in functions to methods is that sometimes we end up making the code really difficult to read by doing so but when we're dealing with services this seems to be one of the best and most obvious uses of Actions/Funcs in C# 3.0 and it leads to a more reusable and easy to understand API.
Coding: It's all about the context
Date: 2009-04-05 19:45:56

I think one of the easiest things to do as a developer is to look at some code that you didn't write and then start trashing it for all the supposed mistakes that the author has made that you wouldn't have.

It's certainly something I've been guilty of doing and probably will be again in the future.

Sometimes it's justified but most of the time we lack the context for http://www.markhneedham.com/blog/2008/08/08/if-they-were-that-rubbish/[understanding why the code was written the way it was] and therefore our criticism is not very useful to anyone.

I think the more projects that I work on the more I realise that there's no single set of rules that we can apply in all contexts.

I think rules or principles do still have value but http://www.markhneedham.com/blog/2009/02/13/ferengi-programmer-and-the-dreyfus-model/[we shouldn't rigidly stick to them], but be aware when there is more value in not following the rule and then go for it.

To give a simple example, one of the forms of good practice when using the NUnit testing framework is to minimise our use of the TestFixtureSetUp attribute and instead use SetUp so that the common bit of code is repeated before each test is run rather than one time before all the tests are run.

One time when we found it useful to break this rule is when writing tests for mapping code when there are a lot of different things to assert and only one method call to make.

Using our normal approach of keeping each test as it's own little specification resulted in tests that were really difficult so we broke the rule and using an approach which http://www.markhneedham.com/blog/2009/03/01/nunit-tests-with-contextspec-style-assertions/[resembles the context/spec approach to driving code].

Looking at that code without the context of what I've just described you would probably think that it's terrible code and that we don't know how to use the framework but in this case it actually made our lives easier so I think it's fine to break the rule in this case.

Another example is passing booleans into methods - in general I think this is really bad practice but it actually helps to significantly simplify code when we pass them into HtmlHelpers so that it knows whether to render the read only version of a control or not.

I'm not sure who said that 'if you rewrite a system that you didn't write the first time you'll probably make the same mistakes as the original team did' but it's certainly becoming more clear to me how this would be the case.

The conclusion I'm pretty much coming to is that *it's great to follow a set of practices*, and doing so helps ensure that we are doing the right thing most of the time, but *having the flexibility of thought to step away from that and try something different is very important*.
TDD: Testing mapping code
Date: 2009-04-02 23:11:12

I've previously written about http://www.markhneedham.com/blog/2009/03/25/coding-isolate-the-data-not-just-the-endpoint/[some] http://www.markhneedham.com/blog/2009/03/10/ddd-repository-not-only-for-databases/[of the aspects] of the mapping efforts that we've done on recent projects and what we've found from our testing (or lack of) around this type of code is that somewhere along the line you are going to have to check that you're mapping these values correctly, be it in an automated test or just by manually checking that the correct values are being sent across our integration points and into other systems.

Writing unit tests around mapping code is certainly one of the areas of testing where it feels like there isn't that much value in doing so - after all we are just copying data from one data structure to another, what could possibly go wrong?!

While I would certainly agree that in this case we are not using the tests to drive the design of our code, I think they are still very valuable for helping us to ensure that our specific bit of mapping code is doing what we expect it to.

Let's say we have data flowing across our application like so:

image::{{<siteurl>}}/uploads/2009/04/test-your-mapping.gif[test_your_mapping.gif,459]

We get the data from the UI and we need it to end up being sent to the service. Along the way there are a few different places where data could get lost and from (painful) experience I've found that if we aren't testing that all our data is being mapped then *we will forget to map something* and then we will have the fun job of debugging end to end trying to work out where it got lost.

I would certainly relax the notion of taking small steps a bit when doing this type of testing otherwise it can get immensely frustrating - maybe write the tests for a set of similar fields and then writing the mapping code rather than creating the test \-> code cycle individually for each one.

These tests can end up getting quite difficult to read so an approach we've been trying is to http://www.markhneedham.com/blog/2009/03/01/nunit-tests-with-contextspec-style-assertions/[setup the test data in a TestFixtureSetUp at the top of our NUnit test fixture and then creating just the assertions for similar sets of fields in each test]. I think it's working reasonably well even though maybe it goes against the convention of the way you would typically use NUnit.

We're still got higher level tests around this code and while they're useful they don't help us zoom into the point of error that easily so the humble unit test still has a part to play!