August 2011 Blog Posts
I had a dry run today for an upcoming presentation that did not go quite as well as I would like, though I completely expected this as I was unprepared. The good news is, it was a dry run and not the real thing, so I have plenty of time to adjust.
Even so, there’s one thing I did wrong, that I should have known better than to do. In my crazy sleep deprived work frazzled mind, I broke the cardinal rule of a dry run – Treat it like the real thing!
Kitty Hawk by gilderm from sxc.huFor example, I have a little pre-flight checklist for every talk I give. I just place it in a file named preflight.txt in the root of each presentation folder and adapt it for each presentation. Even though I try to adapt it to each presentation, there is a core set of items that never really changes from one presentation to another. These are items that almost always apply and many are tips learned from other great presenters such as Scott Hanselman and Brad Wilson.
I thought this might be useful for others who find themselves in a position where they are giving presentations. Perhaps some of you will add to my checklist. I divided it into several categories. The last section isn’t actually a check-list, but a reminder of important keyboard shortcuts.
System
- Set Notepad default font size to 16
- Hide Desktop Icons
- Close unnecessary toolbar/tray icons
- Close all unecessary windows including Solution Explorer (use CTRL ALT L to show it)
Visual Studio
- Launch Visual Studio
- Set font size to 16
- Drag necessary files into desktop
- Start and minimize magnifier
- Prepare snippets (if you use them)
- Disable all unnecessary VS extensions
- Or better yet, set up a DEMO instance of Visual Studio (thanks Mike Minutillo!)
General
- Reset all demos. That might mean clearing cookies, clearing browser forms saved data, etc.
- Open the PowerPoint deck to the right spot
- Consolidate your demo scripts into a single document per talk
- Print out notes (and don’t accidentally throw them away like I did)
- Relax
Important Keyboard shortcuts
- Window + to zoom in one level (and start magnifier)
- Windows - to zoom out one level
- Windows ESC to zoom fully out
- CTRL . smart tag expansion
- CTRL , Navigate to
- SHIFT ALT K to display Solution Explorer (I remapped this on Brad's advice because CTRL ALT L conflicts with Windows magnifier)
- CTRL + and CTRL - change font size in NotePad2
I think this checklist nicely complements my presentation tips I learned from my (many) mistakes blog post. Did I forget an obvious preflight option? Do tell!
UPDATE: We found an issue with 1.5 when running behind some proxies that caused an “Arithmetic operation resulted in an overflow” exception message and another issue with signed PS1 scripts. We’ve now posted an update (NuGet 1.5.20902.9023) that fixes the issues.
I’m happy to announce the release of NuGet 1.5 just in time to make sure our roadmap isn’t a liar. I won’t bore you by repeating the details of the release, but instead direct you to the NuGet 1.5 release notes.
If you are running a private NuGet.Server repository, you’ll need to update that repository the latest version of NuGet.Server to connect to it using NuGet 1.5.
I’ve updated our roadmap to reflect what we’re thinking about next. The next release is going to focus more on continuous integration scenarios that we’ve heard from customers, pre-release “beta” packages and multiple UI improvements such as allowing folks to disable package sources.
Also, on occasion, the NuGet feature team hangs out in a home-grown IRC style web based chat application written by David Fowler in his spare time as a test app for SignalR. We’re contemplating the idea of making it a more regular thing if possible.
In a recent blog post, I wrote a a controller inspector to demonstrate Controller and Action Descriptors. In this blog post, I apply that knowledge to build something more useful.
One pain point when you write Ajax heavy applications using ASP.NET MVC is managing the URLs that Routing generates on the server. These URLs aren’t accessible from code in a static JavaScript file.
There are techniques to mitigate this:
- Generate the URLs in the view and pass them into the JavaScript API. This approach has the drawback that it isn’t unobtrusive and requires some script in the view.
- If you prefer the unobtrusive approach, embed the URLs in the HTML in a logical and semantic manner and the script can read them from the DOM.
Both approaches get the job done, but they start to break down when you have a list. For example, suppose I have a page that lists comic books retrieved from the server, each with a link to edit the comic book. Do I then need to generate a URL for each comic on the server and pass it into the script?
That’s not necessarily a bad idea. After all, isn’t that how Hypertext is supposed to work? When you render a set of resources, shouldn’t the response include a navigation URL for each resource?
On the other hand, you might prefer your services to return just comic books and infer the URLs by convention.
How does MvcHaack.Ajax help?
Thinking about this problem led me to build up a quick proof-of-concept prototype based on something David Fowler showed me a long time ago.
The library provides a base controller class, I tentatively named JsonController (I could extend it to support other formats, but I wanted to keep this prototype focused on one common scenario). This class sets up a custom action invoker which does a lot of the work.
With this library in place, a <script> reference pointing to the controller itself generates a jQuery based JavaScript API with methods for calling controller actions.
This API enables passing JSON objects from the client to the server, taking advantage of ASP.NET MVC’s argument model binding.
Perhaps an illustration is in order.
Lets see some codez!
The first step is to write a controller. I’ll start simple and step it up a notch later.
The controller has a single action method that returns an enumeration of anonymous objects. Since I’m inheriting from JsonController, I don’t need to specify an action result return type. I could have returned real objects too, but for the sake of simplicity, I wanted to start here.
public class ComicsController : JsonController {
public IEnumerable List() {
return new[] {
new {Id = 1, Title = "Groo"},
new {Id = 1, Title = "Batman"},
new {Id = 1, Title = "Spiderman"}
};
}
}
The next step is to make sure I have a route to the controller, and not to the controller’s action. The special invoker I wrote handles action method selection. This prototype lets you use a regular route, but the JsonRoute ensures correctness.
public static void RegisterRoutes(RouteCollection routes) {
// ... other routes
routes.Add(new JsonRoute("json/{controller}"));
// ... other routes ...
}
As a reminder, this second step with the JsonRoute is not required!
With this in place, I can add a script reference to the controller from an HTML page and call methods on it from JavaScript. Let’s do that and display each comic book.
First, I’ll write the HTML markup.
<script src="/json/comics?json"></script>
<script src="/scripts/comicsdemo.js"></script>
<ul id="comics"></ul>
The first script tag references an interesting URL, /json/comics?json. That URL points to the controller (not an action of the controller), but passes in a query string value. This value indicates that the controller descriptor should short circuit the request and generate a JavaScript with methods to call each action of the controller using the same technique I wrote about before.
Here’s an example of the generated script. It’s very short. In fact, most of it is pretty statick. The generated part is the array of actions passed to the $.each block and the URL.
if (typeof $mvc === 'undefined') {
$mvc = {};
}
$mvc.Comics = [];
$.each(["List","Create","Edit","Delete"], function(action) {
var action = this;
$mvc.Comics[this] = function(obj) {
return $.ajax({
cache: false,
dataType: 'json',
type: 'POST',
headers: {'x-mvc-action': action},
data: JSON.stringify(obj),
contentType: 'application/json; charset=utf-8',
url: '/json/comics?invoke&action=' + action
});
};
});
For those of you big into REST, you’re probably groaning right now with the RPC-ness of this API. It wouldn’t be hard to extend this prototype to take a more RESTful approach. For now, I stuck with this because it more closely matches the conceptual model for ASP.NET MVC out of the box.
Reference the script, and I can now call action methods on the controller from JavaScript. For example, in the following code listing, I call the List action of the ComicsController and append the results to an unordered list. Since I didn’t need to mix client and server code to write this script, I can place it in a static script file, comicsdemo.js.
$(function() {
$mvc.Comics.List().success(function(data) {
$.each(data, function() {
$('#comics').append('<li>' + this.Title + '</li>');
});
});
});
One more thing
It’s easy to call a parameter-less action method, but what about an action that takes in a type? Not a problem. To demonstrate, I’ll create a type on the server first.
public class ComicBook {
public int Id { get; set; }
public string Title { get; set; }
public int Issue { get; set; }
}
Great! Now let’s add an action method that accepts a ComicBook as an action method parameter. For demonstration purposes, the method just returns the comic along with a message. The invoker serializes the return value to JSON for you. There is no need to wrap the return value in a JsonResult. The invoker handles that for us.
public object Save(ComicBook book) {
return new { message = "Saved!", comic = book };
}
I can now call that action method from JavaScript and pass in a a comic book. I just need to pass in an anonymous JavaScript object with the same shape as a ComicBook. For example:
$mvc.Comics.Save({ Title: 'Adventurers', Issue: 123 })
.success(function(data) {
alert(data.message + ' Comic: ' + data.comic.Title);
});
The code results in the alert pop up. This proves I posted a comic book to the server from JavaScript.
_3.png)
Get the codez!
Ok, enough talk! If you want to try this out, I have a live demo here. One of the demos shows how this can nicely fit in with KnockoutJS.
If you want to try the code yourself, it’s available in NuGet under the ID MvcHaack.Ajax.
The source code is up at Github. Take a look and let me know what you think. Should we put something like this in ASP.NET MVC 4?
EDITOR’S NOTE: Microsoft has an amazing intern program. For a summer, these bright college students work with a feature crew getting real work done, all the while attending cool events nearly every week that, frankly, make the rest of us jealous! Just look at some of the perks listed in this news article!
This summer, the ASP.NET MVC is hosting an intern, Stephen Halter, who while very smart, doesn’t have a blog of his own (booo! hiss!). Being the nice guy that I am (and also being amenable to bribes), I’m letting him guest author a post on my blog (first guest post ever!) to talk about the cool project he’s been doing.
Editor Update: A lot of folks are wondering why we built our own grid. The plan is to build this on top of the jQuery UI Grid when it’s complete. It’s not done yet so we built a scaled down implementation to allow us to test out the interactions with ASP.NET MVC controllers and make sure everything is in place. It’s mostly T4 files that extends our existing Add Controller Scaffolding feature. You can tweak the T4 to build any kind of grid you want.
Hello everyone – my name is Stephen Halter, and I am a summer intern on the ASP.NET MVC team who is excited to show you the new Ajax grid scaffolder that I have been working on for ASP.NET MVC 4. Phil has graciously allowed me to use his blog to get the word out about my project.
We want to get some feedback before releasing the scaffolder as part of the MVC Framework, and we figured what better way to get feedback than to release a preview of the scaffolder as a NuGet package?
To install the package, search for “AjaxGridScaffolder” in the NuGet Package Manager dialog or just enter the following command
PM> Install-Package AjaxGridScaffolder
in the Package Manager Console to try it out.
The NuGet package, once installed, registers itself to the Add Controller dialog as a ScaffolderProvider named “Ajax Grid Controller.” When run, the scaffolder generates a controller and corresponding views for an Ajax grid representation of the selected model and data context class.
The Ajax grid controller scaffolder has many similarities to the current “Controller with read/write actions and views, using Entity Framework”, but it provides pagination, reordering and inline editing of the content using Ajax.


