<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0"><channel><title>digitalBush</title> <link>http://digitalbush.com</link> <description>Tales of a Tormented Software Developer</description> <lastBuildDate>Tue, 06 Mar 2012 02:59:48 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.2.1</generator> <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/digitalbush" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="digitalbush" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">digitalbush</feedburner:emailServiceId><feedburner:feedburnerHostname xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://feedburner.google.com</feedburner:feedburnerHostname><item><title>Mass Assignment Vulnerability in ASP.NET MVC</title><link>http://digitalbush.com/2012/03/05/mass-assignment-aspnet-mvc/</link> <comments>http://digitalbush.com/2012/03/05/mass-assignment-aspnet-mvc/#comments</comments> <pubDate>Tue, 06 Mar 2012 02:54:23 +0000</pubDate> <dc:creator>josh</dc:creator> <category><![CDATA[development]]></category> <category><![CDATA[c#]]></category> <category><![CDATA[mass assignment]]></category> <category><![CDATA[mvc]]></category> <category><![CDATA[security]]></category><guid isPermaLink="false">http://digitalbush.com/?p=1174</guid> <description><![CDATA[By now you may have seen what happened to github last night. In case you didn't, let me bring you up to speed. In a Ruby on Rails application, you can make a call to update your model directly from request parameters. Once you've loaded an ActiveRecord model into memory, you can poke its values [...]]]></description> <content:encoded><![CDATA[<p>By now you may have <a
href="https://github.com/blog/1068-public-key-security-vulnerability-and-mitigation">seen what happened to github</a> last night. In case you didn't, let me bring you up to speed.</p><p>In a Ruby on Rails application, you can make a call to update your model directly from request parameters. Once you've loaded an ActiveRecord model into memory, you can poke its values by calling <code>update_attributes</code> and passing in the request parameters. This is bad because sometimes your model might have properties which you don't want to be updated by just anyone. In a rails application, you can protect this by adding <code>attr_accessible</code> to your model and explicitly stating which properties can be updated via mass assignment.</p><p>I'm not going to pretend to be a Ruby dev and try to explain this with a Rails example. Github already linked to this fantastic post on the subject regarding Rails <a
href="http://blog.mhartl.com/2008/09/21/mass-assignment-in-rails-applications/">here</a>. What I'm here to tell you is that this situation exists in ASP.NET MVC also. If you aren't careful, you too could end up with a visit from <a
href="https://github.com/rails/rails/issues/5239">Bender in the future</a>.</p><p>So, let's see this vulnerability in action on an ASP.NET MVC project.</p><p>First, let's set up a model:</p><pre class='prettyprint'><code>public class User {
    public int Id { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool IsAdmin { get; set; }
}</code></pre><p>Then let's scaffold out a controller to edit this user:</p><pre class='prettyprint'><code>public class UserController : Controller {
    IUserRepository _userRepository;
    public UserController(IUserRepository userRepository) {
        _userRepository = userRepository;
    }

    public ActionResult Edit(int id) {
        var user = _userRepository.GetUserById(id);
        return View(user);
    }

    [HttpPost]
    public ActionResult Edit(int id, FormCollection collection) {
        try {
            var user = _userRepository.GetUserById(id);
            UpdateModel(user);
            _userRepository.SaveUser(user);
            return RedirectToAction("Index");
        } catch {
            return View();
        }
    }
}</code></pre><p>Do you see that <code>UpdateModel</code> call in the POST to '/User/Edit'. Pay attention to that. It looks innocent enough, but we'll see in a minute why that is bad.</p><p>Next, we scaffold up a view and remove the checkbox that allows us to update the user's Admin status. Once we're done, it looks like this:<br
/> <img
src="http://digitalbush.com/wp-content/uploads/2012/03/Screen-shot-2012-03-04-at-11.26.43-PM.png" alt="" title="Screen shot 2012-03-04 at 11.26.43 PM" width="549" height="325" class="alignnone size-full wp-image-199" /></p><p>That works. We can ship it, right? Nope. Look what happens when we doctor up the URL by adding a query parameter:<br
/> <img
src="http://digitalbush.com/wp-content/uploads/2012/03/Screen-shot-2012-03-04-at-11.26.55-PM.png" alt="" title="Screen shot 2012-03-04 at 11.26.55 PM" width="549" height="324" class="alignnone size-full wp-image-198" /></p><p>I bet you guess what's about to happen now. Here, I'll break execution right at the problematic line so you can watch the carnage:<br
/> <img
src="http://digitalbush.com/wp-content/uploads/2012/03/Screen-shot-2012-03-04-at-11.27.23-PM.png" alt="" title="Screen shot 2012-03-04 at 11.27.23 PM" width="650" height="189" class="alignnone size-full wp-image-197" /></p><p>Okay, you can see the current values to the right. We've loaded user #42 from the database and we're about to update all of his values based on the incoming request. Step to the next line and we see this:<br
/> <img
src="http://digitalbush.com/wp-content/uploads/2012/03/Screen-shot-2012-03-04-at-11.27.32-PM.png" alt="" title="Screen shot 2012-03-04 at 11.27.32 PM" width="649" height="182" class="alignnone size-full wp-image-196" /></p><p><strong>UH OH.</strong> That's not good at all. User #42 is now an administrator. All it takes is an industrious user guessing the names of properties on your entities for you to get burned here.</p><p><strong>So, what can we do to prevent it?</strong> One way would be to change the way we call <code>UpdateModel</code>.  You can use the overload which allows you to pass in an array of properties you want to include. That looks like this:</p><pre class='prettyprint'><code>UpdateModel(user,new[]{"FirstName","LastName","Email"});</code></pre><p>We've just created a whitelist of properties we will allow to be updated. That works, but it's ugly and would become unmanageable for a large entity. Aesthetics aside, using this method isn't secure by default. The developer has to actively do something here to be safe. It should be the other way around, it should be hard to fail and easy to succeed. <a
href="http://www.codinghorror.com/blog/2007/08/falling-into-the-pit-of-success.html">The Pit of Success</a> is what we want.</p><p><strong>So, what can we <em>really</em> do to prevent it?</strong> The approach I typically take is to model bind to an object with only the properties I'm willing to accept. After I've validated that the input is well formed, I use <a
href="http://automapper.org/">AutoMapper</a> to apply that to my entities. There are other ways to achieve what we want too, but I don't have time to enumerate all of the scenarios.</p><p><strong>Wrapping up</strong><br
/> The point of all of this is that you need to understand exactly what your framework is doing for you. Just because there is a gun available, it doesn't mean you have to shoot it. Remember folks, frameworks don't kill people; developers with frameworks kill people. Stay safe out there friends, it's a crazy world.</p><p><em>Cross posted from <a
href="http://freshbrewedcode.com/joshbush/2012/03/05/mass-assignment-aspnet-mvc/">Fresh Brewed Code</a>. If you haven't taken a look over there, please take a moment to see what we've been up to.</em></p> <div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/digitalbush?a=55Wv_-mq6X4:t2WXNDAQ_-E:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/digitalbush?i=55Wv_-mq6X4:t2WXNDAQ_-E:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/digitalbush?a=55Wv_-mq6X4:t2WXNDAQ_-E:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/digitalbush?d=yIl2AUoC8zA" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://digitalbush.com/2012/03/05/mass-assignment-aspnet-mvc/feed/</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>Getting Started with Box2D Physics</title><link>http://digitalbush.com/2012/02/29/box2d/</link> <comments>http://digitalbush.com/2012/02/29/box2d/#comments</comments> <pubDate>Thu, 01 Mar 2012 01:20:50 +0000</pubDate> <dc:creator>josh</dc:creator> <category><![CDATA[development]]></category> <category><![CDATA[box2d]]></category> <category><![CDATA[canvas]]></category> <category><![CDATA[javascript]]></category> <category><![CDATA[physics]]></category><guid isPermaLink="false">http://digitalbush.com/?p=1169</guid> <description><![CDATA[The past few days I've been messing around with the Box2D physics engine. For someone who spends his days buried in business applications, this has been a fun bit of learning. Box2D has been ported to a ton of languages and I found a nice port to javascript called box2dweb. First, let's look at a [...]]]></description> <content:encoded><![CDATA[<p>The past few days I've been messing around with the <a
href="http://box2d.org/about/">Box2D physics engine</a>. For someone who spends his days buried in business applications, this has been a fun bit of learning. Box2D has been ported to a ton of languages and I found a nice port to javascript called <a
href="http://code.google.com/p/box2dweb/">box2dweb</a>.</p><p>First, let's look at a simple demo:</p><p><iframe
style="width: 600px; height: 300px" src="http://jsfiddle.net/digitalbush/JrzPH/embedded/result,js"></iframe><br
/> <a
href='http://jsfiddle.net/digitalbush/JrzPH/'>Click here for full jsFiddle</a></p><p>The first thing you'll need to do is set up a world and a loop to update it. The basics look like this:</p><pre class='prettyprint'><code>var world = new b2World(
   new b2Vec2(0, 10), //gravity vector
   true
);

