<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Pace yourself</title>
  <id>www.paceyourself.net</id>
  <updated>2010-07-30</updated>
  <author>
    <name>Bob Pace</name>
  </author>
  <entry>
    <title>MvcToFubu - Transition your website from ASP.NET MVC to FubuMVC Part 1</title>
    <link rel="alternate" href="http://www.paceyourself.net/2011/06/11/mvctofubu---transition-your-website-from-aspnet-mvc-to-fubumvc-part-1/"/>
    <id>http://www.paceyourself.net/2011/06/11/mvctofubu---transition-your-website-from-aspnet-mvc-to-fubumvc-part-1/</id>
    <published>2011-06-11</published>
    <updated>2011-06-11</updated>
    <author>
      <name>Bob Pace</name>
    </author>
    <summary type="html">&lt;p&gt;So you are thinking about using FubuMVC but you are having a hard time
justifying to your coworkers or boss or even yourself the level of effort it
would take to switch your existing ASP.NET MVC website over to a new web&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;So you are thinking about using FubuMVC but you are having a hard time
justifying to your coworkers or boss or even yourself the level of effort it
would take to switch your existing ASP.NET MVC website over to a new web
framework. You wish there was a way you could get into FubuMVC with the ability
to slowly transition your site piece by piece and not all at once.&lt;/p&gt;

&lt;p&gt;Or perhaps you are content using ASP.NET MVC for your project, but are
interested in taking advantage of FubuMVC behavior chains to deal with common
before and after request responsibilities.&lt;/p&gt;

&lt;p&gt;It is the goal of the MvcToFubu project to help enable these two scenarios and
encourage everyone to try FubuMVC out for themselves. By smoothing the
transition away from ASP.NET MVC towards FubuMVC hopefully anyone who was
sitting on the fence about giving Fubu a try will be able to check it out with
less risk.&lt;/p&gt;

&lt;p&gt;Clone from the github repository here:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/bobpace/MvcToFubu"&gt;https://github.com/bobpace/MvcToFubu&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Make sure you have ASP.NET MVC 3 installed to view the sample projects.&lt;/p&gt;

&lt;p&gt;Also, when you build for the first time it will have build errors before
it pulls down the nuget package references, just build again and you will be
good.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;NOTE:&lt;/em&gt; Since FubuMVC runs on StructureMap, if your website uses a different container
you will need to use StructureMap in order to take advantage of any of the
techniques shown by this MvcToFubu project.&lt;/p&gt;

&lt;h1&gt;Part 1&lt;/h1&gt;

&lt;p&gt;Enable FubuMVC Behavior chains in your ASP.NET MVC web application.&lt;/p&gt;

&lt;p&gt;I will assume some familiarity with behavior chains already but you can read
more about them here:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://guides.fubumvc.com/getting_started.html#behaviorsand-behavior-chains"&gt;http://guides.fubumvc.com/getting_started.html#behaviorsand-behavior-chains&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After pulling down the MvcToFubu source and building, set the
MVCWithFubuBehaviors project as the startup project and run it.&lt;/p&gt;

&lt;p&gt;After arriving at the example view you can look in your Visual Studio Output
window and you should see a line containing:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Executing example behavior...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This ExampleBehavior is set up in the ExamplePolicy class to be applied to all
actions on the ExampleController.&lt;/p&gt;

&lt;p&gt;I want to point out a few of the important pieces that help make this work.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;MvcToFubuApplication&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Creates and populates a &lt;code&gt;BehaviorChainIdLookup&lt;/code&gt; that matches ASP.NET MVC
controller action invocations to their corresponding behavior chain. This
lookup is used in the &lt;code&gt;MvcToFubuControllerActionInvoker&lt;/code&gt; so that when the
normal ASP.NET MVC pipeline invokes a controller action it can defer the
execution of the ActionResult until the MvcActionCall node in your behavior
chain. Behaviors for OutputNodes, or nodes that come after the ActionCall are
not supported since after running the MvcActionCall the default ASP.NET MVC
rendering pipeline takes over.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;MvcToFubuRegistry&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Ignores methods that come from base ASP.NET MVC Controller class, since
controllers will be inheriting it.&lt;/p&gt;

&lt;p&gt;Replaces the default ActionCall in the behavior chain with our MvcActionCall
which will enable us to invoke the regular ASP.NET MVC pipeline for the
controller action.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ControllerContextBehavior&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;A base class for behaviors for your convenience since much of what you may want
to deal with will be contained on the ControllerContext.&lt;/p&gt;

&lt;p&gt;Part 2 will go over the details of how to run FubuMVC right inside your
existing ASP.NET MVC site, letting you transition your site slowly to FubuMVC
while maintaining existing ASP.NET MVC site functionality.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Getting Started With Develop With Passion Specifications for Unit Testing</title>
    <link rel="alternate" href="http://www.paceyourself.net/2011/06/05/getting-started-with-develop-with-passion-specifications-for-unit-testing/"/>
    <id>http://www.paceyourself.net/2011/06/05/getting-started-with-develop-with-passion-specifications-for-unit-testing/</id>
    <published>2011-06-05</published>
    <updated>2011-06-05</updated>
    <author>
      <name>Bob Pace</name>
    </author>
    <summary type="html">&lt;p&gt;One area I am seeking to improve myself in is better unit testing of the code
that I write. After attending the develop with passion training course in&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;One area I am seeking to improve myself in is better unit testing of the code
that I write. After attending the develop with passion training course in
Denver last month I saw an excellent approach to testing demonstrated by
&lt;a href="http://blog.developwithpassion.com"&gt;JP Boodhoo&lt;/a&gt; that I would like to share with
anyone who is interested.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.developwithpassion.com/2011/03/introducing-developwithpassion-specifications"&gt;Develop with Passion specifications&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Easy to use consistent approach to unit testing that gives you access to all
the tools necessary and encourages design choices in the tests themselves.&lt;/p&gt;

&lt;p&gt;Prerequisites:&lt;/p&gt;

&lt;p&gt;Have a copy of resharper (not absolutely necessary, but greatly enchances the
experience of using these specifications)&lt;/p&gt;

&lt;h2&gt;Goal 1:&lt;/h2&gt;

&lt;p&gt;Be able to run develop with passion specifications from within Visual Studio.&lt;/p&gt;

&lt;p&gt;Install machine.specifications for your version of Resharper so you can run
these unit tests via Resharpers test menu.
&amp;mdash; optionally you can install for test driven .net if you prefer to use that.&lt;/p&gt;

&lt;p&gt;Resources:
readme @ &lt;a href="https://github.com/agross/machine.specifications/"&gt;https://github.com/agross/machine.specifications/&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git clone git://github.com/agross/machine.specifications.git
cd machine.specifications
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;if using git bash or cygwin / can &lt;code&gt;cmd&lt;/code&gt; into command prompt, otherwise just:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;build.cmd
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;After build is complete, change directory to &lt;code&gt;Build/Debug&lt;/code&gt; and run the
appropriate .bat file to install for either resharper or test driven .net. I
ran &lt;code&gt;InstallResharperRunner.5.1 - VS2010.bat&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;Goal 2:&lt;/h2&gt;

&lt;p&gt;Import resharper live templates provided for develop with passion specifications.&lt;/p&gt;

&lt;p&gt;Obtain the following template files:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="/templates/file_templates_developwithpassion_specifications_rhino_mocks.xml"&gt;file_templates_developwithpassion_specifications_rhino_mocks.xml&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/templates/live_templates_developwithpassion_specifications.xml"&gt;live_templates_developwithpassion_specifications.xml&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/templates/live_templates_machine_specifications.xml"&gt;live_templates_machine_specifications.xml&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;Open resharper live templates menu (Resharper: Live Templates)&lt;/p&gt;

&lt;p&gt;On the file templates tab select the User Templates node and then click the
import icon and navigate to
&lt;code&gt;file_templates_developwithpassion_specifications_rhino_mocks.xml&lt;/code&gt; and click
open.&lt;/p&gt;

&lt;p&gt;Next, select and drag the ObservationsWithContract,
  ObservationsWithoutContract, and StaticObservations templates over to the
  right side window and drop them on the C# projects section.  Now you will be
  able to create these when using resharpers alt + insert shortcut to add new
  files.&lt;/p&gt;

&lt;p&gt;On the live templates tab, import both live template files into User Templates: C#&lt;/p&gt;

&lt;p&gt;&lt;code&gt;live_templates_developwithpassion_specifications.xml&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;deps &amp;ndash; for providing mocks that are automatically dependency injected to your sut&lt;/li&gt;
&lt;li&gt;fake &amp;ndash; for providing all other mocks&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;&lt;code&gt;live_templates_machine_specifications.xml&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;bddb &amp;ndash; because block&lt;/li&gt;
&lt;li&gt;bddc &amp;ndash; establish block&lt;/li&gt;
&lt;li&gt;tc &amp;ndash; it block&lt;/li&gt;
&lt;li&gt;sa &amp;ndash; subject class&lt;/li&gt;
&lt;li&gt;bddcu &amp;ndash; cleanup&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;Making good use of these resharper templates greatly enhances the experience of
using these specifications for consistent unit testing throughout projects.&lt;/p&gt;

&lt;h2&gt;Goal 3:&lt;/h2&gt;

&lt;p&gt;Change resharper formatting options for optimal test readability.&lt;/p&gt;

&lt;p&gt;This step is optional but I find the improved readability is pretty nice.&lt;/p&gt;

&lt;p&gt;Make the following changes to your resharper formatting options: (Resharper: Options)&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Languages: C#: Formatting Style: Braces Layout&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Anonymous method declaration: At next line (BSD style)&lt;/li&gt;
&lt;li&gt;Array and object initializer: At next line (BSD style)&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;&lt;em&gt;Languages: C#: Formatting Style: Other&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Modifiers: Use explicit private modifier: Uncheck&lt;/li&gt;
&lt;li&gt;Align Multiline Constructs: Expression: Uncheck&lt;/li&gt;
&lt;li&gt;Other: Indent anonymous method body: Uncheck&lt;/li&gt;
&lt;li&gt;Align Multiline Constructs: Array, object and collection initializer: Uncheck&lt;/li&gt;
&lt;li&gt;Other: Indent array, object and collection initializers: Uncheck&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Goal 4:&lt;/h2&gt;