Currently, the Ajax Grid Scaffolder only generates C# code, but both Razor and ASPX views are supported. We’ll add VB.NET support later. If you selected “None” from the Views drop down in the Add Controller dialog, only the controller will be generated.
The generated controller has 8 actions. There is Index, Create (POST/GET), Edit (POST/GET), Delete (POST), GridData, and RowData. Most of these actions probably sound familiar, but there are a few that might not be obvious. The GET versions of Create and Edit provide editing widgets to the client using HtmlHelper.EditorFor or HtmlHelper.DropDownList if the property is a foreign key. The GridData action renders a partial view of a range of rows while RowData renders a partial view a specific row given its primary key. These *Data actions aren’t very verby (editor’s note: “verby?” Seriously?) and improved naming suggestions are welcome.

The scaffolder also provides three views: Index, GridData, and Edit. The Index view includes JavaScript and small amount of CSS required to make the Ajax grid usable. Due to all the possible ways a master or layout page can be done, it isn’t possible to ensure that JavaScript and CSS will be included in the <head> element of the document. However, we are looking at possible fixes for the MVC 4 release.

The GridData and Edit views are partial views that are rendered when retrieving non-editable and editable rows respectively via XMLHttpRequest instances (XHRs) using jQuery. Sending HTML snippets in response to XHRs (as opposed to JSON for example) makes using DisplayFor, EditorFor and ValidationFor more natural and progressive enhancement simpler.
With or without JavaScript, the Index view provides pagination and reordering by column. With JavaScript enabled, rows can be created/edited/deleted all inside the grid without ever leaving the index view.
Tell us what your thoughts are on the Ajax Grid Scaffolder. Is it important to you that we support editing without JavaScript? Do you want the back button to take you to your previous view of the grid? Do you have any suggestions on how to clean up the generated code? Did you encounter any bugs/issues? If so, we want to know.
This is an age old problem and one that’s probably been solved countless times before, but I’m going to write about it anyways.
Say you’re writing code like this:
<p>You have the following themes:</p>
<ul>
@foreach(var theme in Model) {
<li>@theme.Id</li>
}
</ul>
The natural inclination for the lazy developer is to leave enough alone and stop there. It’s good enough, right? Right?
Sure, when the value of Model.Count is zero or larger than one. But when it is exactly one, the phrase is incorrect English as it should be singular “You have the following theme”.
I must fight my natural inclination here! On the NuGet team, we have a rallying cry intended to inspire us to strive for better, “Apple Polish!”. We tend to blurt it out at random in meetings. I’m thinking of purchasing each member of the team a WWSJD bracelet (What Would Steve Jobs Do?).
To handle this case, I wrote a simple extension method:
public static string CardinalityLabel(this int count, string singular,
string plural)
{
return count == 1 ? singular : plural;
}
Notice that I didn’t try automatic pluralization. That’s just a pain.
With this method, I can change the markup to say:
<p>You have the following
@Model.Count.CardinalityLabel("theme", "themes"):</p>
I’m still just not sure about the name of that method though. What should it be?
Do you have such a method? Or are you fine with the awkward phrasing once in a while?
Stumbling around the net, I ran into the “funny verticals” meme. These are typically a vertical strip of screenshots pulled from a movie or television with funny captions tacked on.
If you do an image search for “funny verticals”, you’ll see a whole slew of them. Be forewarned, there are some very crude and offensive ones.
For the lazy, here are a few representative ones I found to be funny. The first example is from the movie Inception:

