August 2009 Blog Posts

7 Stages of new language keyword grief

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!

Or

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.

Conclusion

Thanks to everyone on Twitter who provided examples of language keywords that provoked pushback. It was helpful.

Fun With Method Missing and C# 4

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);
  Console.ReadLine();
}

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>
  <p>
    <%= Data._Body %>
  </p>
</asp:Content>

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

Here’s a screenshot of the end result.

dynamic-mvc

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!

Simpler Transactions

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()) 
{
  DoSomeWork();
  SaveWorkToDatabase();

  transaction.Complete();
}

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(() => {
    DoSomeWork();
    SaveWorkToDatabase();
  });
}

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())
   {
      action();
      transaction.Complete();
    }
  }
}

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(() => {

  DoSomeWork();
  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()) {
      transaction.Complete();
    }
  }
}

Rest For ASP.NET MVC SDK and Sample

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!

Demeter Transmogrifiers To The Rescue

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!

transmogrifier_small

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.

Put Your Views (and Pages) On a Diet

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).

Before

<%@ Page Language="C#" 
  MasterPageFile="~/Views/Shared/Site.Master" 
  Inherits="System.Web.Mvc.ViewPage" %>

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

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

After

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

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

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.

views-webconfig

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):

<configuration>
  <system.web>
    <compilation defaultLanguage="C#" />
    <pages
        masterPageFile="~/Views/Shared/Site.master"
        pageBaseType="System.Web.Mvc.ViewPage"
        userControlBaseType="System.Web.Mvc.ViewUserControl">
    </pages>
  </system.web>
</configuration>

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.

<configuration>
  <system.web>
    <pages>
      <namespaces>
        <add namespace="Haack.Mvc.Helpers" />
      </namespaces>
    </pages>
  </system.web>
</configuration>

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?

Default Templated Views

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 folder are 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.

shared-index-view

Thus any controller with an action named Index would 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>

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

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

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.

add-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).

Add Controller

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 (2)

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; }
    [DisplayName("Shurikens")]
    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.

updated-ninja-details

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.

Add-Partial-View

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.

DisplayTemplates

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

scaffolded-details

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.

Ninja-Details-View

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.