<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom"><title type="text">johncoder</title><subtitle type="text">a place for my stuff</subtitle><id>http://johncoder.com/</id><updated>2012-01-19T10:57:31Z</updated><link rel="alternate" href="http://johncoder.com/" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/johncoderblog" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="johncoderblog" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry><id>http://johncoder.com/Post/fine-tuning-screen-size-media-queries</id><title type="text">Fine Tuning Screen Size Media Queries</title><summary type="text">I've been trying to incorporate responsive web design at my day job. Here's a couple of quick tips to make your life easier for smoothing over quirks.</summary><published>2012-01-19T10:57:28-05:00</published><updated>2012-01-19T10:57:31Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/fine-tuning-screen-size-media-queries" /><content type="html">&lt;p&gt;When you first get CSS media queries working on your site, it's a great accomplishment. You show people how well your site adapts to different screen sizes, and you receive an approving chorus of "Nice!" and golf claps. Then, in the middle of your demo, some strange quirk causes your CSS transitions to fire in a chaotic loop of confusion, situating elements in unspeakable places. So you go back to your desk and troubleshoot them. At this point, it can feel like an endless sea of UI quirks. Here's a couple of tips to make this less painful.&lt;/p&gt;

&lt;h2&gt;Query Hints&lt;/h2&gt;

&lt;p&gt;If you find yourself saying "I think it's between widths X and Y that causes that quirk," that's not specific enough. Guessing takes too much time. Wouldn't it be better to just know? In which case, use those media queries! Everything is already there. Just drop in some visual elements.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;div class="media-queries"&amp;gt;
    &amp;lt;span class="media-query-default"&amp;gt;Default&amp;lt;/span&amp;gt;
    &amp;lt;span class="media-query-1920"&amp;gt;1920&amp;lt;/span&amp;gt;
    &amp;lt;span class="media-query-1650"&amp;gt;1650&amp;lt;/span&amp;gt;
    &amp;lt;span class="media-query-1280"&amp;gt;1280&amp;lt;/span&amp;gt;
    &amp;lt;span class="media-query-1024"&amp;gt;1024&amp;lt;/span&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then, in your media queries show/hide them as necessary.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/* Styles for displaying which display mode you're in */
.media-queries { right: 0; position: absolute; }
.media-queries span { display: none; }
.media-queries .media-query-default { display: inline; }