This is another one from Inception. There seems to be a lot using this specific sequence.

And here’s one from the television show, LOST.

On a lark, I thought it’d be funny to try and do a geek version of this meme. I chose two personalities in our community I figured would be very well known, Scott Hanselman and Scott Guthrie. This has absolutely nothing to do with Hanselman posting this photo on his blog because I’m not the vengeful type. Nosiree.
I’ll post my versions here as well as the raw image because I know you’ll do much better than me. I needed to keep it tame because I do enjoy my employer’s salary continuation plan.

Here’s another one using the same template.

I tried changing this last one up a bit.

It’s pretty challenging to do this with folks who are not television/movie celebrities because you have far fewer images to work from, so I did the best I could with what I could find.
If you think you can do a lot better, download the raw images and prove it! When you do, post a link in the comments so we can see it. 
99.99999% of the time (yes, I measured it), a controller in ASP.NET MVC is a type, and an action is a method — with reflection as the glue that holds it all together. For most folks, that’s the best way to view how ASP.NET MVC works.
But some folks like to dig deeper and get their hands dirty a bit by taking a peek under the hood. Doing so reveals that while the reflection based mapping of controllers types and actions to methods is true by default, it can be easily changed to something else entirely.
ASP.NET MVC contains powerful abstractions for the controllers and actions via the ControllerDescriptor and ActionDescriptor classes. These abstractions make it possible to implement completely different underlying implementations of a controller and action. For example, one could implement a version of ASP.NET MVC on top of a dynamic language using the DLR such as the IronRuby ASP.NET MVC I wrote about a long time ago.
Using these abstractions, we can implement something useful like a Controller Inspector, a nice complement to the Route Debugger I wrote a while back.
Installing the Controller Inspector
The Controller Inspector is available as a NuGet package with the package id MvcHaack.ControllerInspector (my Paint.net skills are top notch!).
Install-Package MvcHaack.ControllerInspector
After installing the package, visit any URL in your application rendered by a controller action. For example, here’s a standard request for a boring action.

