code, tdd comments edit

UPDATE: For a better approach, check out MoQ Sequences Revisited.

One area where using MoQ is confusing is when mocking successive calls to the same method of an object.

For example, I was writing some tests for legacy code where I needed to fake out multiple calls to a data reader. You remember data readers, don’t you?

Here’s a snippet of the code I was testing. Ignore the map method and focus on the call to reader.Read.

while(reader.Read()) {
  yield return map(reader);

Notice that there are multiple calls to reader.Read. The first couple times, I wanted Read to return true. The last time, it should return false. And here’s the code I hoped to write to fake this using MoQ:

reader.Setup(r => r.Read()).Returns(true);
reader.Setup(r => r.Read()).Returns(true);
reader.Setup(r => r.Read()).Returns(false);

Unfortunately, MoQ doesn’t work that way. The last call wins and nullifies the previous two calls. Fortunately, there are many overloads of the Returns method, some of which accept functions used to return the value when the method is called.

That’s the approach I found on Matt Hamilton’s blog post (Mad Props indeed!) where he describes his clever solution to this issue involving a Queue:

var pq = new Queue<IDbDataParameter>(new[]
mockCommand.Expect(c => c.CreateParameter()).Returns(() => pq.Dequeue());

Each time the method is called, it will return the next value in the queue.

One cool thing I stumbled on is that the syntax can be made even cleaner and more succinct by passing in a method group. Here’s my MoQ code for the original IDataReader issue I mentioned above.

var reader = new Mock<IDataReader>();
reader.Setup(r => r.Read())
  .Returns(new Queue<bool>(new[] { true, true, false }).Dequeue);

I’m defining a Queue inline and then passing what is effectively a pointer to its Dequeue method. Notice the lack of parentheses at the end of Dequeue which is how you can tell that I’m passing the method itself and not the result of the method.

Using this apporach, MoQ will call Dequeue each time it calls r.Read() grabbing the next value from the queue. Thanks to Matt for posting his solution! This is a great technique for dealing with sequences using MoQ.

UPDATE: There’s a great discussion in the comments to this post. Fredrik Kalseth proposed an extension method to make this pattern even simpler to apply and much more understandable. Why didn’t I think of this?! Here’s the extension method he proposed (but renamed to the name that Matt proposed because I like it better).

public static class MoqExtensions
  public static void ReturnsInOrder<T, TResult>(this ISetup<T, TResult> setup, 
    params TResult[] results) where T : class  {
    setup.Returns(new Queue<TResult>(results).Dequeue);

Now with this extension method, I can rewrite my above test to be even more readable.

var reader = new Mock<IDataReader>();
reader.Setup(r => r.Read()).ReturnsInOrder(true, true, false);

In the words of Borat, Very Nice!

Tags: TDD, unit testing, MoQ, code, mvc comments edit

This is the first in a three part series related to HTML encoding blocks, aka the <%: ... %> syntax.

One great new feature being introduced in ASP.NET 4 is a new code block (often called a Code Nugget by members of the Visual Web Developer team) syntax which provides a convenient means to HTML encode output in an ASPX page or view.

<%: CodeExpression %>

I often tell people it’s <%= but with the = seen from the front.

Let’s look at an example of how this might be used in an ASP.NET MVC view. Suppose you have a form which allows the user to submit their first and last name. After submitting the form, the same view is used to display the submitted values.

First Name: <%: Model.FirstName %>
Last Name: <%: Model.FirstName %>

<form method="post">
  <%: Html.TextBox("FirstName") %>
  <%: Html.TextBox("LastName") %>

By using the the new syntax, Model.FirstName and Model.LastName are properly HTML encoded which helps in mitigating Cross Site Scripting (XSS) attacks.

Expressing Intent with the new IHtmlString interface

If you’re paying close attention, you might be asking yourself “Html.TextBox is supposed to return HTML that is already sanitized. Wouldn’t using this syntax with Html.TextBox cause double encoding?

ASP.NET 4 also introduces a new interface, IHtmlString along with a default implementation, HtmlString. Any method that returns a value that implements the IHtmlString interface will not get encoded by this new syntax.

In ASP.NET MVC 2, all helpers which return HTML now take advantage of this new interface which means that when you’re writing a view, you can simply use this new syntax all the time and it will just work.By adopting this habit, you’ve effectively changed the act of HTML encoding from an opt-in model to an opt-out model.

The Goals

There were four primary goals we wanted to satisfy with the new syntax.

  1. Obvious at a glance. When you look at a page or a view, it should be immediately obvious which code blocks are HTML encoded and which are not. You shouldn’t have to refer back to flags in web.config or the page directive (which could turn encoding on or off) to figure out whether the code is actually being encoded. Also, it’s not uncommon to review code changes via check-in emails which only show a DIFF. This is one reason we didn’t reuse existing syntax.

    Not only that, code review becomes a bit easier with this new syntax. For example, it would be easy to do a global search for <%= in a code base and review those lines with more scrutiny (though we hope there won’t be any to review). Also, when you receive a check-in email which shows a DIFF, you have most of the context you need to review that code.

  2. Evokes a similar meaning to <%=. We could have used something entirely new, but we didn’t have the time to drastically change the syntax. We also wanted something that had a similar feel to <%= which evokes the sense that it’s related to output. Yeah, it’s a bit touchy feely and arbitrary, but I think it helps people feel immediately familiar with the syntax.

  3. Replaces the old syntax and allows developers to show their intent. One issue with the current implementation of output code blocks is there’s no way for developers to indicate that a method is returning already sanitized HTML. Having this in place helps enable our goal of completely replacing the old syntax with this new syntax in practice.

    This also means we need to work hard to make sure all new samples, books, blog posts, etc. eventually use the new syntax when targeting ASP.NET 4.

    Hopefully, the next generation of ASP.NET developers will experience this as being the default output code block syntax and <%= will just be a bad memory for us old-timers like punch cards, manual memory allocations, and Do While Not rs.EOF.

  4. Make it easy to migrate from ASP.NET 3.5. We strongly considered just changing the existing <%= syntax to encode by default. We eventually decided against this for several reasons, some of which are listed in the above goals. Doing so would make it tricky and painful to upgrade an existing application from earlier versions of ASP.NET.

    Also, we didn’t want to impose an additional burden for those who already do practice good encoding. For those who don’t already practice good encoding, this additional burden might prevent them from porting their app and thus they wouldn’t get the benefit anyways.

When Can I Use This?

This is a new feature of ASP.NET 4. If you’re developing on ASP.NET 3.5, you will have to continue to use the existing <%= syntax and remember to encode the output yourself.

In ASP.NET 4 Beta 2, you will have the ability to try this out yourself with ASP.NET MVC 2 Preview 2. If you’re running on ASP.NET 3.5, you’ll have to use the old syntax.

What about ASP.NET MVC 2?

As mentioned, ASP.NET MVC 2 supports this new syntax in its helper when running on ASP.NET 4.

In order to make this possible, we are making a breaking change such that the relevant helper methods (ones that return HTML as a string) will return a type that implements IHtmlString.

In a follow-up blog post, I’ll write about the specifics of that change. It was an interesting challenge given that IHtmlString is new to ASP.NET 4, but ASP.NET MVC 2 is actually compiled against ASP.NET 3.5 SP1. :)

comments edit

In my last post, I presented a general overview of the CodePlex foundation and talked a bit about what it means to the .NET OSS developer, admittedly without much in the way of details. I plan to fix some of that in this post.

Before I continue, I encourage you to read Scott Bellware’s great analysis of the CodePlex foundation which covers some of the points I planned to make (making my life easier). It’s a must-read to better understand the potential and opportunity presented by the foundation.

There’s one particular point he makes which I’d like to expound upon.

The CodePlex Foundation will bring influential open source projects under its auspices. The details aren’t clear yet, but it’s reasonable to assume that the foundation will support its projects the way that other software foundations support their projects, with protection for these projects as they are used in corporate and commercial contexts and who knows, maybe even some financial support will be part of the deal.

I talked to Bill Staples recently and he pointed out that The Apache Foundation is one source (among many) of inspiration for the CodePlex Foundation. If you go to the Apache FAQ, you’ll find the answer to the following question, “How does the ASF help its projects?” (emphasis mine)

As a corporate entity, the Apache Software Foundation is able to be a party to contracts, such as for technical services or guarantee-bonds for conferences. It can also accept donations on behalf of its projects, clarifying the associated tax issues, and create additional self-funded services via community-building activities, such as Apache-related T-shirts and user conferences.

In addition, the Foundation provides a framework for limiting the legal exposure of individual volunteers while they work on behalf of one of the ASF projects. In the past, these volunteers have been personally vulnerable to lawsuits, whether legitimate or frivolous, which impaired many activities that might have significantly improved contributions to the projects and benefited our users.

The first paragraph is what I alluded to in my last post, and this is something that the CodePlex Foundation would like to do in the long run, but as I mentioned before, it all depends on the level of participation and sponsorship funding. In an ideal world, the foundation would be able to add some level of funding of projects to this list of benefits for a member project.

The second paragraph is something that the CodePlex Foundation definitely wants to do right off the bat.

This is great news for those of us hosting open source projects. It’s generally not a worry for many small .NET open source projects, but the risk is always there that if a project starts to get noticed, some company may come along and sue the project owner for patent infringement etc. Typical projects may not have any money to go after, but I can imagine a commercial company going after a competing OSS product simply to shutter it.

Assigning your project’s copyright to the CodePlex Foundation would afford some level of legal protection against this sort of thing, similar to the way it works with the Apache Foundation.

One nice thing about the CodePlex Foundation is you have the option to assign copyright to the foundation or license your code to the foundation. I’m not a lawyer so I don’t understand if one provides more legal protection than the other. Honestly, once the foundation starts accepting projects at large, I would want to assign Subtext’s copyright over so that my name doesn’t appear as the big red bulls-eye in the Subtext copyright notice! ;)

And if you’re wondering, “am I losing control over my project by assigning copyright over”you are not. As I wrote in my post Who Owns The Copyright For An Open Source Project (part of my series called the Developer’s Guide To Copyright Law) you’d be assigning it under the open source license of your choice (yes, the CodePlex Foundation is more or less license agnostic. It doesn’t require a specific license to join), which always gives you the freedom to fork it should the foundation suddenly be overtaken by evil Ninjas.

As I said before, many of these details are still being hashed out and I’m guessing some of them won’t be finalized until the final board of directors is in place. But in the meanwhile, I think understanding the sources of inspiration for this new foundation will help provide insight into the direction it may take.

I hope this provides more concrete details than my last post.

comments edit

UPDATE: Be sure to read my follow-up post on this topic as well.

Yesterday, Microsoft announced some exciting news about the formation of the CodePlex Foundation (not to be confused with project hosting website despite the unfortunately confusing same name) whose mission is to “enable the exchange of code and understanding among software companies and open source communities”.


This is an 501(c)(6) organization completely independent of Microsoft. For example, search the by-laws for mentions of Microsoft and you’ll find zero. Zilch.

One thing to keep in mind about this organization is that it’s very early in its formation. There was debate on trying to hash out all the details first and perhaps announcing the project some time further in the future, but that sort of goes against the open source ethos. As the main website states (emphasis mine):

We don’t have it all figured out yet. We know that commercial software developers are under-represented on open source projects. We know that commercial software companies face very specific challenges in determining how to engage with open source communities. We know that there are misunderstandings on both sides. Our aim is to advance the IT industry for both commercial software companies and open source communities by helping to meet these challenges.

Meeting these challenges is a collaborative process. We want your participation.

I’m personally excited about this as I’ve been a proponent of open source on the Microsoft stack for a long time and have called for Microsoft to get more involved in the past. I remember way back then, Scott Hanselman suggested Microsoft form an INETA like organization for open source as an editorial aside in his post on NDoc.

How does it benefit .NET OSS projects?

However, all is not roses just yet. If you read the mission statement carefully, it’s a very broad statement. In fact, it’s not specific to the Microsoft open source ecosystem, though obviously Microsoft will benefit from the mission statement being carried out.

If you look at it from Microsoft’s perspective, there are many legal and other challenges to participating in open source more fully. While Microsoft has made contributions to Linux, has collaborated closely with PHP, etc. Each time presents a unique set of challenges.

If the foundation succeeds in its mission, I believe it will open the doors for Microsoft to collaborate with and encourage the .NET open source ecosystem in a more meaningful manner.I don’t know what shape that will take in the end, but I believe that removing roadblocks to Microsoft’s participation is required and a great first step.

I’m honored to serve as an advisor to the board. In our first advisory board conference call, my first question asked the question, “what does this mean for those running open source projects on the .NET platform?” After all, while I’m a Microsoft employee by day, I also run an open source project at night and I have my own motivations as such.

I’m happy to see the mission statement take such a broad stance as it seems to be focused on the greater good and not focused on Microsoft specifically, but I am personally interested in seeing more details on why this is good for the open source developer who runs a project on the .NET platform. For example, can the foundation provide something more than moral support to .NET OSS projects such as MSDN licenses or more direct funding?

These are all interesting questions and I don’t know the answers. Microsoft put some skin in the game by seeding the foundation with a million dollars for the first year. The foundation, as an independent organization, will be looking for more sponsors to also pony up money. They will have to find the right balance in how they spend that money so that they can continue to operate. I imagine the answer to these questions will depend in how successful they are in finding sponsors and operating within their budget. As an advisor, I’ll be pushing for more clarity around this.

The full details for what the foundation will do are still being hashed out. The interim board has 100 days to choose a more permanent board of directors. Now is the time to get involved if you want to help make sure it continues in the right direction.

comments edit

My last post on the new dynamic keyword sparked a range of reactions which are not uncommon when discussing a new language keyword or feature. Many are excited by it, but there are those who feel a sense of…well…grief when their language is “marred” by a new keyword.

C#, for example, has seen it with the var keyword and now with the dynamic keyword. I don’t know, maybe there’s something to this idea that developers go through the seven stages of grief when their favorite programming language adds new stuff (Disclaimer: Actually, I’m totally making this crap up)

1. Shock and denial.

With the introduction of a new keyword, initial reactions include shock and denial.

No way are they adding lambdas to the language! I had a hard enough time with the delegate keyword!

What is this crazy ‘expression of funky tea’ syntax? I’ll just ignore it and hope it goes away.

Generics will never catch on! Mark my words.

2. Longing for the past

Immediately, even before the new feature is even released, developers start to wax nostalgic remembering a past that never was.

I loved language X 10 years ago when it wasn’t so bloated, man.

They forget that the past also meant managing your own memory allocations, punch cards, and dying of the black plague, which totally sucks.

3. Anger and FUD

Soon this nostalgia turns to anger and FUD.

Check out this reaction to adding the goto keyword to PHP, emphasis mine.

This is a problem. Seriously, PHP has made it \ this far without goto, why turn the language into a public menace?

Yes Robin, PHP is a menace terrorizing Gotham City. To the Batmobile!

The dynamic keyword elicited similar anger with comments like:

C# was fine as a static language. If I wanted a dynamic language, I’d use something else!


I’ll never use that feature!

It’s never long before anger turns to spreading FUD (Fear Uncertainty Doubt). The var keyword in C# is a prime example of this. Many developers wrote erroneously that using it would mean that your code was no longer strongly typed and would lead to all hell breaking use.

My friend used the var keyword in his program and it formatted his hard drive, irradiate his crotch, and caused the recent economic crash. True story.

Little did they know that the dynamic keyword was on its way which really would fulfill all those promises. ;)