&lt;p&gt;Create a test project to contain your develop with passion tests.&lt;/p&gt;

&lt;p&gt;Suggested project name: &lt;code&gt;ProjectName&lt;/code&gt;.Specs&lt;/p&gt;

&lt;p&gt;Obtain NuGet Package Manager extension for Visual Studio 2010:&lt;/p&gt;

&lt;p&gt;Add developwithpassion.specifications via NuGet package installation.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Right click References: Add Library Package Reference&lt;/li&gt;
&lt;li&gt;Search for developwithpassion (all one word)&lt;/li&gt;
&lt;li&gt;Install the developwithpassion package of your choice, I am using the rhino mocks one.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;Use the resharper file templates available via ALT+INSERT to create new
ObservationsWithContract, ObservationsWithoutContract, or StaticObservations.&lt;/p&gt;

&lt;p&gt;Suggested test classes naming convention: &lt;code&gt;SystemUnderTest&lt;/code&gt;Specs&lt;/p&gt;

&lt;h2&gt;Goal 5:&lt;/h2&gt;

&lt;p&gt;Learn to use develop with passion specifications.&lt;/p&gt;

&lt;p&gt;There is an execellent example project available to inspect and gain an
understanding of how to make use of the features provided, pull it down with
git and take a look through it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/developwithpassion/developwithpassion.specifications/"&gt;https://github.com/developwithpassion/developwithpassion.specifications/&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git clone git://github.com/developwithpassion/developwithpassion.specifications.git
cd developwithpassion.specifications
start solution.sln
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Spend some time familiarizing yourself with the
&lt;code&gt;developwithpassion.specifications.examples&lt;/code&gt; project.  These are excellent
examples that demonstrate the various features available which should cover
every scenario you will encounter while unit testing.&lt;/p&gt;

&lt;p&gt;Well that should get you on your feet to evaluating this for yourself. I am
pretty excited to be using it, I feel it will help to streamline much of the
repetitive work involved with test setup that deterred me from bettering my
testing techniques in the past.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Nothing But .NET Postmortem</title>
    <link rel="alternate" href="http://www.paceyourself.net/2011/05/28/nothing-but-net-postmortem/"/>
    <id>http://www.paceyourself.net/2011/05/28/nothing-but-net-postmortem/</id>
    <published>2011-05-28</published>
    <updated>2011-05-28</updated>
    <author>
      <name>Bob Pace</name>
    </author>
    <summary type="html">&lt;p&gt;I just got back from attending the Nothin' but .NET developer training course
in Denver, Colorado last week and wanted to pass on some of the take aways from&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;I just got back from attending the Nothin' but .NET developer training course
in Denver, Colorado last week and wanted to pass on some of the take aways from
it.&lt;/p&gt;

&lt;p&gt;It was an awesome experience, JP had a great setup for teaching our group of 15
people. He had us fork one of his repositories on github and used various
scripts to automate the process of pulling change sets from students back into
the master branch as well as allowing students to catch back up to the latest
version of what was going on.&lt;/p&gt;

&lt;p&gt;It was seriously the best way to run an all day workshop that I have ever seen
implemented. I think back to various code camps or competitions where this kind
of a setup would have trivialized the difficulty in enabling efficient
collaboration between a group of people.&lt;/p&gt;

&lt;p&gt;After presenting a concept he would check in some code, have us pull it down
and then we would go to work on trying to solve the problem for ourselves. As
soon as someone had something finished they would push their changes and the
class would stop their work on the exercise and watch as JP looked over the
changes and then refactored the code using a true object oriented approach
where each concern was broken down into its individual parts and tackled
gracefully with the appropriate design pattern that was best suited to the job.&lt;/p&gt;

&lt;p&gt;Oh, and he did it at like 100 miles per hour. I thought I was fast, but now I have
a new definition for the word.&lt;/p&gt;

&lt;p&gt;Watching JP&amp;rsquo;s speed and sheer amount of automation while he coded in front of
an audience was a nice glimpse into the true potential of what we can all
become if we are willing to invest the time to hone our craft.&lt;/p&gt;

&lt;p&gt;Overall this was a great course which has inspired me to better myself as a
developer.&lt;/p&gt;

&lt;p&gt;Here&amp;rsquo;s my list of goals after attending the course:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Craft your work bench!&lt;/li&gt;
&lt;li&gt;Learn a shell like the back of your hand&lt;/li&gt;
&lt;li&gt;Make the business concerns you deal with first class citizens in your code
base.&lt;/li&gt;
&lt;li&gt;Tests to drive the design.&lt;/li&gt;
&lt;li&gt;Don&amp;rsquo;t just apply refactorings to your code base, but to your programming
experience in general.&lt;/li&gt;
&lt;/ul&gt;

</content>
  </entry>
  <entry>
    <title>Managing client side javascript with require.js</title>
    <link rel="alternate" href="http://www.paceyourself.net/2011/05/14/managing-client-side-javascript-with-requirejs/"/>
    <id>http://www.paceyourself.net/2011/05/14/managing-client-side-javascript-with-requirejs/</id>
    <published>2011-05-14</published>
    <updated>2011-05-14</updated>
    <author>
      <name>Bob Pace</name>
    </author>
    <summary type="html">&lt;p&gt;Its been a long while since my last post, which is mostly due to the amount of
work projects going on.&lt;/p&gt;

&lt;p&gt;Of the many interesting things I would like to blog about the first one that&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;Its been a long while since my last post, which is mostly due to the amount of
work projects going on.&lt;/p&gt;

&lt;p&gt;Of the many interesting things I would like to blog about the first one that
comes to mind is what we&amp;rsquo;ve been doing with our client side javascript lately.
Javascript can feel like the wild wild west sometimes with the way that it gets
haphazardly strewn about littering the global namespace with who knows what
variables and generally just being a giant mess that gets harder to maintain
over time.&lt;/p&gt;

&lt;p&gt;Most people are at least using a modular approach with something along the
lines of:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(function() {
 //export something useful to global namespace
})()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But what do you do when you start to get a lot of these, and they start to
interact with each other in ways such that certain modules are dependent on
others being there or having to juggle whether or not you&amp;rsquo;ve already loaded it
so as not to have to load it again, etc&amp;hellip;&lt;/p&gt;

&lt;p&gt;Well gone are those days, enter &lt;a href="http://requirejs.org"&gt;Require.js&lt;/a&gt; and a
civilized approach to organizing your client side javascript into modules that
can be easily managed and comes with the perk of an optimization tool which
enables you to combine all dependencies for a page into practically one single
minified/obfuscated file to get screaming fast load times with far fewer
requests that need to be made to bring down your content.&lt;/p&gt;

&lt;p&gt;So not only am I going to describe a possible approach to getting set up, but
I&amp;rsquo;ve already got it running on this page right now so feel free to open your
web development tool of choice be it FireBug or Chromes Javascript console and
take a look for yourself. &lt;strong&gt;It goes without saying that if you are using
Internet Explorer you should seriously reconsider your web browsing habits.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So first things first, the idea of using require is that you include a snippet
such as this up in your head tag.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;script type="text/javascript"&amp;gt;
  var require = {
    priority: ['jquery-1.6.min', 'underscore']
  };