With the package installed and while running the site on localhost (it won’t work when the site is deployed), append the query string parameter ?inspect. For example, in my sample, I just visit: http://localhost:38249/?inspect and voila!

I nicely formatted page that displays information about the controller and each of its actions. If you’re wondering, “hey, isn’t this like Glimpse!” please skip to the end of this blog post where I address that.
Here’s a look at an action method.

Notice that it conveniently shows the HTTP verbs next to the name to differentiate action methods of the same name. If an action method accepts a complex type as a parameter, the inspector displays details about that type (though not recursively yet).

Accessing controller metadata
The ControllerDescriptor class provides ways to get at metadata about the controller. The interesting members include:
ControllerName ControllerType GetCanonicalActions GetCustomAttributes
The first two properties are self evident. The method GetCanonicalActions returns an enumeration of ActionDescriptor instances, each of which describes an action. GetCustomAttributes returns attributes applied to the controller. These are typically the filters applied to the controller itself.
In the case of the default controller descriptor, ReflectedControllerDescriptor, the filters returned by GetCustomAttributes are retrieved via reflection. But a custom descriptor could load those filters from elsewhere (as is the case with the IronRuby implementation).
The ActionDescriptor also has a few interesting properties.
ActionName ControllerDescriptor GetCustomAttributes GetFilters GetParameters GetSelectors
Despite what you might expect, you can’t obtain everything you’d want to know from an ActionDescriptor. For example, if you’re interested in the return type of an action method, the ActionDescriptor won’t help? Why not? Well, it may be impossible to tell you that. For example, the type might not be known ahead of time because it requires the action method to be invoked first, as would be the case in a dynamically typed language.
So these abstractions were carefully designed not to assume too much about the underlying implementation of an action/controller.
But as we learned before, 99.99999% of the time we’re dealing with the default reflection based approach. So what the Controller Inspector does is to try and cast the ActionDescriptor to ReflectedActionDescriptor and if that succeeds, it can reflect over the action method normally to provide a lot more details.
Hooking itself up
To hook the code up that outputs all this information, I made use of David Ebbo’s WebActivator package. This allows me to run a bit of code at startup that replaces the current controller factory with an InspectorControllerFactory.
[assembly: PostApplicationStartMethod(typeof(AppStart), "Start")]
namespace MvcHaack.ControllerInspector {
public static class AppStart {
public static void Start() {
var factory = ControllerBuilder.Current.GetControllerFactory();
ControllerBuilder.Current.SetControllerFactory(
new InspectorControllerFactory(factory));
}
}
}
The InspectorControllerFactory wraps the existing controller factory. All it does is call into the existing factory to create a controller, and if the request is a local request with the proper “inspect” query string parameter, it sets its invoker to be an InspectorActionInvoker. This way, for normal requests, there is pretty much no overhead.
public IController CreateController(RequestContext requestContext,
string controllerName) {
var controller = _controllerFactory.CreateController(requestContext,
controllerName);
if (IsInspectorRequest(requestContext.HttpContext.Request)) {
var normalController = controller as Controller;
var invoker = normalController.ActionInvoker;
normalController.ActionInvoker = new InspectorActionInvoker(invoker);
}
return controller;
}
private static bool IsInspectorRequest(HttpRequestBase httpRequest) {
return httpRequest.IsLocal
&& httpRequest.QueryString.Keys.Count > 0
&& httpRequest.QueryString.GetValues(null).Contains("inspect");
}
What the InspectorActionInvoker does is build up a model of all the information we want to display and passes it to a precompiled Razor template using the approach I wrote about recently in Text Templating using Razor the easy way. I simply build up a huge anonymous class and pass it to a dynamic model in the template. Note that this probably won’t work in medium trust, but I can easily fix that later by either using an ExpandoObject or by using a strongly typed model. I was just being lazy as this is a proof of concept.
What about Glimpse?
As soon as I showed this to some co-workers they asked me why I was trying to re-implement Glimpse. If you haven’t heard of Glimpse, stop and go read this blog post. Glimpse is like a server-side Firebug for ASP.NET MVC applications. However, when I last checked, it didn’t have something exactly like this.
The point in writing this was to teach folks about the ControllerDescriptor and ActionDescriptor. I’ll make the code available later when I finish part three of this informal series and perhaps someone can help me turn this into a Glimpse plugin if that makes sense. In the meanwhile, I built the package with symbols so you can debug into it to see the source.
UPDATE: The code is available on Github!
In the third part, I blog about what originally lead me down this path to write about the descriptors, which in turn lead me down the path to write about the Razor Generator. Yes, I’m easily sidetracked!
As a reminder, to try it out, install the MvcHaack.ControllerInspector package then use the ?inspect query string parameter when viewing a page rendered by a controller.
I hate code samples in technical books! No seriously, this is bile I’m not afraid to give a permalink to (nor am I afraid to end a sentence with a preposition, so there!).
Even the shortest code samples are a pain to type in. And if they show anything reasonably interesting, they’re probably too long to type in.
Of course, nobody actually types in the sample code, they grab the code from the companion CD (blech!) or download zip files containing the code from the companion website.
With Professional ASP.NET MVC 3 (print edition | kindle edition) we experimented with a different approach. We made our sample code available as NuGet packages.
It seemed fitting given that ASP.NET MVC 3 included NuGet 1.0 as part of the product. The benefit of this approach is that there’s no fiddling around with downloading and unpacking files and copying source files into the right place.
Throughout the book, you’ll run into a call-out with a command that says something like Install-Package Wrox.SomethingOrOther. If you’re following along with an ASP.NET MVC 3 project open in Visual Studio, it’s as easy as installing that package and you have the source code nicely organized and immediately runnable!
Along with the easily installable code samples, the book covers all the cool new features of ASP.NET MVC 3 including EF Code First Scaffolding, NuGet, and Razor.
For those that like to dig deeper, the book covers the concept of dependency injection and ASP.NET MVC 3’s support for it as well as Test Driven Development (TDD) with ASP.NET MVC. These chapters were written by Brad Wilson, who’s also a co-author of the xUnit.net unit test framework.
Along with Brad, I had the pleasure of also working with Jon Galloway and K. Scott Allen. This was a bit of a reunion for K. Scott, Jon, and I as we co-authored a book with Jeff Atwood (aka CodingHorror) a lifetime ago.
Since Brad and I are on the product team, we were able to sprinkle in behind-the-scene tidbits from the product team that provide insight into how or why certain decisions were made when it came to the product design.
If you read the book (again, available in both a print edition and a kindle edition. Don’t be shy about collecting them all!
), please do write a review on Amazon.com. We appreciate all the feedback we can get and already have ideas on how to improve the next one!
Also, a lot of folks have asked me why the Kindle is priced more than the paperback in some areas. We’re not really in control of that. The suggested retail price of the two editions are exactly the same, but Amazon provides different discounts for each edition.
As to the question, why are the suggested retail prices the same? I really don’t know but I plan to suggest that the electronic edition ought to be cheaper.
A few weeks ago I felt burned out and was in sore need of a vacation. I suggested to my wife that we take the kids somewhere and she sagely noted that taking the kids anywhere at their ages is not a vacation. Perhaps I should go somewhere on my own.
Like a deserted lighthouse!Did I mention she’s the best wife ever?
I decided to take a week off and mix a bit of “staycation” with my vacation. Spend a few days at home and maybe a couple of days away.
The first thing I did was call up Hanselman who was game for a trip to Los Angeles for E3. Unfortunately that fell through when we couldn’t score tickets (yes, we’re cheap). We did find some guy on Craigslist who could score us cheap tickets, but his badges looked hand-drawn and made me a wee bit suspicious. I seriously doubt E3 uses Comic Sans as their badge font.
After much deliberation, I decided to take a trip to the nearby San Juan Island for two nights. The plan was to go sea kayaking, but based on the glowing reports of my co-worker Brad Wilson, I also decided to try ziplining.
Kenmore Air
There are two ways to get to San Juan Island, take a ferry or fly. Well, you could also try to swim, but I wouldn’t much recommend it. A ferry is much cheaper, but it’ll take you three hours to get there. Not only that, the view doesn’t compare to that of an airplane that takes off and lands on water. So I went with a sea plane, figuring taking off and landing on water would be really fun.
The plane was cozy (aka small) which allowed me to sit right behind the cockpit and enjoy a panoramic view during the flight to the island. The landing was whisper soft and I barely noticed it.
So I wonder what this button does.I even had the opportunity to help out by holding the mooring rope for the pilot while he got in to start the plane and take off. I thought about holding onto the rope for an exhilarating ride, but my better judgment kicked in.
You’re going to tell me when to let go right? RIGHT?!
Friday Harbor House
It was a short walk to the Friday Harbor House, my lodgings for the trip. I splurged a bit for a room with a view overlooking the harbor, affording me a view of the incoming sea planes and ferries. I also had a view of the folks dining in the garden just outside the restaurant downstairs under my balcony.
The view of the harbor from my room.
And their view was supplemented by a direct view into my room, keen as I was to keep my window open. Fortunately (for them or for me, I can’t decide), I noticed this before having the occasion to create a very awkward moment.
Unlike most vacations, I actually did spend a lot of time in my room curled up with a good book while enjoying a nice view, so the extra money for the view was well spent.
As a bonus, I learned that the restaurant just under my room was considered by many on the island to be one of the better restaurants.
Ziplining
If you find yourself on San Juan Island, I highly recommend setting apart a bit of time (around 3 hrs) to go ziplining with Zip San Juan. It’s a small operation run by a husband and wife team who exude competence while being extremely friendly. Pat even fashions himself to be a bit of a comedian. I’ll only say I was indeed entertained on the drive there and back.
You better believe I’m not letting go of this rope.
The group I ended up with was a rambunctious extended family on a trip from their home state of Ohio. They graciously treated me as part of their family which apparently means enduring sarcastic quips for the duration of the trip.
Flinging yourself off of a platform bolted 50 feet up a tree harnessed to a cable is surprisingly a lot of fun. Unless you’re deathly afraid of heights. We ran through eight different lines each more interesting than the previous.
Sea Kayaking
For sea kayaking I went with Discovery Sea Kayaks. They are an outfit that is committed to keeping the size of their tours small. My tour had five folks, not counting the guide. I saw another group with what looked like 12 people.
A tour starts with a brief tutorial on safety and proper paddling before setting out in a set of double canoes. We set out on the west side of the island with a nice view of Canada across the sound. We didn’t catch any whales but did see jellyfish, sea lions, and some doll porpoises.
Who said anything about having to actually paddle?
I was fortunate to be sharing a canoe with the guide ensuring I wouldn’t have any problems hearing the guide as he regaled us with interesting stories about the island’s history and our natural surroundings.
I spent two days and two nights on the Island before returning home feeling much refreshed. I look forward to the next opportunity to take such a trip and highly recommend it if you feel yourself being weighed down by work.
As a web guy, I’ve slung more than my fair share of angle brackets over the tubes of the Internet. The Razor syntax quickly became my favorite way of generating those angle brackets soon after its release. But its usefulness is not limited to just the web.
The ASP.NET team designed Razor to generate HTML markup without being tightly coupled to ASP.NET. This opens up the possibility to use Razor in many other contexts other than just a web application.
For example, the help documentation for NuGet.exe is written using the Markdown format that is produced by NuGet.exe. NuGet.exe reflects over its own commands and and uses a Razor template to generate the properly formatted output.
The check-in that enabled this caught my eye and prompted me to write this blog post as it’s a very clean approach. I’ll show you how to do the same thing in no time at all.
RazorGenerator
The first step is to install the RazorGenerator extension from the Visual Studio Extension Gallery.
If you haven’t used the Extension Gallery before, within Visual Studio click on the Tools > Extension Manager menu option to launch the Extension Manager dialog. Select the Online tab and type in “RazorGenerator” (without the quotes) in the upper right search bar.
Make sure to install the one named “Razor Generator” (not to be confused with “Razor Single File Generator for MVC”).