setInterval(function(){
    world.Step(1 / 60, 10, 10);
    world.ClearForces();
},1000/60);
</code></pre><p>We just declared a world with some gravity. In the example above, we're applying gravity down, but you can have it pushing any direction you'd like. Next we set up an interval to run 60 times per second. Inside of that we tell the world to step 1/60th of a second while specifying the velocity and position iterations. For the velocity and positon iterations, the values can be altered to meet your needs. Lower will yield better performance, higher will yield better accuracy.</p><p>So, now you have a world with nothing in it. What fun is that? We'll need to add some stuff and start crashing it into each other.</p><p>There are two type of objects you can create. Static objects, like the triangle above, are fixed in the space. They are not affected by gravity or other objects. Dynamic objects are the fun ones that you get to move around. Our circles above are created and then nudged slightly to make them fall on either side of the triangle.</p><p>Triangle</p><pre class='prettyprint'><code>var fixDef = new b2FixtureDef;
fixDef.shape = new b2PolygonShape;
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = .5;

fixDef.shape.SetAsArray([
    new b2Vec2(-1, 0),
    new b2Vec2(0, -1),
    new b2Vec2(1, 0)],3
);

var bodyDef = new b2BodyDef;
bodyDef.type = b2Body.b2_staticBody;
bodyDef.position.Set(7, 7);
world.CreateBody(bodyDef).CreateFixture(fixDef);
</code></pre><p>Circle</p><pre class='prettyprint'><code>//Same fixture density, friction and restitution from above.
fixDef.shape = new b2CircleShape(.5);
bodyDef.position.Set(7,0);
var body=world.CreateBody(bodyDef);
body.CreateFixture(fixDef);</code></pre><p>I mentioned above that I'm nudging the circles. In order to push the shapes, we can use the <code
class='prettyprint'>ApplyImpulse</code> method. It needs two parameters, a vector defining the force to be applied and a point that it should be applied to. Take a moment to go poke around in the fiddle and change the vector for the impulse. You can do some fun stuff like punch them straight up in the air. Go ahead, I'll wait.</p><p>There is one last bit you'll need to get your own samples going. All of the code we've done above describes the objects and their interactions. We still need a way to visualize it though. Luckily box2dweb has a debug drawing mode to render the objects on a canvas element. Here's what you need to set it up:</p><pre class='prettyprint'><code>var debugDraw = new b2DebugDraw();
debugDraw.SetSprite(document.getElementById("playground").getContext("2d"));
debugDraw.SetDrawScale(20.0);
debugDraw.SetFillAlpha(0.5);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(b2DebugDraw.e_shapeBit);
world.SetDebugDraw(debugDraw);
</code></pre><p>With that, all that is left is to call <code
class='prettyprint'>world.DrawDebugData()</code> right after you step. Now we can see our demolition derby in action!</p><p>I think that covers the basics. There is a lot of fun things you can do with the sample. Try changing the restitution (bounciness), the force of gravity, the direction of gravity, which direction you "nudge" the falling circles... heck, just start changing stuff and watch. It's way more fun than it should be.</p> <div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/digitalbush?a=ayNlE8_GGyI:3xXtFUHeGxM:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/digitalbush?i=ayNlE8_GGyI:3xXtFUHeGxM:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/digitalbush?a=ayNlE8_GGyI:3xXtFUHeGxM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/digitalbush?d=yIl2AUoC8zA" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://digitalbush.com/2012/02/29/box2d/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Knockout.js Observable Extensions</title><link>http://digitalbush.com/2011/12/29/knockout-js-observable-extensions/</link> <comments>http://digitalbush.com/2011/12/29/knockout-js-observable-extensions/#comments</comments> <pubDate>Thu, 29 Dec 2011 21:40:58 +0000</pubDate> <dc:creator>josh</dc:creator> <category><![CDATA[development]]></category> <category><![CDATA[extensions]]></category> <category><![CDATA[javascript]]></category> <category><![CDATA[Knockout.js]]></category> <category><![CDATA[mvvm]]></category><guid isPermaLink="false">http://digitalbush.com/?p=1165</guid> <description><![CDATA[This started out as a post about how to implement the new extender feature in Knockout.js 2.0. I wanted to see how well that would improve the experience of a money observable I created several months back. Once I had it implemented though, I was a bit disappointed. My extender doesn't have any arguments, but [...]]]></description> <content:encoded><![CDATA[<p>This started out as a post about how to implement the <a
href="http://knockoutjs.com/documentation/extenders.html">new extender feature in Knockout.js 2.0</a>. I wanted to see how well that would improve the experience of a <a
href="http://digitalbush.com/2011/05/03/knockout-js-money-observable/">money observable</a> I created several months back. Once I had it implemented though, I was a bit disappointed. My extender doesn't have any arguments, but the knockout observable extend call only accepts a hash in the form of <code
class ='prettyprint'>{extenderName:extenderOptions}</code>. I ended up with a call that looked like this: <code
class='prettyprint'>var cash=ko.observable(5.23).extend({money:null});</code></p><p>That didn't leave a very good taste in my mouth. So, I pulled down knockout and set out to change the way the extenders were implemented. I've grown fond of how jQuery chaining worked, so why not bring that to Knockout's observables? Luckily <a
href="http://twitter.com/#!/RPNiemeyer">Ryan Niemeyer</a> was there to save me from myself and pointed out that I could just <a
href="http://twitter.com/#!/RPNiemeyer/status/150399095893266432">extend ko.subscribable.fn</a> to achieve the desired effect.</p><p>I'm happy with the outcome. Let's explore the strategy a bit. Before I get in too deep, here's the end result:</p><p><iframe
style="width: 680px; height: 300px" src="http://jsfiddle.net/digitalbush/R6MPU/embedded/result,html,js"></iframe><br
/> <a
href='http://jsfiddle.net/digitalbush/R6MPU/'>Click here for full jsFiddle</a></p><p>You may be asking yourself, "What's so great about this?" This is basically the same as my previous sample with one exception. This implementation attaches directly to the subscribable type that KO provides. You might not have seen this unless you've spent some time digging around the knockout.js source. This type serves as a base for observables, obervableArrays and <del
datetime="2011-12-27T02:54:37+00:00">dependentObservables</del> computed observables.</p><p>Here's the code that provides the money formatting:</p><pre class='prettyprint linenums'>
(function(){
    var format = function(value) {
        toks = value.toFixed(2).replace('-', '').split('.');
        var display = '$' + $.map(toks[0].split('').reverse(), function(elm, i) {
            return [(i % 3 === 0 &#038;& i > 0 ? ',' : ''), elm];
        }).reverse().join('') + '.' + toks[1];

        return value < 0 ? '(' + display + ')' : display;
    };

    ko.subscribable.fn.money = function() {
        var target = this;

        var writeTarget = function(value) {
            target(parseFloat(value.replace(/[^0-9.-]/g, '')));
        };

        var result = ko.computed({
            read: function() {
                return target();
            },
            write: writeTarget
        });

        result.formatted = ko.computed({
            read: function() {
                return format(target());
            },
            write: writeTarget
        });

        return result;
    };
})();
</pre><p><strong>Breakdown</strong><br
/> Line 11 is where we start. By extending the <code>subscribable.fn</code> object we are adding a property to each and every subscriabable object that KO creates for us. This will give us the ability to chain observables to one another as long as we return an observable from our method(line 32).</p><p>On line 12 we see that 'this' references the observable we're extending. I like this because there are no special method signatures we need to implement. Here I'm just grabbing my own reference of this as a variable named target.</p><p>Line 18 is where this starts to get a little interesting. I'm creating a writable computed observable that will return the value from the base observable when read. When it gets written to, it will sanitize the input and then write that to the base observable. This will be the observable we return for public consumption(line 32).</p><p>Line 25 is where the formatting comes into play. To the observable we're returning we'll add another observable as a property named 'formatted'. This is what we'll bind to whenever we want to see a pretty version of our value. This is another read/write computed observable like we did above. When the property is read from, it will pass the base observable's value through a formatter. The write is the same as the base observable.</p><p><strong>Use It</strong></p><pre class='prettyprint linenums'>
var viewModel = {
    Cash: ko.observable(-1234.56).money(),
    Check: ko.observable(2000).money(),
    showJSON: function() {
        alert(ko.toJSON(viewModel));
    }
};

viewModel.Total = ko.computed(function() {
    return this.Cash() + this.Check();
}, viewModel).money();
ko.applyBindings(viewModel);
</pre><p>On lines 2,3, and 11 you can see where I've used the observable extension I created above. The cool thing about this technique is that we don't care what kind of observable we're extending, it just works.</p><p>The <code>showJSON</code> function on line 4 is what gets fired when we click the "Show View Model JSON" button on the example above. Click this and you will see that our json serialization is clean. This is because the base observable we return is the unformatted (no dollar signs, commas, or parenthesis) version.</p><p><strong>The Payoff</strong></p><pre class='prettyprint linenums'><code>&lt;div class='ui-widget-content'>
    &lt;p>
        &lt;label>How much in Cash?&lt;/label>
        &lt;input data-bind="value:Cash.formatted,css:{negative:Cash()<0}" />
    &lt;/p>
    &lt;p>
        &lt;label>How much in Checks?&lt;/label>
        &lt;input data-bind="value:Check.formatted,css:{negative:Check()<0}" />
    &lt;/p>
    &lt;p>
        &lt;label>Total:&lt;/label>
        &lt;span data-bind="text:Total.formatted,css:{negative:Total()<0}" />
    &lt;/p>
    &lt;p>
        &lt;button data-bind="click:showJSON">Show View Model JSON</button>
    <&lt;p>
&lt;/div>
</code></pre><p>Lines 4 and 8 we've bound the input's value to the formatted version of the extended observable. Line 12 has the text of a span bound to the formatted version of the computed observable.</p><p>I've rehashed this example 3 times now, but I'm happiest with this implementation. <del
datetime="2011-12-27T19:00:24+00:00">Extending *.fn.* isn't documented anywhere I saw, but maybe it should be. <img
src='http://digitalbush.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </del> Maybe I should RTFM, it's clearly documented <a
href="http://knockoutjs.com/documentation/fn.html">here</a>.  This chaining technique will be familiar to anyone who has used jQuery. What do you think about this technique?</p><p><em>Cross posted from <a
href="http://freshbrewedcode.com/joshbush/2011/12/27/knockout-js-observable-extensions/">Fresh Brewed Code</a>. If you haven't taken a look over there, please take a moment to see what we've been up to.</em></p> <div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/digitalbush?a=-Ve3E_MQMp8:naKVaPaauk4:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/digitalbush?i=-Ve3E_MQMp8:naKVaPaauk4:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/digitalbush?a=-Ve3E_MQMp8:naKVaPaauk4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/digitalbush?d=yIl2AUoC8zA" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://digitalbush.com/2011/12/29/knockout-js-observable-extensions/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Manage Your Dependencies with Rake and NuGet</title><link>http://digitalbush.com/2011/12/15/manage-your-dependencies-with-rake-and-nuget/</link> <comments>http://digitalbush.com/2011/12/15/manage-your-dependencies-with-rake-and-nuget/#comments</comments> <pubDate>Thu, 15 Dec 2011 21:09:04 +0000</pubDate> <dc:creator>josh</dc:creator> <category><![CDATA[development]]></category> <category><![CDATA[.NET]]></category> <category><![CDATA[nuget]]></category> <category><![CDATA[rake]]></category> <category><![CDATA[ruby]]></category><guid isPermaLink="false">http://digitalbush.com/?p=1161</guid> <description><![CDATA[Earlier I blogged about how to perform some basic build tasks in your .NET project with Rake and Albacore. There was one bit about managing dependencies I left off though because I thought it warranted its own post. For the projects I've been working on lately, we've managed to keep our source repository light and [...]]]></description> <content:encoded><![CDATA[<p>Earlier I blogged about <a
href="http://digitalbush.com/2011/12/12/take-control-of-your-net-builds-with-rake-and-albacore/">how to perform some basic build tasks</a> in your .NET project with Rake and Albacore. There was one bit about managing dependencies I left off though because I thought it warranted its own post. For the projects I've been working on lately, we've managed to keep our source repository light and nimble by not checking in binaries for all of the dependencies.</p><p>NuGet 1.6 came out this week and this functionality is baked in. You can check out the NuGet way in the <a
href="http://docs.nuget.org/docs/Workflows/Using-NuGet-without-committing-packages">documentation</a>. The bummer of this is that you have to enable "Package Restore" for each project in your solution. You also now have multiple packages.config to maintain per project. Yes, you can manage it all though the GUI or the package manager console for your projects, but I want it all in one place. I also like not having to do anything on a per project basis other than standard references.</p><p>After several iterations on what <a
href="http://lostechies.com/derekgreer/2011/09/20/dependency-management-in-net-using-nuget-without-visual-studio/">Derek Greer</a> started, I've ended up with the solution below. Dependencies are declared in the same packages.config format that nuget uses, so you can take something you've already created and centralize it. We have one build step to refresh our dependencies and it looks like this:</p><pre class='prettyprint linenums'>
require 'rexml/document'
TOOLS_PATH = File.expand_path("tools")
LIB_PATH = File.expand_path("lib")

FEEDS = [
	#Your internal repo can go here
	"http://go.microsoft.com/fwlink/?LinkID=206669"
]

task :dependencies do
	file = File.new("packages.config")
	doc = REXML::Document.new(file)
	doc.elements.each("packages/package") do |elm|
		package=elm.attributes["id"]
		version=elm.attributes["version"]

		packagePath="#{LIB_PATH}/#{package}"
		versionInfo="#{packagePath}/version.info"
		currentVersion=IO.read(versionInfo) if File.exists?(versionInfo)
		packageExists = File.directory?(packagePath)

		if(!(version or packageExists) or currentVersion!= version) then
			feedsArg = FEEDS.map{ |x| "-Source " + x }.join (' ')
			versionArg = "-Version #{version}" if version
			sh "\"#{TOOLS_PATH}/nuget/nuget.exe\" Install #{package} #{versionArg} -o \"#{LIB_PATH}\" #{feedsArg} -ExcludeVersion" do |ok,results|
				File.open(versionInfo,'w'){|f| f.write(version)} if ok
			end
		end
	end
end
</pre><p>There's a little bit of code there, but we're getting some good benefits from this one task.</p><p><strong>Control over where our dependencies go.</strong><br
/> I'm not a big fan of the packages/ folder that nuget uses by default. You may be able to change this in the GUI somewhere, but I haven't seen it yet. Yes, I'm aware that this is trivial, but I got used to storing my dependencies in lib/ and I'm okay with keeping that. <img
src='http://digitalbush.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> Every team has their own conventions they like to follow and it's nice to not have to change those just because you want to adopt a new tool.</p><p><strong>No weird version number suffixes on our folders.</strong><br
/> The default convention nuget uses is to store packages under a folder named {name}.{version}. That's cool until you need to update your dependency to a new version. When you do, you (or your tooling) will have to update the reference paths in all of your *.csproj files to accomodate the new path. I would prefer to store it in a folder with just the name of the package. Keep in mind, this removes the ability to run multiple versions of the same library for different projects within a solution. This hasn't come up on my projects yet though.</p><p><strong>No need to keep tabs on what dependencies our dependency has.</strong><br
/> I'm hoping this issue will change one day. As it stands right now (NuGet 1.6), if I have a single entry in my packages.config like so: <code
class='prettyprint'>&lt;package id="NHibernate" version="3.2.0.4000"/&gt;</code> then calling <code
class='prettyprint'>$&gt; nuget.exe install packages.config</code> will not get NHibernate's dependency 'Iesi.Collections'. It turns out though, calling nuget like this: <code
class='prettyprint'>$&gt; nuget.exe install NHibernate -Version 3.2.0.4000</code> will get that dependency for us, so that's exactly how our rake script does it.</p><p>I feel like the ruby syntax reads fairly easy even if you aren't familiar with the language. Still though, I think it would be beneficial to add a little commentary.</p><p>Line 5 is where we define our source(s) for nuget packages. At work we're using a file share to cache packages and then falling back to the default source when needed.</p><p>Lines 11 and 12 are where we load up the packages.config xml file using the XML parser that ships with a default Ruby install. From my reading, there are better gems to accomplish this faster, but this is a really tiny XML file we're dealing with.</p><p>Line 13 selects each package node and iterates over it. The next two lines just pick out the id and version attributes into variables. On lines 19 and 20 we read in the version file if it exists and also check if the package directory exists. We use all of that on line 22 to see if we need to restore this package.</p><p>If we're all systems go for NuGet launch, then line 23 turns the array of feeds from line 5 into '-Source' arguments for nuget.exe. Line 24 creates a version argument for nuget.exe if we have one. Finally, line 25 shells out to nuget.exe and assembles all of the command line arguments it needs to do the job. When we get our package, we poke(line 26) a version.info file to track the version we've downloaded for future runs.</p><p><strong>Wrapping Up</strong><br
/> That's it. I almost didn't write this post since NuGet 1.6 supports this scenario out of the box. I still feel like it's worthwhile to have this as part of our rakefile if for no other reason than to manage my packages from a single place. What do you think? Please let me know if you see anywhere I could improve the process.</p><p><em>Cross posted from <a
href="http://freshbrewedcode.com/joshbush/2011/12/14/manage-your-dependencies-with-rake-and-nuget/">Fresh Brewed Code</a>. If you haven't taken a look over there, please take a moment to see what we've been up to.</em></p> <div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/digitalbush?a=8HX3-AmA0Yg:6lUeceL6jlc:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/digitalbush?i=8HX3-AmA0Yg:6lUeceL6jlc:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/digitalbush?a=8HX3-AmA0Yg:6lUeceL6jlc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/digitalbush?d=yIl2AUoC8zA" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://digitalbush.com/2011/12/15/manage-your-dependencies-with-rake-and-nuget/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Take Control of Your .NET Builds with Rake and Albacore</title><link>http://digitalbush.com/2011/12/12/take-control-of-your-net-builds-with-rake-and-albacore/</link> <comments>http://digitalbush.com/2011/12/12/take-control-of-your-net-builds-with-rake-and-albacore/#comments</comments> <pubDate>Mon, 12 Dec 2011 14:16:39 +0000</pubDate> <dc:creator>josh</dc:creator> <category><![CDATA[development]]></category> <category><![CDATA[.NET]]></category> <category><![CDATA[albacore]]></category> <category><![CDATA[rake]]></category> <category><![CDATA[ruby]]></category><guid isPermaLink="false">http://digitalbush.com/?p=1156</guid> <description><![CDATA[If Rake is a gateway drug to Ruby, then Derick Bailey is your dealer. He's created a project named Albacore which makes building your .NET projects stupid easy with Rake. Doing anything in angle brackets for msbuild was painful for me. I write code for a living, so it just makes sense to write code [...]]]></description> <content:encoded><![CDATA[<p>If Rake is a gateway drug to Ruby, then <a
href="http://twitter.com/#!/derickbailey">Derick Bailey</a> is your dealer. He's created a project named <a
href="http://albacorebuild.net/">Albacore</a> which makes building your .NET projects stupid easy with Rake. Doing anything in angle brackets for msbuild was painful for me. I write code for a living, so it just makes sense to write code to build my stuff.</p><p>Lately I've been doing some work with our builds and TeamCity. A coworker pointed me to Rake and next I discovered Albacore. I just wanted to take a moment to show you how simple it is to set up a build that compiles your code, runs your tests and assembles the output.</p><pre class='prettyprint linenums'>
require 'albacore'

PRODUCT_NAME = "Autofac.Settings"
BUILD_PATH = File.expand_path("build")
TOOLS_PATH = File.expand_path("tools")
LIB_PATH = File.expand_path("lib")

configuration = ENV['Configuration'] || "Debug"

task :default => :all

task :all => [:clean,:dependencies,:build,:specs,:copy]

task :clean do
	rmtree BUILD_PATH
end

task :dependencies do
	#future post. <img src='http://digitalbush.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />
end

msbuild :build=>[:dependencies] do |msb|
	msb.properties :configuration => configuration
	msb.targets :Clean, :Build
	msb.verbosity = "minimal"
	msb.solution = "#{PRODUCT_NAME}.sln"
end

mspec :specs => [:build] do |mspec|
	mspec.command = "lib/Machine.Specifications/tools/mspec-clr4.exe"
	mspec.assemblies Dir.glob('specs/**/*Specs.dll')
end

task :copy => [:specs] do
	Dir.glob("src/**/*.csproj") do |proj|
		name=File.basename(proj,".csproj")
		puts "Copying output for #{name}"
		src=File.dirname(proj)
		dest = "#{BUILD_PATH}/#{name}/"
		mkdir_p(dest)
		cp_r("#{src}/bin/#{configuration}/.",dest)
	end
end
</pre><p><strong>:default</strong><br
/> So, let's start from the top. Line 10 defines a default task. This is what will get called when you just call <code
class='prettyprint'>rake</code> without any arguments from the command line.</p><p><strong>:clean</strong><br
/> Line 14 defines a task which just nukes the build output directory. This makes sure we don't accidentally leave artifacts around from a previous build.</p><p><strong>:build</strong><br
/> Line 22 is my first albacore task. This is the task where I'm compiling my code. Line 23 would be 'Debug' or 'Release' if you're using the default build configurations. The line after is where I tell it to clean the build output and then Build. Point it at a solution file and you're good to go. Easy enough.</p><p><strong>:specs</strong><br
/> Line 29 is another albacore task to run my Machine.Specifications based tests. Tell it where mspec lives and  what assemblies contain your tests. Done.</p><p><strong>:copy</strong><br
/> Line 34 is a simple file copy task to assemble the build output from src/ and copy them to the build folder.  Find all of the project files and go to bin/{config} and get the output files. Move them to a folder with the name of the project.</p><p>That's about it. Thanks to <a
href="http://twitter.com/#!/derekgreer">Derek Greer</a> for getting me started with Rake. I was able to look at his sample Rakefile and start hacking away. Within a few minutes I had my own rakefile running with albacore tasks. Ruby is pretty straightforward and fun. Playing with Ruby via Rake just makes me want to write more Ruby.</p><p><em>Since I'm a Ruby n00b, I'm sure my Ruby is less than perfect. If you have some suggestions for me to make my code suck less, please leave a comment.</em></p><p><em>Cross posted from <a
href="http://freshbrewedcode.com/joshbush/2011/12/08/take-control-of-your-net-builds-with-rake-and-albacore/">Fresh Brewed Code</a>. If you haven't taken a look over there, please take a moment to see what we've been up to.</em></p> <div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/digitalbush?a=YWBzqlcti_8:nR9iWjIS0jU:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/digitalbush?i=YWBzqlcti_8:nR9iWjIS0jU:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/digitalbush?a=YWBzqlcti_8:nR9iWjIS0jU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/digitalbush?d=yIl2AUoC8zA" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://digitalbush.com/2011/12/12/take-control-of-your-net-builds-with-rake-and-albacore/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced
Database Caching 7/10 queries in 0.003 seconds using apc

Served from: _ @ 2012-05-07 16:47:20 -->