Pretty much the new feature will destroy life on the planet as we know it and make for some crappy code.

4. Depression, reflection, and wondering about its performance

Sigh. I now have to actually learn this new feature, I wonder how well it performs.

This one always gets me. It’s almost always the first question developers ask about a new language feature? “Does it perform?”.

I think wondering about its performance is a waste of time. For your website which gets 100 visitors a day, yeah, it probably performs just fine.

The better question to ask is “Does my application perform well enough for my requirements?” And if it doesn’t then you start measuring, find the bottlenecks, and then optimize. Odds are your performance problems are not due to language features but to common higher level mistakes such as the Select N+1 problem.

5. The upward turn

Ok, my hard drive wasn’t formatted by this keyword. Maybe it’s not so bad.

At this point, developers start to realize that the new feature doesn’t eat kittens for breakfast and just might not be evil incarnate after all. Hey! It might even have some legitimate uses.

This is the stage where I think you see a lot of experimentation with the feature as developers give it a try and try to figure out where it does and doesn’t work well.

6. Code gone wild! Everything is a nail

I think we all go through this phase from time to time. At some point, you realize that this new feature is really very cool so you start to go hog wild with it. In your hands the feature is the Hammer of Thor and every line of code looks like a nail ready to be smitten.

Things can get ugly at this stage in a fit of excitement. Suddenly every object is anonymous, every callback is a lambda, and every method is generic, whether it should be or not.

It’s probably a good idea to resist this, but once in a while, you have to let yourself give in and have a bit of fun with the feature. Just remember the following command.

svn revert -R

Or whatever the alternative is with your favorite source control system.

7. Acceptance and obliviousness

At this point, the developer has finally accepted the language feature as simply another part of the language like the class or public keyword. There is no longer a need to gratuitously use or over-use the keyword. Instead the developer only uses the keyword occasionally in cases where it’s really needed and serves a useful purpose.

It’s become a hammer in a world where not everything is a nail. Or maybe it’s an awl. I’m not sure what an awl is used for, but I’m sure some of you out there do and you probably don’t use it all the time, but you use it properly when the need arises. Me, I never use one, but that’s perfectly normal, perfectly fine.

For the most part, the developer becomes oblivious to the feature much as developers are oblivious to the using keyword. You only think about the keyword when it’s the right time to use it.


Thanks to everyone on Twitter who provided examples of language keywords that provoked pushback. It was helpful., code, mvc comments edit

UPDATE: Looks like the CLR already has something similar to what I did here. Meet the latest class with a superhero sounding name, ExpandoObject

Warning: What I’m about to show you is quite possibly an abuse of the C# language. Then again, maybe it’s not. ;) You’ve been warned.

Ruby has a neat feature that allows you to hook into method calls for which the method is not defined. In such cases, Ruby will call a method on your class named method_missing. I showed an example of this using IronRuby a while back when I wrote about monkey patching CLR objects.

Typically, this sort of wild chicanery is safely contained within the world of those wild and crazy dynamic language aficionados, far away from the peaceful waters of those who prefer statically typed languages.

Until now suckas! (cue heart pounding rock music with a fast beat)

C# 4 introduces the new dynamic keyword which adds dynamic capabilities to the once staid and statically typed language. Don’t be afraid, nobody is going to force you to use this (except maybe me). In fact, I believe the original purpose of this feature is to make COM interoperability much easier. But phooey on the intention of this feature, I want to have some fun!