Create your application
For my sample application, I created a simple console application and added a reference to the following assemblies:
- System.Web.WebPages.dll
- System.Web.Helpers.dll
- System.Web.Razor.dll
I then added a new text file and named it RazorTemplate.cshtml. You can name yours whatever you want of course.
Make sure to set the Custom Tool for the CSHTML file to be “RazorGenerator”. To do that, simply right click on the file and select the Properties menu option. Type in “RazorGenerator” (sans quotes) in the field labeled Custom Tool.

I added the following code within the CSHTML file:
@* Generator : Template TypeVisibility : Internal *@
@functions {
public dynamic Model { get; set; }
}
<ul>
@foreach (var item in Model) {
<li>@item.Name (@item.Id)</li>
}
</ul>
That first line is a generator declaration. It’s required to by the Razor Generator. I chose to make the generated template class internal.
The next line starts a functions block. I specify a property for the template named Model in there. If you’re not a fan of the dynamic keyword, please don’t freak out. At least not yet.
I simply chose a dynamic property for the purposes of demonstration, but I could have just as easily made it a strongly typed property. Well, not just as easily as I would have had to create a another type first. But you get the idea.
In fact, I could have added multiple properties to this template if so desired. These properties and methods added here will show up in the generated template class.
The next section is simply the usual razor syntax markup you know and love which is written against the property I defined. In case you’re out of practices with Razor, be sure to check out the C# Razor Syntax Quick Reference I wrote a while back.
Render the template
Now all we need to do is instantiate the template, populate the properties we defined in the template with real values, and we’re done!
So what exactly are we instantiating? The steps we took up until now results in the Razor file generating a template class. If you expand the CSHTML file, you can see the generated class.