&amp;lt;/script&amp;gt;
&amp;lt;script type="text/javascript" data-main="/js/main" src="/js/require.js"&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is but one of many possible ways to set this up, but it&amp;rsquo;s my current
preferred approach. Dependencies that you know you are going to want before any
of your modules even try to load can be specifed in the priority array. The
data-main attribute lets require know which javascript file you want to be the
main entry point aka the require bootstrapper as I like to call it. Note that
you leave off the .js extension.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;main.js&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require(['util/module-activator', 'util/analytics'],
  function(moduleActivator, analytics){
    analytics.track('UA-17910584-1');
    moduleActivator.execute();
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The example above takes in an array of dependencies as a first parameter, and a
function which will make use of those dependencies as its second parameter.&lt;/p&gt;

&lt;p&gt;Not every dependency needs to be included as a parameter to the function. If
all you need to do is just execute some arbitrary javascript or link to a .js
file that is not defined in the require syntax then feel free to leave it out
of the parameters to your function however anything like that will need to be
at the end of your dependency array as the arguments to the function are passed
in the order they were specified.&lt;/p&gt;

&lt;p&gt;The two modules you see me using here are great examples of some of the things
you can get done using require. Lets take a look at them.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;util/analytics&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;define(function(){
    var exports = {
      track: function(accountId) {
        var _gaq = window._gaq = _gaq || [],
            ga = document.createElement('script'),
            s = document.getElementsByTagName('script')[0];

        _gaq.push(['_setAccount', accountId]);
        _gaq.push(['_trackPageview']);

        ga.type = 'text/javascript';
        ga.async = true;
        ga.src = ('https:' == document.location.protocol ?
          'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

        s.parentNode.insertBefore(ga, s);
      }
    };

  return exports;
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You may recognize this as the google analytics script, but rewritten according
to my interpretation of current best javascript practices gleaned from
&lt;a href="http://www.crockford.com"&gt;Javascript: The Good Parts&lt;/a&gt; which if you haven&amp;rsquo;t
read yet I would recommend that you do.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;util/module-activator&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;define(function(){
  var module = {};

  function loadModule(domElement) {
    var element = $(domElement),
        moduleName = element.data("module");

    require([moduleName], function(module) {
      module.init(element);
    });
  };

  module.execute = function(element) {
    var element = element || $("html"),
        dataModules = $("[data-module]", element);

    _.each(dataModules, loadModule);
  };

  return module;
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The module activators power is second only to its mystery.  It scrapes the page
for any elements with a data-module attribute on them and issues a require call
to load a module by the name of the value provided and then invokes an init
function on the module passing it the element as a jquery wrapped set. The
element can then be used to scope selectors against inside your module using
jquery or put to any purpose you can think of.&lt;/p&gt;

&lt;p&gt;Step 1: Add a data-module attribute to an element on page:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;div id="color-changer" data-module="color-changer"&amp;gt;&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Step 2: Enjoy your functionality. Click the &lt;span
data-module="color-changer"&gt;div&lt;/span&gt; below and watch it change colors.&lt;/p&gt;

&lt;div id="color-changer" data-module="color-changer"&gt;&lt;/div&gt;


&lt;p&gt;The implementation of color-changer looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;define(function() {
  var exports = {},
      colors = ['red', 'blue', 'yellow', 'green', 'orange', 'purple'],
      getRandomColor = function() {
        var max = colors.length,
            index = Math.floor(Math.random()*max+1);
        return colors[index];
      };

  exports.init = function(element) {
    var previousColor;
    element.click(function() {
      var color;
      while (!color || color === previousColor) {
        color = getRandomColor();
      }
      element.css('background', color);
      previousColor = color;
    });
  };

  return exports;
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To demonstrate this modules reusability look back up at Step 2 and try clicking
on the word &amp;ldquo;div&amp;rdquo;. The markup for it looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;span data-module="color-changer"&amp;gt;div&amp;lt;/span&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It will also change colors, and if you notice the two different color changers
keep their own state of previous color to ensure that the next random color
selected is not the same as the one before.&lt;/p&gt;

&lt;p&gt;I hope this shows you some of the potential an approach like this can have and
gets you excited about using require.js for yourself.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>The Enumerang: A CQRS helper with potential other uses</title>
    <link rel="alternate" href="http://www.paceyourself.net/2010/10/21/the-enumerang-a-cqrs-helper-with-potential-other-uses/"/>
    <id>http://www.paceyourself.net/2010/10/21/the-enumerang-a-cqrs-helper-with-potential-other-uses/</id>
    <published>2010-10-21</published>
    <updated>2010-10-21</updated>
    <author>
      <name>Bob Pace</name>
    </author>
    <summary type="html">&lt;p&gt;To give a little bit of background we have a shopping cart we are developing
that performs adds or removes via ajax posts. As all operations are asynchronous&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;To give a little bit of background we have a shopping cart we are developing
that performs adds or removes via ajax posts. As all operations are asynchronous
when we fire off a command to add/remove an item and then immediately refresh
the view of the cart it will not yet contain the newly added item or in the case
of remove it will still contain the removed item. Our goal was to make it as
smooth an operation as possible, without waiting for a response back to confirm
that the operation had finished before refreshing the view.&lt;/p&gt;

&lt;p&gt;So I thought if we could make something that could temporarily alter an
IEnumerable to make it seem as if a particular operation had already taken place
then the resulting view would look correct, and then later when the view is
refreshed again if the item that the pending operation was standing in for was
actually there (or not there if it was a remove) then that pending operations
purpose will have been fulfilled and it will drop out of the list of known
pending operations.&lt;/p&gt;

&lt;p&gt;It worked out for my needs pretty nicely so I went ahead and put it up on
&lt;a href="http://github.com/bobpace/Enumerang"&gt;GitHub&lt;/a&gt; if anyone is interested in checking it out. I&amp;rsquo;ll go over it a
bit and explain what the thought process was behind it and show some potential
usages.&lt;/p&gt;

&lt;p&gt;The Enumerang holds onto a list of PendingOperations, but it does not actually
contain the source collection itself. You pass the sourceCollection through its
&lt;code&gt;AlterCollection&lt;/code&gt; method to get the end effect of what each pending operation
would have done to the source collection.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Enumerang&amp;lt;T&amp;gt;
{
    public Enumerang()
    {
        PendingOperations = new List&amp;lt;IPendingOperation&amp;lt;T&amp;gt;&amp;gt;();
    }

    public IEnumerable&amp;lt;T&amp;gt; AlterCollection(IEnumerable&amp;lt;T&amp;gt; sourceCollection)
    {
        var result = PendingOperations.Aggregate(
            sourceCollection, (current, operation) =&amp;gt; operation.Alter(current))
            .ToList();
        PendingOperations = PendingOperations.Where(x =&amp;gt; !x.PurposeFulfilled).ToList();
        return result;
    }

    public IList&amp;lt;IPendingOperation&amp;lt;T&amp;gt;&amp;gt; PendingOperations { get; private set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;IPendingOperations can alter an IEnumerable in any way you choose, and just need
to know when their purpose has been fulfilled so they can drop out of the list
of pending operations.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IPendingOperation&amp;lt;T&amp;gt;
{
    bool PurposeFulfilled { get; }
    IEnumerable&amp;lt;T&amp;gt; Alter(IEnumerable&amp;lt;T&amp;gt; source);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I have provided two IPendingOperation implementations, the AddPendingOperation
and the RemovePendingOperation.&lt;/p&gt;

&lt;p&gt;The AddPendingOperation checks each item in the source collection as it yield
returns them and if nothing in the source collection matches the &lt;code&gt;MatchTarget&lt;/code&gt;
condition then it will additionally yield return the result of the &lt;code&gt;ProvideItem&lt;/code&gt;
func that you provide. If the item is already in the source collection then the
AddPendingOperation&amp;rsquo;s purpose is fulfilled and it is removed from the list of
PendingOperations.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class AddPendingOperation&amp;lt;T&amp;gt; : IPendingOperation&amp;lt;T&amp;gt;
{
    public Func&amp;lt;T, bool&amp;gt; MatchTarget { get; set; }
    public bool PurposeFulfilled { get; set; }
    public Func&amp;lt;T&amp;gt; ProvideItem { get; set; }

    public IEnumerable&amp;lt;T&amp;gt; Alter(IEnumerable&amp;lt;T&amp;gt; source)
    {
        foreach (var item in source)
        {
            if (!PurposeFulfilled &amp;amp;&amp;amp; MatchTarget(item))
            {
                PurposeFulfilled = true;
            }
            yield return item;
        }

        if (!PurposeFulfilled)
        {
            yield return ProvideItem();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The RemovePendingOperation returns all items from the source collection as long
as they don&amp;rsquo;t match the &lt;code&gt;MatchTarget&lt;/code&gt; func that you provide for it. If it does
match, then that item is excluded from the list. If your RemovePendingOperation
fails to match an item in the source collection then its purpose is fulfilled
and it drops out of the list of PendingOperations.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class RemovePendingOperation&amp;lt;T&amp;gt; : IPendingOperation&amp;lt;T&amp;gt;
{
    public Func&amp;lt;T, bool&amp;gt; MatchTarget { get; set; }
    public bool PurposeFulfilled { get; set; }
    private bool _wasUsed;

    public IEnumerable&amp;lt;T&amp;gt; Alter(IEnumerable&amp;lt;T&amp;gt; source)
    {
        _wasUsed = false;
        Func&amp;lt;T, bool&amp;gt; noPendingRemoveOperationsForItem = x =&amp;gt;
            {
                var result = MatchTarget(x);
                if (result)
                {
                    _wasUsed = true;
                }
                return !result;
            };

        foreach (var item in source.Where(noPendingRemoveOperationsForItem))
        {
            yield return item;
        }

        PurposeFulfilled = !_wasUsed;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The way we are using this right now is to store one instance of an
Enumerang&lt;ShoppingCartItem&gt; which we call the &lt;code&gt;CartActivityMonitor&lt;/code&gt; in the session
and any time we send off a command to add or remove an item we also add a
PendingOperation to it like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CartActivityMonitor.PendingOperations.Add(new AddPendingOperation&amp;lt;ShoppingCartItem&amp;gt;
{
    MatchTarget = x =&amp;gt; x.Id == 1,
    ProvideItem = () =&amp;gt; new ShoppingCartItem { Id = 1},
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or in the case of a remove:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CartActivityMonitor.PendingOperations.Add(new RemovePendingOperation&amp;lt;ShoppingCartItem&amp;gt;
{
    MatchTarget = x =&amp;gt; x.Id == 1,
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For simplicity this example uses only single int id to match on, but if your
needs are more complex you can provide any Func&amp;lt;T, bool&gt; to consider what
&amp;lsquo;matching&amp;rsquo; means to you.&lt;/p&gt;

&lt;p&gt;We can then immediately refresh our view, and even if it does not yet reflect
the changes we have made from our adds/removes if we pass our
IEnumerable&lt;ShoppingCartItem&gt; through the &lt;code&gt;AlterCollection&lt;/code&gt; method on the
CartActivityMonitor it will project them as if they had already occurred.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;List&amp;lt;ShoppingCartItem&amp;gt; shoppingCartItems = //get shopping cart items
var shoppingCartItemsToDisplay = CartActivityMonitor.AlterCollection(shoppingCartItems);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note: AlterCollection does not modify the underlying source collection, so you
need to use the IEnumerable returned from it, which in the example above would
be &lt;code&gt;shoppingCartItemsToDisplay&lt;/code&gt; instead of &lt;code&gt;shoppingCartItems&lt;/code&gt;.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Refactoring object comparison code in C#</title>
    <link rel="alternate" href="http://www.paceyourself.net/2010/09/20/refactoring-object-comparison-code-in-c/"/>
    <id>http://www.paceyourself.net/2010/09/20/refactoring-object-comparison-code-in-c/</id>
    <published>2010-09-20</published>
    <updated>2010-09-20</updated>
    <author>
      <name>Bob Pace</name>
    </author>
    <summary type="html">&lt;p&gt;I&amp;rsquo;ve come across many occasions where we have a giant statement that compares a
number of properties on two objects of the same type to determine whether to&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;I&amp;rsquo;ve come across many occasions where we have a giant statement that compares a
number of properties on two objects of the same type to determine whether to
perform some logic or other.&lt;/p&gt;

&lt;p&gt;You know, the kind of code like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if (object1.Property1 == object2.Property1 &amp;amp;&amp;amp;
        object1.Property2 == object2.Property2 &amp;amp;&amp;amp;
        object1.Property3 == object2.Property3)
{
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Whether its found in an overriden Equals method, an IComparer implementation, or
just exists in your code somewhere else (which it tends to) this code has the
potential to get pretty large once you are comparing a large number of
properties.&lt;/p&gt;

&lt;p&gt;The first place I usually start when attempting to refactor something is to try
to sort out what is different and what is the same. Then we can usually identify
a pattern to the similar parts and extract them out which leaves us with only
the truly different pieces left.&lt;/p&gt;

&lt;p&gt;Lets use the following class for our example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And update our example to make use of it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if (person1.FirstName == person2.FirstName &amp;amp;&amp;amp;
        person1.LastName == person2.LastName &amp;amp;&amp;amp;
        person1.DateOfBirth.Equals(person2.DateOfBirth))
{
    //logic of some kind
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we take inventory of what we are working with at the moment, we could break
it down like this:&lt;/p&gt;

&lt;p&gt;We have 3 &lt;em&gt;different&lt;/em&gt; properties&lt;/p&gt;

&lt;p&gt;We have 2 instances of the &lt;em&gt;same&lt;/em&gt; class&lt;/p&gt;

&lt;p&gt;We compare each of our properties on the 2 instances of the same class in the
&lt;em&gt;same&lt;/em&gt; way&lt;/p&gt;

&lt;p&gt;So if we list the differences only it would look like this:&lt;/p&gt;

&lt;p&gt;FirstName&lt;/p&gt;

&lt;p&gt;LastName&lt;/p&gt;

&lt;p&gt;DateOfBirth&lt;/p&gt;

&lt;p&gt;Now if we could represent that in code in as close to that form as possible that
would be a lot of noise taken out of our comparison code.&lt;/p&gt;

&lt;p&gt;Using a list of &lt;code&gt;Func&amp;lt;Person, object&amp;gt;&lt;/code&gt; we can do something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;x =&amp;gt; x.FirstName
x =&amp;gt; x.LastName
x =&amp;gt; x.DateOfBirth
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This lets us describe the properties, regardless of which of the two instances
they belong to.&lt;/p&gt;

&lt;p&gt;Now we can extract out the code to compare the values of each of the properties
we care about on the two different instances.&lt;/p&gt;

&lt;p&gt;We can use the All extension from System.Linq to make sure all of the comparisons share
similar comparison code. We would like whatever value comes off the first
instance to equal the value that comes off the second instance.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Person firstInstance = new Person();
Person secondInstance = new Person();

var comparisons = new List&amp;lt;Func&amp;lt;Person, object&amp;gt;&amp;gt;
{
    x =&amp;gt; x.FirstName,
    x =&amp;gt; x.LastName,
    x =&amp;gt; x.DateOfBirth,
}

var result = comparisons.All(x =&amp;gt; x(firstInstance) == x(secondInstance));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However the &lt;code&gt;==&lt;/code&gt; is not sufficient in all cases, as is the case with DateTime&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var firstDateTime = new DateTime(2010, 1, 1);
var secondDateTime = new DateTime(2010, 1, 1);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;firstDateTime == secondDateTime&lt;/code&gt; will be false&lt;/p&gt;

&lt;p&gt;&lt;code&gt;firstDateTime.Equals(secondDateTime)&lt;/code&gt; is true&lt;/p&gt;

&lt;p&gt;So we can change it to be this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var result = comparisons.All(x =&amp;gt; x(firstInstance).Equals(x(secondInstance)));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But then if FirstName is null on the first instance, it will throw a null
reference exception when attempting to call the &lt;code&gt;Equals&lt;/code&gt; method on it, so to
prevent that we can do this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;comparisons.All(x =&amp;gt;
    {
        var firstValue = x(instance);
        var secondValue = x(otherInstance);
        return firstValue == null &amp;amp;&amp;amp; secondValue == null ||
               firstValue != null &amp;amp;&amp;amp; secondValue != null &amp;amp;&amp;amp; firstValue.Equals(secondValue);
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That way if our comparison func returns null from both instances that will count
as true, if only one produces null it will be false, and if both produce non
null values we will use the Equals implementation to determine equality.&lt;/p&gt;

&lt;p&gt;Then we can put it behind a helper extension method for reuse:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static bool Compare&amp;lt;T&amp;gt;(this T instance, T otherInstance, params Func&amp;lt;T, object&amp;gt;[] equalityMembers) where T : class
{
    var comparisons = new List&amp;lt;Func&amp;lt;T, object&amp;gt;&amp;gt;(equalityMembers);
    return comparisons.All(x =&amp;gt;
        {
            var firstValue = x(instance);
            var secondValue = x(otherInstance);
            return firstValue == null &amp;amp;&amp;amp; secondValue == null ||
                   firstValue != null &amp;amp;&amp;amp; secondValue != null &amp;amp;&amp;amp; firstValue.Equals(secondValue);
        });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Edit 9/28/2010&lt;/strong&gt; As Ryan pointed out we can make it even better by using the
static object.Equals method for the comparison:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static bool Compare&amp;lt;T&amp;gt;(this T instance, T otherInstance, params Func&amp;lt;T, object&amp;gt;[] equalityMembers) where T : class
{
    var comparisons = new List&amp;lt;Func&amp;lt;T, object&amp;gt;&amp;gt;(equalityMembers);
    return comparisons.All(x =&amp;gt;
        {
            var firstValue = x(instance);
            var secondValue = x(otherInstance);
            return object.Equals(firstValue, secondValue);
        });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And now our original example can make use it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if (person1.Compare(person2,
            x =&amp;gt; x.FirstName,
            x =&amp;gt; x.LastName,
            x =&amp;gt; x.DateOfBirth))
{
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If our comparison needs grow to include more properties its easy to add a new
member to the list and I think it ends up being overall less code to write and
maintain.&lt;/p&gt;

&lt;p&gt;This could be extended further as needed, however the point of most value I
would like to reinforce is the refactoring technique used to enable us to
describe the differences in the shortest most concise way possible and let any
similarities take advantage of reusing the same code.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Breaking down C# Flags enums into individual values for comparison</title>
    <link rel="alternate" href="http://www.paceyourself.net/2010/09/13/breaking-down-c-flags-enums-into-individual-values-for-comparison/"/>
    <id>http://www.paceyourself.net/2010/09/13/breaking-down-c-flags-enums-into-individual-values-for-comparison/</id>
    <published>2010-09-13</published>
    <updated>2010-09-13</updated>
    <author>
      <name>Bob Pace</name>
    </author>
    <summary type="html">&lt;p&gt;In dealing with C# flags enums I have rarely needed to do anything too fancy to
get the job done, however I recently came across a scenario that required a bit&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;In dealing with C# flags enums I have rarely needed to do anything too fancy to
get the job done, however I recently came across a scenario that required a bit
of extra work to produce the desired result and so I thought I would share it
with everyone.&lt;/p&gt;

&lt;p&gt;Consider the following simple enum:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Flags]
public enum MyColor
{
    None = 0,
    Red = 1,
    Green = 2,
    Blue = 4,
    White = 8,
    Magenta = 16,
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now lets say you have an instance of this enum with any number of the flags
turned on.&lt;/p&gt;

&lt;p&gt;How would you ouput a list of the individual flags turned on?&lt;/p&gt;

&lt;p&gt;If you had two instances of this enum, each with a different set of flags turned
on, how would you compare the two and ouput a list of the differences?&lt;/p&gt;

&lt;p&gt;As an extra catch, lets say the enum has a few combined values and it looks like
this instead:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Flags]
public enum MyColor
{
    None = 0,
    Red = 1,
    RedAndGreen = Red | Green,
    Green = 2,
    Blue = 4,
    White = 8,
    WhiteAndGreen = White | Green,
    Magenta = 16,
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But for your comparisons you only care about pure values of the enum, and the
combined ones should be broken down into the pure values that make them up.&lt;/p&gt;

&lt;p&gt;When I first started thinking about how to solve this problem I threw together
some quick unit tests to poke around at a few ideas.&lt;/p&gt;

&lt;p&gt;I observed the following ToString() results from different instances of the MyColor enum:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;MyColor.RedAndGreen&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;RedAndGreen&lt;/p&gt;

&lt;p&gt;&lt;code&gt;MyColor.Blue&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Blue&lt;/p&gt;

&lt;p&gt;&lt;code&gt;MyColor.Red | MyColor.Green | MyColor.Blue&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;RedAndGreen, Blue&lt;/p&gt;

&lt;p&gt;&lt;code&gt;MyColor.Blue | MyColor.Green&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Green, Blue&lt;/p&gt;

&lt;p&gt;Which sent me down this path:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static IEnumerable&amp;lt;T&amp;gt; GetIndividualValues&amp;lt;T&amp;gt;(this Enum myEnum) where T : struct
{
    return myEnum
        .ToString()
        .Split(new[] { ',' })
        .Select(x =&amp;gt; (T)Enum.Parse(typeof(T), x.Trim()))
        .ToUniqueFlagEnumValues();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Relying on the ToString() emitting valid values of the enum, parsing them back
into values, and then I was left with the task of determining which values were
pure and which were combined. Which led to the following extension methods:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static bool IsPowerOfTwo(this int value)
{
    return (value &amp;amp; (value - 1)) == 0;
}

public static IEnumerable&amp;lt;T&amp;gt; ToUniqueFlagEnumValues&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; flagsEnumValues) where T : struct
{
    foreach (T item in flagsEnumValues)
    {
        int intValue = Convert.ToInt32(item);
        //if our int is a power of two, its a unique value of the flags enum
        if (intValue.IsPowerOfTwo())
        {
            yield return item;
        }
        //otherwise its a combination of several unique values and we need to break it down further
        else
        {
            //the enum value output as binary string representation
            string fullBinaryString = Convert.ToString(intValue, 2);
            //an empty template with all 0's that is the length of our binary string
            char[] individualBitTemplate = new string('0', fullBinaryString.Length).ToCharArray();

            IEnumerable&amp;lt;T&amp;gt; individualFlagsEnumValues = fullBinaryString
                .Select((character, index) =&amp;gt;
                    {
                        //project each individual bit into its own binary string with 0's in every position
                        //other than the index of the individual bit
                        //Example: binary string 1111
                        //produces 4 individual binary strings
                        //0001
                        //0010
                        //0100
                        //1000
                        char[] template = (char[])individualBitTemplate.Clone();
                        template[index] = character;
                        return new string(template);
                    })
                .Where(individualBitBinaryString =&amp;gt;
                    {
                        //filter the results to exclude any binary strings that are all 0's
                        return !individualBitBinaryString.All(character =&amp;gt; character == '0');
                    })
                .Select(individualBitBinaryString =&amp;gt;
                    {
                        //cast the individual binary strings back to their int value, and then into the enum value
                        int intValueOfIndividualBit = Convert.ToInt32(individualBitBinaryString, 2);
                        return (T)Enum.ToObject(typeof (T), intValueOfIndividualBit);
                    });

            foreach (T value in individualFlagsEnumValues)
            {
                yield return value;
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So if it was a pure value (aka if it was a power of 2) then I yield return the
item and move on. If it is not a pure value, then I use the following strategy to
break it down into the individual pure values that it contains.&lt;/p&gt;

&lt;p&gt;1) Convert the numeric value to a binary string&lt;/p&gt;

&lt;p&gt;2) Break the binary string down further into one binary string per bit turned
on.&lt;/p&gt;

&lt;p&gt;If our value is 1111
Then we produce the following 4 binary strings:
0001
0010
0100
1000&lt;/p&gt;

&lt;p&gt;3) Eliminate empty entries&lt;/p&gt;

&lt;p&gt;Since not every flag will be on in sequential order we will sometimes be left
with empty binary strings, so I filter them out.&lt;/p&gt;

&lt;p&gt;4) Cast the resulting binary strings back to a numeric value and then cast them
back into the enum.&lt;/p&gt;

&lt;p&gt;5) Yield return each of these results&lt;/p&gt;

&lt;p&gt;So now that we are able to ouput a list of unique values, we can accomplish the
task of comparing two instances and outputting the differences with the
following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class FlagsEnumDifference&amp;lt;T&amp;gt;
{
    private List&amp;lt;T&amp;gt; _added;
    private List&amp;lt;T&amp;gt; _removed;

    public FlagsEnumDifference(IEnumerable&amp;lt;T&amp;gt; added, IEnumerable&amp;lt;T&amp;gt; removed)
    {
        Added = new List&amp;lt;T&amp;gt;(added);
        Removed = new List&amp;lt;T&amp;gt;(removed);
    }

    public List&amp;lt;T&amp;gt; Added
    {
        get { return _added; }
        private set { _added = value; }
    }

    public List&amp;lt;T&amp;gt; Removed
    {
        get { return _removed; }
        private set { _removed = value; }
    }

    public override string ToString()
    {
        return string.Format("Added: {0} - Removed: {1}", Added.ToCommaSeperatedList(), Removed.ToCommaSeperatedList());
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With a few more extension methods to help it out:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static string ToCommaSeperatedList&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; enumerable)
{
    StringBuilder stringBuilder = new StringBuilder();
    foreach (T item in enumerable)
    {
        stringBuilder.Append(item).Append(',');
    }
    //trim the last , off
    if (stringBuilder.Length &amp;gt; 0)
    {
        stringBuilder.Remove(stringBuilder.Length - 1, 1);
    }
    return stringBuilder.ToString();
}

public static FlagsEnumDifference&amp;lt;T&amp;gt; GetDifference&amp;lt;T&amp;gt;(this Enum source, Enum compare) where T : struct
{
    IEnumerable&amp;lt;T&amp;gt; sourceValues = source.GetIndividualValues&amp;lt;T&amp;gt;();
    IEnumerable&amp;lt;T&amp;gt; compareValues = compare.GetIndividualValues&amp;lt;T&amp;gt;();

    IEnumerable&amp;lt;T&amp;gt; added = compareValues.Where(value =&amp;gt; !sourceValues.Contains(value));
    IEnumerable&amp;lt;T&amp;gt; removed = sourceValues.Where(value =&amp;gt; !compareValues.Contains(value));
    return new FlagsEnumDifference&amp;lt;T&amp;gt;(added, removed);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The usage can be seen here:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var color1 = MyColor.Green | MyColor.Blue;
var color2 = MyColor.Blue | MyColor.Red;
var color3 = MyColor.RedAndGreen | MyColor.Magenta;

var result1 = color1.GetDifference&amp;lt;MyColor&amp;gt;(color2);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;result1.ToString()&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Added: Red &amp;ndash; Removed: Green&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var result2 = color1.GetDifference&amp;lt;MyColor&amp;gt;(color3);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;result2.ToString()&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Added: Red,Magenta &amp;ndash; Removed: Blue&lt;/p&gt;

&lt;p&gt;While writing this blog post it occurred to me that I should probably have just
used an algorithm to break the numeric value of the enum down into unique powers
of two rather than rely on the ToString() implementation and working backwards
from there. However I still thought it would be useful to go over the thought
process behind this solution.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Adding collection binding support to FubuMVC Part 2</title>
    <link rel="alternate" href="http://www.paceyourself.net/2010/09/07/adding-collection-binding-support-to-fubumvc-part-2/"/>
    <id>http://www.paceyourself.net/2010/09/07/adding-collection-binding-support-to-fubumvc-part-2/</id>
    <published>2010-09-07</published>
    <updated>2010-09-07</updated>
    <author>
      <name>Bob Pace</name>
    </author>
    <summary type="html">&lt;p&gt;Continuing from the &lt;a href="/2010/08/30/adding-collection-binding-support-to-fubumvc-part-1/"&gt;last post&lt;/a&gt;, my next question was how exactly did&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;Continuing from the &lt;a href="/2010/08/30/adding-collection-binding-support-to-fubumvc-part-1/"&gt;last post&lt;/a&gt;, my next question was how exactly did
the current model binding implementation work in Fubu?&lt;/p&gt;

&lt;p&gt;The first place I looked was at the OneInOneOutActionInvoker which is the
IActionBehavior that represents a controller action that takes in one parameter
and returns one result.&lt;/p&gt;

&lt;p&gt;Inside the OneInOneOutActionInvoker, you can see the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private readonly IFubuRequest _request;
...

protected override DoNext performInvoke()
{
    var input = _request.Get&amp;lt;TInput&amp;gt;();
    TOutput output = _action(_controller, input);
    _request.Set(output);

    return DoNext.Continue;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which shows us that the FubuRequest is responsbile for providing the input parameter to the action.&lt;/p&gt;

&lt;p&gt;How does that work? If you look at the FubuRequest:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private readonly Cache&amp;lt;Type, BindResult&amp;gt; _values = new Cache&amp;lt;Type, BindResult&amp;gt;();

public FubuRequest(IRequestData data, IObjectResolver resolver)
{
    _values.OnMissing = (type =&amp;gt; resolver.BindModel(type, data));
}

public T Get&amp;lt;T&amp;gt;() where T : class
{
    return _values[typeof (T)].Value as T;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can see that the values are being provided via the OnMissing func which calls
the ObjectResolvers BindModel method.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public virtual BindResult BindModel(Type type, IBindingContext context)
{
    IModelBinder binder = _binders.BinderFor(type);
    try
    {
        return new BindResult()
        {
            Value = binder.Bind(type, context),
            Problems = context.Problems
        };
    }
    catch (Exception e)
    {
        throw new FubuException(2201, e, "Fatal error while binding model of type {0}.  See inner exception", type.AssemblyQualifiedName);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That &lt;code&gt;_binders&lt;/code&gt; is the IModelBinderCache which at the moment has only one
binder: the &lt;code&gt;StandardModelBinder&lt;/code&gt; in it.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;StandardModelBinder&lt;/code&gt; is the place where the actual instance of your model gets
instanciated, and then each property gets bound one by one by looking to the
IPropertyBinderCache to see which IPropertyBinder should step in to provide the
value, as can be seen here:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public object Bind(Type type, IBindingContext context)
{
    object instance = Activator.CreateInstance(type);
    Bind(type, instance, context);

    return instance;
}

public void Bind(Type type, object instance, IBindingContext context)
{
    context.StartObject(instance);
    populate(type, context);
    context.FinishObject();
}

private void populate(Type type, IBindingContext context)
{
    _typeCache.ForEachProperty(type, prop =&amp;gt;
    {
        IPropertyBinder binder = _propertyBinders.BinderFor(prop);
        binder.Bind(prop, context);
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So then the &lt;code&gt;PropertyBinderCache&lt;/code&gt; when asked to bind a certain property for the
first time will check its own OnMissing function to attempt to look through the
list of IPropertyBinders that have been supplied for one that matches the
current PropertyInfo for the property being bound.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private readonly IList&amp;lt;IPropertyBinder&amp;gt; _binders = new List&amp;lt;IPropertyBinder&amp;gt;();
private readonly Cache&amp;lt;PropertyInfo, IPropertyBinder&amp;gt; _cache = new Cache&amp;lt;PropertyInfo, IPropertyBinder&amp;gt;();

public PropertyBinderCache(IEnumerable&amp;lt;IPropertyBinder&amp;gt; binders, IValueConverterRegistry converters, ICollectionTypeProvider collectionTypeProvider)
{
    _binders.AddRange(binders);
    _binders.Add(new ConversionPropertyBinder(converters));
    _binders.Add(new NestedObjectPropertyBinder());

    _cache.OnMissing = prop =&amp;gt; _binders.FirstOrDefault(x =&amp;gt; x.Matches(prop));
}

public IPropertyBinder BinderFor(PropertyInfo property)
{
    return _cache[property];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Each IPropertyBinder provides a &lt;code&gt;Matches(PropertyInfo property)&lt;/code&gt; method to
determine if the property should be bound by it.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ConversionPropertyBinder&lt;/code&gt; matches by checking the ValueConverterRegistry for an
IConverterFamily that matches the PropertyInfo and if it finds one it uses it to
perform a custom conversion.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;NestedObjectPropertyBinder&lt;/code&gt; matches everything which is why it is listed last.
It serves as the fallback case when none of the other IPropertyBinders match
anything.&lt;/p&gt;

&lt;p&gt;It calls &lt;code&gt;context.BindChild&lt;/code&gt; inside its Bind method providing the propertys name
to be used as a prefix to the request data and then creating a new
BindingContext from that and attempts the process all over again using the
ObjectResolver which calls the StandardModelBinder and then passes back through
all the IPropertyBinders again.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public void BindChild(PropertyInfo property, Type childType, string prefix)
{
    var target = Object;
    if (_propertyStack.Any(p =&amp;gt; p.PropertyType == childType))
    {
        _propertyStack.Push(property);
        throw new FubuException(2202, "Infinite recursion detected while binding child properties: {0} would try to resolve {1} again.", string.Join("=&amp;gt;", _propertyStack.Reverse().Select(p =&amp;gt; "{1}.{0}".ToFormat(p.Name, p.ReflectedType.Name)).ToArray()), childType.Name);
    }
    _propertyStack.Push(property);

    var resolver = Service&amp;lt;IObjectResolver&amp;gt;();
    var context = prefixWith(prefix, _propertyStack.Reverse());

    try
    {
        var result = resolver.BindModel(childType, context);
        property.SetValue(target, result.Value, null);
    }
    catch (Exception e)
    {
        LogProblem(e);
    }

    _problems.AddRange(context._problems);

    _propertyStack.Pop();
}

private BindingContext prefixWith(string prefix, IEnumerable&amp;lt;PropertyInfo&amp;gt; properties)
{
    var prefixedData = new PrefixedRequestData(_requestData, prefix);
    var child = new BindingContext(prefixedData, _locator);
    properties.Each(p =&amp;gt; child._propertyStack.Push(p));
    return child;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;After seeing all of this I decided to try and fit in collection binding support
by providing a new type of IPropertyBinder, the CollectionPropertyBinder, and
put it in between the other two.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;_binders.Add(new ConversionPropertyBinder(converters));
_binders.Add(new CollectionPropertyBinder(collectionTypeProvider));
_binders.Add(new NestedObjectPropertyBinder());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And have it match anything that looks like a collection:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public bool Matches(PropertyInfo property)
{
    var type = property.PropertyType;
    return type.IsGenericType &amp;amp;&amp;amp;
           type.GetInterfaces().Any(x =&amp;gt; x.IsGenericType &amp;amp;&amp;amp; x.GetGenericTypeDefinition() == typeof(ICollection&amp;lt;&amp;gt;));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With the following Bind implementation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public void Bind(PropertyInfo property, IBindingContext context)
{
    var type = property.PropertyType;
    var itemType = type.GetGenericArguments()[0];
    if (type.IsInterface)
    {
        type = _collectionTypeProvider.GetCollectionType(type, itemType);
    }

    object collection = Activator.CreateInstance(type);
    var collectionType = collection.GetType();

    Func&amp;lt;object, bool&amp;gt; addToCollection = obj =&amp;gt;
        {
            if (obj != null)
            {
                var addMethod = _addMethods[collectionType];
                addMethod.Invoke(collection, new[] { obj });
                return true;
            }
            return false;
        };

    //TODO: work in the IElementNamingConvention somehow to ensure that it still can deserialze when others provide
    //a different implementation

    var formatString = property.Name + "[{0}]";

    int index = 0;
    string prefix;
    do
    {
        prefix = formatString.ToFormat(index);
        index++;
    } while (addToCollection(context.BindCollectionItem(prefix, itemType)));

    property.SetValue(context.Object, collection, null);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If the PropertyInfo type is an interface we need to pick a concrete type to back
it. I put this behind an ICollectionTypeProvider interface along with a
DefaultCollectionProvider to hand out List&amp;lt;&gt; for everything, but with the intent
that someone can swap in their own if necessary.&lt;/p&gt;

&lt;p&gt;Based on the concrete type chosen, we need to invoke its Add method which is
backed by a cache to match each unique collection type to its Add MethodInfo.&lt;/p&gt;

&lt;p&gt;We then greedily try to grab as many collection items as we can by calling into
&lt;code&gt;context.BindCollectionItem&lt;/code&gt; which I made following the example provided by the
NestedObjectPropertyBinder and its usage of &lt;code&gt;context.BindChild&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public object BindCollectionItem(string prefix, Type childType)
{
    var resolver = Service&amp;lt;IObjectResolver&amp;gt;();
    var context = prefixWith(prefix, _propertyStack.Reverse());

    //need to determine if the item is in there or not since we will be greedy
    //and try to get as many items for our list as possible
    if (_requestData.HasValueThatStartsWith(prefix))
    {
        var bindResult = resolver.BindModel(childType, context);
        return bindResult.Value;
    }
    return null;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So it also ties back into the existing model binding capabilities and correctly
binds anything further along after the collection items are resolved.&lt;/p&gt;

&lt;p&gt;Since I had no idea how many collection items would be there ahead of time I had
to extend the RequestData to able to check for values that start with a value
rather than knowing exactly what the value was.&lt;/p&gt;

&lt;p&gt;The RequestData uses the AggregateDictionary to provide its values, which in
turn relies on a set of Locators to check various places for values. I extended
the Locator with an additional StartsWithChecker to determine if it had a value
that started with a given key.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Locator
{
    public RequestDataSource Source { get; set; }
    public Func&amp;lt;string, object&amp;gt; Getter { get; set; }
    public Func&amp;lt;string, bool&amp;gt; StartsWithChecker { get; set; }

    public bool Locate(string key, Action&amp;lt;RequestDataSource, object&amp;gt; callback)
    {
        object value = Getter(key);
        if (value != null)
        {
            callback(Source, value);
            return true;
        }

        return false;
    }

    public bool StartsWith(string key)
    {
        return StartsWithChecker != null &amp;amp;&amp;amp; StartsWithChecker(key);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Added an overload:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public AggregateDictionary AddLocator(RequestDataSource source, Func&amp;lt;string, object&amp;gt; locator, Func&amp;lt;string, bool&amp;gt; startsWith)
{
    _locators.Add(new Locator
                  {
                      Getter = locator,
                      StartsWithChecker = startsWith,
                      Source = source
                  });

    return this;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And then changed out the configuration inside the AggregateDictionary for the
Locator that represents the request to include the StartsWithChecker so I can
greedibly grab for things until I determine that no more are available.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private void configureForRequest(HttpContextBase @base)
{
    HttpRequestBase request = @base.Request;

    AddLocator(RequestDataSource.Request,
               key =&amp;gt; request[key],
               key =&amp;gt; request.Form.AllKeys.Any(x =&amp;gt; x.StartsWith(key)));
    AddLocator(RequestDataSource.File, key =&amp;gt; request.Files[key]);
    AddLocator(RequestDataSource.Header, key =&amp;gt; request.Headers[key]);
    AddLocator(RequestDataSource.RequestProperty, key =&amp;gt; GetRequestProperty(request, key));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There are a few holes in the implementation still, the biggest being properly
considering the IElementNamingConvention when checking for form values to try
and bind from within the CollectionPropertyBinders Bind method.&lt;/p&gt;

&lt;p&gt;I think what needs to happen is to reassamble an Accesor out of the current
properety info and prefixs we know about and then run it through the
IElementNamingConvention to produce the prefix name to check with rather than
assuming it will always be the property.Name + &amp;ldquo;[{0}]&amp;rdquo;. I will attempt to come
up with something to test this idea out.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Adding collection binding support to FubuMVC Part 1</title>
    <link rel="alternate" href="http://www.paceyourself.net/2010/08/30/adding-collection-binding-support-to-fubumvc-part-1/"/>
    <id>http://www.paceyourself.net/2010/08/30/adding-collection-binding-support-to-fubumvc-part-1/</id>
    <published>2010-08-30</published>
    <updated>2010-08-30</updated>
    <author>
      <name>Bob Pace</name>
    </author>
    <summary type="html">&lt;p&gt;We have been considering the idea of using FubuMVC for an internally hosted site
to hold a suite of tools available to administrators. One feature we knew for&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;We have been considering the idea of using FubuMVC for an internally hosted site
to hold a suite of tools available to administrators. One feature we knew for
certain we would need that Fubu did not yet support was the ability to model
bind collections since we were already using that feature heavily in ASP.NET
MVC. So with this in mind I set out to try and come up with an implemenation
that not only met our needs but that could possibly be contributed back and be
useful to others as well.&lt;/p&gt;

&lt;p&gt;This serves a dual purpose as part of my goal to get a new blog post out weekly
and also to potentially prove useful as documentation to anyone who is curious
about what changes were made and the thought process behind them.&lt;/p&gt;

&lt;p&gt;To give a little bit of background, we had already started using Fubu Html
Conventions in our ASP.NET MVC project using &lt;a href="http://github.com/ryanohs/Fubu-HtmlTags-For-ASP.NET-MVC"&gt;ryanohs&lt;/a&gt; approach from
his Fubu-HtmlTags-For-ASP.NET.MVC Git hub project.&lt;/p&gt;

&lt;p&gt;We had also swapped out the default IElementNamingConvention:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class DefaultElementNamingConvention : IElementNamingConvention
{
    public string GetName(Type modelType, Accessor accessor)
    {
        return accessor.Name;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With this one to produce a more familiar naming convention for what we were
using to dealing with in ASP.NET MVC:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class PropertyNamesElementNamingConvention : IElementNamingConvention
{
    public string GetName(Type modelType, Accessor accessor)
    {
        return accessor.PropertyNames.Join(".");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;My goal starting out was just to get the existing ASP.NET MVC collection model
binding to work with the Fubu Html Conventions Input/Label/Display for stuff.&lt;/p&gt;

&lt;p&gt;I wanted to be able to do something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Html.InputFor(x =&amp;gt; x.CollectionOfSomeKind[0].PropertyName)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So I started digging into what happens inside the InputFor call.&lt;/p&gt;

&lt;p&gt;The TagGenerator takes an Expression you provide it&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public HtmlTag InputFor(Expression&amp;lt;Func&amp;lt;T, object&amp;gt;&amp;gt; expression)
{
    return buildTag(expression, _profile.Editor);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Builds an ElementRequest from it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private HtmlTag buildTag(Expression&amp;lt;Func&amp;lt;T, object&amp;gt;&amp;gt; expression, TagFactory factory)
{
    ElementRequest request = GetRequest(expression);

    return factory.Build(request);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;By first turning it into an Accessor:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public ElementRequest GetRequest(Expression&amp;lt;Func&amp;lt;T, object&amp;gt;&amp;gt; expression)
{
    Accessor accessor = expression.ToAccessor();
    return GetRequest(accessor);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And invoking the IElementNamingConvention implementation to provide the
ElementId:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public ElementRequest GetRequest(Accessor accessor)
{
    var request = new ElementRequest(_model, accessor, _services, _stringifier);
    determineElementName(request);
    return request;
}

private void determineElementName(ElementRequest request)
{
    // TODO -- this is a klooge because of the tag wrapping around partials
    if (request.Accessor == null) return;

    var prefix = ElementPrefix ?? string.Empty;
    request.ElementId = prefix + _namingConvention.GetName(typeof(T), request.Accessor);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And then over in DefaultHtmlConventions you&amp;rsquo;ll find this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Editors.Always.Modify(AddElementName);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And the AddElementName implementation here:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void AddElementName(ElementRequest request, HtmlTag tag)
{
    if (tag.IsInputElement())
    {
        tag.Attr("name", request.ElementId);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So we can see how the ElementId ends up on the input that gets generated.&lt;/p&gt;

&lt;p&gt;Which left me with a few questions to explore. What is that Accessor? How is it
created? It seems there are two kinds of them, a PropertyChain and a
SingleProperty. What was the difference?&lt;/p&gt;

&lt;p&gt;So continuing onward into the creation of that Accessor inside the
ReflectionHelper class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static Accessor ToAccessor&amp;lt;T&amp;gt;(this Expression&amp;lt;Func&amp;lt;T, object&amp;gt;&amp;gt; expression)
{
    return ReflectionHelper.GetAccessor(expression);
}

public static Accessor GetAccessor&amp;lt;TModel&amp;gt;(Expression&amp;lt;Func&amp;lt;TModel, object&amp;gt;&amp;gt; expression)
{
    MemberExpression memberExpression = getMemberExpression(expression);

    return GetAccessor(memberExpression);
}

public static Accessor GetAccessor(MemberExpression memberExpression)
{
    var list = new List&amp;lt;PropertyInfo&amp;gt;();

    while (memberExpression != null)
    {
        list.Add((PropertyInfo) memberExpression.Member);
        memberExpression = memberExpression.Expression as MemberExpression;
    }

    if (list.Count == 1)
    {
        return new SingleProperty(list[0]);
    }

    list.Reverse();
    return new PropertyChain(list.ToArray());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This was where I could see that the expression was being turned into an
Accessor, either one SingleProperty or a PropertyChain of many SingleProperties.&lt;/p&gt;

&lt;p&gt;This is the first place I found where I thought I might actually change
something to move a step in the direction I wanted to take.&lt;/p&gt;

&lt;p&gt;I knew I could get the collection binding to work if I could just get the names
on the form inputs to align with the current expectation of how to bind a
collection. So I tried something like this on my page:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;%= Html.InputFor(x =&amp;gt; x.Collection[0].PropertyName) %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And then proceeded to debug through the GetAccessor implementation to see what I
was working with and how I might go about changing it.&lt;/p&gt;

&lt;p&gt;When it got to the &lt;code&gt;[0]&lt;/code&gt; part of the expression the line&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;memberExpression = memberExpression.Expression as MemberExpression;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;evaluated to null and it was unable to proceed. But I could see
&lt;code&gt;memberExpression.Expression&lt;/code&gt; was actually a MethodCallExpression represeting
the get call on the collection with the index to get as the method call
expressions first argument. This looked like it would work out for me so I
decided to go with it.&lt;/p&gt;

&lt;p&gt;My next step was to extend the PropertyChain to be able to handle more than just
PropertyInfo. I made the following interface:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IValueGetter
{
    object GetValue(object target);
    string Name { get; }
    Type DeclaringType { get; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And then made two implementations. PropertyValueGetter to represent the
PropertyInfo that was there before:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class PropertyValueGetter : IValueGetter
{
    private readonly PropertyInfo _propertyInfo;

    public PropertyValueGetter(PropertyInfo propertyInfo)
    {
        _propertyInfo = propertyInfo;
    }

    public PropertyInfo PropertyInfo { get { return _propertyInfo; } }

    public object GetValue(object target)
    {
        return _propertyInfo.GetValue(target, null);
    }

    public string Name
    {
        get { return _propertyInfo.Name; }
    }

    public Type DeclaringType
    {
        get { return _propertyInfo.DeclaringType; }
    }

    public bool Equals(PropertyValueGetter other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;

        return _propertyInfo.Equals(other._propertyInfo);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != typeof(PropertyValueGetter)) return false;
        return Equals((PropertyValueGetter)obj);
    }

    public override int GetHashCode()
    {
        return (_propertyInfo != null ? _propertyInfo.GetHashCode() : 0);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And MethodValueGetter to represent the MethodCallExpressions that would be the collection indexers:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class MethodValueGetter : IValueGetter
{
    private readonly MethodInfo _methodInfo;
    private readonly object _firstArgument;

    public MethodValueGetter(MethodInfo methodInfo, object firstArgument)
    {
        _methodInfo = methodInfo;
        _firstArgument = firstArgument;
    }

    public object GetValue(object target)
    {
        return _methodInfo.Invoke(target, new[] { _firstArgument });
    }

    public string Name
    {
        get { return "[{0}]".ToFormat(_firstArgument); }
    }

    public Type DeclaringType
    {
        get { return _methodInfo.DeclaringType; }
    }

    public bool Equals(MethodValueGetter other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;

        return _methodInfo.Equals(other._methodInfo) &amp;amp;&amp;amp; _firstArgument == other._firstArgument;
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != typeof(MethodValueGetter)) return false;
        return Equals((MethodValueGetter)obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return ((_methodInfo != null ? _methodInfo.GetHashCode() : 0) * 397) ^ (_firstArgument != null ? _firstArgument.GetHashCode() : 0);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I then changed out the &lt;code&gt;_chain&lt;/code&gt; field inside the PropertyChain class to hold an
array of these &lt;code&gt;IValueGetter&lt;/code&gt; types so we could have a mixture of properties and
collection indexers instead of just PropertyInfos.&lt;/p&gt;

&lt;p&gt;Then I altered the ReflectionHelpers GetAccessor implementation to treat
MethodCallExpressions as those MethodValueGetters and the regular
MemberExpressions as PropertyValueGetters.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static Accessor GetAccessor(MemberExpression memberExpression)
{
    var list = new List&amp;lt;IValueGetter&amp;gt;();

    BuildValueGetters(memberExpression, list);

    if (list.Count == 1)
    {
        var propertyValueGetter = list[0] as PropertyValueGetter;
        return propertyValueGetter != null ? new SingleProperty(propertyValueGetter.PropertyInfo) : null;
    }

    list.Reverse();
    return new PropertyChain(list.ToArray());
}

private static void BuildValueGetters(Expression expression, IList&amp;lt;IValueGetter&amp;gt; list)
{
    var memberExpression = expression as MemberExpression;
    if (memberExpression != null)
    {
        var propertyInfo = (PropertyInfo)memberExpression.Member;
        list.Add(new PropertyValueGetter(propertyInfo));
        if (memberExpression.Expression != null)
        {
            BuildValueGetters(memberExpression.Expression, list);
        }
    }

    //deals with collection indexers, list[0] will be get(0) method call expression 
    var methodCallExpression = expression as MethodCallExpression;
    if (methodCallExpression != null)
    {
        var methodInfo = methodCallExpression.Method;
        //only supporting constant expression as means of providing index
        var firstArgumentExpression = methodCallExpression.Arguments.First() as ConstantExpression;
        if (firstArgumentExpression != null)
        {
            var value = firstArgumentExpression.Value;
            var methodValueGetter = new MethodValueGetter(methodInfo, value);
            list.Add(methodValueGetter);
        }
        if (methodCallExpression.Object != null)
        {
            BuildValueGetters(methodCallExpression.Object, list);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So after all this, I went to try it out to see how things were working and I
could see one definite problem. Since my IElementNamingConvention that I was
using joined the PropertyNames together with a . like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;return accessor.PropertyNames.Join(".");
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It was resulting in the following output:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CollectionOfSomeKind.[0].PropertyName
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Not exactly what I needed with that extra . in there, but close. So to prevent
that from happening I threw in a collapse properties method on the PropertyChain
to identify places where indexers had been put and collapse them back into the
previous entry. This piece I am iffy on and would like to see something better
as it will definitely not play nice when it comes time to work in other
IElementNamingConvention implementations.&lt;/p&gt;

&lt;p&gt;Here are the changes:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public string[] PropertyNames
{
    get
    {
        return collapseCollectionIndexes(_valueGetters.Select(x =&amp;gt; x.Name).ToList()).ToArray();
    }
}

private static IEnumerable&amp;lt;string&amp;gt; collapseCollectionIndexes(IList&amp;lt;string&amp;gt; strings)
{
    //Find any occurrences of indexer and collapse them back into previous entry
    var list = new List&amp;lt;string&amp;gt;(strings);
    Func&amp;lt;string, bool&amp;gt; matches = x =&amp;gt; x.StartsWith("[") &amp;amp;&amp;amp; x.EndsWith("]");
    for (int i = 0; i &amp;lt; strings.Count(); i++)
    {
        var currentString = strings[i];
        if (matches(currentString))
        {
            var previousIndex = i - 1;
            //attempt to combine this with previous entry
            if (previousIndex &amp;gt; -1)
            {
                list[previousIndex] += currentString;
                list.RemoveAt(i);
            }
        }
    }
    return list;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I wonder if we need to put another member on the IElementNamingConvention
interface that allows someone to specify custom behavior to help the
PropertyChain produce its PropertyNames, and then this piece could go into the
custom IElementNamingConvetion that we are using instead of being direcly on the
PropertyChain like it is now.&lt;/p&gt;

&lt;p&gt;This was all for the first part of the collection binding implementation, I will
follow up with details on the second half to the implementation in the next blog
post.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Using Sass via Compass in ASP.NET MVC</title>
    <link rel="alternate" href="http://www.paceyourself.net/2010/08/23/using-sass-via-compass-in-aspnet-mvc/"/>
    <id>http://www.paceyourself.net/2010/08/23/using-sass-via-compass-in-aspnet-mvc/</id>
    <published>2010-08-23</published>
    <updated>2010-08-23</updated>
    <author>
      <name>Bob Pace</name>
    </author>
    <summary type="html">&lt;p&gt;&lt;a href="http://sass-lang.com/"&gt;Sass&lt;/a&gt; brings some much desired functionality to CSS. We recently adopted
it into an ASP.NET MVC project that I am working on and I would like to share&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;&lt;a href="http://sass-lang.com/"&gt;Sass&lt;/a&gt; brings some much desired functionality to CSS. We recently adopted
it into an ASP.NET MVC project that I am working on and I would like to share
some of that experience with anyone that may be interested.&lt;/p&gt;

&lt;p&gt;If you are unfamiliar with some of the reasons why you might want to use Sass, I
would recommend reading up on their website and see for yourself. The focus of
this post will be to go over what it takes to get it and work with it in a
windows environment for an ASP.NET MVC project.&lt;/p&gt;

&lt;p&gt;How to get started?&lt;/p&gt;

&lt;p&gt;1) Get &lt;a href="http://ruby-lang.org/en"&gt;Ruby&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you want to use Sass then you need to get some form of Ruby up and running on
your computer. Maybe that&amp;rsquo;s out of your comfort zone, maybe not, but rest
assured that you don&amp;rsquo;t need to know too much about Ruby in order to make use of
Sass.&lt;/p&gt;

&lt;p&gt;If you are already familiar with how to do this, feel free to skip on to the
next section.&lt;/p&gt;

&lt;p&gt;Start by grabbing the latest &lt;a href="http://rubyforge.org/frs/?group_id=167"&gt;installer&lt;/a&gt; that is available and
run it with the &amp;lsquo;add Ruby executables to your Path&amp;rsquo; option checked.&lt;/p&gt;

&lt;p&gt;Open up a command prompt and type &lt;code&gt;ruby -v&lt;/code&gt; and you should see something like
this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ruby 1.9.1p430 (2010-08-16 revision 28998) [i386-mingw32]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Nice and easy. Congratulations you have Ruby.&lt;/p&gt;

&lt;p&gt;You can even use the .NET port of Ruby called &lt;a href="http://ironruby.net"&gt;Iron Ruby&lt;/a&gt; for this if
you like, which is what we started out with but we soon encountered unacceptably
slow compile times once we had written a fair number of sass files that shared a
common base partial. Any change to that partial sass file would take a long time
to recompile all the sass files that depended on it. In frustration we switched
over to regular Ruby 1.9 and our performance issues went away and we were once
again happy with the speedy compile times. For this reason I recommend using
Ruby and not Iron Ruby.&lt;/p&gt;

&lt;p&gt;2) Get &lt;a href="http://compass-style.org/"&gt;Compass&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Compass is our choice for how to get sass compiled into css in a windows
environment, as mentioned in this stack overflow &lt;a href="http://stackoverflow.com/questions/796788/using-sass-with-asp-net"&gt;post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I would recommend taking the time to watch the tutorial videos available on
their site and read up more on everything else that Compass can do for you as
well, but for now I&amp;rsquo;m just going to focus on a few things you can do from the
command line to get started.&lt;/p&gt;

&lt;p&gt;Installation is easy, just open a command prompt and type &lt;code&gt;gem install compass&lt;/code&gt;
and let it download and install.&lt;/p&gt;

&lt;p&gt;Next you should open a command prompt in your ASP.NET MVC project folder and use
&lt;code&gt;compass create&lt;/code&gt; to generate a few things for you.&lt;/p&gt;

&lt;p&gt;Your project structure likely does not follow the defaults that compass will
provide for you, so you will need to inform it about a few important folder
locations such as where to look for sass files, where to put the generated css
and where your images and javascript folders are located. You can freely edit
the &lt;code&gt;config.rb&lt;/code&gt; file that will be created to change any of this after the fact
but if you want to get it all set up in one shot they have various options
available that you can pass to the &lt;code&gt;compass create&lt;/code&gt; command when you run it such
as &lt;code&gt;--sass-dir&lt;/code&gt; and &lt;code&gt;--css-dir&lt;/code&gt;.  You can type &lt;code&gt;compass create -h&lt;/code&gt; to view the
complete set of options available. Feel free to use any combination of this you
are comfortable with to get things set up for your particular project.&lt;/p&gt;

&lt;p&gt;3) Start writing Sass&lt;/p&gt;

&lt;p&gt;We are using the newer SCSS syntax that Sass provides so be aware that anytime I
say sass the actual file extension will be &lt;code&gt;.scss&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If you create a new .scss file in your sass folder, write a little bit of sass
and then use &lt;code&gt;compass compile&lt;/code&gt; from the command line you will likely see
something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Encoding::CompatibilityError on line ["786"] of c: incompatible encoding regexp
match (UTF-8 regexp with IBM437 string)
Run with --trace to see the full backtrace
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Text files created via Visual Studio are given a Unicode (UTF-8 with signature)
encoding, but if we look at the sample .scss files that are generated when you
do a regular &lt;code&gt;compass create&lt;/code&gt; their encoding is all Western European (Windows).
If you change the encoding on your file you will be able to use &lt;code&gt;compass
compile&lt;/code&gt; and see it work properly.&lt;/p&gt;

&lt;p&gt;You can change the encoding for your files in Visual Studio by opening the file
in question and then going to File &amp;ndash; Advanced Save Options and pick a different
encoding from the drop down menu.&lt;/p&gt;

&lt;p&gt;During development time you should make use of the &lt;code&gt;compass -w&lt;/code&gt; feature from the
command prompt as it will monitor your sass files for changes and when it
detects that something has changed it will automatically compile them to css for
you without you having to manually run the &lt;code&gt;compass compile&lt;/code&gt; command. This is
pretty nice as you can tweak your sass and just refresh the browser to see the
effects immediately.&lt;/p&gt;

&lt;p&gt;You can also automate the sass compliation by including a step in your project
file to run &lt;code&gt;compass compile&lt;/code&gt; for you when you build. We use this approach to
handle sass compilation for our release builds.&lt;/p&gt;

&lt;p&gt;To do this you need to unload your project, right click to edit the project file
and then you can add something like this to the end of it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;Target Name="AfterCompile" Condition=" '$(Configuration)' == 'Release' "&amp;gt;
    &amp;lt;Exec Command="compass compile" /&amp;gt;
    &amp;lt;ItemGroup&amp;gt;
        &amp;lt;Content Include="Styles\*.css" /&amp;gt;
    &amp;lt;/ItemGroup&amp;gt;
&amp;lt;/Target&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Where &lt;strong&gt;Styles&lt;/strong&gt; would be the folder location that you told compass where to put
your css files in after it compiles.&lt;/p&gt;

&lt;p&gt;One problem you may run into if you use some kind of versioning system with your
code is that merging files may change the encoding for you and insert a byte
order mark into the beginning of your file. We encountered this with &lt;a href="http://en.wikipedia.org/wiki/Team_Foundation_Server"&gt;TFS&lt;/a&gt;
when merging our sass files on check in. This prevents compass from being able
to compile your files properly but luckily its not too difficult to get around
with a fix.&lt;/p&gt;

&lt;p&gt;The necessary steps are to remove the byte order mark and then prevent it from
being inserted again by putting a place holder there.&lt;/p&gt;

&lt;p&gt;Thanks and credit belong to &lt;a href="http://jxs.me"&gt;Jason Staten&lt;/a&gt; for identifying the
problem and coming up with this nice solution:&lt;/p&gt;

&lt;p&gt;Get Rake if you don&amp;rsquo;t have it already with &lt;code&gt;gem install rake&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Create a Rakefile in your project folder, it can be named rakefile.rb or just
rakefile with no extension if you prefer.&lt;/p&gt;

&lt;p&gt;Put the following code into it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;task :bomfix do
    puts "Begin Bomfix"
    files = Dir["Scss/*.scss"]
    files.each do |file|
        if !File.writable?(file)
            puts "Please checkout #{file} for edit"
            next
        end
        puts "Fixing #{file}"
        content = IO.read(file)
        content.gsub!("\xEF\xBB\xBF", '')
        File.open(file, 'w') do |f|
            f.write("//Do Not Remove This Comment -- BOM Safety\n") unless (content =~ /Do Not Remove This Comment/)
            f.write(content)
        end
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Make sure you change the directory from the line &lt;code&gt;files = Dir["Scss/*.scss"]&lt;/code&gt; to
point where your actual sass files are located and then you can just type &lt;code&gt;rake
bomfix&lt;/code&gt; to correct your files.&lt;/p&gt;

&lt;p&gt;Another step you can take to speed up your sass compile times is make use of the
sass-cache by adding this to your config.rb, you can read documentation on this
&lt;a href="http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#options"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sass_options = { :cache_location =&amp;gt; ".\\tmp\\sass-cache" }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you want the cached files to go elsewhere feel free to change the folder
location. Also note that you will need to create these folders before they will
be used. You can verify they are working by running &lt;code&gt;compass compile&lt;/code&gt; and then
go look in the sass-cache directory and you should see a bunch of new folders
with GUIDS for names.&lt;/p&gt;

&lt;p&gt;Well that&amp;rsquo;s it for now. I hope this helps give you ideas on how to integrate
sass into a web project hosted in a windows environment.&lt;/p&gt;
</content>
  </entry>
</feed>