@media screen and (min-width: 1860px) {
    .media-queries .media-query-default { display: none; }
    .media-queries .media-query-1920 { display: inline; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With styling and elements like this in place, you'll be able to find the answer on the page. No guessing necessary.&lt;/p&gt;

&lt;h2&gt;Resizing Your Browser&lt;/h2&gt;

&lt;p&gt;It's great that responsive web design causes your page to adjust while resizing the browser. The problem is that you're still in the realm of guesswork. Dragging lets you cover a lot of distance, so how can you be sure of exactly where the problem is? No need for a fancy extension, plugin, tool, module, or otherwise third party helper. Your browser and OS can do this (I guess I can only vouch for Windows on this...). Right click on the browser title bar, and go to "Size". It not only places your cursor in a convenient place for resizing, but it also maps the arrow keys on the keyboard to their respective resizing directions. Hitting an arrow resizes the browser in that direction by a set number of pixels (I don't know exactly what that is, but we'll call it 10). To resize the browser pixel by pixel, hold the &lt;code&gt;Ctrl&lt;/code&gt; key. Combine this with the query hints suggestion above, and you can watch transitions, knowing exactly where the problem is occurring.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/openidportablearea-update-01-18-2012</id><title type="text">OpenIdPortableArea Update</title><summary type="text">A new version of OpenIdPortableArea is avaialble on NuGet.</summary><published>2012-01-18T09:02:57-05:00</published><updated>2012-01-18T21:03:01Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/openidportablearea-update-01-18-2012" /><content type="html">&lt;p&gt;OpenIdPortableArea 2.0.0.1 is available for download on NuGet. Not much going on in this release:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Upgraded to DotNetOpenAuth v3.4.7&lt;/li&gt;
&lt;li&gt;Fixed an Azure compatibility issue. Previously, the return Url did not include the port number. (Big thanks to DarthChucks for opening the issue and providing a fix!)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Remember that there are two separate packages for the project on NuGet based on View Engines:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://nuget.org/packages/OpenIdPortableArea.RazorViews"&gt;OpenIdPortableArea.RazorViews&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://nuget.org/packages/OpenIdPortableArea.WebFormsViews"&gt;OpenidPortableArea.WebFormsViews&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Enjoy!&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/differential-design</id><title type="text">Differential Design</title><summary type="text">I currently work on a very small team, and noticed a pattern in the way we work and design our software. I haven't really heard about anyone else doing this.</summary><published>2011-11-29T10:53:10-05:00</published><updated>2011-11-29T22:53:18Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/differential-design" /><content type="html">&lt;h2&gt;Preface&lt;/h2&gt;

&lt;p&gt;This post discusses a process that emerged from the small team of two developers that I work on. &lt;a href="http://hookscode.com/"&gt;Steven Hook&lt;/a&gt; is the other developer, whom I've known since college. We've been good friends outside of work, and design various aspects of software on a near daily basis.&lt;/p&gt;

&lt;p&gt;Our working environment is somewhat unique; no product manager or QA to speak of. Generally speaking, we're given little guidance on requirements or desired features. This situation requires us to wear a lot of different hats, from UX designer to software architect. Rather than impose a formal process on such a small team, we let ourselves arrive at a process that works for us. One that stays out of our way, and lets us do what we need to do: design and implement software.&lt;/p&gt;

&lt;p&gt;This process isn't geared toward anyone but the small team I work on. Take from it what you will.&lt;/p&gt;

&lt;h2&gt;What's in a Name, Anyway?&lt;/h2&gt;

&lt;p&gt;All processes have to have a name. "Differential Design" is the name I've been using to describe it to others. The structure of the process resembles that of a &lt;a href="http://en.wikipedia.org/wiki/Differential_diagnosis"&gt;differential diagnosis&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Differential diagnosis is a method by which doctors start with a list of symptoms, and arrive at a correct diagnosis by process of elimination. The diagnoses begin as simple as possible, gradually becoming more complicated as they're ruled out. This is the collaborative paradigm of our process.&lt;/p&gt;

&lt;p&gt;Following a trail of links, you might stumble onto the wikipedia entry for the &lt;a href="http://en.wikipedia.org/wiki/Hypothetico-deductive_method"&gt;Hypothetico-deductive model&lt;/a&gt;. This model is what will drive the process toward the best design. Consider this excerpt from the article:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;"According to [the Hypothetico-deductive model], scientific inquiry
  proceeds by formulating a hypothesis
  in a form that could conceivably be
  falsified by a test on observable
  data. A test that could and does run
  contrary to predictions of the
  hypothesis is taken as a falsification
  of the hypothesis. A test that could
  but does not run contrary to the
  hypothesis corroborates the theory. It
  is then proposed to compare the
  explanatory value of competing
  hypotheses by testing how stringently
  they are corroborated by their
  predictions."&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This demonstrates the more scientific aspect of our process. Basically, test theories to figure out how they work toward solving the problem at hand. Then, take the results and compare them to other available solutions.&lt;/p&gt;

&lt;p&gt;For the rest of the post, I'll refer to the "Differential Design" process as "DDx." &lt;/p&gt;

&lt;p&gt;This is strictly anecdotal, but I attribute a lot of this process to House, M.D. I'm a big fan of the series, and having seen many differentials performed on the show, I started to notice similarities in how my team worked, and how House's team worked. Naturally there's less narcissism and insults flying around, but the process is largely the same. The goal is to arrive at a conclusion, and we're all there to make it happen.&lt;/p&gt;

&lt;h2&gt;Process Format&lt;/h2&gt;

&lt;p&gt;The format of our process is somewhat informal (mostly because it's just something we do). Here's a basic outline of what happens during DDx:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Define Success Criteria&lt;/li&gt;
&lt;li&gt;Suppose a Candidate Solution&lt;/li&gt;
&lt;li&gt;Determine Pros and Cons&lt;/li&gt;
&lt;li&gt;Justify Pros and Cons with Rationalizations&lt;/li&gt;
&lt;li&gt;Repeat Steps 2-4 (as necessary to gather a sufficient selection of candidate solutions)&lt;/li&gt;
&lt;li&gt;Sandbox Candidate Solutions (to provide further evidence of feasibility)&lt;/li&gt;
&lt;li&gt;Consider All Candidate Solutions (weigh pros and cons against success criteria)&lt;/li&gt;
&lt;li&gt;Implement Least Objectionable Solution&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The following sections expand on each of the steps listed above.&lt;/p&gt;

&lt;h3&gt;1. Define Success Criteria&lt;/h3&gt;

&lt;p&gt;This is a fairly simple step. As a group, brainstorm a list of conditions that constitute a favorable solution. Items on this list can be anything, from a &lt;em&gt;must have&lt;/em&gt; to a &lt;em&gt;nice to have&lt;/em&gt;. Here are some examples: In a UX, you might look for one or two happy-path scenarios, where a user can perform an action in the least possible amount of clicks. In an API, you might require a happy-path scenario of instantiating a class with sensible defaults, allowing a user of the API to do a specific task in the fewest number of lines of code as possible.&lt;/p&gt;

&lt;h3&gt;2. Suppose a Candidate Solution&lt;/h3&gt;

&lt;p&gt;As a group, take turns suggesting solutions to the problem. These solutions may cater to any number of the success criterion (but more is better than less). No solution is too silly to suggest. Always use everything at your disposal to come up with candidate solutions: past experiences, recently read articles, and an ocean of buzzwords. Google/Bing is also a great tool. Do a brief search to see what others are doing to solve the problem at hand. This is an excellent opportunity to explore nontraditional solutions, like CQRS and NoSql. This process gives them a fair chance to weigh in against tried and true approaches.&lt;/p&gt;

&lt;h3&gt;3. Determine Pros and Cons&lt;/h3&gt;

&lt;p&gt;Given a candidate solution, enumerate pros and cons based on the merits of the solution itself, as well as compared to the success criteria. This should be collaborative and objective. Each participant of the DDx is likely to have a slightly different perspective, which naturally leads to a strong list of pros and cons.&lt;/p&gt;

&lt;h3&gt;4. Justify Pros and Cons with Rationalizations&lt;/h3&gt;

&lt;p&gt;This step is important. Each of the pros and cons should be scrutinized carefully. They may only stay on the list if presented with a strong rationalization. Lack of rationality is grounds for elimination. Remember to be objective, and welcome input from all participants.&lt;/p&gt;

&lt;h3&gt;5. Repeat Steps 2-4&lt;/h3&gt;

&lt;p&gt;This is just our idea loop. Steps 2-4 are about generating well thought out candidate solutions. You can always return to this step later in the DDx if other options should prove to be fruitless. Bear in mind that you could also circle back to the same problem in another DDx session altogether!&lt;/p&gt;

&lt;h3&gt;6. Sandbox Candidate Solutions&lt;/h3&gt;

&lt;p&gt;Sometimes an idea is hard to imagine, making it difficult to enumerate the full list of pros and cons. In this context, sandbox can mean lots of things. The participants can collaborate on a common medium, such as a whiteboard. Or, they can break off to create a proof of concept for a candidate solution. This should be kept as small in scope as possible. More involved sandboxing endeavors tend to be great pairing exercises. Writing unit tests is a great way to sandbox candidate solutions.&lt;/p&gt;

&lt;h3&gt;7. Consider All Candidate Solutions&lt;/h3&gt;

&lt;p&gt;The pros and cons of each solution need to be weighed. Some solutions are better than others, and usually for drastically different reasons. This analysis is really where the DDx becomes exciting. Each participant needs to be an advocate for the success criteria, because the goal is to choose a solution to implement. Choices are difficult, which is why the result of this step should be known as the &lt;em&gt;Least Objectionable Solution&lt;/em&gt;. Choose the solution that best meets all of the success criteria.&lt;/p&gt;

&lt;p&gt;An odd outcome that happens often is the combination of candidate solutions. Sometimes two candidate solutions are both complementary and compatible. That is to say, you can implement both to get the benefits of either solution, while effectively cancelling out the disadvantages of either solution. Repeat the earlier steps of the process on this newly formed idea. This is a great technique for getting some truly unique ideas on the table.&lt;/p&gt;

&lt;h3&gt;8. Implement Least Objectionable Solution&lt;/h3&gt;

&lt;p&gt;Take the selection from the previous step, and implement it. Occasionally, the selected solution ends up being the wrong one for unforeseen reasons. When that happens, start another DDx (either picking up where you left off, or with a completely new one).&lt;/p&gt;

&lt;p&gt;If the implementation is deeply committed, a new DDx should include that as a constraint. Working within the parameters is the name of the game. New ideas should work to alleviate problems with the current implementation in order to meet the impending deadline.&lt;/p&gt;

&lt;p&gt;ASIDE: The &lt;em&gt;Least Objectionable Solution&lt;/em&gt; term pays homage to Dr. Sheldon Cooper's "Friendship Algorithm" in the Big Bang Theory (to which this entire process has a strong corollary):&lt;/p&gt;

&lt;p&gt;&lt;img src="http://images.wikia.com/bigbangtheory/images/6/69/The_Friendship_Algorithm.jpg" alt="The Friendship Algorithm" /&gt;&lt;/p&gt;

&lt;p&gt;(credit: above image from &lt;a href="http://bigbangtheory.wikia.com/wiki/The_Friendship_Algorithm"&gt;http://bigbangtheory.wikia.com/wiki/The_Friendship_Algorithm&lt;/a&gt;)&lt;/p&gt;

&lt;h2&gt;DDx in Practice&lt;/h2&gt;

&lt;p&gt;So far I've painted a picture of a methodical process, with meticulous intricacies and rules of operation. Sorry. It's really very simple. I can reduce all of the above down to the following: "Have a conversation about what you need to do." Conversations move in two directions, and conversations about decisions generally have outcomes. That's all you really need to know. All of this rhetoric is just a formalization of something that can happen very organically (and often does).&lt;/p&gt;

&lt;p&gt;Starting out with this process, your team is likely to follow the set steps. Eventually, it will evolve in to a conversation under fire. Everyone understands the rules and goal of the DDx, which lets the whole team move from solution to solution very quickly.&lt;/p&gt;

&lt;h2&gt;Other Things to Consider&lt;/h2&gt;

&lt;p&gt;Q: &lt;strong&gt;How does this affect design?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A: Expedience and quality. When tasked with designing and implementing features individually, Steve and I tend to do a really great job solving most of the problem at hand. Upon demonstrating progress to one another, we generally expose a lot of gaps in the solution. The DDx process gives us a chance to put our minds together to shorten that feedback cycle. The shortened cycle makes it quicker overall.&lt;/p&gt;

&lt;p&gt;Q: &lt;strong&gt;How long is a typical DDx?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A: As long as it needs to be. Some sessions are brief, lasting only 15 to 20 minutes. More complicated success criteria can draw out a DDx over the course of a few hours, even spanning several sessions. It may help to break down success criteria into smaller pieces for shorter DDx sessions.&lt;/p&gt;

&lt;p&gt;Q: &lt;strong&gt;Who is DDx for? Designers, developers, or architects? Somebody else?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A: Everyone. As I said earlier, I wear a lot of hats at my job. I find that no topic is too small for DDx. My team often uses it for designing user interfaces, from functionality to font sizes. DDx has also been great for connecting our architectural dots. Web application here, windows service there, connected by an API, all talking to a centralized database and denormalized to a reporting database. Which solution works the best is the perfect topic for DDx. The process isn't limited to design, either. We often employ these same tactics for troubleshooting and resolving issues.&lt;/p&gt;

&lt;p&gt;Q: &lt;strong&gt;How do we keep from offending one another during DDx sessions?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A: It's all in the team dynamics. All of the participants really need to have mutual respect and understanding. The key to progress in DDx is keeping a favorable argumentative-to-abrasive ratio. Argumentative by definition is good; "Using or characterized by systematic reasoning." Abrasive is bad. Reject ideas, not people.&lt;/p&gt;

&lt;p&gt;Try to weigh each idea equally, and disregard who originates the idea. Objectivity and rationalization will help mitigate animosity. A common source of animosity is appeal to probability. That is to say, someone deems a solution "feels wrong" will inevitably conclude that it &lt;em&gt;is wrong&lt;/em&gt;. When that is the case, ask each DDx participant to try and come up with concrete evidence that is contrary to the desired outcome. It is actually wrong if there is a sound reason.&lt;/p&gt;

&lt;p&gt;Q: &lt;strong&gt;What do you produce during a DDx? A spec? A napkin diagram? Wile E. Coyote grade blueprint?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A: Whatever you need to get the job done. Typically, our DDx sessions result in a diagram on a whiteboard that stays there until enough progress is made to continue on. Other times a to-do list, or a short written summary. Often enough, the solution is "as simple as possible, but not simpler." On rare occasions, a few page spec has been produced.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Over the course of this long post I've detailed the process that my coworker, &lt;a href="http://hookscode.com/"&gt;Steve Hook&lt;/a&gt;, and I use to design software every day. The process is not nearly this formal. The steps I detailed out are merely a foundation for using DDx to design software as a team. I'm interested in what others think of our methods, and perhaps how it applies outside of our somewhat unique development environment.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/4-rules-of-simple-design</id><title type="text">4 Rules of Simple Design</title><summary type="text">Corey Haines briefly mentioned "4 Rules of Simple Design" on Herding Code while talking about Coderetreats. Naturally, I had to go find out what they were.</summary><published>2011-11-29T07:29:25-05:00</published><updated>2011-11-29T19:32:06Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/4-rules-of-simple-design" /><content type="html">&lt;p&gt;Everyone has acronyms, mnemonic devices, and lists of rules to describe everything they find important in software development. In order to get the most out of these rules, I need a reminder somewhere. This post is mostly a reminder for myself.&lt;/p&gt;

&lt;p&gt;A recent episode of Herding Code featured &lt;a href="http://twitter.com/#!/coreyhaines"&gt;Corey Haines&lt;/a&gt;, discussing Coderetreats among other topics. While talking about this, he mentioned an emphasis on the "4 Rules of Simple Design" during the Coderetreat sessions. He didn't go into it on the podcast, so I ended up doing some research to figure out exactly what those four rules were. It did not take long to find, but here's a bullet point summary (taken from &lt;a href="http://blog.coderetreat.com/on-the-role-of-the-coderetreat-facilitator"&gt;this post&lt;/a&gt;):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Tests tell you if you broke something.&lt;/li&gt;
&lt;li&gt;No duplication allows you to make a change in one place for all pieces of knowledge in your system.&lt;/li&gt;
&lt;li&gt;Good names allow you to easily understand the structure of your design and where you should make your change.&lt;/li&gt;
&lt;li&gt;Small helps keep your head above water when looking through the system.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can find these rules and more at the &lt;a href="http://blog.coderetreat.com/"&gt;Coderetreat blog&lt;/a&gt;.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/write-your-own-mapreduce</id><title type="text">Write Your Own: MapReduce</title><summary type="text">Often a difficult topic to understand, I take a quick look at a crude implementation of MapReduce in C# to get a better idea about what is going on.</summary><published>2011-10-06T10:33:12-04:00</published><updated>2011-10-06T22:33:14Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/write-your-own-mapreduce" /><content type="html">&lt;p&gt;MapReduce first came to my attention while exploring &lt;a href="http://ravendb.net/"&gt;RavenDB&lt;/a&gt;. It's a great product, and I really enjoy the way it makes you think about writing your applications. The hard thing to get used to, however, is modeling things in the way that we tend to naturally think about them, rather than as the RDMBS likes to think about them. That also requires a different approach to querying data. Querying is performed on a precomputed index. That's where MapReduce comes in.&lt;/p&gt;

&lt;p&gt;Here's a clumsy explanation: A data set (some persisted data) is passed to a Map function. That function projects a new data set containing some interesting portions of the input data, called intermediate data. Then, the intermediate data is passed to a Reduce function. The job of the Reduce function is to further aggregate the data, creating a desired result.&lt;/p&gt;

&lt;h2&gt;Write Your Own&lt;/h2&gt;

&lt;p&gt;Rather than babble on about the &lt;a href="http://labs.google.com/papers/mapreduce.html"&gt;academic&lt;/a&gt; aspect of MapReduce, let's get our hands dirty and write our own implementation. Our end result will look and feel similar to creating an index in RavenDB. Our primary goal will be to take this class...&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class BlogPost
{
    public string Title { get; set; }
    public string Body { get; set; }
    public string AuthorName { get; set; }
    public DateTime DatePublished { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;...and calculate the number of posts each author has written. It starts by thinking about the overall function. If we take a moment to envision the actual process, we might come up with the following pseudo code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public ... Execute(...)
{
    return Reduce(Map(data));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This follows the description above. Pass data to Map, then the result of Map to Reduce, and you get your answer. So let's get this going into a class. We'll follow suit with RavenDB and create an abstract class. That way, users of our MapReduce operation can derive a new class and be on their way. We will call this class MapReduceTask, and it will have 3 methods:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Map&lt;/li&gt;
&lt;li&gt;Reduce&lt;/li&gt;
&lt;li&gt;Execute&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Execute method will look just like the pseudo code from above. The Map and Reduce functions will be defined in the descendant class's constructor. Lambda expressions can be used for both Map and Reduce. Since the Map and Reduce functions project result data from input data, a LINQ query is a great fit for these lambda expressions. This won't mean as much to you until we look at writing a derived MapReduceTask later on. For now, here's the abstract class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public abstract class MapReduceTask&amp;lt;TType, TReduceResult&amp;gt;
{
    public Func&amp;lt;IEnumerable&amp;lt;TType&amp;gt;, IEnumerable&amp;lt;dynamic&amp;gt;&amp;gt; Map { get; protected set; }
    public Func&amp;lt;IEnumerable&amp;lt;dynamic&amp;gt;, IEnumerable&amp;lt;TReduceResult&amp;gt;&amp;gt; Reduce { get; protected set; }

    public IEnumerable&amp;lt;TReduceResult&amp;gt; Execute(IEnumerable&amp;lt;TType&amp;gt; input)
    {
        return Reduce(Map(input));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;These signatures might look a little scary at first, but it's pretty straight forward. As we said before, Map is a function that takes input data, and projects intermediate data. Translated to code, Map is a &lt;code&gt;Func&amp;lt;TInput, TResult&amp;gt;&lt;/code&gt; delegate, whose input type is an enumeration of a specific type, &lt;code&gt;TType&lt;/code&gt;, and returns an enumeration of dynamic intermediate data. Similarly, Reduce is a &lt;code&gt;Func&amp;lt;TInput, TResult&amp;gt;&lt;/code&gt; delegate whose input type is an enumeration of dynamic intermediate data, and returns an enumeration of a specific reduce result, &lt;code&gt;TReduceResult&lt;/code&gt;. If it still doesn't make much sense, look at the Execute method signature:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public IEnumerable&amp;lt;TReduceResult&amp;gt; Execute(IEnumerable&amp;lt;TType&amp;gt; input)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It takes an enumeration of TType items as input, and returns an enumeration of TReduceResults. If the dynamic part from above is confusing, just think of it as a friendly way of passing data from the Map function to the Reduce function.&lt;/p&gt;

&lt;p&gt;One more step gives us an easy starting point for creating the derived MapReduceTask type:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public abstract class MapReduceTask : MapReduceTask&amp;lt;dynamic, dynamic&amp;gt;
{

}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This basically lets us create our derived MapReduceTask without having to know the types right away. Then, we can explore our query freely, and add types as the projections become more clear to us. That's kind of a weak justification, but try it without it and you'll see what I mean.&lt;/p&gt;

&lt;h2&gt;Using What We Wrote&lt;/h2&gt;

&lt;p&gt;Now we have the distinct pleasure of using what we just wrote to solve the aforementioned problem: count of blog posts per author. Let's start with the shell of our MapReduceTask descendant:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class BlogPostCountByAuthorTask : MapReduceTask
{
    public BlogPostCountByAuthorTask()
    {
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As we said before, this descendant is intended to provide Map and Reduce functions to be used during the base Execute method. So let's start with the Map function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class BlogPostCountByAuthorTask : MapReduceTask
{
    public BlogPostCountByAuthorTask()
    {
        Map = items =&amp;gt; from item in items
                       select new
                       {
                           Count = 1,
                           item.AuthorName
                       };
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A lambda expression is assigned to the Map property. Items in this case will be a list of blog posts. The lambda basically says this: For each blog post, extract the fields of interest (AuthorName, having a count of 1). This doesn't appear helpful at the surface. Given a list of posts, it would return something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[
    { "AuthorName": "jnelson", "Count": 1 },
    { "AuthorName": "jnelson", "Count": 1 },
    { "AuthorName": "jnelson", "Count": 1 },
    { "AuthorName": "shook", "Count": 1 }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But you can almost see that it's sending us down a path toward solving the question: "How many posts did 'jnelson' write?" Next, the data is molded into the desired result. Let's write the Reduce function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public BlogPostCountByAuthorTask()
    {
        Map = items =&amp;gt; from item in items
                       select new
                       {
                           Count = 1,
                           item.AuthorName
                       };

        Reduce = results =&amp;gt; from result in results
                            group result by result.AuthorName into authors
                            select new ReduceResult
                            {
                                Count = authors.Sum(m =&amp;gt; m.Count),
                                AuthorName = authors.Key
                            };
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Another lambda expression is assigned, this time to the Reduce property. Results in this case will be the intermediate data that was returned from the Map function. This query is only slightly more tricky, because it uses grouping to aggregate final results. The query says this: Group my intermediate by the AuthorName. Then, project results with the fields of interest. AuthorName is the group key, and Count is the sum of all Count properties in the group. This operation will take the above results and reduce them to something more interesting:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[
    { "AuthorName": "jnelson", "Count": 3 },
    { "AuthorName": "shook", "Count":1 }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now that looks like a data set capable of answering our question. Let's go back and clean it up just a little bit. You may have noticed that the Reduce function uses a &lt;code&gt;ReduceResult&lt;/code&gt; type as its projection. Since we know what the input type is (BlogPost) and are returning a specific type (ReduceResult), we can go back and make this class derive from the more generic MapReduceTask:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class BlogPostCountByAuthorTask : MapReduceTask&amp;lt;BlogPost, BlogPostCountByAuthorTask.ReduceResult&amp;gt;
{
    public class ReduceResult
    {
        public int Count { get; set; }
        public string AuthorName { get; set; }
    }

    public BlogPostCountByAuthorTask()
    {
        Map = items =&amp;gt; from item in items
                       select new
                       {
                           Count = 1, 
                           item.AuthorName
                       };

        Reduce = results =&amp;gt; from result in results
                            group result by result.AuthorName into authors
                            select new ReduceResult
                            {
                                Count = authors.Sum(m =&amp;gt; m.Count),
                                AuthorName = authors.Key
                            };
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Ayende has said before that this kind of implementation is confusing. Using a nested class as the generic argument to the base type. Truthfully, it does have a certain &lt;em&gt;Chicken and the Egg&lt;/em&gt; essence about it. It works just the same without the nested class. Do as you please.&lt;/p&gt;

&lt;h2&gt;Performing MapReduce&lt;/h2&gt;

&lt;p&gt;Now that we have an implementation and a MapReduce task for answering our burning question, here is a console application that uses the classes to perform the MapReduce operation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Program
{
    static void Main(string[] args)
    {
        var blogPosts = new[]
        {
            new BlogPost { AuthorName = "jnelson" },
            new BlogPost { AuthorName = "jnelson" },
            new BlogPost { AuthorName = "jnelson" },
            new BlogPost { AuthorName = "shook" }
        };

        var task = new BlogPostCountByAuthorTask();

        var results = task.Execute(blogPosts);

        foreach (var result in results)
        {
            Console.WriteLine("{0} - {1}", result.AuthorName, result.Count);
        }

        Console.ReadKey();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Analysis&lt;/h2&gt;

&lt;p&gt;At first, this feels a little free form. You get some data, you return some data. It's all enumerations, and some of it is dynamic. Here are some other noteworthy rules and properties of MapReduce:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Reduce functions must return the same fields of interest as the Map function.&lt;/li&gt;
&lt;li&gt;The output of a Reduce function is acceptable as input to the same function.&lt;/li&gt;
&lt;li&gt;Map and Reduce functions are intended to be run in parallel.&lt;/li&gt;
&lt;li&gt;Input data is immutable. That is to say, MapReduce does not change input data; it creates new data as the result.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By now you have seen an extremely simplified implementation of MapReduce. While it's not a complete explanation, it should help you to understand how data is transformed and massaged to produce a useful result. These operations are typically done as a computation, and the results are treated as an index. This makes querying a large data set very quick and easy, since you can skip to the end and find the answer.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/get-some-web-in-your-topshelf-with-nancyfx</id><title type="text">Get Some Web In Your Topshelf With NancyFx</title><summary type="text">I recently wrote a windows service, and I wanted to have a web dashboard. Luckily, NancyFx makes that really easy to do.</summary><published>2011-09-09T10:16:36-04:00</published><updated>2011-11-29T18:18:13Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/get-some-web-in-your-topshelf-with-nancyfx" /><content type="html">&lt;p&gt;&lt;a href="http://topshelf-project.com/"&gt;Topshelf&lt;/a&gt; makes windows services a breeze. But, I'm a web oriented guy and I like using a browser to get an inside look at what my service is doing. For that I chose to use &lt;a href="http://nancyfx.org"&gt;NancyFx&lt;/a&gt; (mostly as a learning experience and excuse to use something new).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;UPDATE:&lt;/strong&gt; Andreas had some great suggestions to improve my example, which I have updated the post with.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;UPDATE:&lt;/strong&gt; I have made the example code for this post available on &lt;a href="https://bitbucket.org/johncoder/nancyfxtopshelfexample"&gt;bitbucket&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;NuGet Packages&lt;/h2&gt;

&lt;p&gt;For this set up, I used the following NuGet packages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://nuget.org/List/Packages/Topshelf"&gt;Topshelf&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://nuget.org/List/Packages/Nancy"&gt;Nancy&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://nuget.org/List/Packages/Nancy.Viewengines.Razor"&gt;Nancy.Viewengines.Razor&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://nuget.org/List/Packages/Nancy.Hosting.Wcf"&gt;Nancy.Hosting.Wcf&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://nuget.org/List/Packages/Nancy.Bootstrappers.Ninject"&gt;Nancy.Bootstrappers.Ninject&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Configuring Topshelf&lt;/h2&gt;

&lt;p&gt;The service we'll be using polls for new tweets on a specific search term. Here's some code to set up the service:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private static void StartHosting()
{
    var stopwatch = new Stopwatch();
    stopwatch.Start();
    using (Container)
    {
        var host = HostFactory.New(config =&amp;gt;
        {
            config.EnableDashboard();
            config.Service&amp;lt;PghDotNetTwitterWatcherService&amp;gt;(s =&amp;gt;
            {
                s.SetServiceName("NancyTopshelfExample.PghDotNetTwitterWatcherService");
                s.ConstructUsing(c =&amp;gt; Container.Get&amp;lt;PghDotNetTwitterWatcherService&amp;gt;());
                s.WhenStarted(n =&amp;gt; StartService(n, stopwatch));
                s.WhenStopped(n =&amp;gt; StopService(n, stopwatch));
            });
            config.RunAsLocalSystem();
            config.SetDescription("A service for watching twitter for new tweets about pghdotnet.");
            config.SetDisplayName("NancyTopshelfExample.PghDotNetTwitterWatcherService");
            config.SetInstanceName("NancyTopshelfExample.PghDotNetTwitterWatcherService");
            config.SetServiceName("NancyTopshelfExample.PghDotNetTwitterWatcherService");
        });
        host.Run();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This really isn't all that interesting, except for the fact that Nancy will being running at the same time as this service. Nancy will be able to talk to the service on each page request to find out how things are going, and then return them in a view to the user's browser.&lt;/p&gt;

&lt;h2&gt;Example Service&lt;/h2&gt;

&lt;p&gt;The service doesn't do much. Once every 5 seconds, it makes an http request to get tweets. It adds new tweets to the WorkLog, and increments some counters to keep track of successes and failures. The Nancy module will be using these counters.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class PghDotNetTwitterWatcherService : IService
{
    private readonly Dictionary&amp;lt;string, string&amp;gt; _tweets;
    private bool _stopped;
    private Task _task;

    public List&amp;lt;string&amp;gt; WorkLog { get; private set; }
    public long TotalRequestsMade { get; private set; }
    public long TotalFailures { get; private set; }

    public PghDotNetTwitterWatcherService()
    {
        _tweets = new Dictionary&amp;lt;string, string&amp;gt;();
        WorkLog = new List&amp;lt;string&amp;gt;();
        Tick();
    }

    private void Tick()
    {
        var sb = new StringBuilder();

        try
        {
            GetTweets("pghdotnet");
            TotalRequestsMade++;
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception);
            WorkLog.Add(exception.Message);
            TotalFailures++;
        }

        if (sb.Length &amp;gt; 0)
        {
            AddToWorkLog(sb);
        }

        Thread.Sleep(5000);

        if (!_stopped)
            _task = Task.Factory.StartNew(Tick);
    }

    private void AddToWorkLog(StringBuilder stringBuilder)
    {
        WorkLog.Add(stringBuilder.ToString());
        var last5 = WorkLog.AsQueryable().Reverse().Take(5).ToArray();
        WorkLog.RemoveAll(s =&amp;gt; !last5.Contains(s));
    }

    protected void GetTweets(string term)
    {
        // omitted for brevity, but go get tweets from twitter
        // check for new ones in the results
        // write new tweets to the WorkLog
    }

    public void Start()
    {
        Console.WriteLine("Starting PghDotNetTwitterWatcherService...");
    }

    public void Stop()
    {
        _stopped = true;
        Console.WriteLine("Stopping PghDotNetTwitterWatcherService...");
        _task.Wait();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I really only want one instance of this service running, so I configured the &lt;code&gt;PghDotNetTwitterWatcherService&lt;/code&gt; class to be a singleton. Since I'm using Ninject to resolve the service with Topshelf, I'll need to make use of the Ninject bootstrapper package for Nancy. More on that in a bit.&lt;/p&gt;

&lt;h2&gt;Running Nancy&lt;/h2&gt;

&lt;p&gt;I chose to use WCF as my Nancy host, and Razor as my view engine. I wrapped it in an &lt;code&gt;IWebComponent&lt;/code&gt; interface with simple &lt;code&gt;Start&lt;/code&gt; and &lt;code&gt;Stop&lt;/code&gt; methods:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class NancyComponent : IWebComponent
{
    private WebServiceHost _nancyHost;

    public Uri BaseUri { get; private set; }

    public NancyComponent(Uri baseUri)
    {
        BaseUri = baseUri;
    }

    public void Start()
    {
        var service = new NancyWcfGenericService();
        _nancyHost = new WebServiceHost(service, BaseUri);
        _nancyHost.AddServiceEndpoint(typeof(NancyWcfGenericService), new WebHttpBinding(), "");

        // this can fail if there isn't a urlacl for the desired port
        // if it fails, open a cmd with "run as administrator" and run:
        // netsh http add urlacl url=http://+:8585/ user=\Everyone
        _nancyHost.Open();
        Console.WriteLine("Nancy: Listening to requests on {0}", BaseUri);
    }

    public void Stop()
    {
        _nancyHost.Close();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Starting Nancy up under WCF is easy, a staggering 4 lines of code. Not much of a big deal. Now that there's hosting, we have to have a NancyModule to host.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class MainModule : NancyModule
{
    private readonly PghDotNetTwitterWatcherService _service;

    public MainModule(PghDotNetTwitterWatcherService service)
    {
        _service = service;

        Get["/"] = parameters =&amp;gt;
        {
            if (!Request.Headers.Host.StartsWith("localhost:"))
                return 404;

            var indexViewModel = new IndexViewModel { CurrentDateTime = DateTime.Now, WorkLog = _service.WorkLog };

            return View["index", indexViewModel];
        };

        Get["/style/{file}"] = p =&amp;gt;
        {
            return Response.AsCss("content/themes/base/" + p.file as String);
        };

        Get["/status"] = parameters =&amp;gt;
        {
            return Response.AsJson(new { _service.TotalCommitsProcessed, _service.TotalFailures });
        };
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This module goes out to the IoC container, and pulls back an instance of the service. There's a few ways to do this, the choice is yours. Essentially, I only want the local machine to have access to this status page. To do this I look at the host header to see if it starts with localhost. If not, return a 404. Otherwise, a view model is prepared and returned to the client. You could also use  an authentication provider to limit this access, but this was simple for the example.&lt;/p&gt;

&lt;p&gt;You'll also need to wire up some views. After &lt;a href="http://stackoverflow.com/questions/6469163/blank-responses-using-nancy-self-host-topshelf"&gt;struggling with this&lt;/a&gt; for a short while, I settled on using this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class AssemblyLocationRootPathProvider : IRootPathProvider
{
    public string GetRootPath()
    {
        return new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With this approach, you'll have to set views to copy during your build. Otherwise, you could take advantage of Nancy's support for embedded views.&lt;/p&gt;

&lt;p&gt;The module above has a dependency, but won't know how to get the singleton instance that Ninject is holding onto. In this case, we'll make great use of the Ninject bootstrapper. As Andreas indicated, you just need to derive a custom bootstrapper from the &lt;code&gt;NinjectNancyBootstrapper&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class NinjectCustomBootstrapper : NinjectNancyBootstrapper
{
    protected override Ninject.IKernel GetApplicationContainer()
    {
        return Program.Container;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Extras&lt;/h2&gt;

&lt;p&gt;As you may have noticed, I also had an action mapped for &lt;code&gt;/status&lt;/code&gt; in my Nancy module. It returns a JSON object with some counter values. Endpoints like this one are useful for allowing service health monitoring from a widget or similar.&lt;/p&gt;

&lt;p&gt;In the service I wrote using this approach, I was interacting with a database which made &lt;a href="http://nuget.org/List/Packages/Dapper"&gt;Dapper&lt;/a&gt; a great addition. What's more, it would be great to work in &lt;a href="http://nuget.org/List/Packages/MiniProfiler"&gt;MiniProfiler&lt;/a&gt; to get some extra insight on performance (it would probably have to be adapted to work with Nancy). Maybe someday.&lt;/p&gt;

&lt;p&gt;If anyone is interested in this code, I'll gladly add it to my example code repository.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/ipads-and-crappy-code-part-1</id><title type="text">iPads and Crappy Code: Part 1</title><summary type="text">Bold? Sure. In this part of a possible series on designing sites for iPad, I talk about tricking the iPad into letting you have functionality similar to "beforeunload" and why it's no good.</summary><published>2011-09-01T04:52:44-04:00</published><updated>2011-09-01T16:52:48Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/ipads-and-crappy-code-part-1" /><content type="html">&lt;p&gt;My &lt;a href="http://hookscode.com/"&gt;accomplice&lt;/a&gt; and I ran into an issue with using an iPad to view a site we develop. The page in question saves up some data, and posts it to the server after certain events take place. This batch of data needs to be sent when they suddenly click the back button. &lt;em&gt;Obviously&lt;/em&gt; iPad doesn't really want you to do that. It doesn't let you handle "beforeunload" events.&lt;/p&gt;

&lt;p&gt;I came up with a hacky idea of using a &lt;a href="http://benalman.com/projects/jquery-hashchange-plugin/"&gt;hash change&lt;/a&gt; event to do our dirty work. Here's the example code:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DISCLAIMER&lt;/strong&gt;: This isn't suitable for mission critical applications. Don't use it. Also, all error handling code has been pretty much omitted from this snippet. If you choose to use it, be smart and take the time to handle any errors you can.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function setupHash() {

    var url = window.location.toString();

    if (url.indexOf('#busy') == -1) {
        window.location = url + '#busy';
    }

    $(window).hashchange(function() {
        if (!window.location.hash) {
            myCustomModule.SendData(function () {
                history.go(-1);
            });
            return;
        }
    });
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When the user lands on the page with their iPad, it checks to see if the window location is on a hash of "busy". This is our trick to make the browser push another entry into its history. Think of it this way, the history has something like this: &lt;code&gt;["PageA", "PageB", "PageB#busy"]&lt;/code&gt;. If you're on "PageB#busy", hitting back takes you to "PageB".&lt;/p&gt;

&lt;p&gt;When you click back, and a hash changed event is triggered, we'll see that there's no hash avaialble. That's our signal to do our dirty work. In this case, &lt;code&gt;myCustomModule.SendData(...)&lt;/code&gt; is being passed a callback function. We're performing an ajax post, and the callback gets invoked after it's done. The callback contains &lt;code&gt;history.go(-1);&lt;/code&gt;. When that callback executes, it'll take the user back to "PageA" (which is what they probably expected to happen anyway).&lt;/p&gt;

&lt;h2&gt;It works, so why does it suck?&lt;/h2&gt;

&lt;p&gt;Because it's evil and doesn't account for a lot of possibilities. For one, what if the user just types in a new address and hits go? There's no hash change for that. All of the data is lost. I suspect something like HTML5 local storage could help with this by picking up on it with the next page visit (I don't know much about local storage, just a hunch).&lt;/p&gt;

&lt;p&gt;What if using the hash causes complications with other url-bound data? Or another hash? Then you have to program yourself out of a corner.&lt;/p&gt;

&lt;p&gt;What if the user refreshes the page? "Just tell them not to do that."&lt;/p&gt;

&lt;p&gt;In short, this method probably won't be the endgame for solving this problem. I'm sure it will evolve into something more fool proof, and less hacky. In time, I suppose.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/metro-launchy-skin</id><title type="text">Metro Skin For Launchy</title><summary type="text">To go along with my Metro UI kick, I thought I would show an example of a Metro skin I made for Launchy a while back.</summary><published>2011-08-17T11:21:05-04:00</published><updated>2011-08-17T11:22:54Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/metro-launchy-skin" /><content type="html">&lt;p&gt;If you're not using &lt;a href="http://launchy.net/"&gt;Launchy&lt;/a&gt;, you should be. Here's a screenshot of the Metro skin I made:&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm7.static.flickr.com/6186/6053209926_aed7c27c29_b.jpg" alt="Metro skin for Launchy" /&gt;&lt;/p&gt;

&lt;p&gt;I didn't spend a whole lot of time on this. All I really wanted was a clean skin with the right font and a drop shadow. It would be great if I could get animations in, but this was good enough for now. If anyone is interested in having this skin, send me an email. If I get a lot of interest from people, I'll post the skin somewhere where you can download it freely.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Related Resources&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://hookscode.com/Post/metro-ui-inspiration"&gt;Steven Hook's Metro UI Inspiration&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://johncoder.com/Post/metro-loading-dots-jquery-plugin"&gt;Metro Loading Dots&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Have you seen any other Metro skins for existing apps?&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/metro-loading-dots-jquery-plugin</id><title type="text">Metro Loading Dots jQuery Plugin</title><summary type="text">If you've ever used Windows Phone 7, you're probably familiar with its loading animation. I've written a simple jQuery plugin to emulate that animation.</summary><published>2011-08-13T02:20:39-04:00</published><updated>2011-08-13T14:35:50Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/metro-loading-dots-jquery-plugin" /><content type="html">&lt;p&gt;The loading dots plugin is available (un-minified) on &lt;a href="https://bitbucket.org/johncoder/loadingdots"&gt;bitbucket&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I'm on the metro bandwagon. I can't help it. It's just a fun, simple, clean way to design your user interfaces. The animations give life to the otherwise bland arrangement of pixels. Your users will be drawn to changing focal points in your application as they are emphasized with tiny bounces and sliding entrances. The feedback is invaluable from the user's perspective. One easy way to give that kind of feedback is to add an indication that something is happening. It adds some level of perceived performance in your applications.&lt;/p&gt;

&lt;p&gt;This plugin animates a collection of dots across the screen left to right. The animation sweeps each dot one by one to the middle section of a container, and then one by one easing them out. It respects the bounds of the parent container, adding some neat degrees of variation to how it can impact your user interface.&lt;/p&gt;

&lt;p&gt;Even as I wrote this plugin, I sat in sheer enthrallment over several dots flying across my screen. It's a neat plugin, even if you only ever look at it once.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm7.static.flickr.com/6194/6038580837_0dcfc28295_b.jpg" alt="loading dots example page screenshot" /&gt;&lt;/p&gt;

&lt;p&gt;This animation seems to work best in IE9. It's considerably smoother than in Chrome or FireFox. I have tested it in IE9, Chrome, FireFox, and Safari. At some point I'd like to see how it works on a mobile browser.&lt;/p&gt;

&lt;h2&gt;Examples&lt;/h2&gt;

&lt;h3&gt;Basic Example&lt;/h3&gt;

&lt;p&gt;If you have html like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;div class="example"&amp;gt;
    &amp;lt;button&amp;gt;toggle&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can add loading dots like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('.example button').loadingDots();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The plugin expects that the element you selected is the trigger. Think of it as adding the ability to show and hide loading dots to the button under the example div. The dots are added after the button, producing essentially:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;div class="example"&amp;gt;
    &amp;lt;button&amp;gt;toggle&amp;lt;/button&amp;gt;
    &amp;lt;div class="loader"&amp;gt;
        &amp;lt;ul&amp;gt;
            &amp;lt;li&amp;gt; &amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt; &amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt; &amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt; &amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt; &amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt; &amp;lt;/li&amp;gt;
        &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To show or hide the loading dots, use a click handler like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('.example button').click(function() {
    $(this).toggleLoadingDots();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Ajax Example&lt;/h3&gt;

&lt;p&gt;You can use these dots at the global ajax level as well. If you have a div like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;div id="#ajax-example"&amp;gt;&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Set up your loading dots like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('body').loadingDots({ destination: '#ajax-example' });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This uses the body as a trigger (it doesn't really matter what element you use). By specifying the &lt;code&gt;destination&lt;/code&gt; in the options, the plugin will add the dots as a child of the destination, as opposed to adding them after the trigger.&lt;/p&gt;

&lt;p&gt;Toggle the animations by handling jQuery's &lt;code&gt;ajaxStart&lt;/code&gt; and &lt;code&gt;ajaxStop&lt;/code&gt; events:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('#ajax-example').ajaxStart(function(){
    $('body').showLoadingDots();
}).ajaxStop(function() {
    $('body').hideLoadingDots();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Options&lt;/h2&gt;

&lt;p&gt;These are the options and their respective defaults:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var settings = {
    dotColor: '#00B4FF',
    dotSize: '4',   // size in pixels
    dotQuantity: 6,
    duration: 1300, // time in milliseconds it takes to animate half way across the screen
    destination: '' // element to append dots to
};
&lt;/code&gt;&lt;/pre&gt;
</content></entry><entry><id>http://johncoder.com/Post/pittsburgh-givecamp-2011-1</id><title type="text">Pittsburgh GiveCamp 2011.1</title><summary type="text">A couple of weeks ago was the first GiveCamp held in Pittsburgh. I had no idea what to expect going into it, other than sleepless nights and a stiff deadline.</summary><published>2011-08-03T08:50:53-04:00</published><updated>2011-08-03T21:00:03Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/pittsburgh-givecamp-2011-1" /><content type="html">&lt;p&gt;A few lucky organizations were selected for the first Pittsburgh GiveCamp. I was assigned to the &lt;a href="http://mentoringpittsburgh.org/"&gt;Mentoring Partnership of Southwest Pennsylvania&lt;/a&gt;. Most of the other projects were CMS based, requiring mostly a rehash of an existing site with a new, fresh perspective. This was definitely not one of those projects. I received the requirements during the week before. At first glance, I could only describe them as ambitious.&lt;/p&gt;

&lt;h2&gt;Team Ambitious&lt;/h2&gt;

&lt;p&gt;What started out as a team of only a few people gradually expanded to a team of at least seven over the weekend (usually no more than 5 at once). Our project would not have survived had it not been for the other people who joined us. Huge thanks to them!&lt;/p&gt;

&lt;p&gt;Shortly after arriving at &lt;a href="http://www.ddiworld.com/"&gt;DDI&lt;/a&gt; for the event, I was introduced to several members of the Mentoring Partnership. We were all well acquainted by the kickoff meeting. Then we dove in and started writing on the walls. Literally.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm7.static.flickr.com/6024/5962183999_eda8e944f0_b.jpg" alt="Team Ambitious" /&gt;&lt;/p&gt;

&lt;p&gt;Ever get the feeling that a project was doomed from the start? I was overwhelmed with that feeling for probably the first 6 hours. It was simply &lt;em&gt;too much&lt;/em&gt; to do in such a small amount of time. The team members and I distilled the complicated business model into a simpler, more manageable one for the narrow time frame. Essentially, it consisted of three major business entities, and a few associations, and what amounts to a pile of metadata.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm7.static.flickr.com/6141/5962738674_9ba89ff0fc_b.jpg" alt="Team Ambitious" /&gt;&lt;/p&gt;

&lt;p&gt;We made progress in leaps and bounds. On Sunday, we were proud to demonstrate the brand new application (despite my original doubts about the project).&lt;/p&gt;

&lt;h2&gt;It Was For Everyone&lt;/h2&gt;

&lt;p&gt;To say that the organizations selected for GiveCamp were the only ones to get something out of the deal is preposterous. Our team experienced something unique that I had never heard about in any other GiveCamp.&lt;/p&gt;

&lt;p&gt;It was at least a few hours into the event before anyone even brought up which stack to use for the project. We pontificated long and hard about what it was we needed to do, not how we were going to do it. How often does that happen? The eventual recommendation came not from me, but from &lt;a href="http://twitter.com/#!/rjygraham"&gt;Ryan Graham&lt;/a&gt;. He mentioned ASP.NET MVC3, and SQL Server 2008 R2 Express. Add to that Entity Framework Code First and MvcScaffolding, and we quickly had a new project started and ready to go. Since this is pretty much my daily gig, I agreed. The discussion about source control lasted about 2 minutes before we settled on Mercurial. &lt;a href="http://johncoder.com/Post/HelpfulMercurialResources"&gt;Twist my arm why don't you&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The technology stack we chose to use was convenient for me, but for a lot of my teammates it would be a first time. Some had experience with WebForms, and others had a basic knowledge of MVC. A majority of the people had been NHibernate fans, but were optimistic about giving EntityFramework a chance. I don't think anyone had ever used Mercurial in an everyday project other than myself.&lt;/p&gt;

&lt;p&gt;It was a rough start to the project. While the team members came up to speed on the technology stack, we were faced with interesting scenarios like this one:&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm7.static.flickr.com/6026/5962229251_d39033e998.jpg" alt="Merge gone wrong" /&gt;&lt;/p&gt;

&lt;p&gt;This was the result of a few concurrent commits and an awkward merge. This was pretty much the worst of the stuck points for the weekend. Merges became easier as we each diverged into individual areas.&lt;/p&gt;

&lt;p&gt;It was not until some time Saturday afternoon that we really struck a great balance as a team. Everyone grabbed tasks to do and collaborated around the table. My laptop was connected to the projector, serving as the focal point for our work. The interesting part about our team was how we worked together. There was no nerd-posturing, no fight for dominance or superiority over technology A or B. Instead, everyone was focused on the project, and genuinely interested in learning to apply the chosen technology stack. A lot of my time was spent jumping from person to person, helping them merge source locally, and showing how to use Entity Framework Code First effectively. For this, I was awarded the "Most Geeky" award of the weekend.&lt;/p&gt;

&lt;p&gt;Working this way came natural to me; a sort of group twist on the standard fare of XP practices we've all heard about. In college, I learned to program by sitting down with people like &lt;a href="http://hookscode.com"&gt;Steven Hook&lt;/a&gt;. We handed off a single mouse and keyboard, taking turns writing code. Through group effort and collaboration, we got work done while learning a bunch. Much to my surprise, this happened very naturally for our team during GiveCamp.&lt;/p&gt;

&lt;p&gt;Based on some discussions with the event's coordinators, Irwin Hurst and John Hidey, achieving this with each project could be a future goal of the Pittsburgh based GiveCamp events. I can't wait to see what they come up with.&lt;/p&gt;

&lt;h2&gt;Sunday = Done Day&lt;/h2&gt;

&lt;p&gt;The code freeze came on Sunday, wrapping up the weekend of labor. After that, the weekend came to an end with a presentation from each group about who the project was for, and what the end result was. We were proud to show what we were able to finish.&lt;/p&gt;

&lt;p&gt;I remember a moment during our presentation where I realized that &lt;strong&gt;we actually got some work done&lt;/strong&gt;, in spite of using a technology stack unfamiliar to a majority of the team. Most of my consciousness had been devoted to helping everyone understand the problems they ran into, and how to fix them, that I hadn't taken a moment to look at exactly how far we had come. My team members were awesome, and did a lot of good work on the project.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm7.static.flickr.com/6025/5976261634_8941f325aa_b.jpg" alt="Group picture after closing presentations" /&gt;&lt;/p&gt;

&lt;h2&gt;Thoughts&lt;/h2&gt;

&lt;p&gt;The projects that organizations brought to the event were interesting, but probably didn't do as well as they might have. Programmers are going to make more of an impact on an organization when can utilize their true skills. In my case, I worked on a project where my skills made a big difference. For others, projects were mostly geared for designers and CMS specialists, requiring little to no actual programming. I agree that a good public website is a necessity for most organizations, but I feel that it deters from the true value-add that can result from pooling programmers together at GiveCamp events. It would be great to see more projects as ambitious as the one I worked on for the Mentoring Partnership. Until those projects start coming around to GiveCamp, we need to find a way to get more designers!&lt;/p&gt;

&lt;p&gt;Rumor has it there will be another GiveCamp event around October this year. Watch the &lt;code&gt;#pghgivecamp&lt;/code&gt; twitter hashtag for more details, or visit the &lt;a href="http://pghgivecamp.org/"&gt;site&lt;/a&gt;.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/fun-with-regex-and-dynamic</id><title type="text">Fun With Regex And Dynamic</title><summary type="text">Parsing obscure file formats can be a fun exercise at times, and I decided to flex my regex muscle and experiment with some dynamic objects to solve a simple problem.</summary><published>2011-04-17T04:38:07-04:00</published><updated>2011-04-17T16:37:59Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/fun-with-regex-and-dynamic" /><content type="html">&lt;p&gt;If you're saying "I don't care, show me the code!", then go check out the code in my &lt;a href="https://bitbucket.org/johncoder/example-code/src"&gt;example code repository&lt;/a&gt; on bitbucket. It's in the CaldendarParser directory.&lt;/p&gt;

&lt;p&gt;The file format in question is &lt;a href="http://en.wikipedia.org/wiki/ICalendar"&gt;iCalendar (*.ics)&lt;/a&gt;. You can export your calendar from Microsoft Outlook or Google Calendar in this format. Here's a sample taken from wikipedia:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
UID:uid1@example.com
DTSTAMP:19970714T170000Z
ORGANIZER;CN=John Doe:MAILTO:john.doe@example.com
DTSTART:19970714T170000Z
DTEND:19970715T035959Z
SUMMARY:Bastille Day Party
END:VEVENT
END:VCALENDAR
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A majority of this file format is in a "name:value" format, with a somewhat hierarchical structure. The levels of the hierarchy are delimited by "BEGIN" and "END" throughout. Rather than look for a complicated library or write my own absurd iCalendar serializer with a complete set of two way serialization features, I decided to write a dynamic wrapper for it.&lt;/p&gt;

&lt;p&gt;Using regex, I can divide the file into more meaningful, manageable pieces:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;const string ValuePattern = @"^(?&amp;lt;name&amp;gt;[^:;]*)[:;](?&amp;lt;value&amp;gt;.*)$";
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Sometimes the file contains long fields, and the value wraps to the next line, indented with a single tab. Before running the regular expression, I'll have to normalize the input:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fileContents.Replace("\n\t", "");
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So, I've run the regular expression on the normalized iCalendar file. Now, I can loop through the collection of matches, and start building up an &lt;code&gt;ExpandoObject&lt;/code&gt;. The &lt;code&gt;ExpandoObject&lt;/code&gt; actually implements &lt;code&gt;IDictionary&amp;lt;string, object&amp;gt;&lt;/code&gt;, which means that I'll mostly be working with a dictionary to build up the expando.&lt;/p&gt;

&lt;p&gt;For each of the matches, I'll have a named group for a name and value. They'll each be added to the dictionary. After adding the item to the dictionary, it becomes a property on the &lt;code&gt;ExpandoObject&lt;/code&gt; (i.e., calling &lt;code&gt;.Add("SUMMARY","Hi!")&lt;/code&gt; lets you call &lt;code&gt;expando.SUMMARY&lt;/code&gt; later on).&lt;/p&gt;

&lt;p&gt;The bulk of these files are a series of events, which are primarily what I'm after. That means we'll have to take the hierarchical portion of the file into account. I used a stack to coordinate the levels. Each level is a new dynamic object, or a dynamic object that is added to a list of dynamic objects. If the expando already contains an object for the name (like "BEGIN:VEVENT"), I replace the existing property with a list of dynamic objects.&lt;/p&gt;

&lt;p&gt;Here's the method I use to parse the file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public dynamic Parse(string fileContents)
{
    var normalizedFileContents = Normalize(fileContents);

    var regex = new Regex(ValuePattern, RegexOptions.Multiline);
    var matches = regex.Matches(normalizedFileContents).Cast&amp;lt;Match&amp;gt;();

    dynamic expando = new ForgivingExpandoObject();

    var stack = new Stack&amp;lt;dynamic&amp;gt;();

    foreach(var match in matches)
    {
        var name = match.Groups["name"].Value.Trim().Replace("-", string.Empty);
        var value = match.Groups["value"].Value.Trim().Replace("-", string.Empty);

        if (name == "BEGIN" &amp;amp;&amp;amp; value != "VCALENDAR")
        {
            dynamic tempExpando = new ForgivingExpandoObject();
            stack.Push(tempExpando);
            tempExpando[name] = value;

            if (expando.ContainsKey(value))
            {
                var collection = expando[value] as ICollection&amp;lt;dynamic&amp;gt;;

                if (collection != null)
                {
                    collection.Add(tempExpando);
                }
                else
                {
                    var temp = expando[value];
                    expando[value] = new List&amp;lt;dynamic&amp;gt;{temp, tempExpando};
                }
            }
            else
            {
                expando[value] = tempExpando;
            }
        }
        else if (name == "END" &amp;amp;&amp;amp; value != "VCALENDAR")
        {
            var obj = stack.Pop();
            AddValue(obj, name, value);
        }
        else if (stack.Any())
        {
            AddValue(stack.Peek(), name, value);
        }
        else
        {
            AddValue(expando, name, value);
        }
    }

    return expando;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;After using this method, you get back a nice dynamic object that has properties and values, closely matching that of the file. To access the events from the parsed iCalendar file, I can use linq to objects:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var events = from evt in result.VEVENT as IEnumerable&amp;lt;dynamic&amp;gt;
                select new Event
                    {
                        Summary = evt.DESCRIPTION,
                        StartDate = evt.DTSTART,
                        EndDate = evt.DTEND,
                        Title = evt.SUMMARY,
                        Location = evt.LOCATION
                    };
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice that I had to cast &lt;code&gt;result.VEVENT&lt;/code&gt; as &lt;code&gt;IEnumerable&amp;lt;dynamic&amp;gt;&lt;/code&gt;. If you don't do that, you'll get a compiler error.&lt;/p&gt;

&lt;h2&gt;property oddities&lt;/h2&gt;

&lt;p&gt;Some of the fields contain dashes and other characters that are illegal in identifiers. While processing each name, the illegal characters are stripped out. For example, &lt;code&gt;X-WR-CALNAME&lt;/code&gt; becomes &lt;code&gt;XWRCALNAME&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Not all fields are required in the iCalendar format. A great example of this is the "LOCATION" field. If you don't enter this into your event in Outlook, the field isn't included in the export. That means that the linq query above will throw an exception because there is no property "LOCATION" on the dynamic object. To remedy this problem, I wrote a forgiving wrapper for the &lt;code&gt;ExpandoObject&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class ForgivingExpandoObject : DynamicObject
{
    public dynamic Expando { get; set; }

    private readonly IDictionary&amp;lt;string, object&amp;gt; _dict;

    public object this [string index]
    {
        get { return _dict[index]; }
        set
        {
            if (_dict.ContainsKey(index))
            {
                _dict[index] = value;
            }
            else
            {
                _dict.Add(index, value);
            }
        }
    }

    public ForgivingExpandoObject()
    {
        Expando = new ExpandoObject();
        _dict = Expando as IDictionary&amp;lt;string, object&amp;gt;;
    }

    public bool ContainsKey(string key)
    {
        return _dict.ContainsKey(key);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        _dict[binder.Name] = value;
        return true;
    }

    public override IEnumerable&amp;lt;string&amp;gt; GetDynamicMemberNames()
    {
        return _dict.Keys;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (_dict.ContainsKey(binder.Name))
        {
            result = _dict[binder.Name];
            return true;
        }

        if (binder.ReturnType.IsValueType)
        {
            result = Activator.CreateInstance(binder.ReturnType);
        }
        else
        {
            result = null;
        }

        return true;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Its available interface is close to that of the &lt;code&gt;ExpandoObject&lt;/code&gt;, except that it will not throw an exception for trying to access a property for a value that might not have been in the iCalendar file. If the property is not there, it figures out what the return type was supposed to be, and returns its default value. By using this &lt;code&gt;ForgivingExpandoObject&lt;/code&gt;, I can prevent runtime errors for fields that aren't there.&lt;/p&gt;

&lt;h2&gt;value parsing&lt;/h2&gt;

&lt;p&gt;Since we're dealing with events, you'll probably need to get the start and end date of each event. The date time values are represented in a variety of ways, ranging from UTC and local times, as well as specifying the names of timezones. Other fields like SUMMARY and DESCRIPTION sometimes have literal replacement issues, like &lt;code&gt;\n&lt;/code&gt; and &lt;code&gt;\r&lt;/code&gt;. They're leftover and unaccounted for.&lt;/p&gt;

&lt;p&gt;I devised a way to take care of these values, without getting overly complicated using a new interface, &lt;code&gt;IEvaluator&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IEvaluator
{
    string Name { get; }
    dynamic Evaluate(string s);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The Name property is the name of the field in the iCalendar that needs to be parsed differently. The Evaluate function is called to perform the parsing.&lt;/p&gt;

&lt;p&gt;Here's an example of a few evaluators (note that the way I parse out DateTime values isn't 100% in all scenarios, but it gets the point across for the purposes of this post):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class SummaryEvaluator : IEvaluator
{
    public string Name { get { return "SUMMARY"; } }

    public dynamic Evaluate(string s)
    {
        return new Regex(@"LANGUAGE=.*:").Replace(s, m =&amp;gt; string.Empty);
    }
}

public class DescriptionEvaluator : IEvaluator
{
    public string Name { get { return "DESCRIPTION"; } }

    public dynamic Evaluate(string s)
    {
        return s.Replace("\\n", "").Replace("\\r", "");
    }
}

public abstract class DateTimeEvaluator : IEvaluator
{
    public abstract string Name { get; }

    public dynamic Evaluate(string s)
    {
        // TZID="Eastern Standard Time":
        var tzidRegex = new Regex("TZID=\".*\":", RegexOptions.Singleline);
        // VALUE=DATE:20110604
        var valueDateRegex = new Regex("VALUE=DATE:");
        // 20100406T203000Z
        var digitRegex = new Regex(@"^\d\d\d\d\d\d\d\dT\d\d\d\d\d\dZ{0,1}$");

        var dateTimeString = s;
        string pattern = dateTimeString.EndsWith("Z") ? "yyyyMMddTHHmmssZ" : "yyyyMMddTHHmmss";

        if (!digitRegex.IsMatch(s))
        {
            dateTimeString = tzidRegex.Replace(s, m =&amp;gt; string.Empty);
            dateTimeString = valueDateRegex.Replace(dateTimeString, m =&amp;gt; string.Empty);
            pattern = dateTimeString.Length == 8 ? "yyyyMMdd" : dateTimeString.EndsWith("Z") ? "yyyyMMddTHHmmssZ" : "yyyyMMddTHHmmss";
        }

        var dt = DateTime.ParseExact(dateTimeString, pattern, null);
        return dt;
    }
}

public class StartDateEvaluator : DateTimeEvaluator
{
    public override string Name { get { return "DTSTART"; } }
}

public class EndDateEvaluator : DateTimeEvaluator
{
    public override string Name { get { return "DTEND"; } }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;These evaluators are easily testable since their concerns are small. The class that handles all of the parsing will be a collection of these evaluators:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class CalendarParser : Dictionary&amp;lt;string, IEvaluator&amp;gt;
{
    private const string ValuePattern = @"^(?&amp;lt;name&amp;gt;[^:;]*)[:;](?&amp;lt;value&amp;gt;.*)$";

    public CalendarParser()
    {
        Add&amp;lt;SummaryEvaluator&amp;gt;();
        Add&amp;lt;StartDateEvaluator&amp;gt;();
        Add&amp;lt;EndDateEvaluator&amp;gt;();
        Add&amp;lt;DescriptionEvaluator&amp;gt;();
    }

    public void Add&amp;lt;TEvaluator&amp;gt;() where TEvaluator : IEvaluator, new()
    {
        var evaluator = new TEvaluator();
        Add(evaluator.Name, evaluator);
    }

    public dynamic Parse(string fileContents)
    {
        // parsing method from above!
    }

    private static string Normalize(string fileContents)
    {
        return fileContents.Replace("\n\t", "");
    }

    private void AddValue(ForgivingExpandoObject expando, string name, string value)
    {
        if (ContainsKey(name))
            expando[name] = this[name].Evaluate(value);
        else
            expando[name] = value;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;summary&lt;/h2&gt;

&lt;p&gt;I found this to be an interesting exercise, taking very little time to write and accomplishing the majority of a big need at work. In my opinion, this is one of the better uses for a dynamic object, since I'm looking for flexibility. Sure, you lose support for things like intellisense, but I think it's great if I find a new field I need to retrieve from the file, because I just need to reference it. I don't have to add a property to a class or set of classes, and I sure as heck don't have to go back to modify my file parsing code. At most, I'll have a goofy value for the field, and then implement an evaluator to help massage the data.&lt;/p&gt;

&lt;p&gt;If you would like to see this code in a running example, go to my &lt;a href="https://bitbucket.org/johncoder/example-code/src"&gt;example code repository&lt;/a&gt;. You can find it under "CalendarParser".&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/mimeo-interpolation</id><title type="text">Mimeo - Interpolation</title><summary type="text">I added this feature because I needed a way to interject some data into a token, and use it while rendering a template. In this post, I'll go over interpolating tokens.</summary><published>2011-04-17T02:59:18-04:00</published><updated>2011-04-17T14:59:24Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/mimeo-interpolation" /><content type="html">&lt;p&gt;This post is a part of a series:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="http://johncoder.com/Post/introducing-mimeo"&gt;Introducing: Mimeo&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://johncoder.com/Post/mimeo-block-tokens"&gt;Mimeo - Block Tokens&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://johncoder.com/Post/mimeo-conditional-tokens"&gt;Mimeo - Conditional Tokens&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Mimeo - Interpolation&lt;/li&gt;
&lt;li&gt;Mimeo - Theming Your ASP.NET MVC3 Application&lt;/li&gt;
&lt;li&gt;Mimeo - Design Philosophy&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This feature is a bit of an oddball standing next to the rest. I had a hard time finding a way to work this into the order example from the previous posts in this series. Rather than force an awkward example, I've found another way to demonstrate this feature.&lt;/p&gt;

&lt;p&gt;In this example, we'll try to make a token that lets us specify a search term to show tweets in the rendered template. Here's our end goal:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@Tweets(johncoder)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We should expect to see some tweets from johncoder in the output of this template.&lt;/p&gt;

&lt;h2&gt;example&lt;/h2&gt;

&lt;p&gt;Up until now, tokens have been used for simple replacements. They're defined with a string identifier, and a function whose result replaces the identifier. With interpolating tokens, you're still defining a token and a function. The difference being &lt;em&gt;how&lt;/em&gt; the token is defined. The following example builds an interpolating token:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var mimeograph = new Mimeograph&amp;lt;Foo&amp;gt;(builder =&amp;gt;
{
    builder.Interpolate("@Tweets(", "(?&amp;lt;term&amp;gt;.*)", ")", GetTweets);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The token builder has a method called &lt;code&gt;Interpolate&lt;/code&gt;, which uses 3 string parameters to describe the entire token. It consists of a beginning &lt;code&gt;@Tweets(&lt;/code&gt;, argument pattern &lt;code&gt;(?&amp;lt;term&amp;gt;.*)&lt;/code&gt;, and an end &lt;code&gt;)&lt;/code&gt;. The last parameter is the function that receives the arguments while the token is being rendered.&lt;/p&gt;

&lt;p&gt;Using a regular expression, you're able to describe what data can be passed into the method. This is where it gets interesting. The function parameter of the Interpolate method is of type &lt;code&gt;Func&amp;lt;dynamic, string&amp;gt;&lt;/code&gt;. The dynamic parameter is the result of the regular expression. In many cases, a simple expression like &lt;code&gt;.*&lt;/code&gt; will do. Then you can call ToString() on the parameter to get the value. In other cases, you might wish to break the value into several named pieces. To accomplish this, use &lt;a href="http://www.regular-expressions.info/named.html"&gt;named capturing groups&lt;/a&gt;. Each captured group from the regular expression appears as a property on the dynamic object. Take a look at the GetTweets method from the token builder example above:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;protected static string GetTweets(dynamic d)
{
    var request = (HttpWebRequest)WebRequest.Create(@"http://search.twitter.com/search.atom?q=" + d.term);
    using (var stream = new StreamReader(request.GetResponse().GetResponseStream()))
    {
        var response = stream.ReadToEnd();
        var xdoc = XDocument.Parse(response);
        var tweets = string.Join("\n ", xdoc.Descendants(XName.Get("title", "http://www.w3.org/2005/Atom")).Select(c =&amp;gt; c.Value));
        return tweets;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The regular expression captures a group called "term" and in the GetTweets method, the dynamic parameter, d, has a property called term. This is especially cool if you're capturing several groups.&lt;/p&gt;

&lt;h2&gt;template&lt;/h2&gt;

&lt;p&gt;Here's a template that uses the above example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Tweets:

@Tweets(pghdotnet)

@Tweets(wcfhttp)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The same token is used twice in this template. &lt;code&gt;@Tweets(&lt;/code&gt; begins the token, the text &lt;code&gt;pghdotnet&lt;/code&gt; and &lt;code&gt;wcfhttp&lt;/code&gt; are the parameters passed to it, and then the &lt;code&gt;)&lt;/code&gt; ends the tokens.&lt;/p&gt;

&lt;p&gt;Here's a sample of the rendered output:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Tweets:

pghdotnet - Twitter Search
 RT @adrianwright: Excited for my first chance to speak at @pghdotnet on Tuesday!
 RT @adrianwright: Excited for my first chance to speak at @pghdotnet on Tuesday!
 Excited for my first chance to speak at @pghdotnet on Tuesday!
 Goal: Finish the #pghdotnet wp7 app this weekend.
 Not going to be able to make it to #pghdotnet meeting this coming week. Boo
 @DavidHoerster @pghdotnet @johnhidey thanks for the RT.
 RT @johnsterrett: New Blog Post: Changing SQL Server Job Owners against the SQL Server Enterprise http://ow.ly/1cbiFB
 Just registered for Pittsburgh Code Camp 2011.1 http://pghdotnet.org/?page_id=46

wcfhttp - Twitter Search
 @gblock Just getting into #REST. Is it possible to add custom verbs with the new #wcfhttp API? (like WebDav did). Thanx.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is the complete listing of code used in this post:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml.Linq;
using Mimeo;

namespace MimeoInterpolationExample
{
    class Program
    {
        static void Main()
        {
            var mimeograph = new Mimeograph&amp;lt;Foo&amp;gt;(builder =&amp;gt;
            {
                builder.Interpolate("@Tweets(", "(?&amp;lt;term&amp;gt;.*)", ")", GetTweets);
            });

            var mimeographs = new Mimeographs();
            mimeographs.Add(mimeograph);

            string template = @"
Tweets:

@Tweets(pghdotnet)

@Tweets(wcfhttp)
";

            mimeographs.CreateStencil&amp;lt;Foo&amp;gt;("foo-template", template);

            Console.WriteLine(mimeographs.Render("foo-template", new Foo()));

            Console.ReadKey();
        }

        protected static string GetTweets(dynamic d)
        {
            var request = (HttpWebRequest)WebRequest.Create(@"http://search.twitter.com/search.atom?q=" + d.term);
            using (var stream = new StreamReader(request.GetResponse().GetResponseStream()))
            {
                var response = stream.ReadToEnd();
                var xdoc = XDocument.Parse(response);
                var tweets = string.Join("\n ", xdoc.Descendants(XName.Get("title", "http://www.w3.org/2005/Atom")).Select(c =&amp;gt; c.Value));
                return tweets;
            }
        }
    }

    public class Foo
    {

    }
}
&lt;/code&gt;&lt;/pre&gt;
</content></entry><entry><id>http://johncoder.com/Post/mimeo-conditional-tokens</id><title type="text">Mimeo - Conditional Tokens</title><summary type="text">In the last post of this series on Mimeo, I talked about block tokens and how to use them. In this post, I'll cover conditional tokens.</summary><published>2011-04-13T07:49:44-04:00</published><updated>2011-04-17T15:00:22Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/mimeo-conditional-tokens" /><content type="html">&lt;p&gt;This post is a part of a series:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="http://johncoder.com/Post/introducing-mimeo"&gt;Introducing: Mimeo&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://johncoder.com/Post/mimeo-block-tokens"&gt;Mimeo - Block Tokens&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Mimeo - Conditional Tokens&lt;/li&gt;
&lt;li&gt;&lt;a href="http://johncoder.com/Post/mimeo-interpolation"&gt;Mimeo - Interpolation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Mimeo - Theming Your ASP.NET MVC3 Application&lt;/li&gt;
&lt;li&gt;Mimeo - Design Philosophy&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;It may be desirable to conditionally render a block in a template. Mimeo supports this with the &lt;code&gt;TokenizeIf()&lt;/code&gt; method. I may change the name of this method at some point. The order of the parameters is subject to change as well.&lt;/p&gt;

&lt;p&gt;In the last post we continued building on a console application. This time, let's add shipping information to the order class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public ShippingInformation ShipTo { get; set; }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here's the class definition:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class ShippingInformation
{
    public string Street1 { get; set; }
    public string Street2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;example&lt;/h2&gt;

&lt;p&gt;This time, we'll modify the template configuration to optionally support a shipping address for an order. The following snippet is a subset of the token builder code.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;order.TokenizeIf(o =&amp;gt; o.ShipTo, "@ShipTo", o =&amp;gt; o.ShipTo != null, shipto =&amp;gt;
{
    shipto.Tokenize(s =&amp;gt; s.Street1, "@Street1");
    shipto.Tokenize(s =&amp;gt; s.Street2, "@Street2");
    shipto.Tokenize(s =&amp;gt; s.City, "@City");
    shipto.Tokenize(s =&amp;gt; s.State, "@State");
    shipto.Tokenize(s =&amp;gt; s.Zip, "@Zip");
}).EndsWith("@EndShipTo");
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The syntax looks similar to what we've seen so far. There's a mapping to a property, a string token identifier (which, in this case, is the beginning of the block to be rendered), and a child context. The only different part of this is the condition parameter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;o =&amp;gt; o.ShipTo != null
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Before the library will render this block, it executes this delegate using the context. If the method returns true, it is allowed to proceed with rendering the block. Otherwise, it skips it and moves on.&lt;/p&gt;

&lt;p&gt;The condition parameter is a &lt;code&gt;Func&amp;lt;TModel, bool&amp;gt;&lt;/code&gt;. In this case, the order object is passed in, and tested for a null ShipTo property.&lt;/p&gt;

&lt;h2&gt;template&lt;/h2&gt;

&lt;p&gt;We'll use the same template from before, this time adding the ShipTo block.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;==== Order Report ======
@FirstName @LastName is a Person who is @Age years old.
    Submitted On | Amount
@Orders
    @DateSubmitted     | @Amount
    @ShipTo Shipped To:
        @Street1
        @Street2
        @City @State, @Zip
    @EndShipTo
@EndOrders
========================
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here's some sample output from this template. There are three orders, and only the second order has shipping information.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;==== Order Report ======
John Nelson is a Person who is 24 years old.
    Submitted On | Amount

    1/1/2011     | $10.00


    1/2/2011     | $20.00
     Shipped To:
        123 Main St
        Apt B
        Pittsburgh PA, 15203


    1/3/2011     | $30.00


========================
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here is a complete listing of the sample code in this post:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System;
using System.Collections.Generic;
using Mimeo;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            const string template = @"
==== Order Report ======
@FirstName @LastName is a Person who is @Age years old.
    Submitted On | Amount
@Orders
    @DateSubmitted     | @Amount
    @ShipTo Shipped To:
        @Street1
        @Street2
        @City @State, @Zip
    @EndShipTo
@EndOrders
========================";

            var mimeographs = new Mimeographs();

            var mimeograph = new Mimeograph&amp;lt;Person&amp;gt;(builder =&amp;gt;
            {
                builder.Tokenize(p =&amp;gt; p.FirstName, "@FirstName");
                builder.Tokenize(p =&amp;gt; p.LastName, "@LastName");
                builder.Tokenize(p =&amp;gt; p.Age.ToString(), "@Age");
                builder.Block(p =&amp;gt; p.Orders, "@Orders", order =&amp;gt;
                {
                    order.Tokenize(o =&amp;gt; o.Amount.ToString("c"), "@Amount");
                    order.Tokenize(o =&amp;gt; o.DateSubmitted.ToShortDateString(), "@DateSubmitted");
                    order.TokenizeIf(o =&amp;gt; o.ShipTo, "@ShipTo", o =&amp;gt; o.ShipTo != null, shipto =&amp;gt;
                    {
                        shipto.Tokenize(s =&amp;gt; s.Street1, "@Street1");
                        shipto.Tokenize(s =&amp;gt; s.Street2, "@Street2");
                        shipto.Tokenize(s =&amp;gt; s.City, "@City");
                        shipto.Tokenize(s =&amp;gt; s.State, "@State");
                        shipto.Tokenize(s =&amp;gt; s.Zip, "@Zip");
                    }).EndsWith("@EndShipTo");
                }).EndsWith("@EndOrders");
            });

            mimeographs.Add(mimeograph);
            mimeographs.CreateStencil&amp;lt;Person&amp;gt;("person-template", template);

            var person = new Person
            {
                FirstName = "John",
                LastName = "Nelson",
                Age = 24,
                Orders = new List&amp;lt;Order&amp;gt;
                {
                    new Order { Amount = 10m, DateSubmitted = new DateTime(2011,1,1)},
                    new Order
                        {
                            Amount = 20m,
                            DateSubmitted = new DateTime(2011,1,2),
                            ShipTo = new ShippingInformation 
                            {
                                Street1 = "123 Main St",
                                Street2 = "Apt B",
                                City = "Pittsburgh",
                                State = "PA",
                                Zip = "15203" 
                            }
                        },
                    new Order { Amount = 30m, DateSubmitted = new DateTime(2011,1,3)}
                }
            };

            var result = mimeographs.Render("person-template", person);

            Console.WriteLine(result);

            Console.ReadKey();
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public IEnumerable&amp;lt;Order&amp;gt; Orders { get; set; }
    }

    public class Order
    {
        public int Id { get; set; }
        public decimal Amount { get; set; }
        public DateTime DateSubmitted { get; set; }
        public ShippingInformation ShipTo { get; set; }
    }

    public class ShippingInformation
    {
        public string Street1 { get; set; }
        public string Street2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
    }
}
&lt;/code&gt;&lt;/pre&gt;
</content></entry><entry><id>http://johncoder.com/Post/mysterious-dependent-observable</id><title type="text">The Mysterious Dependent Observable</title><summary type="text">I have been using knockout.js for a lot of UI work lately, and I had the hardest time figuring out why my dependent observable wasn't... depending.</summary><published>2011-04-11T10:18:11-04:00</published><updated>2011-04-11T22:18:15Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/mysterious-dependent-observable" /><content type="html">&lt;p&gt;Today I was working on a simple screen. Here's the markup for it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;input type="search" placeholder="Enter Asset Name" data-bind="value: SearchTerm, valueUpdate: 'afterkeydown'"  /&amp;gt;
&amp;lt;div class="results" data-bind='template: { name: "searchResultsTemplate" }'&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;script type="text/html" id="searchResultsTemplate"&amp;gt;
    &amp;lt;ul&amp;gt;
        {{each(i, result) Results}}
            &amp;lt;li&amp;gt;
                ${Name}
            &amp;lt;/li&amp;gt;
        {{/each}}
    &amp;lt;/ul&amp;gt;
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here's my view model for knockout.js:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var searchModule = function ($) {
    var model = {},
        searchViewModel = {};

    model.init = function (url, root) {
        searchViewModel = {
            Results: ko.observableArray([]),
            SearchTerm: ko.observable(''),
            Timeout: function () { }
        };

        searchViewModel.PerformSearch = ko.dependentObservable(function () {
            var searchTerm = this.SearchTerm;
            var results = this.Results;

            if (this.Timeout) clearTimeout(this.Timeout);

            this.Timeout = setTimeout(function () {
                $.getJSON(
                    url,
                    { searchText: searchTerm() },
                    function (data) {
                        results(data);
                    }
                );
            }, 500);
        }, searchViewModel);

        model.SearchViewModel = searchViewModel;
        ko.applyBindings(searchViewModel, document.getElementById(root));
    }

    return model;
} (jQuery);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When this code runs, the initial pass works just fine. A default set of search results show up in the div, but subsequent typing into the search field no longer triggers calls to the PerformSearch method. But, why? Can you see what is wrong?&lt;/p&gt;

&lt;p&gt;Okay, I'll save you from spending 2 hours on it. The problem is with the dependent observable itself. Knockout.js detects dependencies at runtime. It sounds magical, but it's really quite elegant. A dependent observable method executes, and while it runs, any calls to observables on the bound view model are recorded. The recorded calls are determined to be dependencies, and are kept around for when the dependent should be executed. Let's look at the culprit lines:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;searchViewModel.PerformSearch = ko.dependentObservable(function () {
    var searchTerm = this.SearchTerm;
    var results = this.Results;

    if (this.Timeout) clearTimeout(this.Timeout);

    this.Timeout = setTimeout(function () {
        $.getJSON(
            url,
            { searchText: searchTerm() },
            function (data) {
                results(data);
            }
        );
    }, 500);
}, searchViewModel);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A delay is used in this code to prevent calls to the server from happening on every keypress. A timeout is renewed on every keypress.&lt;/p&gt;

&lt;p&gt;The SearchTerm field of the view model is an observable, which means that you use it as a method to interact with it, rather than a property. Using it like a property gets the actual observable object. Passing a parameter to it sets the value, and calling it without parameters gets the value. Knockout.js should pick up on the call to SearchTerm to recognize a dependency, but it doesn't. That is because execution of SearchTerm doesn't happen during this method. Instead, it is deferred for about 500ms.&lt;/p&gt;

&lt;p&gt;The fix is simple. Get the value of search term before setting the timeout, and use a closure. The revised method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;searchViewModel.PerformSearch = ko.dependentObservable(function () {
    var searchTerm = this.SearchTerm();
    var results = this.Results;

    if (this.Timeout) clearTimeout(this.Timeout);

    this.Timeout = setTimeout(function () {
        $.getJSON(
            url,
            { searchText: searchTerm },
            function (data) {
                results(data);
            }
        );
    }, 500);
}, searchViewModel);
&lt;/code&gt;&lt;/pre&gt;
</content></entry><entry><id>http://johncoder.com/Post/philly-cc-2011-1-slides-and-code-generics-and-extension-methods</id><title type="text">Philly CC 2011.1 Slides and Code</title><summary type="text">Slides and code samples from my talk about C# Generics and Extension methods at Philly Code Camp 2011.1.</summary><published>2011-04-11T09:34:46-04:00</published><updated>2011-04-12T08:36:40Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/philly-cc-2011-1-slides-and-code-generics-and-extension-methods" /><content type="html">&lt;p&gt;I had a great time presenting at Philly Code Camp. I'd like to thank everyone that came to my session. It's the second time I've presented this content.&lt;/p&gt;

&lt;p&gt;The code is available on &lt;a href="https://bitbucket.org/johncoder/example-code"&gt;bitbucket&lt;/a&gt;. The main repository has a directory called PhillyCC, and under that is a folder for the 2011.1 code camp. I included both the MessageBusSample, and the ExtensionMethodSample projects. The slides from the presentation are in there as well. Feel free to leave a comment or send me an email with any questions about the topics or sample code.&lt;/p&gt;

&lt;p&gt;For the last part of my talk, I showed some more advanced usage of generics in a library I wrote called Mimeo. You can find that code &lt;a href="https://bitbucket.org/johncoder/mimeo"&gt;here&lt;/a&gt;. I also started blogging about &lt;a href="http://johncoder.com/Post/introducing-mimeo"&gt;how to use it&lt;/a&gt;. Also, here is a nice sentiment from a resident PGH heckler:&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5026/5612589145_dcd5d708a6_z.jpg" alt="alt text" /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;I'll be presenting on nuget at Pittsburgh Code Camp on April 30, 2011. If you're going to be in the area, be sure to drop by. Register for the event &lt;a href="http://pghdotnet.org/?page_id=46"&gt;here&lt;/a&gt;.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/mimeo-block-tokens</id><title type="text">Mimeo - Block Tokens</title><summary type="text">In my last post, I introduced the Mimeo templating library and how to configure a simple token replacement. In this post, I'll talk about block tokens and work through an example.</summary><published>2011-03-30T10:10:18-04:00</published><updated>2011-04-17T15:00:11Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/mimeo-block-tokens" /><content type="html">&lt;p&gt;This post is a part of a series:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="http://www.johncoder.com/Post/introducing-mimeo"&gt;Introducing: Mimeo&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Mimeo - Block Tokens&lt;/li&gt;
&lt;li&gt;&lt;a href="http://johncoder.com/Post/mimeo-conditional-tokens"&gt;Mimeo - Conditional Tokens&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://johncoder.com/Post/mimeo-interpolation"&gt;Mimeo - Interpolation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Mimeo - Theming Your ASP.NET MVC3 Application&lt;/li&gt;
&lt;li&gt;Mimeo - Design Philosophy&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mimeo's token building API supports a block token that can repeat or enclose content. It creates a new section with an exclusive set of tokens. The block tokens are delimited by an identifier and a terminator. Its type context is a member of the current model whose return type is &lt;code&gt;IEnumerable&amp;lt;TChild&amp;gt;&lt;/code&gt;. The new context for each block iteration will be the type of TChild.&lt;/p&gt;

&lt;h2&gt;example&lt;/h2&gt;

&lt;p&gt;In the last post, we defined a Person class.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let's amend Person, adding a collection of orders.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public IEnumerable&amp;lt;Order&amp;gt; Orders { get; set; }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here's the order class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; public class Order
 {
    public int Id { get; set;}
    public decimal Amount { get; set;}
    public DateTime DateSubmitted { get; set; }
 }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Before, we used a builder to tokenize members of the Person class. Now, we'll be creating a block for Person.Orders, which will have its own builder context. The block will be rendered for each Order in the collection.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;builder.Block(p =&amp;gt; p.Orders, "@Orders", order =&amp;gt;
{
    order.Tokenize(o =&amp;gt; o.Amount.ToString("c"), "@Amount");
    order.Tokenize(o =&amp;gt; o.DateSubmitted.ToShortDateString(), "@DateSubmitted");
}).EndsWith("@EndOrders");
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The builder creates a block that starts with "@Orders" and ends with "@EndOrders". The token identifiers are just delimiters, serving no other purpose. The context parameter (order) is a new token builder for an Order object. Inside of this context, members of the Order class can be tokenized. This example shows how the properties Amount and DateSubmitted are tokenized.&lt;/p&gt;

&lt;p&gt;Tokens are not visible outside of their immediate scope. For example, if you wanted to put the person's name inside of the block, you would have to add their name to the Order, or make Person a property on Order and access Order.Person.FirstName. Improvement in this area could be a feature down the road.&lt;/p&gt;

&lt;h2&gt;template&lt;/h2&gt;

&lt;p&gt;With the block token added to our stencil, let's take a look at what a sample template could look like.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;==========
@FirstName @LastName is a Person who is @Age years old.
  Submitted On | Amount
@Orders
  @DateSubmitted     | @Amount
@EndOrders
==========
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you might expect, the tokens for Amount and DateSubmitted are used between the block identifiers @Orders and @EndOrders. Here's some sample output:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;==========
John Nelson is a Person who is 24 years old.
  Submitted On | Amount

  1/1/2011     | $10.00

  1/2/2011     | $20.00

  1/3/2011     | $30.00

==========
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It is worthwhile to note that the templates preserve 100% of whitespace. This isn't generally too much of a problem, but it has potential for making the template look crazy in scenarios where whitespace is important. I designed this library with the intention of generating HTML, which is much less whitespace intensive.&lt;/p&gt;

&lt;p&gt;Here is a complete listing of the sample code in this post:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System;
using System.Collections.Generic;
using Mimeo;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            const string template = @"==========
@FirstName @LastName is a Person who is @Age years old.
  Submitted On | Amount
@Orders
  @DateSubmitted     | @Amount
@EndOrders
==========";

            var mimeographs = new Mimeographs();

            var mimeograph = new Mimeograph&amp;lt;Person&amp;gt;(builder =&amp;gt;
            {
                builder.Tokenize(p =&amp;gt; p.FirstName, "@FirstName");
                builder.Tokenize(p =&amp;gt; p.LastName, "@LastName");
                builder.Tokenize(p =&amp;gt; p.Age.ToString(), "@Age");
                builder.Block(p =&amp;gt; p.Orders, "@Orders", order =&amp;gt;
                {
                    order.Tokenize(o =&amp;gt; o.Amount.ToString("c"), "@Amount");
                    order.Tokenize(o =&amp;gt; o.DateSubmitted.ToShortDateString(), "@DateSubmitted");
                }).EndsWith("@EndOrders");
            });

            mimeographs.Add(mimeograph);
            mimeographs.CreateStencil&amp;lt;Person&amp;gt;("person-template", template);

            var person = new Person
            {
                FirstName = "John",
                LastName = "Nelson",
                Age = 24,
                Orders = new List&amp;lt;Order&amp;gt;
                {
                    new Order { Amount = 10m, DateSubmitted = new DateTime(2011,1,1)},
                    new Order { Amount = 20m, DateSubmitted = new DateTime(2011,1,2)},
                    new Order { Amount = 30m, DateSubmitted = new DateTime(2011,1,3)}
                }
            };

            var result = mimeographs.Render("person-template", person);

            Console.WriteLine(result);

            Console.ReadKey();
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public IEnumerable&amp;lt;Order&amp;gt; Orders { get; set; }
    }

    public class Order
    {
        public int Id { get; set; }
        public decimal Amount { get; set; }
        public DateTime DateSubmitted { get; set; }
    }
}
&lt;/code&gt;&lt;/pre&gt;
</content></entry><entry><id>http://johncoder.com/Post/introducing-mimeo</id><title type="text">Introducing: Mimeo</title><summary type="text">Lately I have been working on a simple templating library focused on meeting various needs. This post will introduce the library, and walk through an example of what it can do.</summary><published>2011-03-23T10:38:45-04:00</published><updated>2011-04-17T15:00:01Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/introducing-mimeo" /><content type="html">&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5298/5504634262_d8381d2bce_b.jpg" alt="alt text" /&gt;&lt;/p&gt;

&lt;p&gt;I uploaded a &lt;a href="http://nuget.org/Packages/Packages/Details/Mimeo-1-0-0-0"&gt;NuGet package&lt;/a&gt; for a C# library called Mimeo. It is a templating library that allows you to define a template language from a type. The project is open source, and you can find it on &lt;a href="http://bitbucket.org/johncoder/mimeo"&gt;bitbucket&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This post is a part of a series:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Introducing: Mimeo&lt;/li&gt;
&lt;li&gt;&lt;a href="http://johncoder.com/Post/mimeo-block-tokens"&gt;Mimeo - Block Tokens&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://johncoder.com/Post/mimeo-conditional-tokens"&gt;Mimeo - Conditional Tokens&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://johncoder.com/Post/mimeo-interpolation"&gt;Mimeo - Interpolation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Mimeo - Theming Your ASP.NET MVC3 Application&lt;/li&gt;
&lt;li&gt;Mimeo - Design Philosophy&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5020/5504004048_f858bbb95a_m.jpg" alt="mimeo logo" /&gt;&lt;/p&gt;

&lt;h2&gt;installation&lt;/h2&gt;

&lt;p&gt;To install the project, type "mimeo" into the "Add Library Package Reference" dialog search box and click install. Or, if you prefer the command line, enter this command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PM&amp;gt; Install-Package Mimeo
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Installing the package adds a reference to your project for Mimeo.dll. Now, you're ready to get started using the templating engine.&lt;/p&gt;

&lt;h2&gt;defining tokens&lt;/h2&gt;

&lt;p&gt;The example will be a simple command line application. In that application, we have a class called Person:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It would be nice to have an instance of Person, and say "Render this person, please." That's where the templating engine comes in. Using the Person type, we are able to define a set of tokens that can be used inside of a template. The library has a Mimeographs class that stores a bunch of Mimeograph objects. Each Mimeograph object has a collection of stencils (generated from templates) that can be used to render an object.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var mimeographs = new Mimeographs();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then, define a new Mimeograph for the Person type:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var mimeograph = new Mimeograph&amp;lt;Person&amp;gt;(builder =&amp;gt;
{
    builder.Tokenize(p =&amp;gt; p.FirstName, "@FirstName");
    builder.Tokenize(p =&amp;gt; p.LastName, "@LastName");
    builder.Tokenize(p =&amp;gt; p.Age.ToString(), "@Age");
});
mimeographs.Add(mimeograph);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this snippet the builder represents a TokenBuilder object, which has methods for tokenizing values using the model type of the Mimeograph object. Let's hone in on the Tokenize calls a bit.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;builder.Tokenize(p =&amp;gt; p.FirstName, "@FirstName");
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This line is saying that whenever you see "@FirstName" in the template, replace it with the value of the Person object's FirstName property. You might notice that the token for "@Age" is mapped to &lt;code&gt;p.Age.ToString()&lt;/code&gt;. Since all of the replacements are done using strings, explicit conversions are necessary. This is tokenizing in its simplest form. More complicated tokenizing scenarios exist, such as conditional, blocking, and interpolated tokens (I'll soon cover each of those in greater detail).&lt;/p&gt;

&lt;h2&gt;templates&lt;/h2&gt;

&lt;p&gt;Now that we've expressed a set of tokens for templating the Person object, let's use those tokens in a custom template.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;==========
@FirstName @LastName is a Person who is @Age years old.
==========
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can read the template from a file (or wherever), and create a stencil from it.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;mimeographs.CreateStencil&amp;lt;Person&amp;gt;("person-template", template);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The template was created with the name "person-template". Many stencils can be created for the same type, as long as they have a unique name. If the name exists, it will be overwritten with the newly created stencil.&lt;/p&gt;

&lt;p&gt;If we instantiate a person like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var person = new Person
{
    FirstName = "John",
    LastName = "Nelson",
    Age = 24
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We are now able to render that person:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var result = mimeographs.Render("person-template", person);
Console.WriteLine(result);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Executing that code will print this message to the screen:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;==========
John Nelson is a Person who is 24 years old.
==========
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;Defining custom templates and rendering objects with them is easy with Mimeo. It has a lot more functionality, which I will cover in blog posts to come.&lt;/p&gt;

&lt;p&gt;Here is a listing of the complete console program code used in this post:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System;
using Mimeo;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            const string template = @"==========
@FirstName @LastName is a Person who is @Age years old.
==========";

            var mimeographs = new Mimeographs();

            var mimeograph = new Mimeograph&amp;lt;Person&amp;gt;(builder =&amp;gt;
            {
                builder.Tokenize(p =&amp;gt; p.FirstName, "@FirstName");
                builder.Tokenize(p =&amp;gt; p.LastName, "@LastName");
                builder.Tokenize(p =&amp;gt; p.Age.ToString(), "@Age");
            });

            mimeographs.Add(mimeograph);
            mimeographs.CreateStencil&amp;lt;Person&amp;gt;("person-template", template);

            var person = new Person
            {
                FirstName = "John",
                LastName = "Nelson",
                Age = 24
            };

            var result = mimeographs.Render("person-template", person);

            Console.WriteLine(result);

            Console.ReadKey();
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
}
&lt;/code&gt;&lt;/pre&gt;
</content></entry><entry><id>http://johncoder.com/Post/handling-messages-in-openidportablearea</id><title type="text">Handling Messages in OpenIdPortableArea</title><summary type="text">The least obvious part of using OpenIdPortableArea is what to do while handling messages. What messages are available, and what the heck should I be doing to handle them appropriately?</summary><published>2011-03-16T05:43:00-04:00</published><updated>2011-03-16T17:43:20Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/handling-messages-in-openidportablearea" /><content type="html">&lt;p&gt;OpenIdPortableArea uses the MvcContrib Bus to communicate with the hosting application. It sends various notifications for events that happen while the user is interacting with the Portable Area. The hosting application must handle these notifications in order make the login work.&lt;/p&gt;

&lt;h2&gt;handling messages&lt;/h2&gt;

&lt;p&gt;MvcContrib's Bus feature is the bread and butter of what makes the OpenIdPortableArea work. Before getting into what messages are provided by the library, it's important to understand what the bus, messages, and handlers are.&lt;/p&gt;

&lt;p&gt;Think of the bus as an application level event propagator. You say "Hey Bus, notify all compatible handlers that X happened." The bus, being a good listener, finds all of the appropriate handlers, and passes the message to them. That's all it does.&lt;/p&gt;

&lt;p&gt;Messages are small, lightweight objects that are passed to handlers, and transport data between parts of the application. In the case of OpenIdPortableArea, it is using messages to transport data about user actions between the main application and itself.&lt;/p&gt;

&lt;p&gt;Message handlers are classes that implement &lt;code&gt;IMessageHandler&lt;/code&gt;. Most commonly, you'll want to derive from the &lt;code&gt;MessageHandler&amp;lt;TMessage&amp;gt;&lt;/code&gt; base class. This example gives you the gist of what a basic implementation of a MessageHandler looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class SomeMessageHandler : MessageHandler&amp;lt;SomeMessage&amp;gt;
{
    public override void Handle(SomeMessage message)
    {
        // do stuff with the message
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The class &lt;code&gt;SomeMessageHandler&lt;/code&gt; derives from &lt;code&gt;MessageHandler&amp;lt;SomeMessage&amp;gt;&lt;/code&gt;, where &lt;code&gt;SomeMessage&lt;/code&gt; is a type that implements &lt;code&gt;IEventMessage&lt;/code&gt;. That means that this class has a method called Handle, which takes a parameter of type &lt;code&gt;SomeMessage&lt;/code&gt;. The Handle method has a void return type, and is only intended as a chance to hand off information from one part of the application to the other. Any expectations around how the message should be handled need to be clearly expressed in documentation.&lt;/p&gt;

&lt;p&gt;As an example, a portable area might send a message through the bus, expecting some handler to set a property on it. When the message is done being sent over the bus, the value in that property can be used by the portable area. This is a very basic way of communicating, and could certainly use some improvement in terms of discoverability.&lt;/p&gt;

&lt;p&gt;With all of that, let's take a look at each of the messages provided by the library.&lt;/p&gt;

&lt;h2&gt;claims request message&lt;/h2&gt;

&lt;p&gt;Initially, this message seems out of place. The user clicks on their provider, enters information, and clicks login. Isn't that request enough? Well, not exactly.&lt;/p&gt;

&lt;p&gt;When a user logs in with an OpenID provider, the provider is able to send your application information about the user that they authenticated. While many providers will honor your requests, there are others that will require a demand level, or simply choose not to supply your application with that information. The third scenario is that the user was prompted to supply the information you required, and denied the request while following through with the login process. The ClaimsRequestMessage is designed to let you specify what data should be required (as long as the provider respects your demands), but don't think for a minute that it is good enough to set those demands. Validate, validate, and validate some more.&lt;/p&gt;

&lt;p&gt;For example, if 99% of providers give the user's email address back to your application when you ask for it, and you absolutely need it in order for your user to be considered &lt;em&gt;a real user&lt;/em&gt;, check to make sure you actually got the value back. If you didn't then you should prompt the user for their email before fully activating them in your system.&lt;/p&gt;

&lt;p&gt;This example implementation sets the demand levels for Email and FullName:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using OpenIdPortableArea.Messages;
using MvcContrib.PortableAreas;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;

namespace MvcApplication1.Services.PortableAreaHandlers
{
    public class ClaimsRequestMessageHandler : MessageHandler&amp;lt;ClaimsRequestMessage&amp;gt;
    {
        public override void Handle(ClaimsRequestMessage message)
        {
            message.Claim.Email = DemandLevel.Require;
            message.Claim.FullName = DemandLevel.Require;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Choosing to handle this message puts you right up against DotNetOpenAuth. Up until now, the portable area does a pretty good job of keeping you out of it. I decided not to hide this aspect from any users of the library because I think it's important to understand what's going on here.&lt;/p&gt;

&lt;p&gt;Using &lt;code&gt;DemandLevel&lt;/code&gt; requires a reference to the &lt;code&gt;DotNetOpenAuth.OpenId.Extensions.SimpleRegistration&lt;/code&gt; namespace. While not overly difficult, I thought it provided just enough exposure to DotNetOpenAuth for the developer to realize that there's some dependency on the honor system at work.&lt;/p&gt;

&lt;p&gt;It's worthwhile to note that some providers will require a DotNetOpenAuth feature cryptically named "AXFetchAsSregTransform Behavior" and additional setup is required in order to set demands (at least with any hope of getting information back).&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;"DotNetOpenAuth offers “behaviors”, which automatically modify outgoing or incoming OpenID messages in a standard way. One built-in behavior is the AXFetchAsSregTransform behavior, which for the relying party automatically translates requests that include the Simple Registration extension into a request that includes that extension and/or any of three formats of Attribute Exchange extensions depending on the Provider you’re authenticating the user with. By activating this behavior in your site, all you have to do is use ClaimsRequest and ClaimsRespones, and you’ll have a very high chance of getting the attributes you’re requesting if the Provider supports attributes at all." - The AXFetchAsSregTransform Behavior
  To enable AXFetchAsSregTransform Behavior, add the following configuration in the web.config (from &lt;a href="http://dotnetopenauth.net"&gt;http://dotnetopenauth.net&lt;/a&gt;):&lt;/p&gt;
&lt;/blockquote&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;configuration&amp;gt;
   &amp;lt;configSections&amp;gt;
      &amp;lt;section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true"/&amp;gt;
   &amp;lt;/configSections&amp;gt;
   &amp;lt;dotNetOpenAuth&amp;gt;
      &amp;lt;openid&amp;gt;
         &amp;lt;relyingParty&amp;gt;
            &amp;lt;behaviors&amp;gt;
               &amp;lt;!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
                    with OPs that use Attribute Exchange (in various formats). --&amp;gt;
               &amp;lt;add type="DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth" /&amp;gt;
            &amp;lt;/behaviors&amp;gt;
         &amp;lt;/relyingParty&amp;gt;
      &amp;lt;/openid&amp;gt;
   &amp;lt;/dotNetOpenAuth&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;authenticated message&lt;/h2&gt;

&lt;p&gt;The next message has been a source for confusion for some people. Let's take a moment and talk about the work flow up until now.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5219/5513543408_d0caab74af_b.jpg" alt="openid workflow" /&gt;&lt;/p&gt;

&lt;p&gt;A user lands on the login page. From there, they choose a provider whom they have an account with. Your application redirects them to the provider's site, and they authenticate with the provider. The provider then redirects them back to your site. This is when the &lt;code&gt;AuthenticatedMessage&lt;/code&gt; is sent by OpenIdPortable area. This message means that the user has been authenticated by a provider. Here's where the confusion sets in.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;You have not yet authenticated the user!&lt;/strong&gt; Remember that the OpenID provider is merely saying "Yeah, I know this user. Their identifier is X." That means the user is technically authenticated two times. Once by their provider, and once by your application.&lt;/p&gt;

&lt;p&gt;At the very least, you have an OpenID claimed identifier. You need to use this identifier to handle this user's attempt to login to your site:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Using the claimed identifier, try to locate the user in your database. If the user isn't found, it means you don't know them yet.&lt;/li&gt;
&lt;li&gt;Issue FormsAuthenticated tickets for known users.&lt;/li&gt;
&lt;li&gt;Direct unknown users to a registration process (to gather required data, for example).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you use that list, you should be well on your way to properly handling authenticated users. Here is a sample implementation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class AuthenticatedMessageHandler : MessageHandler&amp;lt;AuthenticatedMessage&amp;gt;
{
    public override void Handle(AuthenticatedMessage message)
    {
        // this is your database!
        const string openid = "http://johncoder.myopenid.com/";

        // search your database, see if you know who this user is
        if (message.ClaimedIdentifier == openid)
        {
            // In this case, you know who they are, so issue a
            // forms authentication ticket using a helper
            OpenIdHelpers.Login("John Nelson", "jnelson@johncoder.com", new TimeSpan(0, 5, 0), true);
        }
        // don't know who they are!
        else
        {
            // The ClaimsResponse isn't guaranteed, but
            // it may contain information that you can store
            // about this unknown user
            if (message.ClaimsResponse != null)
                HttpContext.Current.Session.Add("OpenIDClaimedEmail", message.ClaimsResponse.Email ?? string.Empty);

            // Drop their claimed identifier in session
            // beacuse you're going to need it during the registration
            // process. Don't store the user yet, because they might
            // abandon the registration process. Make them
            // complete it before adding as a fully fledged user
            HttpContext.Current.Session.Add("OpenIDClaimedIdentifier", message.ClaimedIdentifier);

            // Set the return url to the registration page
            // the default should be "~/"
            message.ReturnUrl = "~/Home/Register";
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The message also has an &lt;code&gt;IsSecure&lt;/code&gt; property, which indicates that the user's OpenID provider used https.&lt;/p&gt;

&lt;p&gt;In your model, it might be useful to allow one user to be identified by multiple OpenID identifiers. After signing up with one, you could easily add more identifiers to the user later. Otherwise, each unique OpenID identifier becomes a new user. This would be a way to reduce that chance, while increasing the chance that the user will be able to login on the first try (provided they're not 100% certain which OpenID account they originally used to register on your site).&lt;/p&gt;

&lt;h2&gt;unauthenticated message&lt;/h2&gt;

&lt;p&gt;This message occurs at essentially the same juncture in the login process. However, this message indicates a failure at the end point. Don't count on this message for anything critical. It only provides a simple string message about what happened.&lt;/p&gt;

&lt;h2&gt;logging &amp;amp; logged out messages&lt;/h2&gt;

&lt;p&gt;Handling these messages lets you customize the logout process, and is entirely optional. The &lt;code&gt;LoggingOutMessage&lt;/code&gt; broadcasts when the user navigates to &lt;code&gt;~/OpenId/Logout&lt;/code&gt;. Here, you can choose to automatically logout the user, or you can decide to show them a confirmation page.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class LoggingOutMessageHandler : MessageHandler&amp;lt;LoggingOutMessage&amp;gt;
{
    public override void Handle(LoggingOutMessage message)
    {
        // Disables the default auto logout behavior
        message.AutoLogout = false;

        // If automatically logging out the user, set the
        // return url. Otherwise, don't worry about it.
        message.ReturnUrl = "~/";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If the autologout feature is enabled, the &lt;code&gt;LoggedOutMessage&lt;/code&gt; will be sent immediately. Even if no handler is available, the user will be logged out via &lt;code&gt;OpenIdHelpers.Logout()&lt;/code&gt;. If it's not enabled, the user is presented with a confirmation screen. Whenever they confirm the logout action, the &lt;code&gt;LoggedOutMessage&lt;/code&gt; will be sent.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class LoggedOutMessageHandler : MessageHandler&amp;lt;LoggedOutMessage&amp;gt;
{
    public override void Handle(LoggedOutMessage message)
    {
        // If you chose to authenticate the user a special way
        // (i.e., not with OpenIdHelpers or a FormsAuthentication)
        // Signal that the OpenIdPortableArea should not handle
        // logging out with its default behavior (default is OpenIdHelpers.Logout())
        message.UseDefaultLogoutMethod = false;

        // Perform logout manually
        // this is not necessary if you let the portable area use its default

        // Set a return url
        message.ReturnUrl = "~/";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The only message you need to handle is the &lt;code&gt;AuthenticatedMessage&lt;/code&gt;. Message handlers are registered automatically at runtime, so there is no need to register them with the bus.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/openidportablearea-2</id><title type="text">OpenIdPortableArea 2.0</title><summary type="text">I recently released a new version of OpenIdPortableArea, with significant changes to the setup experience.</summary><published>2011-03-15T09:34:33-04:00</published><updated>2011-03-15T08:31:38Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/openidportablearea-2" /><content type="html">&lt;p&gt;This portable area project has been around for almost a year now, and it hasn't changed much since the initial release. What has changed, however, is the story around packaging, deploying, and consuming open source projects in the .NET community. OpenIdPortableArea has been available via NuGet since the days of nupack, and will continue to be available through that system.&lt;/p&gt;

&lt;h2&gt;nuget package&lt;/h2&gt;

&lt;p&gt;The NuGet package for OpenIdPortableArea has changed significantly with this release. It is compiled against ASP.NET MVC3, as well as MvcContrib-MVC3-ci, and DotNetOpenAuth. Now, you'll install one of two separate NuGet packages:&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5299/5510576253_c04e9101c9_z.jpg" alt="add library package reference" /&gt;&lt;/p&gt;

&lt;h2&gt;views&lt;/h2&gt;

&lt;p&gt;Previously, the project only supported the WebForms view engine. All of the views were also embedded in the assembly itself, wich relied on conventions for overriding them. The NuGet package now supplies all of the views you need under &lt;code&gt;~/Areas/OpenId/Views&lt;/code&gt; and you are free to change the views to suit your needs. To use the project with the WebForms view engine, install OpenIdPortableArea.WebFormsViews.&lt;/p&gt;

&lt;p&gt;If your project is using Razor, you should choose the OpenIdPortableArea.RazorViews package. It comes with all of the razor versions of each required view.&lt;/p&gt;

&lt;p&gt;Embedded resources no longer exist, so regardless of which project you choose, you'll still get these files:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Content/themes/base/providers.css
Scripts/providers.js
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;future&lt;/h2&gt;

&lt;p&gt;In the future, I may choose to add a NuGet package that has a default implementation of the MessageHandlers. This is something I'm strongly considering, especially after a good conversation about the implementation details with &lt;a href="http://www.marcusoft.net/2011/02/kanbanboards-vititeln-har-or-else.html"&gt;Marcus Hammarberg&lt;/a&gt; I can see how it would be helpful.&lt;/p&gt;

&lt;p&gt;I would also like to improve the login page, by changing up how the default providers behave. For instance, prompting for a username for myopenid.com accounts, rather than forcing the user to edit the text box by removing &lt;code&gt;&amp;lt;Your Account&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If anyone would like to see other additions to this project, please let me know! Don't hesitate to ask. Contributions are happily accepted.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/atomic-apology</id><title type="text">Atomic Apology: Welcome to 2005</title><summary type="text">I'd like to apologize to all of the (handful) subscribers to my blog. I have been changing things around, and made a big mistake with the feed.</summary><published>2011-03-11T09:44:26-05:00</published><updated>2011-03-14T22:11:32Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/atomic-apology" /><content type="html">&lt;h2&gt;apology&lt;/h2&gt;

&lt;p&gt;This is my formal apology to the people who choose to subscribe to my blog feed. My blog has been changing (more on that soon!), and along the line I swapped out my RSS feed with an Atom feed. Little did I know, I was spamming people with old posts that appeared as new posts. What the heck?&lt;/p&gt;

&lt;h2&gt;troubleshooting&lt;/h2&gt;

&lt;p&gt;I was able to test this out on my own machine, using Internet Explorer. After adding my new feed to Internet Explorer's favorite feeds, I noticed that on every refresh it was pulling down the entire set of posts in the feed and marking them as new. It would give me new ones as often as I was willing to hit the refresh button. Something was terribly wrong.&lt;/p&gt;

&lt;p&gt;Viewing the feed in chrome displays the raw Xml that comes back. It's not pretty, but it was helpful to be able to refresh the raw data to see what it's doing. With each refresh, most of the content was staying the same, except for a few small things:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;id&amp;gt;uuid:cb9f1f7b-fc82-4d24-9125-5178accd4779;id=1&amp;lt;/id&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;These &lt;code&gt;&amp;lt;id&amp;gt;&lt;/code&gt; tags were changing on every refresh. Specifically, this element appears as a child of &lt;code&gt;&amp;lt;feed&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;entry&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;welcome to 2005&lt;/h2&gt;

&lt;p&gt;I started googling for information on atom feed ids, and came across &lt;a href="http://www.problogger.net/archives/2006/03/30/rss-vs-atom-whats-the-big-deal/"&gt;this post&lt;/a&gt; from problogger. Just as I suspected, Atom uses the notion of ids and an updated field to determine how to treat data. I was not setting either of the fields in the feed code. According to the &lt;a href="http://www.atomenabled.org/developers/syndication/atom-format-spec.php#element.id"&gt;atom spec&lt;/a&gt;, the id element must be an IRI, or an internationalized resource identifier. With all of this in mind, it seems that I could fix the problem by setting the feed's id with something that wouldn't change (like the domain), and the id on each entry (the url, although I suspect there could be an occasion where I would want to change the url). By setting the LastUpdated fields on the feed and entries, I can be sure that revisions to my posts will not be readded as entirely new entries. So, here we go:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;protected override void WriteFile(HttpResponseBase response)
{
    var items = new List&amp;lt;SyndicationItem&amp;gt;();

    foreach (var post in BlogTemplate.Posts.Posts)
    {

        var item = new SyndicationItem(post.Title, "", new Uri(_rootUrl + post.Url))
        {
            Id = new Uri(_rootUrl + post.Url).ToString(),
            Content = new TextSyndicationContent(post.Body, TextSyndicationContentKind.Html),
            PublishDate = post.DatePosted,
            LastUpdatedTime = post.DateLastUpdated,
            Summary = new TextSyndicationContent(post.Description)
        };

        item.Authors.Add(new SyndicationPerson { Name = BlogTemplate.Author });
        items.Add(item);
    }

    var feed = new SyndicationFeed(BlogTemplate.Name, BlogTemplate.Description, new Uri(_rootUrl + BlogTemplate.HomePageUrl), items)
    {
        LastUpdatedTime = items.Max(i =&amp;gt; i.LastUpdatedTime),
        Id = new Uri(_rootUrl).ToString()
    };

    var format = new Atom10FeedFormatter(feed);

    using (var writer = XmlWriter.Create(response.Output))
    {
        format.WriteTo(writer);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;all fixed&lt;/h2&gt;

&lt;p&gt;After updating the code to set those fields, it appears that the problem has gone away. Local testing showed that the feed behaved as expected. Old posts stayed old, and new posts were added to the feed correctly.&lt;/p&gt;

&lt;p&gt;Yeah, I know. It was a boneheaded mistake, but I said I was sorry!&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/EFCodeFirstDisableUnicodeforallStringProperties</id><title type="text">EF Code First: Disable Unicode for all String Properties</title><summary type="text">** UPDATED FOR EF 4.1 ** At work it was decided not to use unicode in our database.  In Entity Framework, everything defaults to using unicode, which becomes a bit of a problem in this case.  You can go through and manually mark each string field as unicode via the fluent API or an attribute, or you can automate the process a little.  Here’s the code that I wrote to do just that. </summary><published>2010-10-31T09:13:14-04:00</published><updated>2011-04-14T21:18:00Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/EFCodeFirstDisableUnicodeforallStringProperties" /><content type="html">&lt;p&gt;Using Code First, all that this code requires is the DbModelBinder inside of your OnModelCreating() method. The private methods scan the class’s properties that implement IDbSet, and then scans for any string properties on the entity type. The only scenario that this does not cover is an inheritance model (although, this has still proved very helpful).&lt;/p&gt;

&lt;p&gt;I am looking forward to the Conventions API that we got to see a little bit in the recent CTP releases. It will completely remove the need for the code I've used in this post. Unfortunately, it seems that the API didn't make it into the EF 4.1 release. Until it's available, this will have to do.&lt;/p&gt;

&lt;p&gt;You can download a complete running example of the code at my &lt;a href="https://bitbucket.org/johncoder/example-code/src"&gt;example source code repo&lt;/a&gt;, in the directory named "DisableUnicodeStringsInEFCodeFirst".&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class SampleDbContext : DbContext
{
    public IDbSet&amp;lt;Person&amp;gt; People { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        DisableUnicodeForAllEntityStrings(modelBuilder);
    }

    private void DisableUnicodeForAllEntityStrings(DbModelBuilder modelBuilder)
    {
        // Get all IDbSet&amp;lt;&amp;gt; properties from the context
        var entityTypes = from property in GetType().GetProperties()
                          where property.PropertyType.IsGenericType
                              &amp;amp;&amp;amp; property.PropertyType.Name.StartsWith("IDbSet")
                          let entityType = property.PropertyType.GetGenericArguments()[0]
                          select entityType;

        // Disable Unicode support for each table
        foreach (var entityType in entityTypes)
            DisableUnicodeForEntityStrings(modelBuilder, entityType);
    }

    private void DisableUnicodeForEntityStrings(DbModelBuilder modelBuilder, Type entityType)
    {
        // Get all string properties with setters
        var stringProperties = from property in entityType.GetProperties()
                               where property.PropertyType == typeof(string)
                                   &amp;amp;&amp;amp; property.CanWrite
                               select property;

        // Each table field must be varchar for now,
        // so take the string property &amp;amp; call IsNotUnicode.
        foreach (var property in stringProperties)
        {
            // Don't remove this line.
            // Lambda might not work without it.
            PropertyInfo prop = property;

            // Create the correct expression type,
            // should be Expression&amp;lt;Func&amp;lt;TModel, string&amp;gt;&amp;gt;
            var exprType = typeof(Expression&amp;lt;&amp;gt;)
                .MakeGenericType(typeof(Func&amp;lt;,&amp;gt;)
                .MakeGenericType(prop.ReflectedType, typeof(string)));

            // Find and execute the Entity() method,
            // using TModel generic parameter
            var obj = modelBuilder.GetType()
                .GetMethod("Entity")
                .MakeGenericMethod(prop.ReflectedType)
                .Invoke(modelBuilder, null);

            // Runtime Lambda expression to represent
            // something like Property(p =&amp;gt; p.Suffix)
            ParameterExpression pe = Expression.Parameter(prop.ReflectedType, "p");
            var expression = Expression.Lambda(Expression.Property(pe, prop.Name), pe);

            // Find the Property method that takes an expression as a parameter
            // and then invoke it using the expression that was just built
            var p = obj.GetType()
                .GetMethod("Property", new[] { exprType })
                .Invoke(obj, new[] { expression });

            // If all goes well, we'll have a StringPropertyConfiguration.
            // Call IsNotUnicode :-)
            var propertyConfig = p as StringPropertyConfiguration;
            if (propertyConfig != null)
                propertyConfig.IsUnicode(false);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
</content></entry><entry><id>http://johncoder.com/Post/PaginatingAutoMappedViewModels</id><title type="text">Paginating AutoMapped ViewModels</title><summary type="text">I came across a situation where I wanted to use MvcContrib’s Pagination features.  My project consists of an AutoMapper Attribute that performs the actual mapping of my domain to its view model counterpart. </summary><published>2010-08-10T09:18:16-04:00</published><updated>2011-03-15T20:50:19Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/PaginatingAutoMappedViewModels" /><content type="html">&lt;p&gt;Given that my view is of type &lt;code&gt;IEnumerable&amp;lt;TagDisplayModel&amp;gt;&lt;/code&gt;, and my controller passes &lt;code&gt;LazyPagination&amp;lt;Tag&amp;gt;&lt;/code&gt; to &lt;code&gt;View()&lt;/code&gt;, something like &lt;code&gt;Html.Grid(Model).AutoGenerateColumns().Render()&lt;/code&gt; works as expected.  However, adding &lt;code&gt;Html.Page((IPagination)Model)&lt;/code&gt; to our view fails.&lt;/p&gt;

&lt;p&gt;AutoMapper is a delicate worker, doing only as it knows how to do.  It knows how to handle IEnumerable just fine, performing a mapping for each item in the enumeration.  However, it knows nothing about MvcContrib’s IPagination interface, nor how to map to a concrete one.  When we try to specify a mapping from &lt;code&gt;IPagination&amp;lt;Tag&amp;gt;&lt;/code&gt; to &lt;code&gt;IPagination&amp;lt;TagDisplayModel&amp;gt;&lt;/code&gt;, nothing seems to happen (or a type casting error… I forget).&lt;/p&gt;

&lt;p&gt;Luckily, AutoMapper’s API provides a hook for such occasions.  Enter: ConstructUsing().  This method provides a hook for us to specify how it should resolve the destination class.  MvcContrib Pagination, by default, uses &lt;code&gt;LazyPagination&amp;lt;T&amp;gt;&lt;/code&gt;.  It works, but the translation gets hairy if we try to keep up with it.  If the source does not execute the contained IQueryable and perform the actual pagination, it will be lost during the mapping process.  Instead, we can use CustomPagination, whose constructor takes an IEnumerable&lt;T&gt;, as well as paging information.&lt;/p&gt;

&lt;p&gt;Here's the extension method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static class MapExtensions
{
    public static IMappingExpression&amp;lt;IPagination&amp;lt;TSource&amp;gt;, IPagination&amp;lt;TDestination&amp;gt;&amp;gt;
        ConstructPagination&amp;lt;TSource, TDestination&amp;gt;(this IMappingExpression&amp;lt;IPagination&amp;lt;TSource&amp;gt;, IPagination&amp;lt;TDestination&amp;gt;&amp;gt; map)
            where TSource : class
            where TDestination : class
    {
        return map.ConstructUsing(src =&amp;gt; 
                new CustomPagination&amp;lt;TDestination&amp;gt;(
                    src.ToList().Select(p =&amp;gt; AutoMapper.Mapper.Map&amp;lt;TSource, TDestination&amp;gt;(p)),
                    src.PageNumber,
                    src.PageSize,
                    src.TotalItems));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Using this extension method, create a map for your paginated types:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;AutoMapper.Mapper
    .CreateMap&amp;lt;IPagination&amp;lt;Tag&amp;gt;, IPagination&amp;lt;TagDisplayModel&amp;gt;&amp;gt;()
    .ConstructPagination();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then, the following action method will work as you would expect it to:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[AutoMap(typeof(IPagination&amp;lt;Tag&amp;gt;),typeof(IPagination&amp;lt;TagDisplayModel&amp;gt;))]
public ActionResult Index(int page = 1)
{
    var tags = _readonlySession.All&amp;lt;Tag&amp;gt;().AsPagination(page);
    return View(tags);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Thus, allowing you to call &lt;code&gt;&amp;lt;%= Html.Pager((IPagination)Model) %&amp;gt;&lt;/code&gt; inside the view without error (also remember that your view is &lt;code&gt;IEnumerable&amp;lt;TagDisplayModel&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Edit&lt;/strong&gt;: I uploaded a code sample at &lt;a href="https://bitbucket.org/johncoder/example-code/"&gt;https://bitbucket.org/johncoder/example-code/&lt;/a&gt;. Check out the "PaginatingAutoMappedViewModels" folder.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/AdventuresinDebuggingAFriendlierCalltoRenderPartial</id><title type="text">Adventures in Debugging: A Friendlier Call to RenderPartial</title><summary type="text">I’m sure we’ve all experienced this error, and even wasted time on trying to pick apart what is actually happening...</summary><published>2010-08-08T08:22:04-04:00</published><updated>2010-08-08T20:22:04Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/AdventuresinDebuggingAFriendlierCalltoRenderPartial" /><content type="html">&lt;p&gt;At first glance, you say “Gee, must have passed the wrong type to my view,” naively double checking your handy work:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;% Html.RenderPartial("ClassB", Model.B); %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Yup, that’s what you wanted.  Render the darn partial for ClassB using Model.B.  This should work, but why is it throwing the error?  So, you check the partial itself to make sure it’s strongly typed:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Inherits="System.Web.Mvc.ViewUserControl&amp;lt;MvcApplication3.Models.ClassB&amp;gt;"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Nope, that’s right too.  How could this be?  You’re certainly bordering on apoplexy at this point, so you check the class declaration for Model (which is type ClassA):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class ClassA
{
    public string Name { get; set; }
    public ClassB B { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Clearly, something has gone awry.  B absolutely is the correct type.  What is the value of Model.B at runtime?  So you fire up the debugger, and realize that B is null.&lt;/p&gt;

&lt;p&gt;A quick search on StackOverflow, and I found this solution:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“…I think the problem you are getting is a result of the RenderPartial method using the calling (view)'s model to the partial view when the model you pass is null.. you can get around this odd behavior by doing:”&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;% Html.RenderPartial("TaskList", Model.Tasks, new ViewDataDictionary()); %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That solution doesn’t sit right with me, though.  It doesn’t make any sense.  For one, it’s a kludge.  Second, the way I see it, if the model passed into RenderPartial is null, then I wouldn’t expect it to render anything.  As such, I came up with some helper methods that wrap RenderPartial, and include that behavior.&lt;/p&gt;

&lt;p&gt;The helper methods have kind of a wide range of syntax, mainly to accommodate various coding styles.  They all do about the same thing.&lt;/p&gt;

&lt;p&gt;This call arbitrarily checks the model being passed in, and only calls RenderPartial if it is not null:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;% Html.TryRenderPartial("ClassB", Model.B); %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The next two calls are basically identical, and you can choose to use whichever you want. One takes a lambda, and passes in the Model for you to base the condition off of, or you can provide a boolean expression:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;% Html.RenderPartialIf(Model.B != null, "ClassB", Model.B); %&amp;gt;
&amp;lt;% Html.RenderPartialIf(m =&amp;gt; m.B != null, "ClassB", Model.B); %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
</content></entry><entry><id>http://johncoder.com/Post/area-controller-factories-for-portable-areas</id><title type="text">Area Controller Factories for Portable Areas</title><summary type="text">This is something I toyed with a couple of months ago as a proof of concept.  I hope that some aspect of this feature makes its way into the core of ASP.NET MVC.  It rose from experimenting with some ideas for data driven portable areas, and wanting to leverage an IoC container of my own choosing (independent of the consuming application).  I wanted to prove that this was possible in ASP.NET MVC 2.</summary><published>2010-07-29T09:26:28-04:00</published><updated>2011-03-15T08:24:04Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/area-controller-factories-for-portable-areas" /><content type="html">&lt;p&gt;The code for this lives in an MvcContrib fork.&lt;/p&gt;

&lt;p&gt;The idea is simple: a new factory called &lt;code&gt;AreaControllerFactory&lt;/code&gt;.  It inherits from &lt;code&gt;DefaultControllerFactory&lt;/code&gt;, which remains the fallback means of producing a Controller.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class AreaControllerFactory :DefaultControllerFactory
{
    private IControllerFactoryRegistry _registry;

    public AreaControllerFactory(IControllerFactoryRegistry registry)
    {
        _registry = registry;
    }

    public override IControllerCreateController(RequestContext requestContext, string controllerName)
    {
        string areaName = ((Route)requestContext.RouteData.Route).DataTokens["area"] as string;

        IControllerFactory factory = _registry.FactoryFor(areaName);

        if (factory == null)
            returnbase.CreateController(requestContext, controllerName);

        return factory.CreateController(requestContext, controllerName);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;AreaControllerFactory&lt;/code&gt; depends on an &lt;code&gt;IControllerFactoryRegistry&lt;/code&gt; object to manage the controller factories.  The &lt;code&gt;FactoryFor()&lt;/code&gt; method returns a &lt;code&gt;ControllerFactory&lt;/code&gt; that has been registered for a specific area using RouteData.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;IControllerFactoryRegistry&lt;/code&gt; interface looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IControllerFactoryRegistry
{
    void Register(string areaName, IControllerFactoryfactory);
    void Default(IControllerFactory factory);
    IControllerFactory FactoryFor(string areaName);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I have created a default implementation of this interface that uses a simple dictionary internally.  That code isn’t particularly interesting.  Up to now this is pretty intuitive, but I think the real slick part is how everything comes together with the &lt;code&gt;ControllerFactoryRegistrar&lt;/code&gt; class.  It is a singleton wrapper for an &lt;code&gt;IControllerFactoryRegistry&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;Right now, the Area Controller Factories get set up by calling &lt;code&gt;ControllerFactoryRegistrar.BootStrap()&lt;/code&gt;.  It takes the current &lt;code&gt;ControllerFactory&lt;/code&gt; and uses it as a default option.  Then, it builds up a registry for all of the PortableAreas in the AppDomain.  A new &lt;code&gt;AreaControllerFactory&lt;/code&gt; is created with the registry, and set as the new &lt;code&gt;ControllerFactory&lt;/code&gt;.  Now, the creation of a controller will depend on what area it belongs to.&lt;/p&gt;

&lt;p&gt;Non-portable areas can be registered with individual controller factories as well.  Just call &lt;code&gt;ControllerFactoryRegistrar.Register(areaName, factory)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;All of this currently fits into MVC 2.  With Area Controller Factories, Portable Areas have a new option for managing dependencies within its controllers.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/global-mapping-for-all-portable-areas</id><title type="text">Global Mapping For All PortableAreas</title><summary type="text">A change to how mapping embedded views to master pages, based on some great feedback.</summary><published>2010-05-23T09:22:30-04:00</published><updated>2010-05-23T21:22:30Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/global-mapping-for-all-portable-areas" /><content type="html">&lt;p&gt;I got some great feedback on mapping PortableAreas to MasterPages and ContentPlaceHolders:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Wouldn't this need to be repeated for every PA that was used by the host? Could this be changed to just globally map "PageTitle" to Title, "BodyContent" to Content, etc.?” – Steve Michelotti&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;He's right. Seems ridiculous to have to map each area individually when they’ll all be using the same configuration.  Enter MapAll():&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PortableAreaContent.MapAll()
    .Master("~/Views/Shared/PA.master")
    .Title("PageTitle")
    .Body("BodyContent");

PortableAreaContent.Map&amp;lt;AnotherPortableAreaMap&amp;gt;()
    .JavaScript("ScriptContent");

AreaRegistration.RegisterAllAreas();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You’ll notice that I changed “Content” to “PortableAreaContent” in the above snippet.  I did that because I thought that “Content” was too vague, and that the new name expressed more intent.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;MapAll()&lt;/code&gt; method basically works the same as the &lt;code&gt;Map&amp;lt;&amp;gt;()&lt;/code&gt; method, except that it sets the default values for all other PortableAreaMaps.  The &lt;code&gt;Map&amp;lt;&amp;gt;()&lt;/code&gt; method is still available, and in the above snippet it is used to configure a special mapping for a JavaScript ContentPlaceHolder. &lt;/p&gt;

&lt;p&gt;Adding a way to globally set MasterPages and ContentPlaceHolders further simplified the mapping scenarios, while still leaving it robust for slightly more complicated ones.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/portable-areas-mapping-master-pages-to-embedded-views</id><title type="text">PortableAreas: Mapping MasterPages and ContentPlaceHolders</title><summary type="text">Some of the most difficult aspects of consuming PortableAreas (PAs) are MasterPages and ContentPlaceHolders.  The embedded views of a PA are hard coded to use Site.Master, which may be inconsistent with the host application.  It works, but it can be much better.  After some discussion on twitter with Eric Hexter and Steve Michelotti, I had an idea for solving the problem.</summary><published>2010-05-20T09:06:55-04:00</published><updated>2010-05-20T21:06:55Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/portable-areas-mapping-master-pages-to-embedded-views" /><content type="html">&lt;h2&gt;Wiring Things Up&lt;/h2&gt;

&lt;p&gt;In your application, you surely have your own MasterPage.  That MasterPage has ContentPlaceHolders, probably with IDs that conform to the coding standards of your particular project.  The goal is to use a PA, and make it feel like a seamless part of your application.  To do that, you need some way to tie everything together.&lt;/p&gt;

&lt;p&gt;Hypothetically, you wish to utilize “SomePortableArea” with your application.  Inside of your Global.asax.cs, during Application_Start() you can map the PA to your MasterPage and its ContentPlaceHolders like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Content.Map&amp;lt;SomePortableAreaMap&amp;gt;()
    .Master("~/Views/Shared/MyApplication.master")
    .Title("PageTitle")
    .Body("BodyContent");

AreaRegistration.RegisterAllAreas();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The Content static class has a &lt;code&gt;Map&amp;lt;&amp;gt;()&lt;/code&gt; method that returns an instance for the given map type.  The type you provide depends on the PA you’re working with.  The imaginary SomePortableArea.dll has a class called &lt;code&gt;SomePortableAreaMap&lt;/code&gt;.  Thus, the example calls &lt;code&gt;Map&amp;lt;SomePortableAreaMap&amp;gt;()&lt;/code&gt; to get the map.&lt;/p&gt;

&lt;p&gt;PortableAreaMap has three extension methods:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Master()&lt;/code&gt;    - Tells the PortableArea what MasterPage to use.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Title()&lt;/code&gt; - Tells the PortableArea what the Title ContentPlaceHolderID is in the MasterPage.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Body()&lt;/code&gt;  - Tells the PortableArea what the Body ContentPlaceHolderID is in the MasterPage.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;*In order for the mappings to work, they must be done before the areas are registered.
Here is a look at the markup in “MyApplication.Master”:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %&amp;gt;

&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&amp;gt;
&amp;lt;html xmlns="http://www.w3.org/1999/xhtml"&amp;gt;
&amp;lt;head runat="server"&amp;gt;
    &amp;lt;title&amp;gt;&amp;lt;asp:ContentPlaceHolder ID="PageTitle" runat="server" /&amp;gt;&amp;lt;/title&amp;gt;
    &amp;lt;link href="../../Content/Site.css" rel="stylesheet" type="text/css" /&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;div class="page"&amp;gt;
        &amp;lt;div id="header"&amp;gt;
            &amp;lt;div id="title"&amp;gt;
                &amp;lt;h1&amp;gt;MasterPage!&amp;lt;/h1&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;

        &amp;lt;div id="main"&amp;gt;
            &amp;lt;asp:ContentPlaceHolder ID="BodyContent" runat="server" /&amp;gt;

            &amp;lt;div id="footer"&amp;gt;
                Footer!
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Providing a Map Class&lt;/h2&gt;

&lt;p&gt;As the author of a PortableArea, now you can feel confident that people won’t send nasty grams about how your PA ruined their conventions!  Even more good news: it’s not that difficult for you to implement.  Imagine that you’re the author of “SomePortableArea.”  You would define a class like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class SomePortableAreaMap : PortableAreaMap
{
    public SomePortableAreaMap()
    {
        DefaultMasterPageLocation ="~/Views/Shared/Site.Master";
        DefaultBodyID = "MainContent";
        DefaultTitleID = "TitleContent";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Inherit from PortableAreaMap, and provide some default values in the constructor.  These default values come from the MasterPage that you have in your project (mostly for intellisense &amp;amp; View generation reasons):
There is just one part left, and that is to override a new method in SomePortableAreaRegistration:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class SomePortableAreaRegistration :PortableAreaRegistration
{
    // ... other code

    public override PortableAreaMap GetMap()
    {
        return Content.Map&amp;lt;SomePortableAreaMap&amp;gt;();
    }

    // ... other code
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This just grabs the Map for your portable area, using the SomePortableArea type defined earlier.
Extensibility
One way that you might be able to extend the portable area is to use another &lt;asp:Content&gt; tag in your views, perhaps ContentPlaceHolderID="JavaScriptContent" to make sure all of your area’s JavaScript gets rendered to the bottom of the page.  You could then add a method to SomePortableAreaMap, allowing the host to map it to one of their ContentPlaceHolders:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public SomePortableAreaMap JavaScript(string name)
{
    Add("JavaScriptContent", name);
    returnthis;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;Host applications are able to configure a PA to use their MasterPages by calling chainable methods.
PortableAreas provide a PortableAreaMap, making the former possible.  By providing a map class, the PA can more easily support another ContentPlaceHolder (i.e. for JavaScript).  Then, the consuming application can create a special MasterPage, or nest MasterPages to accommodate the PA, all the while retaining their freedom of conventions.
Hopefully this is easy to understand.  The steps seem fairly intuitive, and simple to me (but then again, I’m biased… after all, I wrote it!).  What do you think?&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/easier-message-handling-with-portable-areas</id><title type="text">Easier Message Handling While Using PortableAreas</title><summary type="text">I recently spiked out a new feature for MvcContrib PortableAreas to automatically wire up IMessageHandlers. It’s a small feature, but I think it makes PortableAreas just a little easier. </summary><published>2010-05-18T09:01:58-04:00</published><updated>2010-05-18T21:01:58Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/easier-message-handling-with-portable-areas" /><content type="html">&lt;p&gt;Previously, you would have had to manually wire up each individual handler in the Global.asax.cs like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;MvcContrib.Bus.AddMessageHandler(typeof(AuthenticatedMessageHandler));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, that won’t be necessary. By virtue of descending from MessageHandler&amp;lt;&gt;, the class will be registered &lt;em&gt;automatically&lt;/em&gt;.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/sample-aspnet-mvc-application-using-openidportablearea</id><title type="text">A Sample Application Using OpenIdPortableArea</title><summary type="text">OpenIdPortableArea is a pluggable component that enables support for OpenId.  This post is a short walkthrough for implementing OpenId in a sample application.</summary><published>2010-04-27T06:18:09-04:00</published><updated>2010-04-27T18:18:09Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/sample-aspnet-mvc-application-using-openidportablearea" /><content type="html">&lt;h2&gt;Step 1: Ducks all in a row&lt;/h2&gt;

&lt;p&gt;First, download and unzip the latest release (0.1.0.3 as of today, found at &lt;a href="http://openidportablearea.codeplex.com/"&gt;http://openidportablearea.codeplex.com/&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5056/5494983699_edc33098c3_m.jpg" alt="download" /&gt;&lt;/p&gt;

&lt;p&gt;Open Visual Studio and create a new ASP.NET MVC 2 project.  In the Solution Explorer, right click on the project and go to Add, New Folder and call it “lib” (the name doesn’t really matter, just what I usually use).  Copy all of the .dll and .xml files from the files you extracted, and paste them into the new folder in your project.  Then, add a reference for DotNetOpenAuth.dll, MvcContrib.dll, and OpenIdPortableArea.dll.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5253/5494983573_bfa53c55df.jpg" alt="alt text" /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5059/5495575656_270912d94e.jpg" alt="alt text" /&gt;&lt;/p&gt;

&lt;p&gt;Next, create an Areas folder in your solution and copy the Views\Web.config into it.  This is important because without it, you’ll get a YSOD.  If you forget this and try to run the application it will throw a clearly worded exception during app start.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5180/5494983437_8e4e99206a.jpg" alt="alt text" /&gt;&lt;/p&gt;

&lt;p&gt;Up to this point, the portable area gets hooked up automatically as long as your Application_Start calls AreaRegistration.RegisterAllAreas().&lt;/p&gt;

&lt;h2&gt;Step 2: The Old Switcheroo&lt;/h2&gt;

&lt;p&gt;If you run the application, you’ll notice that the [ Log On ] link still sends you to ~/Account/LogOn.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5220/5495575736_6552447821.jpg" alt="alt text" /&gt;&lt;/p&gt;

&lt;p&gt;The OpenIdPortableArea comes with its own login status widget.  To substitute that behavior, open Site.master and add &lt;code&gt;&amp;lt;%@ Import Namespace="OpenIdPortableArea.UI" %&amp;gt;&lt;/code&gt; to the top of the page, and then add &lt;code&gt;&amp;lt;%= Html.LoginStatusWidget() %&amp;gt;&lt;/code&gt; where the &lt;code&gt;RenderPartial("LogonUserControl")&lt;/code&gt; was.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5014/5494983485_b58b0134d7.jpg" alt="alt text" /&gt;&lt;/p&gt;

&lt;p&gt;Now, when you run the application you should be able to click that link and go to ~/OpenId.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5291/5494983523_c802cdd9b7.jpg" alt="alt text" /&gt;&lt;/p&gt;

&lt;p&gt;Oh yeah!  Don’t forget to change your web.config to &lt;code&gt;&amp;lt;forms loginUrl="~/OpenId" timeout="2880"/&amp;gt;&lt;/code&gt;.  That way, when you use &lt;code&gt;[Authorize]&lt;/code&gt; it will redirect to the correct Url.&lt;/p&gt;

&lt;h2&gt;Step 3: Know Thy User&lt;/h2&gt;

&lt;p&gt;If you enter an OpenId and click “Login” you will be sent to that OpenId provider to authenticate with them.  The provider then redirects you back to the site, and you arrive on ~/OpenId/Success.  If you were already authenticated with the provider, they might have automatically redirected you (i.e. you may have gone from the Login page to the Success page).&lt;/p&gt;

&lt;p&gt;When the provider sends the user back to the site, the portable area sends an &lt;code&gt;AuthenticatedMessage&lt;/code&gt; through MvcContrib’s Bus.  It contains information about the authenticated user, and allows you the opportunity to handle it explicitly.  To handle this message, create a class that inherits from &lt;code&gt;MessageHandler&amp;lt;AuthenticatedMessage&amp;gt;&lt;/code&gt;.  In this class, override the Handle() method.  This is where you can employ your own domain to associate your user with their OpenId.  There are two simple scenarios to code for.  You already know the user, or you don’t.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System;
using System.Web;
using MvcContrib.PortableAreas;
using OpenIdPortableArea.Helpers;
using OpenIdPortableArea.Messages;
using SampleApplication.Models;

namespace SampleApplication.Services.PortableAreaMessageHandlers
{
    public class AuthenticatedMessageHandler
        : MessageHandler&amp;lt;AuthenticatedMessage&amp;gt;
    {
        UserRepository _userRepository = new UserRepository();

       public override void Handle(AuthenticatedMessagemessage)
        {
            User user = _userRepository
                .FindByOpenId(message.ClaimedIdentifier);

            if (user != null)
            {
                OpenIdHelpers.Login(user.Name,
                    user.Email,
                    new TimeSpan(0, 5, 0),
                    true);
            }
            else
            {
                user = newUser
                {
                    OpenId = message.ClaimedIdentifier,
                    Email  = message.ClaimsResponse.Email,
                    Name   = message.ClaimsResponse.FullName
                };

                HttpContext.Current.Session.Add(
                    "user",
                    user);

                message.ReturnUrl = "~/Home/Register";
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this example, I use a UserRepository* to try and find a user by the ClaimedIdentifier (their OpenId).  If a user is found, the OpenIdHelpers class provides a simpler call for issuing a FormsAuthenticationTicket either by passing an instance of FormsAuthenticationTicket, or passing a few parameters.  If a user wasn’t found, a new one gets created and stuffed into session until the user gets redirected.  The ReturnUrl is also set to ~/Home/Register.  More on that later (Step 4).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;*By the way, I cheated and hard coded this to return a user with my own OpenId.  In reality, your UserRepository will really be able to query the database for a user with the matching OpenId.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Notice the message has a ClaimsResponse property containing information about the user.  Yup, you have (some) control over that, as well.  It, too, is a message waiting to be handled.  This time, it’s a ClaimsRequestMessage.  Here’s an example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using OpenIdPortableArea.Messages;
using MvcContrib.PortableAreas;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;

namespace SampleApplication.Services.PortableAreaMessageHandlers
{
    public class ClaimsRequestMessageHandler
        : MessageHandler&amp;lt;ClaimsRequestMessage&amp;gt;
    {
       public override void Handle(ClaimsRequestMessagemessage)
        {
            message.Claim.Email = DemandLevel.Require;
            message.Claim.FullName =DemandLevel.Require;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It's pretty straight forward. Set each member to the desired DemandLevel.  Now, whenever the OpenId Provider redirects the authenticated user back to the site, hopefully these demands will be honored and you can pre-populate your new user’s information.&lt;/p&gt;

&lt;p&gt;In order to make ClaimsRequests work, you must also add the following settings to your ~/Web.config (otherwise message.Claim will be null):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;configuration&amp;gt;
   &amp;lt;configSections&amp;gt;
      &amp;lt;section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true"/&amp;gt;
   &amp;lt;/configSections&amp;gt;
   &amp;lt;dotNetOpenAuth&amp;gt;
      &amp;lt;openid&amp;gt;
         &amp;lt;relyingParty&amp;gt;
            &amp;lt;behaviors&amp;gt;
               &amp;lt;!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
                    with OPs that use Attribute Exchange (in various formats). --&amp;gt;
               &amp;lt;add type="DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth" /&amp;gt;
            &amp;lt;/behaviors&amp;gt;
         &amp;lt;/relyingParty&amp;gt;
      &amp;lt;/openid&amp;gt;
   &amp;lt;/dotNetOpenAuth&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;*If you don’t care about the ClaimsRequest, and aren’t using ClaimsResponse in the message handler for AuthenticatedMessage, then this setting shouldn’t matter.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;WAIT!  Creating the message handlers is great, but the MvcContrib.Bus needs to know about these classes.  Add the following lines to Application_Start() in Global.asax.cs:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;MvcContrib.Bus.AddMessageHandler(typeof(AuthenticatedMessageHandler));
MvcContrib.Bus.AddMessageHandler(typeof(ClaimsRequestMessageHandler));
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Step 4: Paperwork&lt;/h2&gt;

&lt;p&gt;In the future, I may try to alleviate this implementation burden in OpenIdPortableArea.  But for now, you’ve got to do it (cheers!).  Relax, it isn’t so bad.&lt;/p&gt;

&lt;p&gt;Create a Register() method on your HomeController, and create a view for it.  Make the view strongly typed for (at least) your User.  Then, use the templated helper Html.EditorForModel() to get the form on the page.&lt;/p&gt;

&lt;p&gt;HomeController&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private UserRepository _userRepository = new UserRepository();

[HttpGet]
public ActionResult Register()
{
    Useruser = (User)Session["user"];
    return View(user);
}

[HttpPost]
public ActionResult Register(Useruser)
{
    bool exists = _userRepository.FindAll().Any(u =&amp;gt; u.Name == user.Name);
    if (exists)
    {
        ModelState.AddModelError("", "User already exists with that name.");
        return View(user);
    }

    if (ModelState.IsValid)
    {
        _userRepository.Add(user);
        _userRepository.Save();

        // Issue forms authentication ticket.
        OpenIdHelpers.Login(user.Name, string.Empty, new TimeSpan(5, 0, 0, 0), false);

        return RedirectToAction("Index", "Home");
    }
    else
    {
        return View(user);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Views/Home/Register.aspx&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;h2&amp;gt;Register&amp;lt;/h2&amp;gt;
&amp;lt;% Html.EnableClientValidation(); %&amp;gt;
&amp;lt;%= Html.ValidationSummary() %&amp;gt;
&amp;lt;% using (Html.BeginForm())
   { %&amp;gt;

    &amp;lt;%= Html.EditorForModel() %&amp;gt;
    &amp;lt;input type="submit" value="Register" /&amp;gt;
&amp;lt;% } %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The idea is pretty simple.  Show the user their information (filling in as much as possible via ClaimsResponse), and they click the Register button.  On the POST, perform validation on the user.  If everything checks out, add the user to the repository and authenticate them.  Lastly, redirect to wherever you please (or… ~/Home/Index).&lt;/p&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;Now, if you run your sample application you should be able to login with OpenId freely.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://farm6.static.flickr.com/5016/5495575780_601ac7ac8a.jpg" alt="alt text" /&gt;&lt;/p&gt;

&lt;p&gt;The Logout link at the top points to ~/OpenId/Logout.  By default, the portable area will handle this nicely for you.  However, if you wish to intervene there are two messages LoggingOutMessage and LoggedOutMessage.  They’ll be a topic for another post.&lt;/p&gt;

&lt;p&gt;Here’s the short To Do list for implementing this portable area:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Add Files &amp;amp; References&lt;/li&gt;
&lt;li&gt;Add LoginStatusWidget to MasterPage&lt;/li&gt;
&lt;li&gt;Change web.config forms loginurl to ~/OpenId&lt;/li&gt;
&lt;li&gt;Create a MessageHandler&amp;lt;&gt; for AuthenticatedMessage&lt;/li&gt;
&lt;li&gt;Add the message handler to MvcContrib.Bus&lt;/li&gt;
&lt;li&gt;Add User Registration functionality&lt;/li&gt;
&lt;/ol&gt;
</content></entry><entry><id>http://johncoder.com/Post/customizing-output-caching-behavior-in-aspnet-mvc</id><title type="text">Customizing Output Caching Behavior in ASP.NET MVC</title><summary type="text">While working with embedded resources in Portable Areas, I noticed that the newly embedded images started displaying slightly slower than before. Maybe it’s all in my head, but it got me thinking about caching nonetheless. </summary><published>2010-04-14T09:48:20-04:00</published><updated>2010-04-14T21:48:20Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/customizing-output-caching-behavior-in-aspnet-mvc" /><content type="html">&lt;p&gt;I added the new build of MvcContrib to OpenIdPortableArea today, and committed the new embedded resource routes. It worked great, and I’m working on some other things with the portable area.&lt;/p&gt;

&lt;p&gt;I noticed that the newly embedded images started displaying slightly slower than before. Maybe it’s all in my head, but it got me thinking about caching nonetheless. The embedded JavaScript, images, and CSS files are never going to change. As implemented right now, each request for embedded content requires that the mime type be determined, then locate the resource in the assembly, and then returns a &lt;code&gt;FilePathResult()&lt;/code&gt; from the stream of the extracted resource. With caching, we can prevent this operation from happening on every request.&lt;/p&gt;

&lt;p&gt;After thinking of this, I quickly pitched it to Steve Michelotti. I suggested the possiblity of including &lt;code&gt;[OutputCache(CacheProfile="EmbeddedResource")]&lt;/code&gt; on the &lt;code&gt;EmbeddedResourceController&lt;/code&gt;’s Index action. He thought this was an interesting approach, because it leaves the actual cache settings up to the programmer using this particular feature.&lt;/p&gt;

&lt;p&gt;So, as with any good idea I gave it a shot. I found that it worked great, but there was a catch. Using the &lt;code&gt;OutputCache.CacheProfile&lt;/code&gt; property means you absolutely mustprovide that cache profile in the &lt;code&gt;web.config&lt;/code&gt;. You get a yellow screen of death without it. With this in mind, adding such a cache profile requirement is just one more mandatory configuration to remember. How can we make it just work. Maybe the programmer using this code has some insane reason not to cache these resources. Whatever the case may be, it would be nice to allow the consumer to opt into the caching mechanism and allow everything to work without it.&lt;/p&gt;

&lt;h2&gt;First Idea&lt;/h2&gt;

&lt;p&gt;I quickly created a class called &lt;code&gt;OptionalOutputCacheAttribute&lt;/code&gt;, which inherited directly from &lt;code&gt;System.Web.Mvc.OutputCacheAttribute&lt;/code&gt;. The &lt;code&gt;OutputCacheAttribut&lt;/code&gt;e class uses &lt;code&gt;OnResultExecuting()&lt;/code&gt; to serve the cached version of the page. My plan was to check and see if that particular cache profile exists, and bail if it doesn’t. Sounds good in theory, but fails in practice. Why, you say? Because the &lt;code&gt;OutputCacheAttribute.CacheSetting&lt;/code&gt;s property is marked internal. Crap. So much for that idea.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;EDIT:&lt;/strong&gt; On second thought, this is probably not the real reason. The &lt;code&gt;OutputCacheAttribute&lt;/code&gt; doesn't expose its internal &lt;code&gt;OutputCacheParameters&lt;/code&gt; object, nor does it expose an &lt;code&gt;Enabled&lt;/code&gt; property. It is more likely that ASP.NET deals with caching a little deeper than we can get to, and I suspect it just doesn't support the idea of "maybe cache...". If the &lt;code&gt;OutputCache&lt;/code&gt; attribute exists, then cache it. Period.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;Second Idea&lt;/h2&gt;

&lt;p&gt;I have a backup plan, because there just has to be a way to make this work. Keeping the &lt;code&gt;OptionalOutputCacheAttribute&lt;/code&gt; class, what else is there to work with? I found a way to make it work, but some might find it… unsavory.
The attribute takes a moment and inspects the application’s &lt;code&gt;web.config&lt;/code&gt;. Here’s the code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
/// Provides optional chaching
/// &amp;lt;/summary&amp;gt;
public class OptionalOutputCacheAttribute : OutputCacheAttribute
{
    /// &amp;lt;summary&amp;gt;
    /// Contains a record of what CacheProfiles have been looked for
    /// &amp;lt;/summary&amp;gt;
    protected static Dictionary&amp;lt;string&amp;gt;, bool&amp;gt; CacheProfiles { get;set; }

    /// &amp;lt;summary&amp;gt;
    /// Constructor
    /// &amp;lt;/summary&amp;gt;
    public OptionalOutputCacheAttribute()
    {
        CacheProfiles = new Dictionary&amp;lt;string&amp;gt;, bool&amp;gt;();
    }

    /// &amp;lt;summary&amp;gt;
    /// Determines if the target CacheProfile exists before trying
    /// to handle the caching of the page.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="filterContext"&amp;gt;&amp;lt;/param&amp;gt;
    public override void OnResultExecuting(ResultExecutingContextfilterContext)
    {
        if (!CacheProfiles.Keys.Contains(CacheProfile))
        {
            XDocument xdoc =
            XDocument.Load(AppDomain.CurrentDomain.BaseDirectory +"\\web.config");

            var profileExists = xdoc.Descendants("outputCacheProfiles")
                .Descendants(XName.Get("add"))
                .Any(node =&amp;gt; node.Attribute(XName.Get("name")).Value ==CacheProfile);

            CacheProfiles.Add(CacheProfile, profileExists);
        }

        if (CacheProfiles[CacheProfile])
            base.OnResultExecuting(filterContext);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Using Linq to Xml, it’s fairly trivial to parse the web.config. It loads perfectly into an &lt;code&gt;XDocument&lt;/code&gt;. Then, it’s easy to see if the &lt;code&gt;outputCacheProfiles&lt;/code&gt; node has any &lt;code&gt;add&lt;/code&gt; nodes with a &lt;code&gt;name&lt;/code&gt; attribute equivalent to the name of the cache profile.&lt;/p&gt;

&lt;p&gt;As a way of reducing the frequency of &lt;code&gt;web.config&lt;/code&gt; parses, the attribute keeps a static &lt;code&gt;Dictionary&lt;/code&gt;. The first thing to check is if this particular cache profile has been looked up. If it hasn’t, we need to load the &lt;code&gt;web.config&lt;/code&gt; and do the search. The result is added to the dictionary for later use.&lt;/p&gt;

&lt;p&gt;After all of this parsing nonsense, we index into the dictionary and use the bool value. If the dictionary says that the cache profile exists, we allow the base class (&lt;code&gt;System.Web.Mvc.OutputCacheAttribute&lt;/code&gt;) to execute its &lt;code&gt;OnResultExecuting()&lt;/code&gt; method.&lt;/p&gt;

&lt;h2&gt;The Outcome&lt;/h2&gt;

&lt;p&gt;Using this new &lt;code&gt;OptionalOutputCacheAttribute&lt;/code&gt;, we can decorate the &lt;code&gt;EmbeddedResourceController&lt;/code&gt; with it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[OptionalOutputCache(CacheProfile="EmbeddedResource")]
public ActionResult Index(string resourceName, stringresourcePath)
{
    // ....
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;My initial tests for this code have proved successful. What does everyone else think of this? I was a little iffy on the whole web.config parsing thing (still am). However, I think this point of extensibility or configurability is more favorable than either A) not providing any support for caching embedded resources, or B) arbitrarily determining cache settings.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/embedded-static-resources-in-mvccontrib-portable-areas</id><title type="text">Embedded Static Resources in MvcContrib PortableAreas</title><summary type="text">One of the hokey things about the OpenIdPortableArea is that the ProvidersWidget contains some hard coded CSS, JavaScript, and Urls to images on the Internet. Steve Michelotti pushed a change to MvcContrib that provides a way to resolve embedded static resources.  Since the OpenIdPortableArea project could really use this feature, I eagerly downloaded it and tried it out.  Here are my thoughts…</summary><published>2010-04-12T09:58:39-04:00</published><updated>2010-04-12T21:58:39Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/embedded-static-resources-in-mvccontrib-portable-areas" /><content type="html">&lt;p&gt;Getting the &lt;code&gt;EmbeddedResourceController&lt;/code&gt; hooked up isn’t terrible.  First I compiled the MvcContrib source, and then dropped in &amp;amp; re-added a reference to the MvcContrib.dll.  Then, in my PortableArea project I added the following route to the &lt;code&gt;OpenIdAreaRegistration&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;context.MapRoute(
    "OpenId-EmbeddedResource",
    "OpenId/Content/{resourceName}",
    new { controller = "EmbeddedResource", action = "Index" },
    null,
    newstring[]{ "MvcContrib.PortableAreas" }
);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;One of the tricky things to remember is to include the namespace parameter of &lt;code&gt;MvcContrib.PortableAreas&lt;/code&gt; while mapping the route.  Without this, the routing engine won’t find the controller properly.&lt;/p&gt;

&lt;p&gt;After wiring up this route I added a providers.css file and embedded it.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/aspnet-mvc-portable-area-for-openid</id><title type="text">An ASP.NET MVC Portable Area for OpenId</title><summary type="text">PortableAreas are an exciting feature of MvcContrib, and I'm proud to announce a small project for making OpenId that much easier to support in ASP.NET MVC.</summary><published>2010-04-08T07:48:42-04:00</published><updated>2010-04-08T19:48:42Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/aspnet-mvc-portable-area-for-openid" /><content type="html">&lt;p&gt;I’m proud to announce my official entrance to the world of Open Source projects.  I just published &lt;a href="http://openidportablearea.codeplex.com"&gt;OpenIdPortableArea&lt;/a&gt; on &lt;a href="http://codeplex.com"&gt;CodePlex&lt;/a&gt;.  It is a pluggable component for ASP.NET MVC that takes advantage of &lt;a href="http://mvccontrib.org"&gt;MvcContrib&lt;/a&gt;’s &lt;a href="http://www.lostechies.com/blogs/hex/archive/2009/11/01/asp-net-mvc-portable-areas-via-mvccontrib.aspx"&gt;Portable Areas&lt;/a&gt;.  With relatively few requirements, you are able to add basic &lt;a href="http://openid.net"&gt;OpenId&lt;/a&gt; support to your applications.  For details on how to consume this Portable Area, check out the &lt;a href="http://openidportablearea.codeplex.com/documentation"&gt;documentation&lt;/a&gt; I slaved over!&lt;/p&gt;

&lt;p&gt;This project is using mercurial.  It includes one sample project to date.  Please, take a few minutes to check it out and provide feedback.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://i1.codeplex.com/Images/v17601/logo-home.png" alt="CodePlex logo" /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src="http://www.dotnetopenauth.net/wp-content/uploads/2010/12/dnoa-logo.png" alt="DotNetOpenAuth Logo" /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src="http://openid.net/wordpress-content/themes/openid/images/logo_openid.png" alt="OpenID Logo" /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src="http://download.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=mvccontrib&amp;amp;DownloadId=109198&amp;amp;Build=17601" alt="MvcContrib Logo" /&gt;&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/register-single-area-in-aspnet-mvc2</id><title type="text">Register a Single Area in ASP.NET MVC2</title><summary type="text">While working with areas, I found taht there was some occasional unexpected behavior with the order that routes get mapped. I needed a way to register one area at a time to fix the confusion.</summary><published>2010-03-31T07:55:17-04:00</published><updated>2010-03-31T19:55:17Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/register-single-area-in-aspnet-mvc2" /><content type="html">&lt;p&gt;&lt;code&gt;CallingAreaRegistration.RegisterAllAreas()&lt;/code&gt; doesn’t give you any control over which area gets registered first.  If this becomes an issue, you may be so inclined to individually register routes.  Here is an approach:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void RegisterAreas(RouteCollectionroutes)
{
    routes.RegisterArea&amp;lt;BlogAreaRegistration&amp;gt;();
}

protected void Application_Start()
{
    //AreaRegistration.RegisterAllAreas();
    RegisterAreas(RouteTable.Routes);
    RegisterRoutes(RouteTable.Routes);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I created a &lt;code&gt;RegisterAreas&lt;/code&gt; method just like &lt;code&gt;RegisterRoutes()&lt;/code&gt;.  Here, I can clearly register each Area one by one in the order that I choose.  This is done via an extension method on the &lt;code&gt;RoutesCollection&lt;/code&gt; type.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static class Extensions
{
    publicstaticvoidRegisterArea&amp;lt;T&amp;gt;(thisRouteCollectionroutes) whereT : AreaRegistration
    {
        // instantiate the area registration
        AreaRegistrationarea = Activator.CreateInstance&amp;lt;T&amp;gt;();

        // create a context, which is just the name and routes collection
        AreaRegistrationContextcontext = new AreaRegistrationContext(area.AreaName, routes);

        // register it!
        area.RegisterArea(context);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This extention method creates an instance of the &lt;code&gt;AreaRegistration&lt;/code&gt;, and then creates an &lt;code&gt;AreaRegistrationContext&lt;/code&gt;, and then calls &lt;code&gt;RegisterArea()&lt;/code&gt; on the area.&lt;/p&gt;

&lt;p&gt;I find that this approach demystifies &lt;code&gt;RegisterAllAreas&lt;/code&gt; and focuses on intention over convenience.  Registering areas individually is not always necessary, but it can be helpful to reduce routing confusion.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/NamedCapturingGroupsInRegularExpressions</id><title type="text">Named Capturing Groups in Regular Expressions</title><summary type="text">Opinions vary greatly with regular expressions, ranging among obliviousness, adoration, or disgust.  It’s no secret that I commonly use regular expressions to solve silly string problems.  I maintain that they can be simple to understand, and simple to unit test when used often and responsibly.</summary><published>2010-03-25T07:00:00-04:00</published><updated>2010-03-25T19:00:00Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/NamedCapturingGroupsInRegularExpressions" /><content type="html">&lt;p&gt;Using them in small doses is a way to get over the learning curve.  Here’s a simple problem that I came across, and I was able to quickly solve it without going way out of my way.&lt;/p&gt;

&lt;p&gt;Imagine that I’m working in a source base where a Person class contains a string property called Phone which contains a phone number.  That string property can contain an impressive variation of formats for phone numbers.  Now imagine that I was tasked with consuming a third party library, which defines its own Person object.  Instead of having a string property for a phone number, it defines a PhoneNumber class with a property for Area, Exchange, and Phone.  The constructor is parameterless, so it adheres to a tight/formal definition of a phone number.  Crap.&lt;/p&gt;

&lt;p&gt;This is where regular expressions shine.  Sure, I could write a ton of code and account for a million and one cases of what a phone number could look like.  Or, I could be generic about it and describe the pattern that phone numbers follow:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;\W*\(*\d{3}\)*\W*\.*\W*\d{3}\W*-*\W*\d{4}\W*
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This pattern roughly matches sets of 3, 3, and 4 digits with some input forgiveness in between (random spaces, dashes, and parentheses).  With a pattern like this, we are able to reasonably assert that a string is a phone number.  Test it for yourself.&lt;/p&gt;

&lt;p&gt;There is a problem with this pattern.  It only confirms that the string matches.  Sure, that’s a good thing, but let us not forget the original problem.  The PhoneNumber class from this third party is string-ignorant.  I need a way to extract the critical parts of this string to an instance of this PhoneNumber class.
How?  Named Capturing Groups, that’s how.  Named capturing groups aren’t too bad.  Let’s look at a contrived example (those are the best).&lt;/p&gt;

&lt;p&gt;Capture a string of three digits, named "digits":&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(?&amp;lt;digits&amp;gt;\d{3})
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this pattern, &lt;code&gt;\d{3}&lt;/code&gt; matches a string like &lt;code&gt;123&lt;/code&gt; and is grouped by the key "digits".  Groups are created by using &lt;code&gt;(?&amp;lt;&amp;gt;)&lt;/code&gt;.  The group name goes between the angle brackets, &lt;code&gt;&amp;lt;digits&amp;gt;&lt;/code&gt;.  Perhaps it will make more sense to see it in practice.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;string pattern = @"(?&amp;lt;digits&amp;gt;\d{3})";
string input = "hello 123 world";
Match match = Regex.Match(input, pattern);
string result = match.Groups["digits"].Value;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The Regex object has a &lt;code&gt;Match()&lt;/code&gt; method that takes string input and a pattern.  The Match object returned from this call has a GroupCollection on it, which allows you to index into it with string keys.  The keys are the names given to groups.  In this example, our group was named "digits" and the result is &lt;code&gt;123&lt;/code&gt;.  Neat, right?&lt;/p&gt;

&lt;p&gt;Now that we have a pattern that can match phone numbers, it would be nice to allow Regex to do the dirty work for us as it matches.  We can take advantage of named capturing groups here:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;\W*\(*(?&amp;lt;area&amp;gt;\d{3})\)*\W*\.*\W*(?&amp;lt;exchange&amp;gt;\d{3})\W*-*\W*(?&amp;lt;phone&amp;gt;\d{4})\W*
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we’re able to capture "area", "exchange", and "phone" while performing a match.  There’s lots of ways to implement this code.  Since it’s a third party library, I choose to write an extension method.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static class PhoneNumberExtensions
{
    const string pattern = @"\W*\(*(?&amp;lt;area&amp;gt;\d{3})\)*\W*\.*\W*(?&amp;lt;exchange&amp;gt;\d{3})\W*-*\W*(?&amp;lt;phone&amp;gt;\d{4})\W*";

    public static void SetFromString(this PhoneNumber phoneNumber, string input)
    {
        Matchmatch = Regex.Match(input, pattern);

        phoneNumber.Area = match.Groups["area"].Value;
        phoneNumber.Exchange = match.Groups["exchange"].Value;
        phoneNumber.Phone = match.Groups["phone"].Value;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code is virtually the same as the first example.  The usage is also simple.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PhoneNumber myPhoneNumber = newPhoneNumber();
myPhoneNumber.SetFromString("(123) 456 - 7890");
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;These are the kinds of problems I like to solve with Regular Expressions.  It takes the tediousness out of dealing with strings.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/HelpfulMercurialResources</id><title type="text">Helpful Mercurial Resources</title><summary type="text">I can’t help it, Mercurial is my favorite VCS right now for several reasons. I thought it might be helpful to post a list of resources that I’ve come across.</summary><published>2010-03-13T05:59:17-05:00</published><updated>2010-03-13T17:59:17Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/HelpfulMercurialResources" /><content type="html">&lt;ul&gt;
&lt;li&gt;&lt;a href="http://mercurial.selenic.com/downloads/"&gt;TortoiseHg&lt;/a&gt; - Download and install it! TortoiseHg adds an item to context menus in Windows Explorer. It also includes Mercurial.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://mercurial.selenic.com/"&gt;Mercurial&lt;/a&gt; - The Mercurial website; contains lots of educational material.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://mercurial.selenic.com/wiki/MercurialBook"&gt;Mercurial&lt;/a&gt;: The Definitive Guide - by Bryan O’Sullivan. For all of your nitty gritty HG needs.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://hginit.com/"&gt;HgInit&lt;/a&gt; - Joel Spolsky’s introduction to Mercurial, with a little reeducation for SVN users.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://hgtip.com/"&gt;Hg Tip&lt;/a&gt; - Tips for beginner and advanced users alike.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.jeremyskinner.co.uk/2010/02/18/using-mercurial-with-codeplex-and-github/"&gt;Using Mercurial with CodePlex and GitHub&lt;/a&gt; - Great post by Jeremy Skinner.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://tekpub.com/codeplex"&gt;TekPub: Mercurial with CodePlex (free)&lt;/a&gt; - A special free episode. Rob Conery walks through using Mercurial with CodePlex.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://tekpub.com/preview/hg"&gt;TekPub: Mastering Mercurial&lt;/a&gt; - The TekPub series on Mercurial.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://visualhg.codeplex.com/"&gt;VisualHG&lt;/a&gt; - Visual Studio plug-in that adds Mercurial to your list of Source Control plug-ins.&lt;/li&gt;
&lt;li&gt;&lt;a href="https://bitbucket.org/"&gt;BitBucket&lt;/a&gt; - A code hosting site for Mercurial.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.jetbrains.com/teamcity/index.html"&gt;TeamCity&lt;/a&gt; - A continuous integration build management system by JetBrains that Supports Mercurial. I tried this out recently, and configured it in parallel with VSS for a single project. When I ran it cold, Hg was 65% faster than VSS.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://mercurial.selenic.com/wiki/QuickReferenceCardsAndCheatSheets"&gt;Reference Cards &amp;amp; Cheat Sheets&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you have anything to add, please comment and I’ll update the post.&lt;/p&gt;
</content></entry><entry><id>http://johncoder.com/Post/KeepJavaScriptAtTheBottom</id><title type="text">Keep JavaScript at the Bottom</title><summary type="text">JavaScript executes better at the bottom of the page, and MVC will let you do just that.</summary><published>2010-01-21T06:15:43-05:00</published><updated>2011-03-15T08:19:14Z</updated><author><name>John Nelson</name></author><link rel="alternate" href="http://johncoder.com/Post/KeepJavaScriptAtTheBottom" /><content type="html">&lt;p&gt;Frankly, I’m surprised that it took until page 12 of the jQuery Cookbook to mention putting JavaScript at the bottom of the page before the closing tag.  Pages load faster with the JavaScript at the bottom, and it removes the need to use the ready() function.  This is great advice.  Using a ContentPlaceHolder helps keep the scripts in their optimal location.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;html xmlns="http://www.w3.org/1999/xhtml"&amp;gt;
&amp;lt;head runat="server"&amp;gt;
    &amp;lt;title&amp;gt;&amp;lt;asp:ContentPlaceHolder ID="TitleContent" runat="server" /&amp;gt;&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;div&amp;gt;
        &amp;lt;asp:ContentPlaceHolder ID="MainContent" runat="server" /&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;asp:ContentPlaceHolder ID="ScriptContent" runat="server"/&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then, I’m able to include an element inside of my View and use it freely.  Notice that I was able to include jquery.min.js above the ContentPlaceHolder, which means jQuery will already be warm for any JavaScript in my ScriptContent.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;asp:Content ID="Content3" ContentPlaceHolderID="TitleContent" runat="server"&amp;gt;
    About
&amp;lt;/asp:Content&amp;gt;
&amp;lt;asp:Content ID="Content4" ContentPlaceHolderID="MainContent" runat="server"&amp;gt;
    &amp;lt;h2&amp;gt;About&amp;lt;/h2&amp;gt;
    &amp;lt;div class="about-message"&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;/asp:Content&amp;gt;
&amp;lt;asp:Content ID="Content5" ContentPlaceHolderID="ScriptContent" runat="server"&amp;gt;
    &amp;lt;script type="text/javascript"&amp;gt;
        $('.about-message').text("Thisis the About Page!");
    &amp;lt;/script&amp;gt;
&amp;lt;/asp:Content&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Another added perk to this ContentPlaceHolder approach is that it lets me include other JavaScript libraries that individual Views might depend on.  Pretty simple, but I hope you enjoy it!&lt;/p&gt;
</content></entry></feed>