That’s the class we need to instantiate. Here’s some code I added in Program.cs that makes use of this generated template class.
class Program {
static void Main(string[] args) {
var template = new RazorTemplate {
Model = new[] {
new {Name = "Scott", Id = 1},
new {Name = "Steve", Id = 2},
new {Name = "Phil", Id = 3},
new {Name = "David", Id = 4}
}
};
Console.WriteLine(template.TransformText());
Console.ReadLine();
}
}
The code is very straightforward. It simply instantiates an instance of the RazorTemplate class and sets the Model property (which is the property I defined within the template) as an array of anonymous objects.
Again, for demonstration purposes, I’m using a dynamic property to access anonymous objects. You can just as well pass in and render strongly typed properties.
After instantiating the template instance, we simply call the TransformText method on it and write the response to the console.

Easy as stepping on a Lego block in the dark!
Note that using Razor as a general text templating langage might not always produce the best results. It was heavily geared towards rendering markup (aka angle brackets) which it’s very good at. Your mileage may vary when attempting to render other types of textual output.
In a following post, I’ll show you a cool way I’m using this technique for a library I’ve been working on meant to demonstrate some cool internals of ASP.NET MVC.
Related Razor Resources
Some of what I’ve shown here has been shown before in the context of ASP.NET MVC. Those other posts are worth reading as well. For example…
I hope you find this useful for your text templating needs!