I figured I’d try and implement something similar to method_missing.

The first toy I wrote is a simple dynamic dictionary which uses property accessors as the means of adding and retrieving values from the dictionary by using the property name as the key. Here’s an example of the usage:

static void Main(string[] args) {
  dynamic dict = new DynamicDictionary();

  dict.Foo = "Some Value";  // Compare to dict["Foo"] = "Some Value";
  dict.Bar = 123;           // Compare to dict["Bar"] = 123;
  Console.WriteLine("Foo: {0}, Bar: {1}", dict.Foo, dict.Bar);

That’s kind of neat, and the code is very simple. To make a dynamic object, you have the choice of either implementing the IDynamicMetaObjectProvider interface or simply deriving from DynamicObject. I chose this second approach in this case because it was less work. Here’s the code.

public class DynamicDictionary : DynamicObject {
  Dictionary<string, object> 
    _dictionary = new Dictionary<string, object>();

  public override bool TrySetMember(SetMemberBinder binder, object value) {
    _dictionary[binder.Name] = value;
    return true;

  public override bool TryGetMember(GetMemberBinder binder, 
      out object result) {
    return _dictionary.TryGetValue(binder.Name, out result);

All I’m doing here is overriding the TrySetMember method which is invoked when attempting to set a field to a value on a dynamic object. I can grab the name of the field and use that as the key to my dictionary. I also override TryGetMember to grab values from the dictionary. It’s really simple.

One thing to note, in Ruby, there really aren’t properties and methods. Everything is a method, hence you only have to worry about method_missing. There’s no field_missing method, for example. With C# there is a difference, which is why there’s another method you can override, TryInvokeMember, to handle dynamic method calls.

What havoc can we wreack with MVC?

So I have this shiny new hammer in my hand, let’s go looking for some nails!

While I’m a fan of using strongly typed view data with ASP.NET MVC, I sometimes like to toss some ancillary data in the ViewDataDictionary. Of course, doing so adds to syntactic overhead that I’d love to reduce. Here’s what we have today.

// store in ViewData
ViewData["Message"] = "Hello World";

// pull out of view data
<%= Html.Encode(ViewData["Message"]) %>

Sounds like a job for dynamic dictionary!

Before I show you the code, let me show you the end result first. I created a new property for Controller and for ViewPage called Data instead of ViewData (just to keep it short and because I didn’t want to call it VD).

Here’s the controller code.

public ActionResult Index() {
    Data.Message = "<cool>Welcome to ASP.NET MVC!</cool> (encoded)";
    Data.Body = "<strong>This is not encoded</strong>.";
    return View();

Note that Message and Body are not actually properties of Data. They are keys to the dictionary via the power of the dynamic keyword. This is equivalent to setting ViewData["Message"] = "<cool>…</cool>".

In the view, I created my own convention where all access to the Data object will be html encoded unless you use an underscore.

<asp:Content ContentPlaceHolderID="MainContent" runat="server">
 <h2><%= Data.Message %></h2>
    <%= Data._Body %>

Keep in mind that Data.Message here is equivalent to ViewData["Message"].

Here’s a screenshot of the end result.


Here’s how I did it. I started by writing a new DynamicViewData class.

public class DynamicViewData : DynamicObject {
  public DynamicViewData(ViewDataDictionary viewData) {
    _viewData = viewData;
  private ViewDataDictionary _viewData;

  public override bool TrySetMember(SetMemberBinder binder, object value) {
    _viewData[binder.Name] = value;
      return true;

  public override bool TryGetMember(GetMemberBinder binder,
      out object result) {
    string key = binder.Name;
    bool encoded = true;
    if (key.StartsWith("_")) {
      key = key.Substring(1);
      encoded = false;
    result = _viewData.Eval(key);
     if (encoded) {
       result = System.Web.HttpUtility.HtmlEncode(result.ToString());
     return true;

If you look closely, you’ll notice I’m doing a bit of transformation within the body of TryGetMember. This is where I create my convention for not html encoding the content when the property name starts with underscore. I then strip off the underscore before trying to get the value from the database.

The next step was to create my own DynamicController

public class DynamicController : Controller {
  public dynamic Data {
    get {
      _viewData = _viewData ?? new DynamicViewData(ViewData);
      return _viewData;
  dynamic _viewData = null;

and DynamicViewPage, both of which makes use of this new type.

public class DynamicViewPage : ViewPage {
  public dynamic Data {
    get {
      _viewData = _viewData ?? new DynamicViewData(ViewData);
      return _viewData;
  dynamic _viewData = null;

In the Views directory, I updated the web.config file to make DynamicViewPage be the default base class for views instead of ViewPage. You can make this change by setting the pageBaseType attribute of the <pages> element (I talked about this a bit in my post on putting your views on a diet).

I hope you found this to be a fun romp through a new language feature of C#. I imagine many will find this to be an abuse of the language (language abuser!) while others might see other potential uses in this technique. Happy coding!

Tags: dynamic, aspnetmvc, C#, DLR

comments edit

The .NET Framework provides support for managing transactions from code via the System.Transactions infrastructure. Performing database operations in a transaction is as easy as writing a using block with the TransactionScope class.

using(TransactionScope transaction = new TransactionScope()) 


At the end of the using block, Dispose is called on the transaction scope. If the transaction has not been completed (in other words, transaction.Complete was not called), then the transaction is rolled back. Otherwise it is committed to the underlying data store.

The typical reason a transaction might not be completed is that an exception is thrown within the using block and thus the Complete method is not called.

This pattern is simple, but I was looking at it the other day with a co-worker wondering if we could make it even simpler. After all, if the only reason a transaction fails is because an exception is thrown, why must the developer remember to complete the transaction? Can’t we do that for them?

My idea was to write a method that accepts an Action which contains the code you wish to run within the transaction. I’m not sure if people would consider this simpler, so you tell me. Here’s the usage pattern.

public void SomeMethod()
  Transaction.Do(() => {

Yay! I saved one whole line of code! :P

Kidding aside, we don’t save much in code reduction, but I think it makes the concept slightly simpler. I figured someone has already done this as it’s really not rocket science, but I didn’t see anything after a quick search. Here’s the code.

public static class Transaction 
  public static void Do(Action action) 
    using (TransactionScope transaction = new TransactionScope())

So you tell me, does this seem useful at all?

By the way, there are several overloads to the TransactionScope constructor. I would imagine that if you used this pattern in a real application, you’d want to provide corresponding overloads to the Transaction.Do method.

UPDATE: What if you don’t want to rely on an exception to determine whether the transaction is successful?

In general, I tend to think of a failed transaction as an exceptional situation. I generally assume transactions will succeed and when they don’t it’s an exceptional situation. In other words, I’m usually fine with an exception being the trigger that a transaction fails.

However, Omer Van Kloeten pointed out on Twitter that this can be a performance problem in cases where transaction failures are common and that returning true or false might make more sense.

It’s trivial to provide an overload that takes in a Func<bool>. When you use this overload, you simply return true if the transaction succeeds or false if it doesn’t, which is kind of nice. Here’s an example of usage.

Transaction.Do(() => {

  if(SaveWorkToDatabaseSuccessful()) {
    return true;
  return false;

The implementation is pretty similar to what we have above.

public static void Do(Func<bool> action) {
  using (TransactionScope transaction = new TransactionScope()) {
    if (action()) {

comments edit

When building a web application, it’s a common desire to want to expose a simple Web API along with the HTML user interface to enable various mash-up scenarios or to simply make accessing structured data easy from the same application.

A common question that comes up is when to use ASP.NET MVC to build out REST-ful services and when to use WCF? I’ve answered the question before, but not as well as Ayende does (when discussing a different topic). This is what I tried to express.

In many cases, the application itself is the only reason for development [of the service]

[of the service]” added by me. In other words, when the only reason for the service’s existence is to service the one application you’re currently building, it may make more sense  would stick with the simple case of using ASP.NET MVC. This is commonly the case when the only client to your JSON service is your web application’s Ajax code.

When your service is intended to serve multiple clients (not just your one application) or hit large scale usage, then moving to a real services layer such as WCF may be more appropriate.

However, there is now a third hybrid choice that blends ASP.NET and WCF. The WCF team saw that many developers building ASP.NET MVC apps are more comfortable with the ASP.NET MVC programming model, but still want to supply more rich RESTful services from their web applications. So the WCF team put together an SDK and samples for building REST services using ASP.NET MVC.

You can download the samples and SDK from ASP.NET MVC 1.0 page on CodePlex.

Do read through the overview document as it describes the changes you’ll need to make to an application to make use of this framework. Also, the zip file includes several sample movie applications which demonstrate various scenarios and compares them to the baseline of not using the REST approach.

At this point in time, this is a sample and SDK hosted on our CodePlex site, but many of the features are in consideration for a future release of ASP.NET MVC (no specifics yet).

This is where you come in. We are keenly interested in hearing feedback on this SDK. Is it important to you, is it not? Does it do what you need? Does it need improvement. Let us know what you think. Thanks!

comments edit

In a recent post, The Law of Demeter Is Not A Dot Counting Exercise, I wanted to peer into the dark depths of the Law of Demeter to understand it’s real purpose. In the end I concluded that the real goal of the guideline is to reduce coupling, not dots, which was a relief because I’m a big fan of dots (and stripes too judging by my shirt collection).

However, one thing that puzzled me was that there are in essence two distinct formulations of the law, the object form and the class form. Why are there two forms and how do they differ in a practical sense?

Let’s find an example of where the law seems to break down and perhaps apply these forms to solve the conundrum as a means of gaining better understanding of the law.

Rémon Sinnema has a great example of where the law seems to break down that can serve as a starting point for this discussion.

Code that violates the Law of Demeter is a candidate for Hide Delegate, e.g. manager = john.getDepartment().getManager() can be refactored to manager = john.getManager(), where the Employee class gets a new getManager() method.

However, not all such refactorings make as much sense. Consider, for example, someone who’s trying to kiss up to his boss: sendFlowers(john.getManager().getSpouse()). Applying Hide Delegate here would yield a getManagersSpouse() method in Employee. Yuck.

This is an example of one common drawback of following LoD to the letter. You can end up up with a lot of one-off wrapper methods to propagate a property or method to the caller. In fact, this is so common there’s a term for such a wrapper. It’s called a Demeter Transmogrifier!


Who knew that Calvin was such a rock star software developer?

Too many of these one-off “transmogrifier” methods can clutter your API like a tornado in a paper factory, but like most things in software, it’s a trade-off that has to be weighed against the benefits of applying LoD in any given situation. These sort of judgment calls are part of the craft of software development and there’s just no “one size fits all follow the checklist” solution.

While this criticism of LoD may be valid at times, it may not be so in this particular case. Is this another case of dot counting?

For example, suppose the getManager method returns an instance of Manager and Manager implements the IEmployee interface. Also suppose that the IEmployee interface includes the getSpouse() method. Since John is also an IEmployee, shouldn’t he be free to call the getSpouse() method of his manager without violating LoD? After all, they are both instances of IEmployee.

Let’s take another look at the the general formulation of the law:

Each unit should have only limited knowledge about other units: only units “closely” related to the current unit. Or: Each unit should only talk to its friends; Don’t talk to strangers.

Notice that the word closely is in quotes. What exactly does it mean that one unit is closely related to another? In the short form of the law, Don’t talk to strangers,we learn we shouldn’t talk to strangers. But who exactly is a stranger? Great questions, if I do say so myself!

The formal version of the law focuses on sending messages to objects. For example, a method of an object can always call methods of itself, methods of an object it created, or methods of passed in arguments. But what about types? Can an object always call methods of an object that is the same type as the calling object? In other words, if I am a Person object, is another Person object a stranger to me?

According to the general formulation, there is a class form of LoD which applies to statically typed languages and seems to indicate that yes, this is the case. It seems it’s fair to say that for a statically typed language, an object has knowledge of the inner workings of another object of the same type.

Please note that I am qualifying that statement with “seems” and “fair to say” because I’m not an expert here. This is what I’ve pieced together in my own reading and am open to someone with more expertise here clearing up my understanding or lack thereof.

comments edit

One of the complaints I often here with our our default view engine and Pages is that there’s all this extra cruft in there with the whole page directive and stuff. But it turns out that you can get rid of a lot of it. Credit goes to David Ebbo, the oracle of all hidden gems within the inner workings of ASP.NET, for pointing me in the right direction on this.

First, let me show you what the before and after of our default Index view (reformatted to fit the format for this blog).


<%@ Page Language="C#" 
  Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="indexTitle" 
  ContentPlaceHolderID="TitleContent" runat="server">
    Home Page

<asp:Content ID="indexContent" 
  ContentPlaceHolderID="MainContent" runat="server">
    <h2><%= Html.Encode(ViewData["Message"]) %></h2>
        To learn more about ASP.NET MVC visit <a href="" 
        title="ASP.NET MVC Website"></a>.

After {.clear}

<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
    Home Page

<asp:Content ContentPlaceHolderID="MainContent" runat="server">
    <h2><%= Html.Encode(ViewData["Message"]) %></h2>
        To learn more about ASP.NET MVC visit <a href="" 
        title="ASP.NET MVC Website"></a>.

That ain’t your pappy’s Web Form view. I can see your reaction now:

Where’s the page declaration!? Where’s all the Content IDs!? Where’s the Master Page declaration!? Oh good, at least runat=”server” is still there to anchor my sanity and comfort me at night.

It turns out that ASP.NET provides ways to set many of the defaults within Web.config. What I’ve done here (and which you can do in an ASP.NET MVC project or Web Forms project) is to set several of these defaults.

In the case of ASP.NET MVC, I opened up the Web.config file hiding away in the Views directory, not to be confused with the Web.config in your application root.


This Web.config is placed here because it is the default for all Views. I then made the following changes:

  1. Set the compilation element’s defaultLanguage attribute to “C#”.
  2. Set the pages element’s masterPageFile attribute to point to ~/Views/Shared/Site.master.
  3. Set the pages element’s pageBaseType attribute to System.Web.Mvc.ViewPage (in this case, it was already set as part of the default ASP.NET MVC project template).

Below is what the web.config file looks like with my changes (I removed some details like other elements and attributes just to show the gist):

    <compilation defaultLanguage="C#" />

With this in place, as long as my views don’t deviate from these settings, I won’t have to declare the Page directive.

Of course, if you’re using strongly typed views, you’ll need the Page directive to specify the ViewPage type, but that’s it.

Also, don’t forget that you can get rid of all them ugly Register declarations by registering custom controls in Web.config.

You can also get rid of those ugly Import directives by importing namespaces in Web.config.

        <add namespace="Haack.Mvc.Helpers" />

By following these techniques, you can get rid of a lot of cruft within your pages and views and keep them slimmer and fitter. Of course, what I’ve shown here is merely putting your views on a syntax diet. The more important diet for your views is to keep the amount of code minimal and restricted to presentation concerns, but that’s a post for another day as Rob has already covered it.

Sadly, there is no getting rid of runat="server" yet short of switching another view engine. But at this point, I like to think of him as that obnoxious friend from high school your wife hates but you still keep around to remind you of your roots. ;)

Hope you enjoy these tips and use them to put your views on a diet. After all, isn’t it the view’s job to look good for the beach?


comments edit

Note, this blog post is based on Preview 1 of ASP.NET MVC 2 and details are subject to change. I’ll try to get back to normal ASP.NET MVC 1.0 content soon. :)

While in a meeting yesterday with “The Gu”, the topic of automatic views came up. Imagine if you could simply instantiate a model object within a controller action, return it to the “view”, and have ASP.NET MVC provide simple scaffolded edit and details views for the model automatically.

That’s when the light bulb went on for Scott and he briefly mentioned an idea for an approach that would work. I was excited by this idea and decided to prototype it tonight. Before I discuss that approach, let me lead in with a bit of background.

One of the cool features of ASP.NET MVC is that any views in our ~/Views/Shared folderare shared among all controllers. For example, suppose you wanted a default Index view for all controllers. You could simply add a view named Index into the Shared views folder.


Thus any controller with an action named Indexwould automatically use the Index in the Shared folder unless there was also an Index view in the controller’s view folder.

Perhaps, we can use this to our advantage when building simple CRUD (Create, Read, Update, Delete) pages. What if we included default views within the Shared folder named after the basic CRUD operations? What would we place in these views? Well calls to our new Templated Helpers of course! That way, when you add a new action method which follows the convention, you’d automatically have a scaffolded view without having to create the view!

I prototyped this up tonight as a demonstration. The first thing I did was add three new views to the Shared folder, Details, Edit, and Create.

crud-views Let’s take a look at the Details view to see how simple it is.

<%@ Page Inherits="System.Web.Mvc.ViewPage"%>
<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
    Details for <%= Html.Encode(ViewData.Eval("Title")) %>

<asp:Content ContentPlaceHolderID="MainContent" runat="server">

    <fieldset class="default-view">
        <legend><%= Html.Encode(ViewData.Eval("Title")) %></legend>
        <% ViewData["__MyModel"] = Model; %>
        <%= Html.Display("__MyModel") %>

What we see here is a non-generic ViewPage. Since this View can be used for multiple controller views and we won’t know what the model type is until runtime, we can’t use a strongly typed view here, but we can use the non-generic Html.Display method to display the model.

One thing you’ll notice is that this required a hack where I take the model and add it to ViewData using an arbirtrary key, and then I call Html.Display using the same view data key. This is due to an apparent bug in Preview 1 in which Html.Display("") doesn’t work against the current model. I’m confident we’ll fix this in a future preview.

Html.DisplayFor(m => m) also doesn’t work here because the expression works against the declared type of the Model, not the runtime type, which in this case, is object.

With these views in place, I now have the basic default CRUD (well Create, Edit, Details to be exact) views in place. So the next time I create an action method named the same as these templates, I won’t have to create a view.

Let’s see this in action. I love NerdDinner, but I’d like to use another domain for this sample for a chain. Let’s try Ninjas!

First, we create a simple Ninja class.

public class Ninja
    public string Name { get; set; }
    public int ShurikenCount { get; set; }
    public int BlowgunDartCount { get; set; }
    public string  Clan { get; set; }

Next we’ll add a new NinjaController using the Add Controller dialog by right clicking on the Controllers folder, selecting Add, and choosing Controller.


This brings up a dialog which allows you to name the controller and choose to scaffold some simple action methods (completely configurable of course using T4 templates).


Within the newly added Ninja controller, I create sample Ninja (as a static variable for demonstration purposes) and return it from the Details action.

static Ninja _ninja = new Ninja { 
    Name = "Ask a Ninja", 
    Clan = "Yokoyama", 
    BlowgunDartCount = 23, 
    ShurikenCount = 42 };

public ActionResult Details(int id)
  ViewData["Title"] = "A Very Cool Ninja";
  return View(_ninja);

Note that I also place a title in ViewData since I know the view will display that title. I could also have created a NinjaViewModel and passed that to the view instead complete with Title property, but I chose to do it this way for demo purposes.

Now, when I visit the Ninja details page, I see:

Details for One awesome Ninja - Windows Internet Explorer

With these default templates in place, I can quickly create other action methods without having to worry about the view yet. I’ll just get a default scaffolded view.

If I need to make minor customizations to the scaffolded view, I can always apply data annotation attributes to provide hints to the templated helper on how to display the model. For example, let’s add some spaces to the fields via the DisplayNameAttribute.

public class Ninja
    public string Name { get; set; }
    public int ShurikenCount { get; set; }
    [DisplayName("Blowgun Darts")]
    public int BlowgunDartCount { get; set; }
    public string  Clan { get; set; }

If it concerns you that I’m adding these presentation concerns to the model, let’s pretend this is actually a view specific model for the moment and set those concerns aside. Also, in the future we hope to provide means to provide this meta-data via other means so it’s doesn’t have to be applied directly to the model but can be stored elsewhere.

Now when I recompile and refresh the page, I see my updated labels.


Alternatively, I can create a display template for Ninjas. All I need to do is add a folder named DisplayTemplates to the Shared views folder and add my Ninja template there.

Then I right click on that folder and select the Add View dialog, making sure to check Create a strongly-typed view. In this case, since I know I’m making a template specifically for Ninjas, I can create a strongly typed partial view and select Ninja as model type.


When I’m done, I should see the following template in the DisplayTemplates folder. I can go in there and make any edits I like now to provide much more detailed customization.


Now I just recompile and then refresh my details page and see:


Finally, if I need even more control, I can simply add a Details view to the Ninja views folder, which provides absolute control and overrides the default Details view in the Shared folder.


So that’s the neat idea which I’m calling “default templated views” for now. This walkthrough not only shows you the idea, but how to implement it yourself! You can easily take this idea and have it fit your own conventions.

At the time that he mentioned this idea, Scott exclaimed “Why didn’t I think of this before, it’s so obvious.” (or something to that effect, I wasn’t taking notes).

I was thinking the same thing until I just realized, we didn’t have Templated Helpers before, so having default CRUD views would not have been all that useful in ASP.NET MVC 1.0. ;)

But ASP.NET MVC 2 Preview 1 does have Templated Helpers and this post provides a neat means to provide scaffolded views while you build your application.

And before I forget, here’s a download containing my sample Ninja project.

code, mvc comments edit

UPDATEThis post is now obsolete. Single project areas are a core part of ASP.NET MVC 2.

Preview 1 of ASP.NET MVC 2 introduces the concept of Areas. Areas provide a means of dividing a large web application into multiple projects, each of which can be developed in relative isolation. The goal of this feature is to help manage complexity when developing a large site by factoring the site into multiple projects, which get combined back into the main site before deployment. Despite the multiple projects, it’s all logically one web application.

One piece of feedback I’ve already heard from several people is that they don’t want to manage multiple projects and simply want areas within  single project as a means of organizing controllers and views much like I had it in my prototype for ASP.NET MVC 1.0.


Well the bad news is that the areas layout I had in that prototype doesn’t work right out of the box. The good news is that it is very easy to enable that scenario. All of the components necessary are in the box, we just need to tweak the installation slightly.

We’ve added a few area specific properties to VirtualPathProviderViewEngine, the base class for our WebFormViewEngine and others. Properties such as AreaViewLocationFormats allow specifying an array of format strings used by the view engines to locate a view. The default format strings for areas doesn’t match the structure that I used before, but it’s not hard for us to tweak things a bit so it does.

The approach I took was to simply create a new view engine that had the area view location formats that I cared about and inserted it first into the view engines collection.

public class SingleProjectAreasViewEngine : WebFormViewEngine {
    public SingleProjectAreasViewEngine() : this(
        new[] {
        new[] {
        ) {

    public SingleProjectAreasViewEngine(
            IEnumerable<string> areaViewLocationFormats, 
            IEnumerable<string> areaPartialViewLocationFormats, 
            IEnumerable<string> areaMasterLocationFormats) : base() {
        this.AreaViewLocationFormats = areaViewLocationFormats.ToArray();
        this.AreaPartialViewLocationFormats = (areaPartialViewLocationFormats ?? 
        this.AreaMasterLocationFormats = areaMasterLocationFormats.ToArray();

The constructor of this view engine simply specifies different format strings. Here’s a case where I wish the Framework had a String.Format method that efficiently worked with named formats.

This sample is made slightly more complicated by the fact that I have another constructor that accepts all these formats. That makes it possible to change the formats when registering the view engine if you so choose.

In my web.config file, I then registered this view engine like so:

protected void Application_Start() {
    ViewEngines.Engines.Insert(0, new SingleProjectAreasViewEngine());

Note that I’m inserting it first so it takes precedence. I could have cleared the collection and added this as the only one, but I wanted the existing areas format for multi-project solutions to continue to work just in case. It’s really your call.

Now I can register my area routes using a new MapAreaRoute extension method.

public static void RegisterRoutes(RouteCollection routes) {

    routes.MapAreaRoute("Blogs", "blogs_area", 
        new { controller = "Home", action = "Index", id = "" }, 
        new string[] { "SingleProjectAreas.Areas.Blogs.Controllers" });
        new { controller = "Home", action = "Index", id = "" }, 
        new string[] { "SingleProjectAreas.Areas.Forums.Controllers" });
    routes.MapAreaRoute("Main", "default_route", 
        new { controller = "Home", action = "Index", id = "" }, 
        new string[] { "SingleProjectAreas.Controllers" });

And I’m good to go. Notice that I no longer have a default route. Instead, I mapped an area named “Main” to serve as the “main” project. The Route URL pattern there is what you’d typically see in the default template.

If you prefer this approach or would like to see both approaches supported, let me know. We are looking at having the single project approach supported out of the box as a possibility for Preview 2.

If you want to see this in action, download the following sample., code, mvc comments edit

UPDATE: This post is outdated. ASP.NET MVC 2 RTM was released in March.

Four and a half months after my team released ASP.NET MVC 1.0, I am very happy to announce that the release of our first Preview of version 2 of ASP.NET MVC is now available for download. Go download it immediately and enjoy its coolness. :) Don’t be afraid to install it as it will sit nicely side-by-side with ASP.NET 1.0.

The release notes provide more details on what’s in this release and I’ve also updated the Roadmap on CodePlex, which describes the work we want to do in Preview 2 and beyond.

After shipping ASP.NET MVC 1.0, the team and I spent time pitching in on ASP.NET 4 which was a nice diversion for me personally as I got a chance to work on something different for a while and it let ideas for ASP.NET MVC 2 percolate.

But now I’m very happy to be back in the saddle going full bore working on ASP.NET MVC again. As mentioned in the roadmap and elsewhere, ASP.NET MVC 2 will run on both ASP.NET 3.5 SP1 and ASP.NET 4. We will be shipping ASP.NET MVC 2 in the box with Visual Studio 2010 and be making a separate installer for Visual Studio 2008 SP 1 available via download.

Templated Helpers

One of my favorite new additions in Preview 1 is what we call the Templated Helpers. You can watch a short Channel 9 Video that Scott Hanselman filmed of me giving a last minute impromptu demo of Templated Helpers.

Templated Helpers allow you to automatically associate templates for editing and displaying values base on the data type. For example, a date picker UI element can be automatically rendered every time data of type System.DateTime is used.

If you’re familiar with Field Templates in ASP.NET Dynamic Data, then this is very similar to that, but specific to ASP.NET MVC.

To find out more about the helpers, check out the pre-release documentation for a walkthrough of using Templated Helpers.

We also include support for Areas and Data Annotations, along with various bug fixes and minor API improvements. Everything is detailed in the Release Notes.

The Team

I have to say, I really like being a part of a team that I feel is working very well together and am proud of the work they’ve done. Some of them already have blogs such as Eilon (rarely updated) andBrad Wilson. The QA guys recently started a podcast. But others (Levi, looking at you) really need to start a blog. ;) Great work fellas!

Be sure to let us know what you think and provide feedback in our forums!

Related Links

Note: the official name of this version of the product is ASP.NET MVC 2 and not ASP.NET MVC 2.0 as some might expect. Maybe it’s part of a new marketing initiative to get rid of dots in product names. I guess they didn’t read my Law of Demeter post to understand it’s not about reducing dots ;).

comments edit

A member of the Subtext team discovered a security vulnerability due to our integration with the FCKEditor control as well as the FreeTextBox control. This vulnerability would potentially allow unauthenticated users to upload files using the file upload tools included with these editors.

The Fix

If you’re running the latest version of Subtext (Subtext 2.1.1), the quickest way to patch your installation is to copy the following web.config file…

            <allow roles="Admins" />
            <deny roles="HostAdmins"/>
            <deny users="*" />

…to the following directories within the Providers\BlogEntryEditor

  • FCKeditor\editor\filemanager\browser\default\connectors\aspx\
  • FCKeditor\editor\filemanager\upload\aspx\
  • FTB\

If you’re running an older version or would rather not have to hunt through your installation, upgrade to Subtext 2.1.2. The only difference between this version and 2.1.1 is the change mentioned above.


This is the second time we’ve been bitten by integration issues with these rich text editors. The Subtext team takes security very seriously and regret that this vulnerability was released. We’ll take a hard look at these integration points and may consider turning them off by default or some other mitigations. I have a feeling that most of our users use Windows Live Writer or some other such application to post to their blog anyways.

You might wonder why we don’t simply include that web.config file within the Providers directory. I tested that out and unfortunately it breaks FCKEditor for no good reason that I could deduce.

Again, I feel terrible that this happened and we’ll work hard to ensure it doesn’t again. My thanks goes to Si Philp who found the issue and discreetly reported it.


The URL to the new version of Subtext is here.

comments edit

Recently I read a discussion on an internal mailing list on whether or not it would be worthwhile to add a null dereferencing operator to C#.

For example, one proposed idea would allow the following expression.

object a = foo.?bar.?baz.?qux;

This would assign the variable a the value null if any one of foo, bar, or baz is null instead ofthrowing a NullReferenceException. It’s a small, but potentially helpful, mitigation for the billion dollar mistake.

Sure enough, it did not take long for someone to claim that this syntax would be unnecessary if the code here was not violating the sacred Law of Demeter (or LoD for short). I think this phenomena is an analog to Godwin’s Law and deserves its own name. Let’s call it the “LoD Dot Counting Law”:

As a discussion of a code expression with more than one dot grows longer, the probability that someone claims a Law of Demeter violation approaches 1.

dippindots Count the dots and win a prize!

What is wrong with the claim that the above expression violates LoD? To answer that let’s briefly cover the Law of Demeter. I’m not going to cover it in detail but rather point to posts that describe it in much better detail than I would.

The Many Forms of Demeter

The formal object form of the law can be summarized as:

A method of an object may only call methods of:

  1. The object itself.
  2. An argument of the method.
  3. Any object created within the method.
  4. Any direct properties/fields of the object.

A general formulation of the law is:

Each unit should have only limited knowledge about other units: only units “closely” related to the current unit. Or: Each unit should only talk to its friends; Don’t talk to strangers.

This of course leads to the succinct form of the law:

Don’t talk to strangers

In other words, try to avoid calling methods of an object that was returned by calling another method. Often, people shorten the law to simply state “use only one dot”.

One of the key benefits of applying LoD is low coupling via encapsulation. In his paper, The Paperboy, The Wallet, and The Law of Demeter (PDF) (it’s a relatively quick read so go ahead, I’ll be here), David Bock provides a great illustration of this law with an analogy of a paperboy and a customer. Rather than having a customer hand over his wallet to pay the paperboy, he instead has the paperboy request payment from the customer.

In answer to “Why is this better?” David Bock gives these three reasons.

The first reason that this is better is because it better models the real world scenario…  The Paperboy code is now ‘asking’ the customer for a payment.  The paperboy does not have direct access to the wallet.  

The second reason that this is better is because the Wallet class can now change, and the paperboy is completely isolated from that change…

The third, and probably most ‘object-oriented’ answer is that we are now free to change the implementation of ‘getPayment()’.

Note that the first benefit is an improvement not only in encapsulation but the abstraction is also improved.

Dot Counting Is Not The Point

You’ll note that David doesn’t list “50% less dots in your code!” as a benefit of applying LoD. The focus is on reduced coupling and improved encapsulation.

So going back to the initial expression, does violate LoD? Like most things, it depends.

For example, suppose that foo is of type Something and it contains properties named Bar, Baz, and Qux which each simply return this.

In this semi-contrived example, the expression is not an LoD violation because each property returns the object itself and according to the first rule of LoD, “you do not talk about LoD” … wait … sorry… “a method is free to call any properties of the object itself” (in a future post, I will cover the class form of LoD which seems to indicate that if Bar, Baz, and Qux return the same type, whether it’s the same object or not, LoD is preserved).

This pattern is actually quite common with fluent interfaces where each method in a calling chain might return the object itself, but transformed in some way.

So we see that counting dots is not enough to indicate an LoD violation. But lets dig deeper. Are there other cases where counting dots leads do not indicate an LoD violation? More importantly, is it always a bad thing to violate LoD? Are there cases where an LoD violation might even be the right thing to do?

Go Directly to Jail, Do Not Pass Go

Despite its name, violating the Law of Demeter will not get you on an episode of Cops nor is it some inviolable law of nature.

As the original paper points out, it was developed during design and implementation of the Demeter system (hence the name) and was held to be a law for the developers of that system.

The designers of the system felt that this practice ensured good Object-Oriented design:

The motivation behind the Law of Demeter is to ensure that the software is as modular as possible. The law effectively reduces the occurrences of nested message sendings (function calls) and simplifies the methods.

However, while it was a law in the context of the Demeter system, whether it should hold the weight that calling it a Law implies is open to debate.

David Bock refers to it as an idiom:

This paper is going to talk about a particluar (sic) ‘trick’ I like, one that is probably better classified as an ‘idiom’ than a design pattern (although it is a component in many different design patterns).

 Martin Fowler suggests (emphasis mine)

I’d prefer it to be called the Occasionally Useful Suggestion of Demeter.

Personally, I think most developers are guilty of bad encapsulation and tight coupling. I’m a bit more worried about that than applying this law inappropriately (though I worry about that too). Those who have deep understanding of this guideline are the ones who are likely to know when it shouldn’t be applied.

For the rest of us mere mortals, I think it’s important to at least think about this guideline and be intentional about applying or not applying it.

I Fought The Law and The Law Won

So what are the occasions when the Law of Demeter doesn’t necessarily apply? There’s some debate out there on the issue.

In his post, Misunderstanding the Law of Demeter, Daniel Manges argues that web page views aren’t domain objects and thus shouldn’t be subject to the Law of Demeter. His argument hinges on a Rails example where you send an Order object to the view, but the view needs to display the customer’s name.

<%= %>

Counting two dots, he considers the change that would make it fit LoD:

<%= @order.customer_name %>

He then asks:

Why should an order have a customer_name? We’re working with objects, an order should have a customer who has a name.

…when rendering a view, it’s natural and expected that the view needs to branch out into the domain model.

Alex Blabs of Pivotal Labs takes issue with Daniel’s post and argues that views aredomain objects and an order ought to have a customer_name property.

It’s an interesting argument, but the following snippet of a comment by Zak Tamsen summarizes where I currently am on this subject (though my mind is open).

because they don’t. the primary job of the views (under discussion) is to expose the internal state of objects for display purposes. that is, they are expressly for data showing, not data hiding. and there’s the rub: these kind of views flagrantly violate encapsulation, LoD is all about encapsulation, and no amount of attribute delegation can reconcile this.

The problem as I see it with Alex’s approach is where do you stop? Does the Order object encapsulate every property of Customer? What about sub-properties of the Customer’s properties? It seems the decision to encapsulate the Customer’s name is driven by the view’s need to display it. I wouldn’t want my domain object’s interface to be driven by the needs of the view as that would violate separation of concerns.

There’s another option which might be more common in the ASP.NET MVC world than in the Rails world, I’m not sure. Why not have a view specific model object. This would effectively be the bridge between the domain objects and the view and could encapsulate many of the these properties that the view needs to display.

Another case where an LoD violation might not be such a bad idea is in cases where the object structure is public and unlikely to change. While in Norway, I had the opportunity to briefly chat with Michael Feathers about LoD and he pointed out the example of Excel’s object model for tables and cells. If LoD is about encapsulation (aka information hiding) then why would you hide the structure of an object where the structure is exactly what people are interested in and unlikely to change?

Use It or Lose It

When I learn a new guideline or principle, I really like to dig into where the guideline breaks down. Knowing where a guideline works, and what its advantages are is only half the story in really understanding it. When I can explain where it doesn’t work and what its disadvantages are, only then do I feel I’m starting to gain understanding.

However, in writing about my attempts at understanding, it may come across that I’m being critical of the guideline. I want to be clear that I think the Law of Demeter is a very useful guideline and it applies in more cases than not. It’s one of the few principles that can point to an empirical study that may point to its efficacy.

In a Validation of Object-Oriented Design Metrics as Quality Indicators, the authors of the study provide evidence that suggests The Law of Demeter reduces the probability of software faults.

the-count Still, I would hope that those who apply it don’t do it blindly by counting dots. Dot counting can help you find where to look for violations, but always keep in mind that the end goal is reducing coupling, not dots.

humor comments edit

Ok, I haven’t had a good track record with making up jokes before. Just see exhibit A,this groaner of an MVC joke.

However, I think I did oke recently with a few geeky Your Momma jokes that I can’t just leave to Twitter alone. Here they are:

Your momma so fat, Bloatware is her clothing line.

Your momma so fat I called her and got a stack overflow.

your momma so ugly its just best to forego the “V” in MVC with her.

So now it’s your turn. Please post your best ones in the comments to this post. :)

comments edit

When you visit Norway, it takes a week to recover. Ok, at least when I visit Norway, it takes a week. But that’s just a testament to the good time I had. As they say, what happens in Vegas stays in Vegas, but what happens in Oslo gets recorded as a .NET Rocks Live episode.

The week before last, I spent the week in Oslo, Norway attending and speaking at the Norwegian Developer’s Conference (NDC 09). This conference was not your typical Microsoft conference I usually attend but was a conference on .NET with a heavy Agile Software bent.


Just looking at the speaker line-up will tell you that. Scott Bellware tweeted a blurb recently that succinctly summarized my impression of the conference:

how to know you’re at a good conference: the speakers are going to sessions (at least the ones who aren’t working on their sessions)

That is definitely true. I didn’t attend as many talks as I would have liked, but I did manage to attend two by Mary Poppendieck which really sparked my imagination and got me excited about the concept of a problem solving organization and learning more about Lean. She had promised to put her slides on her site, but I can’t for the life of me find them! ;)

While there, I gave three talks, one of them being a joint talk with the Hanselnator (aka Mr. Hanselman).

Black Belt Ninja Tips ASP.NET MVC \ This covered several tips on getting more out of ASP.NET MVC and included the first public demonstration of David Ebbo’s T4 template.

**ASP.NET MVC + AJAX = meant for each other \ **This covered the Ajax helpers included with ASP.NET MVC and drilled into some of the lesser known client aspects of these helpers, such as showing the Sys.Mvc.AjaxContext object and how to leverage it. The talk then moved into a demonstration of the client templating feature of ASP.NET Ajax 4 Preview 4. I showed off some of the work Jonathan Carter and I (mostly Jonathan) did to make two-way data binding work with ASP.NET MVC. The audience really dug it.

**The Haacked and Hanselman Show \ **So named because we didn’t have any agenda until about a week before the conference, this ended up being a web security talk where Scott would present a common “secure” implementation of a feature, I would then proceed to “Haack” the feature, and then Scott would fix the feature, all the while explaining what was going on. I think this was very big hit as we saw messages on Twitter like “I’m now too afraid to build a web application”. ;) Of course, I hope more attendees felt empowered rather than fearful. :P

IMG_3484The conference was held in an indoor soccer stadium since it was a venue large enough for all the attendees. They curtained off sections of the bleachers to create rooms for giving the talks. On the outside of the curtains was a large screen which allowed attendees to walk around from talk to talk with a headset on the conference floor if they didn’t feel like sitting in the bleachers.

IMG_3455Plenty of bean bags on the floor provided a comfortable place to relax and listen in. In fact, that’s where I would often find some of my new friends lounging around such as the crazy Irishman.

On the second night of the conference, we all rocked out at the big attendee party featuring the band, DataRock which played some rocking music with geek friendly lyrics like:

I ran into her on computer camp \ (Was that in 84?) \ Not sure \ I had my commodore 64 \ Had to score

– DataRock, Computer Camp Love

data-rockMany thanks to Kjetil Klaussen for posting those lyrics in his NDC 09 highlights post because I had forgotten pretty much every lyric. :) After DataRock, we all went upstairs for the after party to enjoy a more intimate setting with LoveShack, an 80s cover band.

One interesting highlight of the show was a live recording of .NET Rocks. The show was originally going to simply feature Scott Hanselman, but while hanging out in the speakers lounge Carl Franklin, one of the hosts of the show, suggested I join in the fun too.

haack-hanselman-dotnetrocksWhile it was great fun, Scott is a big, no ginormous, personality and I rarely got a word in edgewise, except for the few times I swooped right in just in time to put my foot in my mouth to apparently great comedic effect. In any case, you can listen to the results yourself, though I hope they post the video soon to get the full effect of how much fun everyone was having. :) Be warned, there’s not a lot of real software development content in the show.

The conference ended on Friday leaving all of Saturday for me to relax and actually get out and see Oslo. On Saturday, I headed out to Vigeland Statue Park with an eclectic group of people, Ted Neward, Rocky Lhotka and his wife, Jeremy Miller, and Anna K{Something With Too Many Syllables in a Row}, a conference organizer herself.

The park was very beautiful and I took a ton of pictures, but unfortunately I lost my camera on the flight home from Norway. :( So instead, I’ll just include this Creative Commons licensed picture taken by Cebete from Flickr. The main difference was the sky was a deep blue when we visited.

Vigeland-ParkThat evening, Sondre Bjellås, an attendee, was kind enough to invite several of us over to his flat for a little gathering. I headed over with Bellware and Anna since everyone else was pretty much flattened by the previous weeks activities. It was great to meet non-techie Norwegians such as his wife and friends in order to get a different perspective on what it’s like to live in Norway. The answer: expensive!

In an odd coincidence, on my connecting flight in Philadelphia, I ran into my good friend Walter who happened to be flying home from Belgium. In fact, we were on the same flight in the same exit row with seats right next to each other. How’s that for a funny coincidence?

Show me the Code!

Rune, one of the organizers of the conference, assures me that the videos of the talks will be posted online soon, so you’ll get to see them if you’d like. I’ve also posted my powerpoint slides and code samples here.

Please note that my talks tend to be heavy in demos so the Powerpoint decks don’t have much content in them. Likewise, the code samples represent the “before” state of my talks, not the “after” state. I usually write up a checklist for each talk which I use a to remind myself where I am in those cases where I have a total brain fart and forget my own name under the pressure of presenting.

Other NDC 09 Posts

comments edit

In my last post, I wrote about the hijacking of JSON arrays. Near the end of the post, I mentioned a comment whereby someone suggests that what really should happen is that browsers should be more strict about honoring content types and not execute code with the content type of application/json.

I totally agree! But then again, browsers haven’t had a good track record with being strict with such standards and it’s probably too much to expect browsers to suddenly start tightening ship, not to mention potentially breaking the web in the process.

Another potential solution that came to mind was this: Can we simply change JSON? Is it too late to do that or has that boat left the harbor?


Let me run an idea by you. What if everyone got together and decided to version the JSON standard and change it in such a way that when the entire JSON response is an array, the format is no longer executable script. Note that I’m not referring to an array which is a property of a JSON object. I’m referring to the case when the entire JSON response is an array.

One way to do this, and I’m just throwing this out there, is to make it such that the JSON package must always begin and end with a curly brace. JSON objects already fulfill this requirement, so their format would remain unchanged.

But when the response is a JSON array, we would go from here:


to here:


Client code would simply check to see if the JSON response starts with {[ to determine whether it’s an array, or an object. There many alternatives, such as simply wrapping ALL JSON responses in some new characters to keep it simple.

It’d be possible to do this without breaking every site out there by simply giving all the client libraries a head start. We would update the JavaScript libraries which parse JSON to recognize this new syntax, but still support the old syntax. That way, they’d work with servers which haven’t yet upgraded to the new syntax.

As far as I know, most sites that make use of JSON are using it for Ajax scenarios so the site developer is in control of the client and server anyways. For sites that provide JSON as a cross-site service, upgrading the server before the clients are ready could be problematic, but not the end of the world.

So what do you think? Is this worth pursuing? Not that I have any idea on how I would convince or even who I would need to convince. ;)

UPDATE: 6/26 10:39 AM Scott Koon points out this idea is not new (I didn’t think it would be) and points to a great post that gives more detail on the specifics of executable JSON as it relates to the ECMAScript Specification.

comments edit

A while back I wrote about a subtle JSON vulnerability which could result in the disclosure of sensitive information. That particular exploit involved overriding the JavaScript Array constructor to disclose the payload of a JSON array, something which most browsers do not support now.

However, there’s another related exploit that seems to affect many more browsers. It was brought to my attention recently by someone at Microsoft and Scott Hanselman and I demonstrated it at the Norwegian Developers Conference last week, though it has been demonstrated against Twitter in the past.


Before I go further, let me give you the punch line first in terms of what this vulnerability affects.

This vulnerability requires that you are exposing a JSON service which…

  • …returns sensitive data.
  • …returns a JSON array.
  • …responds to GET requests.
  • …the browser making the request has JavaScript enabled (very likely the case)
  • …the browser making the request supports the __defineSetter__ method.

Thus if you never send sensitive data in JSON format, or you only send JSON in response to a POST request, etc. then your site is probably not vulnerable to this particular vulnerability (though there could be others).

I’m terrible with Visio, but I thought I’d give it my best shot and try to diagram the attack the best I could. In this first screenshot, we see the unwitting victim logging into the vulnerable site, and the vulnerable site issues an authentication cookie, which the browser holds onto.


At some point, either in the past, or the near future, the bad guy spams the victim with an email promising a hilariously funny video of a hamster on a piano.


But the link actually points to the bad guy’s website. When the victim clicks on the link, the next two steps happen in quick succession. First, the victim’s browser makes a request for the bad guy’s website.


The website responds with some HTML containing some JavaScript along with a script tag. When the browser sees the script tag, it makes another GET request back to the vulnerable site to load the script, sending the auth cookie along.


The bad guy has tricked the victim’s browser to issue a request for the JSON containing sensitive information using the browser’s credentials (aka the auth cookie). This loads the JSON array as executable JavaScript and now the bad guy has access to this data.

To gain a deeper understanding, it may help to see actual code (which you can download and run) which demonstrates this attack.

Note that the following demonstration is not specific to ASP.NET or ASP.NET MVC in any way, I just happen to be using ASP.NET MVC to demonstrate it. Suppose the Vulnerable Website returns JSON with sensitive data via an action method like this.

public JsonResult AdminBalances() {
  var balances = new[] {
    new {Id = 1, Balance=3.14}, 
    new {Id = 2, Balance=2.72},
    new {Id = 3, Balance=1.62}
  return Json(balances);

Assuming this is a method of HomeController, you can access this action via a GET request for /Home/AdminBalances which returns the following JSON:


Notice that I’m requiring authentication via the AuthorizeAttribute on this action method, so an anonymous GET request will not be able to view this sensitive data.

The fact that this is a JSON array is important. It turns out that a script that contains a JSON array is a valid JavaScript script and can thus be executed. A script that just contains a JSON object is not a valid JavaScript file. For example, if you had a JavaScript file that contained the following JSON:

{“Id”:1, “Balance”:3.14}

And you had a script tag that referenced that file:

<script src=""></script>

You would get a JavaScript error in your HTML page. However, through an unfortunate coincidence, if you have a script tag that references a file only containing a JSON array, that would be considered valid JavaScript and the array gets executed.

Now let’s look at the HTML page that the bad guy hosts on his/her own server:

    <script type="text/javascript"> 
        Object.prototype.__defineSetter__('Id', function(obj){alert(obj);});
    <script src=""></script> 

What’s happening here? Well the bad guy is changing the prototype for Object using the special __defineSetter__ method which allows overriding what happens when a property setter is being called.

In this case, any time a property named Id is being set on any object, an anonymous function is called which displays the value of the property using the alert function. Note that the script could just as easily post the data back to the bad guy, thus disclosing sensitive data.

As mentioned before, the bad guy needs to get you to visit his malicious page shortly after logging into the vulnerable site while your session on that site is still valid. Typically a phishing attack via email containing a link to the evil site does the trick.

If by blind bad luck you’re still logged into the original site when you click through to the link, the browser will send your authentication cookie to the website when it loads the script referenced in the script tag. As far as the original site is concerned, you’re making a valid authenticated request for the JSON data and it responds with the data, which now gets executed in your browser. This may sound familiar as it is really a variant of a Cross Site Request Forgery (CSRF) attack which I wrote about before.

If you want to see it for yourself, you can grab the CodeHaacks solution from GitHub and run the JsonHijackDemo project locally (right click on the project and select Set as StartUp Project. Just follow the instructions on the home page of the project to see the attack in action. It will tell you to visit

Note that this attack does not work on IE 8 which will tell you that __defineSetter__ is not a valid method. Last I checked, it does work on Chrome and Firefox.

The mitigation is simple. Either never send JSON arrays OR always require an HTTP POST to get that data (except in the case of non-sensitive data in which case you probably don’t care). For example, with ASP.NET MVC, you could use the AcceptVerbsAttribute to enforce this like so:

public JsonResult AdminBalances() {
  var balances = new[] {
    new {Id = 1, Balance=3.14}, 
    new {Id = 2, Balance=2.72},
    new {Id = 3, Balance=1.62}
  return Json(balances);

One issue with this approach is that many JavaScript libraries such as jQuery request JSON using a GET request by default, not POST. For example, $.getJSON issues a GET request by default. So when calling into this JSON service, you need to make sure you issue a POST request with your client library.

ASP.NET and WCF JSON service endpoints actually wrap their JSON in an object with the “d” property as I wrote about a while back. While it might seem odd to have to go through this property to get access to your data, this awkwardness is eased by the fact that the generated client proxies for these services strip the “d” property so the end-user doesn’t need to know it was ever there.

With ASP.NET MVC (and other similar frameworks), a significant number of developers are not using client generated proxies (we don’t have them) but instead using jQuery and other such libraries to call into these methods, making the “d” fix kind of awkward.

What About Checking The Header?

Some of you might be wondering, “why not have the JSON service check for a special header such as the X-Requested-With: XMLHttpRequest or Content-Type: application/json before serving it up in response to a GET request?” I too thought this might be a great mitigation because most client libraries send one or the other of these headers, but a browser’s GET request in response to a script tag would not.

The problem with this (as a couple of co-workers pointed out to me) is that at some point in the past, the user may have made a legitimate GET request for that JSON in which case it may well be cached in the user’s browser or in some proxy server in between the victim’s browser and the vulnerable website. In that case, when the browser makes the GET request for the script, the request might get fulfilled from the browser cache or proxy cache. You could try setting No-Cache headers, but at that point you’re trusting that the browser and all proxy servers correctly implement caching and that the user can’t override that accidentally.

Of course, this particular caching issue isn’t a problem if you’re serving up your JSON using SSL.

The real issue?

There’s a post at the Mozilla Developer Center which states that object and array initializers should not invoke setters when evaluated, which at this point, I tend to agree with, though a comment to that post argues that perhaps browsers really shouldn’t execute scripts regardless of their content type, which is also a valid complaint.

But at the end of the day, assigning blame doesn’t make your site more secure. These type of browser quirks will continue to crop up from time to time and we as web developers need to deal with them. Chrome and Firefox 3.0.11 were both vulnerable to this. IE 8 was not because it doesn’t support this method. I didn’t try it in IE 7 or IE 6.

It seems to me that to be secure by default, the default behavior for accessing JSON should probably be POST and you should opt-in to GET, rather than the other way around as is done with the current client libraries. What do you think? And how do other platforms you’ve worked with handle this? I’d love to hear your thoughts.

In case you missed it, here are the repro steps again: grab the CodeHaacks solution from GitHub and run the JsonHijackDemo project locally (right click on the project and select Set as StartUp Project. Just follow the instructions on the home page of the project to see the attack in action. To see a successful attack, you’ll need to do this in a vulnerable browser such as Firefox 3.0.11.

I followed up this post with a proposal to fix JSON to prevent this particular issue.

Tags: aspnetmvc, json, javascript, security, browsers

code comments edit

Every now and then some email or website comes along promising to prove Fred Brooks wrong about this crazy idea he wrote in The Mythical Man Month (highly recommended reading!) that there is no silver bullet which by itself will provide a tenfold improvement in productivity, reliability, and simplicity within a decade.

This time around, the promise was much like others, but they felt the need to note that their revolutionary new application/framework/doohickey will allow business analysts to directly build applications 10 times as fast without the need for programmers![revenge-nerds]( "revenge-nerds")

Ah yeah! Get rid of those foul smelling pesky programmers! We don’t need em!

Now wait one dag-burn minute! Seriously?!

I’m going to try real hard for a moment to forget they said that and not indulge my natural knee jerk reaction which is to flip the bozo bit immediately. If I were a more reflective person, this would raised a disturbing question:

Why are these business types so eager to get rid of us programmers?

It’s easy to blame the suits for not understanding software development and forcing us into a Tom Smykowski moment having to defend what it is we do around here.

Well-well look. I already told you: I deal with the god damn customers so the engineers don’t have to. I have people skills; I am good at dealing with people. Can’t you understand that? What the hell is wrong with you people?

Maybe, as Steven “Doc” List quotes from Cool Hand Luke in his latest End Bracket article on effective communication for MSDN Magazine,

What we’ve got here is a failure to communicate.

Leon Bambrick (aka SecretGeek) recently wrote about this phenomena in his post entitled, The Better You Program, The Worse You Communicate, in which he outlines how techniques that make us effective software developers do not apply to communicating with other humans.

After all, we can sometimes be hard to work with. We’re often so focused on the technical aspects and limitations of a solution that we unknowingly confuse the stakeholders with jargon and annoy them by calling their requirements “ludicrous”. Sometimes, we fail to deeply understand their business and resort to making fun of our stakeholders rather than truly understanding their needs. No wonder they want to do the programming themselves!

Ok, ok. It’s not always like this. Not every programmer is like this and it isn’t fair to lay all the blame at our feet. I’m merely trying to empathize and understand the viewpoint that would lead to this idea that moving programmers out of the picture would be a good thing.

Some blame does deserve to lie squarely at the feet of these snake oil salespeople, because at the moment, they’re selling a lie. What they’d like customers to believe is your average business analyst simply describes the business in their own words to the software, and it spits out an application.

The other day, I started an internal email thread describing in hand-wavy terms some feature I thought might be interesting. A couple hours later, my co-worker had an implementation ready to show off.

Now that my friends, is the best type of declarative programming. I merely declared my intentions, waited a bit, and voila!  Code! Perhaps that’s along the lines of what these types of applications hope to accomplish, but there’s one problem. In the scenario I described, it required feeding requirements to a human. If I had sent that email to some software, it would have no idea what to do with it.

At some point, something close to this might be possible, but only when software has reached the point where it can exhibit sophisticated artificial intelligence and really deal with fuzziness. In other words, when the software itself becomes the programmer, only then might you really get rid of the human programmer. But I’m sorry to say, you’re still working with a programmer, just one who doesn’t scoff at your requirements arrogantly (at least not in your face while it plots to take over the world, carrot-top).

Until that day, when a business analyst wires together an applications with Lego-like precision using such frameworks, that analyst has in essence become a programmer. That work requires many of the same skills that developers require. At this point, you really haven’t gotten rid of programmers, you’ve just converted a business type into a programmer, but one who happens to know the business very well.

In the end, no matter how “declarative” a system you build and how foolproof it is such that a non-programmer can build applications by dragging some doohickeys around a screen, there’s very little room for imprecision and fuzziness, something humans handle well, but computers do not, as Spock demonstrated so well in an episode of Star Trek.

“Computer, compute the last digit of PI” - Spock

Throw into the mix that the bulk of the real work of building an application is not the coding, but all the work surrounding that, as Udi Dahan points out in his post on The Fallacy of ReUse.

This is not to say that I don’t think we should continue to invest in building better and better tools. After all, the history of software development is about building better and better higher level tools to make developers more productive. I think the danger lies in trying to remove the discipline and traits that will always be required when using these tools to build applications.

Even when you can tell the computer what you want in human terms, and it figures it out, it’s important to still follow good software development principles, ensure quality checks, tests, etc…

The lesson for us programmers, I believe is two-fold. One, we have to educate our stakeholders about how software production really works. Even if they won’t listen, a little knowledge and understanding here goes a long way. Be patient, don’t be condescending, and hope for the best. Secondly, we have to educate ourselves about the business in a deep manner so that we are seen as valuable business partners who happen to write the code that matters.