<feed xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns="http://www.w3.org/2005/Atom" xml:lang="en-US">
    <title>NewItUp()</title>
    <link rel="self" type="application/xml" href="http://www.newitup.com/Atom.aspx" />
    <subtitle type="html">Another Alt.Net blog - Dan Donahue</subtitle>
    <id>http://newitup.com/Default.aspx</id>
    <author>
        <name>Dan Donahue</name>
        <uri>http://newitup.com/Default.aspx</uri>
    </author>
    <generator uri="http://subtextproject.com" version="Subtext Version 1.9.5.176">Subtext</generator>
    <updated>2011-01-27T20:52:23Z</updated>
    <entry>
        <title>CQRS In Phases: Phase 2 - Commands, Events And Handlers</title>
        <link rel="self" type="text/html" href="http://newitup.com/archive/2011/01/27/cqrs-in-phases-phase-2---commands-events-and-handlers.aspx" />
        <id>http://newitup.com/archive/2011/01/27/cqrs-in-phases-phase-2---commands-events-and-handlers.aspx</id>
        <published>2011-01-27T20:05:43-06:00:00</published>
        <updated>2011-01-27T20:47:28Z</updated>
        <content type="html">(please read my &lt;a href="http://www.newitup.com/archive/2011/01/26/cqrs-in-phases-introduction.aspx"&gt;Introduction&lt;/a&gt; post in this series for an explanation of what I'm trying to do with this blog series)&lt;br /&gt;
&lt;br /&gt;
In my &lt;a href="http://www.newitup.com/archive/2011/01/26/cqrs-in-phases-phase-1---separate-your-reads-from.aspx"&gt;last post&lt;/a&gt;, I talked about separating your reads from your writes in your applications. Once you've done that - you've already applied CQRS... you've separated the responsibility of reading your data from writing your data.  You're done and your app will b be better for it :)&lt;br /&gt;
&lt;br /&gt;
But if you want to take things further, the next step in applying CQRS as you commonly read about it is to unify the way that data flows through the write side of your application.&lt;br /&gt;
&lt;br /&gt;
Before that though, a quick note on the read side - it's done.  Once you've separated it out, that's really all that needs to be done.  It can now change indepdently of the write side and it should be very simple.  All you're looking to do on the read side is get some data and display it. You can tweak queries and tweak code, but the code should be very simple.  So once you've done step 1 as I outlined in my last post, you're pretty much done the "radical" changes on the read side.&lt;br /&gt;
&lt;br /&gt;
On the write side, the way to unify the data flow through it is to issue commands from your client and have them handled by a command handler.  In the command handler, you load the business object that the command relates to, call a method that performs the command on the business object and, if necessary, have the business object fire off events which can be handled by event handlers.&lt;br /&gt;
&lt;br /&gt;
Whoa. That was a pretty dense amount of information wrapped up in one paragraph. There's a lot of interesting information about what commands and events are and how they should be named, but rather than re-hash it, I'll just share a few links.&lt;br /&gt;
&lt;br /&gt;
For more on commands, &lt;a href="http://cqrsinfo.com/documents/task-based-ui/" target="_blank"&gt;read this&lt;/a&gt;.  For more on events, &lt;a href="http://cqrsinfo.com/documents/events-as-storage-mechanism/" target="_blank"&gt;look here&lt;/a&gt;. And if you want to see a sample application that shows the most simple implementation of commands, events and how they're both handled, check out &lt;a href="https://github.com/gregoryyoung/m-r" target="_blank"&gt;this project&lt;/a&gt; written by Greg Young.&lt;br /&gt;
&lt;br /&gt;
If you don't feel like reading all that other stuff (shame on you), just understand that commands are telling the system to do something and should be named as such - i.e. &lt;span style="font-style: italic;"&gt;UpdateCustomerInfoCommand&lt;/span&gt;. Commands should be in the imperative to imply that they are telling the system to do something.  Events are telling the system that something has occurred in the past.  That's the distinction.  So after you handled the &lt;span style="font-style: italic;"&gt;UpdateCustomerInfoCommand&lt;/span&gt;, you might issue a &lt;span style="font-style: italic;"&gt;CustomerInfoUpdatedEvent&lt;/span&gt; event to let other parts of the system know what happened in case they are interested.  And handlers are just functions that handle the commands/events when they're raised.&lt;br /&gt;
&lt;br /&gt;
If you start following these guidelines of having your client issue commands that are handled and then having your business objects, as part of that handling fire events, you'll see some benefits over your standard architecture, including:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight: bold;"&gt;Consolidation of business logic into the business objects&lt;br /&gt;
&lt;/span&gt;I can't count the number of times I've seen an application that touted their business object layer, only to see all of the actual business logic in code-behind files or in MVC actions or elsewhere.  The business objects were really just DTOs with some data access methods and maybe a bit of validation logic. The actual changes to the object were occurring elsewhere, breaking encapsulation.  When you begin issuing commands, it becomes very natural that all of your business logic is inside your business objects.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight: bold;"&gt;A more human way to understand the system &lt;br /&gt;
&lt;/span&gt;Telling a system what to do and then having the system notify other systems what happened is a very easy thing to understand in human terms, because it models how humans work.&lt;span style="font-weight: bold;"&gt;  &lt;/span&gt;This makes it easy on the developer's brain to understand how data flows through the system and even more important, it makes it easy on the non-developer's brain to understand how the system works as well.  Instead of talking in terms of objects, you can talk in very real world terms which makes sense to non-developers that are part of building a system.  Which brings me to my next point...&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight: bold;"&gt;You head in the direction of domain-driven design&lt;/span&gt;&lt;br /&gt;
I'm not a DDD expert, but I've read &lt;a target="_blank" href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215"&gt;the big blue book&lt;/a&gt; and a lot of what it discusses is handled by moving into commands and events on the write side.  Most CQRS proponents suggest a full blown domain model behind the command handlers and it does make sense.  But you can almost get to a domain model just by consolidating your logic and issuing commands this way.&lt;br /&gt;
&lt;br style="font-weight: bold;" /&gt;
&lt;span style="font-weight: bold;"&gt;Your client apps become simpler and more focused&lt;/span&gt;&lt;br /&gt;
Your client apps, whether they be MVC apps, WebForms or desktop apps can go back to being more focused on what they're good at which is displaying data to a user and handling input from a user.  No longer will they be burdened with also housing business logic as part of their job. You're getting better SRP and SOC.  That's always a good thing.&lt;br /&gt;
&lt;br /&gt;
This change is a little more involved than step 1.  In a larger app, it can take considerable effort to pull your business logic together when its currently spread all over your current system.  But you also get bigger bang for your buck with this step.  Even though refactoring your app to issue commands and raise events make take more effort, you're actually simplifying your system and making it easier to understand for the future.&lt;br /&gt;
&lt;br /&gt;
In the next post, I'll talk about going even further with CQRS by using event sourcing.  This is probably where a lot of developers start to feel uneasy about CQRS.  Not that they don't see the benefits, but it's quite a leap from how they're used to developing that we become unsure if its the right way to go.&lt;br /&gt;
&lt;br /&gt;
As I mentioned in my introduction post, if something here sounds wrong,  or if I'm missing something - please let me know in the comments.   Feedback is very much appreciated. &lt;br /&gt;
&lt;br /&gt;
&lt;ol&gt;
    &lt;li&gt;&lt;a href="http://www.newitup.com/archive/2011/01/26/cqrs-in-phases-introduction.aspx"&gt;Introduction&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="http://www.newitup.com/archive/2011/01/26/cqrs-in-phases-phase-1---separate-your-reads-from.aspx"&gt;Step 1: Separating Your Reads From Your Writes&lt;/a&gt;&lt;br /&gt;
    &lt;/li&gt;
    &lt;li&gt;&lt;a href="http://newitup.com/archive/2011/01/27/cqrs-in-phases-phase-2---commands-events-and-handlers.aspx"&gt;Step 2: Commands, Events And Handlers&lt;/a&gt;&lt;br /&gt;
    &lt;/li&gt;
&lt;/ol&gt;&lt;img src="http://newitup.com/aggbug/137.aspx" width="1" height="1" /&gt;</content>
        <wfw:comment>http://newitup.com/comments/137.aspx</wfw:comment>
        <slash:comments>133</slash:comments>
        <wfw:commentRss>http://newitup.com/comments/commentRss/137.aspx</wfw:commentRss>
        <trackback:ping>http://newitup.com/services/trackbacks/137.aspx</trackback:ping>
    </entry>
    <entry>
        <title>CQRS In Phases: Introduction</title>
        <link rel="self" type="text/html" href="http://newitup.com/archive/2011/01/26/cqrs-in-phases-introduction.aspx" />
        <id>http://newitup.com/archive/2011/01/26/cqrs-in-phases-introduction.aspx</id>
        <published>2011-01-26T06:41:07-06:00:00</published>
        <updated>2011-01-27T20:52:23Z</updated>
        <content type="html">Lately, I've been a bit obsessed with Command-Query Responsibility Segregation (CQRS). I'm not quite sure if I'm late to the party or jumping on the bandwagon because I remember seeing a lot of noise around CQRS in my RSS feed a few months ago but didn't really bother with it at the time.  I'm not sure if it's still a hot topic or was a passing fad, but the more I read about it, the more interested I become.  I agree with a lot of the architectural principles, but I'm not going to re-hash those.&lt;br /&gt;
&lt;br /&gt;
For anyone that wants to learn more about CQRS, &lt;a target="_blank" href="http://cqrsinfo.com/"&gt;http://cqrsinfo.com/&lt;/a&gt; is a great starting place.  There are also great blogs out there maintained by &lt;a target="_blank" href="http://codebetter.com/gregyoung"&gt;Greg Young&lt;/a&gt;, &lt;a target="_blank" href="http://abdullin.com/cqrs/"&gt;Rinat Abdullin&lt;/a&gt;, &lt;a target="_blank" href="http://cre8ivethought.com/blog/index"&gt;Mark Nijhof&lt;/a&gt;, &lt;a target="_blank" href="http://jonathan-oliver.blogspot.com/search/label/DDDD"&gt;Jonathan Oliver&lt;/a&gt; and &lt;a target="_blank" href="http://www.udidahan.com/2009/12/09/clarified-cqrs/"&gt;Udi Dahan&lt;/a&gt; - all of whom are far more knowledgeable on the subject than I am.&lt;br /&gt;
&lt;br /&gt;
When you read about CQRS, you usually see what I call the full monty which includes using event sourcing (capturing all changes to an application state as a sequence of events), using separate databases for the read side and the write side and even distributing the application in the cloud.  There are very compelling benefits to using the full monty, but at the same time, I think there are benefits to using bits of the CQRS architecture without going all out.  So what I hoped to write about in these next few blog posts is dissecting some of the steps you can take in your code to achieve some of the benefits of CQRS without necessarily making it all or nothing proposition.&lt;br /&gt;
&lt;br /&gt;
Allow me to reiterate - no CQRS information I've read has ever said that you need to do all the steps to see benefits in your application.  As a matter of fact, some things I've read have discussed the benefits as being independent.  I've just rarely seen the steps you can take broken out into logical pieces and the benefits of each discussed.  That's what I hope to do with this blog series.&lt;br /&gt;
&lt;br /&gt;
Lastly, I hope to get some feedback from people with far more CQRS experience than I have.  If something I say sounds completely wrong, I'd love to know about it.  I'm just trying to distill the large amount of information I've digested into something that makes sense to me.  So I may have gotten something confused in all of my reading and I don't claim to be an expert.&lt;br /&gt;
&lt;br /&gt;
My next post will talk through the first step I see towards CQRS - which is the most straightforward one... separating your reads from your writes.&lt;br /&gt;
&lt;br /&gt;
&lt;ol&gt;
    &lt;li&gt;&lt;a href="http://www.newitup.com/archive/2011/01/26/cqrs-in-phases-introduction.aspx"&gt;Introduction&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="http://www.newitup.com/archive/2011/01/26/cqrs-in-phases-phase-1---separate-your-reads-from.aspx"&gt;Step 1: Separating Your Reads From Your Writes&lt;/a&gt;&lt;br /&gt;
    &lt;/li&gt;
    &lt;li&gt;&lt;a href="http://newitup.com/archive/2011/01/27/cqrs-in-phases-phase-2---commands-events-and-handlers.aspx"&gt;Step 2: Commands, Events And Handlers&lt;/a&gt;&lt;br /&gt;
    &lt;/li&gt;
&lt;/ol&gt;&lt;img src="http://newitup.com/aggbug/135.aspx" width="1" height="1" /&gt;</content>
        <wfw:comment>http://newitup.com/comments/135.aspx</wfw:comment>
        <slash:comments>105</slash:comments>
        <wfw:commentRss>http://newitup.com/comments/commentRss/135.aspx</wfw:commentRss>
        <trackback:ping>http://newitup.com/services/trackbacks/135.aspx</trackback:ping>
    </entry>
    <entry>
        <title>CQRS In Phases: Phase 1 - Separate Your Reads From Your Writes</title>
        <link rel="self" type="text/html" href="http://newitup.com/archive/2011/01/26/cqrs-in-phases-phase-1---separate-your-reads-from.aspx" />
        <id>http://newitup.com/archive/2011/01/26/cqrs-in-phases-phase-1---separate-your-reads-from.aspx</id>
        <published>2011-01-26T07:10:12-06:00:00</published>
        <updated>2011-01-27T20:46:29Z</updated>
        <content type="html">(please read my &lt;a href="http://www.newitup.com/archive/2011/01/26/cqrs-in-phases-introduction.aspx"&gt;Introduction&lt;/a&gt; post in this series for an explanation of what I'm trying to do)&lt;br /&gt;
&lt;br /&gt;
The first "phase" in Command-Query Responsibility Segregation (CQRS) is probably the most straightforward and obvious - separating your reads (queries) from your writes (commands).  In a typical application (sorry, no samples), this basically means separating the queries that display data on the screen from the ones that perform inserts, updates and deletes on your database.&lt;br /&gt;
&lt;br /&gt;
I should probably take a minute to explain the type of architecture I'm envisioning for this blog post, although benefits of the steps can be seen no matter your architecture.  For the phases, I'm imagining you have a domain model or at least a business logic layer which has business objects for each of the main entities in your system. In all likelihood, these business objects are being hydated from the database and also save their state back to the database.  Again, this isn't the only type of system that can benefit from some of the concepts of CQRS, but its what I have in mind mostly because it's what I deal with at work that I'm trying to improve :)&lt;br /&gt;
&lt;br /&gt;
What do I mean by separate the reads from the writes?  Most them into different objects.  That's it.  If you use business objects, move the functions that read data from the database out of them and into another read-specific object.  If you just use a straight object for data access like a repository, break it up into two repositories - one for reading methods and one for writing methods.  Just separate the methods in your app that read data from the ones that write data.&lt;br /&gt;
&lt;br /&gt;
With even just this simple step, you will see some benefits, including:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight: bold;"&gt;Your code, especially if you have business objects, will become simpler.&lt;br /&gt;
&lt;/span&gt;This may not be as applicable if you're not using business objects, but if you are - you have removed an entire responsibility from them.  The responsibility of hydrating themselves to display on the screen.&lt;span style="font-weight: bold;"&gt;  &lt;/span&gt;This means your business objects become more focused on what they're intended to do - validate things before they get created, updated, deleted, etc.&lt;br /&gt;
&lt;br style="font-weight: bold;" /&gt;
&lt;span style="font-weight: bold;"&gt;Increased ability to optimize your read query performance.&lt;/span&gt;&lt;br /&gt;
There are a few reasons for this.  The big one is that in most cases, your business object represents a row in a database table.  Even if you're using an ORM, you're mapping objects to database table rows. As such, you're usually querying entire rows, using lazy loading to get related child objects and other techniques in order to get the data you need to show a screen.&lt;br /&gt;
&lt;br /&gt;
Once you've removed the concern of reading from business objects and put it into its own class, you're now able to use any techniques in order to get the performance you want.  You can write custom SQL queries to bring back just the data you need because you're not beholden to the business object definition.  If a stored procedure makes more sense here, use that.  If you only need two columns from a row instead of the entire row, just write a query that only returns those two values.  You have much more wiggle room this way.&lt;br /&gt;
&lt;br /&gt;
So with just this simple change you've cleaned up your business objects and given yourself some leeway when it comes to optimizing your queries.  Not bad.&lt;br /&gt;
&lt;br /&gt;
In the next post, I'll talk about the 2nd step as I see it - unifying the way data flows through the write side via the use of commands, events and handlers.&lt;br /&gt;
&lt;br /&gt;
As I mentioned in my introduction post, if something here sounds wrong, or if I'm missing something - please let me know in the comments.  Feedback is very much appreciated.&lt;br /&gt;
&lt;br /&gt;
&lt;ol&gt;
    &lt;li&gt;&lt;a href="http://www.newitup.com/archive/2011/01/26/cqrs-in-phases-introduction.aspx"&gt;Introduction&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="http://www.newitup.com/archive/2011/01/26/cqrs-in-phases-phase-1---separate-your-reads-from.aspx"&gt;Step 1: Separating Your Reads From Your Writes&lt;/a&gt;&lt;br /&gt;
    &lt;/li&gt;
    &lt;li&gt;&lt;a href="http://newitup.com/archive/2011/01/27/cqrs-in-phases-phase-2---commands-events-and-handlers.aspx"&gt;Step 2: Commands, Events And Handlers&lt;/a&gt;&lt;br /&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;img src="http://newitup.com/aggbug/136.aspx" width="1" height="1" /&gt;</content>
        <wfw:comment>http://newitup.com/comments/136.aspx</wfw:comment>
        <slash:comments>112</slash:comments>
        <wfw:commentRss>http://newitup.com/comments/commentRss/136.aspx</wfw:commentRss>
        <trackback:ping>http://newitup.com/services/trackbacks/136.aspx</trackback:ping>
    </entry>
    <entry>
        <title>Book Review:  ASP.NET MVC 2 In Action</title>
        <link rel="self" type="text/html" href="http://newitup.com/archive/2010/10/05/book-review--asp.net-mvc-2-in-action.aspx" />
        <id>http://newitup.com/archive/2010/10/05/book-review--asp.net-mvc-2-in-action.aspx</id>
        <published>2010-10-05T02:04:17-05:00:00</published>
        <updated>2010-10-05T02:08:02Z</updated>
        <content type="html">I was looking for a good book to get started with the ASP.NET MVC framework now that I've found the time to actually sit down and play with it.  I'd used Castle MonoRail pretty extensively in the past on a few client projects and I've played with Ruby On Rails quite a bit too, so the idea of MVC wasn't new to me.  I was really looking for a book that talked about using Microsoft's MVC framework and one that explained some of the best practices, rather than just a primer or reference since I already had the MVC idea down pat.  In that regard, I think ASP.NET MVC 2 In Acton really shined.&lt;br /&gt;
&lt;br /&gt;
ASP.NET MVC 2 In Action is laid out into four sections.  The first section is called High Speed Fundamentals and it focuses on a quick overview of what the Model-View-Controller paradigm is all about and then a chapter delves into each of the layers individually as a primer.  There's also a chapter which explains what things from the WebForms world are still usable in the MVC world.  There's a good amount of valuable info in this section, but it is, as the name, implies - high speed. I think it may even be a bit too high speed if you have no experience with MVC architecture and you're coming over from the WebForms paradigm.  It can be confusing and there's not much info here to really iron out that confusion.  It wasn't a problem for me, but I could see how someone new to the MVC paradigm might still be a little uncomfortable by the time they reach the end of the first section.&lt;br /&gt;
&lt;br /&gt;
The second section, Journeyman Techniques, is where the book really starts to shine.  This is where the authors get into topics like domain modeling, extending the controllers and views and using Ajax.  IoC is covered briefly in this section as well.  The reason I find this so valuable is that I like reading books that are less a reference about the tool and more a real-world guide for usage.  That's exactly what this section of the book does.  Instead of just covering the features of MVC, this book gets into how developers should leverage the ASP.NET MVC framework in their own applications.  The chapter on custom model binding and value providers was very useful, as was the chapter on using IoC to create a custom controller factory - these are things that Microsoft might not tell you to do, but will quickly prove valuable if you work on a real-world, large ASP.NET MVC project.&lt;br /&gt;
&lt;br /&gt;
The third section, Mastering ASP.NET MVC, takes things even further with chapters on routing and making your controllers lightweight.  There are also chapters on doing mapping with AutoMapper (Jimmy Bogard, who created AutoMapper, is an author of the book) and data access with NHibernate.  I could see some people being put off that tools are being suggested as part of the book, but again, I find this refreshing.  The book becomes more valuable than just as a reference of ASP.NET MVC features.  This is where the real value of the book is.  You get information on not just how to build an ASP.NET MVC application, but how to build a rock solid, well-factored ASP.NET MVC application.  Even if you don't choose the specific tooling and stuff they suggest, the ideas behind them are sound - such as keeping your controllers lightweight for easier maintainability and testability.&lt;br /&gt;
&lt;br /&gt;
The final section, Cross-Cutting Advanced Topics, closes the book with some information about testing your applications and customizing Visual Studio for ASP.NET MVC work.  There's also a final chapter that's a short example of tying everything together which I felt was a little TOO short to be of any value.  But the chapter on testing is good as is the route debugging chapter.&lt;br /&gt;
&lt;br /&gt;
Besides the quick introduction to the MVC pattern, I think this book really shines.  There is a lot of helpful information and it's great to see a book on the framework that gets into how developers can and should use it in their projects, rather than just being a reference.  I like that the book is opinionated and lets you know how real programmers are working with the framework, including how they're working around some of the weaker parts of the framework's default implementation.&lt;br /&gt;
&lt;br /&gt;
I'd suggest this book to someone who understands the MVC architecture, but wants to work on an ASP.NET MVC project and is wondering what the best practices in the field are.&lt;img src="http://newitup.com/aggbug/134.aspx" width="1" height="1" /&gt;</content>
        <wfw:comment>http://newitup.com/comments/134.aspx</wfw:comment>
        <slash:comments>100</slash:comments>
        <wfw:commentRss>http://newitup.com/comments/commentRss/134.aspx</wfw:commentRss>
        <trackback:ping>http://newitup.com/services/trackbacks/134.aspx</trackback:ping>
    </entry>
    <entry>
        <title>A Code Sample Is Worth A Thousand Words:  Ruby Is Pretty Cool</title>
        <link rel="self" type="text/html" href="http://newitup.com/archive/2010/09/28/a-code-sample-is-worth-a-thousand-words--ruby.aspx" />
        <id>http://newitup.com/archive/2010/09/28/a-code-sample-is-worth-a-thousand-words--ruby.aspx</id>
        <published>2010-09-28T22:55:40-05:00:00</published>
        <updated>2010-10-01T01:02:42Z</updated>
        <content type="html">&lt;p&gt;Let me make this disclaimer first  before anything else - I'm not jumping off the .NET boat or anything.   But I definitely see value in opening up and seeing how people do things  on the other side of the fence.&lt;/p&gt;
&lt;p&gt;So I've been reading this book online - &lt;a href="http://www.ruby-doc.org/docs/ProgrammingRuby/" class="jive-link-external-small"&gt;Programming Ruby -  The Pragmatic Programmer's Guide&lt;/a&gt;.  In the chapter on &lt;a href="http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_stdtypes.html" class="jive-link-external-small"&gt;Standard  Types&lt;/a&gt;, they showed this really short code sample.  Even though it's  short in lines, it displays a bunch of things about Ruby that I think  are really cool.  And things that are awesome in comparison to the way  .NET handles things.&lt;/p&gt;
&lt;p&gt;Here is the code and the output in Ruby:&lt;/p&gt;
&lt;blockquote&gt; num = 9&lt;br /&gt;
7.times do&lt;br /&gt;
     print num.class, " ", num, "\n"&lt;br /&gt;
     num *= num&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# OUTPUT&lt;br /&gt;
# Fixnum 9&lt;br /&gt;
# Fixnum 81&lt;br /&gt;
# Fixnum 6561&lt;br /&gt;
# Fixnum 43046721&lt;br /&gt;
# Fixnum 1853020188851841&lt;br /&gt;
# Bignum 3433683820292512484657849089281&lt;br /&gt;
# Bignum 11790184577738583171520872861412518665678211592275841109096961 &lt;/blockquote&gt;
&lt;p&gt;Here  is the code to do the same thing in C# and its output:&lt;/p&gt;
&lt;blockquote&gt;  private static void WithoutExtensionMethods()&lt;br /&gt;
{&lt;br /&gt;
     int num = 9;&lt;br /&gt;
     for (int i = 0; i &amp;lt; 7; i++)&lt;br /&gt;
     {&lt;br /&gt;
          Console.WriteLine("{0} {1}", num.GetType(), num);&lt;br /&gt;
          num = num * num;&lt;br /&gt;
     }&lt;br /&gt;
     Console.ReadLine();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// OUTPUT&lt;br /&gt;
// System.Int32 9&lt;br /&gt;
// System.Int32 81&lt;br /&gt;
// System.Int32 6561&lt;br /&gt;
// System.Int32 43046721&lt;br /&gt;
// System.Int32 -501334399&lt;br /&gt;
// System.Int32 2038349057&lt;br /&gt;
// System.Int32 -1970898431&lt;br /&gt;
&lt;/blockquote&gt;
&lt;p&gt;Now, to be a  completist, I also wrote a version that actually allows you to do  something like &lt;strong&gt;7.Times()&lt;/strong&gt; in C# - it used an extension  method on the int type and you had to pass the number you wanted to  multiply (the 'num' variable) as well as a Func&amp;lt;int, int&amp;gt; telling  it what exactly you wanted to do inside the loop.  I didn't show that  example because I figured it was extra work and this is probably more  likely how someone would do the code in the Ruby example in C#.  Ruby does have a for loop construct, but most Rubyists prefer using times, or upto or other methods as they're more clear to the programmer.&lt;br /&gt;
&lt;/p&gt;
&lt;p&gt;I'm going to cover the things  that I think make the Ruby example cooler than the C# from the lighter  "not that big a deal" stuff to the stuff that really IS that big a  deal.  So without further ado.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1.  The Ruby code reads better&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;That's  pretty subjective, but in my opinion it does.  Your brain doesn't have  to parse the for loop and figure out "ok, its starting at zero and  running to less than 7 (meaning 6) so its going to run 0-6, so 7  times".  The loop construct in Ruby is "run this 7.times".  Another cool  thing I found out about Ruby is that you can actually initialize big  values using an underscore to break them up.  So "123_456_789" would  just become "123456789" to the processor.  But its easier for another  programmer to read that value with the underscores - this is the same  thing that commas do in math - allow our brains to process the number  easier.  Same thing that dashes do in phone numbers, etc.  The phone  company doesn't need us to enter dashes in... it just needs 10 numbers  to know what to call.  The dashes are for our brains.  And that's a lot  of what programming is about.  The computer understands complexity.   You're not going to over-complex the computer.  So we write stuff  cleanly and simply so that other programmers can read and understand  your code.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2.  The Ruby code block passed into the times function is actually aware of  the context in which its running&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Again, I didn't show  the C# version of the Times() function that you could write, but you do  have to pass in the &lt;em&gt;num&lt;/em&gt; variable so that the Func&amp;lt;int,  int&amp;gt; knows what to work with.  Not the case with Ruby.  To further  illustrate this point, scroll down to the LAST example at the BOTTOM of &lt;a href="http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_containers.html" class="jive-link-external-small"&gt;this  page of the Ruby book&lt;/a&gt; I mentioned earlier.&lt;/p&gt;
&lt;p&gt;With Ruby, that part between &lt;strong&gt;do  &lt;/strong&gt;and &lt;strong&gt;end &lt;/strong&gt;is a block of code, similar to a  function pointer.  It doesn't run immediately when its called, but  rather waits until its called, just like Func&amp;lt;&amp;gt; or a delegate.   Only, with Ruby, it remembers the context when it was called - the local  variables, the current object, and so on - so its able to work with  those values inside the block.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. Ruby is dynamic&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The  first listing in the output for both types is the class or type of the  variable.  Notice how in the Ruby example, when the value gets large  enough, the variable changes to type Bignum instead of Fixnum and keeps  on chugging.  In C#, that's not the case.  If you defined it as an  Int32, that's what it's going to stay.  And that's deceptive and brings  me to my last point.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;4. Ruby gives you the right answer&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Because  its dynamic, Ruby can compute values this big and store them in the  correct type on the fly.&lt;/p&gt;
&lt;p&gt;I'll be honest... when I coded this example in  C#, I was expecting an OverflowException to be thrown once the number  got too big.  The actual results scared me a little.  It runs just fine,  but the results are incorrect.  In the 5th line, it's gone into  negative numbers as we've overflowed the number of bytes that an Int32  can hold (for the record, I ran this and used an explicitly type Int64  and it overflowed as well).&lt;/p&gt;
&lt;p&gt;I tried running this again and wrapped the  computation in a try-catch block to catch the OverflowException  explicitly.  It still ran just fine.  You have wrap that try-catch block  in ANOTHER block called the &lt;a href="http://msdn.microsoft.com/en-us/library/74b4xzyw%28v=VS.71%29.aspx" class="jive-link-external-small"&gt;checked  block&lt;/a&gt; to get your program to check the exception.  And then your  program will crash and die when you overflow the Int32 type.  That's  good and bad.  It lets you know you've used a type that isn't big enough  for the value you're computing... but it also doesn't get you the right  answer or allow your program to continue to running .&lt;/p&gt;
&lt;p&gt;Of course there are tradeoffs.  Because just like you had  this num variable change from a Fixnum to a Bignum, you could set it to a  String and it'll just chug along and not complain.  It's up to you to  watch that stuff.  You could argue whether that's good or bad (I tend to  think that it's not that bad... you oughta know your code well enough  to know what its doing).  But either way... it's a different  perspective.  Static languages aren't the only way of the world.&lt;/p&gt;&lt;img src="http://newitup.com/aggbug/133.aspx" width="1" height="1" /&gt;</content>
        <wfw:comment>http://newitup.com/comments/133.aspx</wfw:comment>
        <slash:comments>105</slash:comments>
        <wfw:commentRss>http://newitup.com/comments/commentRss/133.aspx</wfw:commentRss>
        <trackback:ping>http://newitup.com/services/trackbacks/133.aspx</trackback:ping>
    </entry>
    <entry>
        <title>Book Review:  Microsoft .NET: Architecting Applications For The Enterprise</title>
        <link rel="self" type="text/html" href="http://newitup.com/archive/2010/09/13/book-review--microsoft-.net-architecting-applications-for-the-enterprise.aspx" />
        <id>http://newitup.com/archive/2010/09/13/book-review--microsoft-.net-architecting-applications-for-the-enterprise.aspx</id>
        <published>2010-09-13T03:43:18-05:00:00</published>
        <updated>2010-09-14T18:11:30Z</updated>
        <content type="html">I was recommended this book by a co-worker who had read it.  I did my due diligence and read reviews on Amazon.com that all spoke of it favorably and checking out the table of contents and such, it seemed to cover things I was interested in learning about.  Put simply, it seemed to be a book that would dive a little deeper into some of that patterns that Martin Fowler exposed in his &lt;a href="javascript:void(0);/*1284245590088*/"&gt;Patterns Of Enterprise Application Architecture&lt;/a&gt; book.&lt;br /&gt;
&lt;br /&gt;
I'll get to the point - I was severely disappointed by this book.  While it did continually reference Fowler's PoEAA book, it didn't really elaborate any of them moreso than the original PoEAA book does.  The rare, short example that was given was always in C#, but other than that, it doesn't do much than rehash the intent of the patterns.&lt;br /&gt;
&lt;br /&gt;
For example, in the Business Logic Layer section of Microsoft .NET: Architecting Applications For The Enterprise, they briefly explain what should be a part of the business logic layer and then proceed to explain four types of model for the BLL - the transaction script, the table module, the active record and the domain model.  These are all gleaned right from Fowler's book and do little to elaborate on Fowler's explanations.&lt;br /&gt;
&lt;br /&gt;
Furthermore, the first section of the book is a bunch of excerpts from IEEE whitepapers and a rehash of good design principles (favoring composition over inheritance, the single responsibility principle, etc.)&lt;br /&gt;
&lt;br /&gt;
I think my biggest disappointment out of the book was that I didn't learn anything.  Everything in the book was stuff I already knew.  And as I always say... I'm far from a master programmer.  It's just that much of the book is built on ideas that are covered in so many books (such as the design principles) and the part of the book that I had the most interest in - the part that dealt with organizing and writing code for enterprise systems, was really light on examples and there was no depth.&lt;br /&gt;
&lt;br /&gt;
This book is really just PoEAA where the examples are specific to .NET.  The only people I could possibly recommend this book to are people who haven't heard of, or read, the PoEAA book and are looking for it's NET-specific counterpart.  Almost everything you find in it can be found elsewhere, covered more thoroughly.&lt;img src="http://newitup.com/aggbug/132.aspx" width="1" height="1" /&gt;</content>
        <wfw:comment>http://newitup.com/comments/132.aspx</wfw:comment>
        <slash:comments>81</slash:comments>
        <wfw:commentRss>http://newitup.com/comments/commentRss/132.aspx</wfw:commentRss>
        <trackback:ping>http://newitup.com/services/trackbacks/132.aspx</trackback:ping>
    </entry>
    <entry>
        <title>Using ASP.NET MVC for cleaner Ajax handling in a WebForms app</title>
        <link rel="self" type="text/html" href="http://newitup.com/archive/2010/09/09/using-asp.net-mvc-for-cleaner-ajax-handling-in-a-webforms.aspx" />
        <id>http://newitup.com/archive/2010/09/09/using-asp.net-mvc-for-cleaner-ajax-handling-in-a-webforms.aspx</id>
        <published>2010-09-09T01:54:43-05:00:00</published>
        <updated>2010-09-09T04:29:50Z</updated>
        <content type="html">&lt;h3&gt;ASP.NET WebForms And Ajax Go  Together Like Oil And Water&lt;/h3&gt;
&lt;p&gt;In the past few months, I've seen some of the  pretty ugly ways in which ASP.NET WebForms works with Ajax.  &lt;/p&gt;
&lt;p&gt;I've seen  the Microsoft Ajax Toolkit which is just embarrassing.  Once again,  Microsoft tries to lock you in to their stuff rather than the industry  standard (jQuery/Prototype) and also provides limited functionality in  the form of Ajax web controls and other proprietary stuff.  Very nice,  but we're big boys now.  We don't need the coddling and MS telling us to  use their stuff and everything will be OK. &lt;/p&gt;
&lt;p&gt;I've seen using a .NET web  service and having your Ajax requests call it to get the data they  need.  It's better than the Microsoft Ajax Toolkit, but it still leaves  something to be desired.  As far as I can tell, you still have to  reference the web service in your page with an &amp;lt;asp:ScriptManager&amp;gt;  tag and it also seems like you're making a poor technology choice by  building out a web service just to get some data back to your system  without the full post back.&lt;/p&gt;
&lt;p&gt;Slightly better, but still crummy, is marking  methods in your code-behind with the [WebMethod] attribute and making  them static so you can get at them in aspx/ascx pages via ajax calls.   This is nice because now you can start to use jQuery instead of relying  on Microsoft's Ajax implementation, but I see two problems with it.   First, the methods have to be static and attributed as WebMethods.  The  static methods don't let you use instance variables of the class without  a lot of ugly and odd workarounds.  Second - as is the case with a lot  of WebForms code, since it's code-behinds you either have your Ajax  methods duplicated across code-behinds or you have different WebMethods  scattered in different code-behinds which is pretty messy.  It's the  same sort of spaghetti code and coupling of responsibilities that a lot  of people see as a big problem with the WebForm/code-behind model. &lt;/p&gt;
&lt;p&gt;Plus - with  all these solutions, I'm pretty sure you need to use a third-party (or  write your own) solution to serialize your returned objects as JSON.&lt;/p&gt;
&lt;p&gt;So what's  the solution?&lt;/p&gt;
&lt;h3&gt;ASP.NET  MVC Works Cleanly With Ajax Out Of The Box&lt;/h3&gt;
&lt;p&gt;Finally, with ASP.NET MVC,  jQuery and Ajax are finally given the attention they deserve.  When you  create a new ASP.NET MVC project in Visual Studio, it creates a Scripts  folder with jquery.js already in it!  But their support for jQuery and  Ajax goes way beyond that.&lt;/p&gt;
&lt;p&gt;I'm not going to get too into the nitty gritty  details on ASP.NET MVC - if you want that, there are plenty of resources on the web.  But on a high level, the things that make Ajax with ASP.NET MVC  so nice are:&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;URLs are just routes to resources, in this case a  controller and an action.  Your URL is not pointing directly to a  physical ASPX file.  This means you can just point your Ajax request to a  controller action and have access to whatever data the controller  action returns when its done processing.  And since the URL points to  the function where the data is coming from, you're less likely to have  duplicated code.  No matter where you need the same data, you can always  just point to that controller action as a URL.&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
    &lt;li&gt;ASP.NET  MVC comes with a JSON serializer.  You simply return a JsonResult from  your controller action and the objects are converted to JSON for you.   This means that you also don't have to mark your methods as WebMethods,  or make them static or anything like that.  They're just regular methods  that return JSON and they're easily called via the controller/action  URL.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here's  an insanely simple example to show just how simplified the code can be:&lt;/p&gt;
&lt;p style="min-height: 8pt; height: 8pt; padding: 0px;"&gt;First, the  javascript: &lt;br /&gt;
&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt; &lt;style type="text/css"&gt;&lt;![CDATA[
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: Consolas, "Courier New", Courier, Monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp { background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}

.csharpcode .lnum { color: #606060; }
]]&gt;&lt;/style&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt; &lt;span class="attr"&gt;type&lt;/span&gt;&lt;span class="kwrd"&gt;="text/javascript"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt; &lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;        $(document).ready(&lt;span class="kwrd"&gt;function&lt;/span&gt;() {&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;            $(&lt;span class="str"&gt;'#ajaxBtn'&lt;/span&gt;).click(&lt;span class="kwrd"&gt;function&lt;/span&gt;() {&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;                $.ajax({&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;                    type: &lt;span class="str"&gt;'POST'&lt;/span&gt;,&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;                    url: &lt;span class="str"&gt;'/Home/GetFakeObjects'&lt;/span&gt;,&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;                    success: &lt;span class="kwrd"&gt;function&lt;/span&gt;(data) { updateDocument(data) },&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;                    error: updateDocument&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;                });&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;            });&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt;        });&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;        &lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  14:  &lt;/span&gt;        &lt;span class="kwrd"&gt;function&lt;/span&gt; updateDocument(data) {&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  15:  &lt;/span&gt;            $.each(data, &lt;span class="kwrd"&gt;function&lt;/span&gt;(key, value) {&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  16:  &lt;/span&gt;                $(&lt;span class="str"&gt;'#results'&lt;/span&gt;).append(&lt;span class="str"&gt;'&amp;lt;li&amp;gt;'&lt;/span&gt; + value +&lt;span class="str"&gt;'&amp;lt;/li&amp;gt;'&lt;/span&gt;);&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  17:  &lt;/span&gt;            });&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  18:  &lt;/span&gt;        }&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  19:  &lt;/span&gt;        &lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  20:  &lt;/span&gt;&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;And now,  the ASP.NET Controller and Action:&lt;/p&gt;

&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt; &lt;style type="text/css"&gt;&lt;![CDATA[
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: Consolas, "Courier New", Courier, Monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp { background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}

.csharpcode .lnum { color: #606060; }
]]&gt;&lt;/style&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;[HandleError]&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; HomeController : Controller&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;{&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;     &lt;span class="kwrd"&gt;public&lt;/span&gt; JsonResult GetFakeObjects()&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;     {&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;          var returnedObjects = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;          returnedObjects.Add(&lt;span class="str"&gt;"Dan Donahue"&lt;/span&gt;);&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;          returnedObjects.Add(&lt;span class="str"&gt;"Somebody Else"&lt;/span&gt;);&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;          returnedObjects.Add(&lt;span class="str"&gt;"Another Person"&lt;/span&gt;);&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt; &lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;          &lt;span class="kwrd"&gt;return&lt;/span&gt; Json(returnedObjects);&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt;     }&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p style="min-height: 8pt; height: 8pt; padding: 0px;"&gt; &lt;/p&gt;
&lt;p&gt;I don't  think the code needs much explanation if you've played with jQuery and  Ajax before, but as you can see in the javascript, the url that we're  posting to via Ajax is "Home/GetFakeObjects" which ASP.NET MVC routes to  new HomeController().GetFakeObjects()  and that method returns a  JsonResult with that list of people's names.  This data is then  available in the successMethod of the ajax request.  Simple as cake.&lt;/p&gt;
&lt;h3&gt;But My App  Isn't Built With ASP.NET MVC&lt;/h3&gt;
&lt;p&gt; Never fear... it doesn't have  to be.  You can actually mix ASP.NET MVC with ASP.NET WebForms in the  same project.  This is great if you want to start moving your project to  ASP.NET MVC piece by piece, or if you want to just take advantage of  the Ajax benefits that I described above without converting your entire  web app to ASP.NET MVC.&lt;br /&gt;
&lt;/p&gt;
&lt;p&gt;Hit the links below for information  on mixing the two technologies in your app.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx" target="_blank"&gt;http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.packtpub.com/article/mixing-asp.net-webforms-and-asp.net-mvc" target="_blank"&gt;http://www.packtpub.com/article/mixing-asp.net-webforms-and-asp.net-mvc&lt;/a&gt;&lt;/p&gt;
&lt;p style="min-height: 8pt; height: 8pt; padding: 0px;"&gt; &lt;/p&gt;
&lt;h3&gt;Wrap Up&lt;/h3&gt;
&lt;p&gt; There  is only so much finagling you should put up with to solve a problem.   This is especially true in code when "finagling" typically means using  hacks or generally degrading the quality of the code you're writing in  order to work around a problem.  When that happens, sometimes it's best  to just look into bringing in a better technology that has already  solved the problem nicely, rather than desperately looking for the next  "quick fix" which will ultimately cause more problems down the line that  will need additional "quick fixes".  As the Pragmatic Programmer  says... quick fixes are quick sand.&lt;/p&gt;
&lt;p&gt;So if you have a WebForms app that  you're jumping through hoops to add jQuery too, maybe bringing in  ASP.NET MVC to, at the very least, handle the Ajax portions, is a good  alternative.&lt;/p&gt;&lt;img src="http://newitup.com/aggbug/131.aspx" width="1" height="1" /&gt;</content>
        <wfw:comment>http://newitup.com/comments/131.aspx</wfw:comment>
        <slash:comments>74</slash:comments>
        <wfw:commentRss>http://newitup.com/comments/commentRss/131.aspx</wfw:commentRss>
        <trackback:ping>http://newitup.com/services/trackbacks/131.aspx</trackback:ping>
    </entry>
    <entry>
        <title>Book Review:  Code Complete</title>
        <link rel="self" type="text/html" href="http://newitup.com/archive/2010/05/12/book-review--code-complete.aspx" />
        <id>http://newitup.com/archive/2010/05/12/book-review--code-complete.aspx</id>
        <published>2010-05-12T09:15:28-05:00:00</published>
        <updated>2010-05-12T09:15:28Z</updated>
        <content type="html">&lt;p&gt;I've been trying to be constantly reading a book for about the past year and a half now.  And in addition, I started a dev book group where I work, where we pick a book and read it a certain amount each week and then meet for an hour to discuss that section - whether it be making decisions on whether this is something we want to do as a department, or how we can apply the topic to our projects, etc.&lt;/p&gt;
&lt;p&gt;The latest book we just finished was &lt;span style="font-weight: bold;"&gt;Code Complete&lt;/span&gt;.  I feel like I was long overdue reading this one as I've heard a few times in the past that this was one of those required reading books on programming.  Actually, on more than one occasion, I've been asking during a job interview what books I've read and liked the most and after giving my list, the interviewer has said "all great books... the only one I'd add is Code Complete".  So I was pretty excited to finally read through this one.&lt;/p&gt;
&lt;p&gt;I've broken up my review into a section of positives, negatives and then a summary.  I find that helpful because sometimes reviews get too verbose and will be filled with double speak such as "the paragraph on *whatever* was great, except ..." .  So I'm going to try to avoid that and just talk about what I liked, what I didn't.&lt;/p&gt;
&lt;p&gt;&lt;span style="font-weight: bold;"&gt;POSITIVE:&lt;/span&gt;&lt;br /&gt;
&lt;/p&gt;
&lt;p&gt;I can't stress enough how much good information  this book is packed with.  There's a ton of information to digest about a  wide range of topics - from how to organize and comment your code to team dynamics, estimation tipis and even programmer human characteristics - this book does a great job of taking a good  1000ft.view of a lot of aspects of software development and also gives a  lot of "read this next" resources for topics that you might want to  delve deeper into.  McConnell (the author) does a pretty good of using  case studies to back up his points.  And while some of the information  is a little out of date in the book (happens often in these types of  books... the software industry just moves too fast), a lot of the  information is plenty applicable no matter what language you develop in,  type of development you do, etc.&lt;/p&gt;
&lt;span style="font-weight: bold;"&gt;NEGATIVE:&lt;/span&gt;&lt;br /&gt;
&lt;p&gt;First off - this book is long... REALLY long.  We actually  skipped a few chapters early on during the book group and it still felt like the book would  never end.  That's a bit nitpicky though as the Lord Of The Rings  trilogy is long as hell, but it's a great read &lt;img class="jive_macro&amp;#xD;&amp;#xA;jive_emote" jivemacro="emoticon" ___jive_emoticon_name="happy" src="http://tspace.totalattorneys.com/4.0.4/images/emoticons/happy.gif" mce_src="/4.0.4/images/emoticons/happy.gif" alt="" /&gt;  I think the biggest disappointment to me was that a lot of  the information put forth was stuff that you learn your first few years  in professional software development and it just becomes common sense.   More often than not, I found myself (and I believe some of the others  in the group) saying "these are great points - but I already knew this"  or "these are great points - but this is common sense".  And then, of  course, the problem with a 1000ft. view that I mentioned earlier is that  if you find yourself interested in one of the ideas that he presents,  you would love to learn more, but it's just not there.  That's not a  problem with this book in particular... but I guess my preference is  with more directed learning books.  Books that take a smaller array of topics  and really delve into them in greater detail.&lt;/p&gt;
&lt;p style="font-weight: bold;"&gt;SUMMARY:&lt;br /&gt;
&lt;/p&gt;
&lt;p&gt;&lt;span style="font-weight: bold;" /&gt;I'm  not sure I'd ever read this one again.  Like I said, it just contains  too much information that I already knew.. and I don't even pretend to be a software guru by any stretch of the imagination.&lt;/p&gt;
However, this  book is far from worthless.  I think this book should be required  reading in a college course on programming, or the first book a young  developer reads before ever working on their first project.  This is  type of stuff that you can either learn organically by being in the  industry for a while and seeing it all come to life in both good and bad  ways in your projects, or you can just read this book and enter the  industry with this knowledge in hand.  It'll put you on level playing  ground with people who take the long path.
&lt;p&gt;I also think  this is one of those books that would be a checkmark in the thumbs up  column if a prospective new employee had mentioned reading it.  It would  be a sign that the developer was equipped with knowledge of good  programming practices and ideas (of course - whether they apply them is a  different story, but you'd rarely get that out of an interview anyway).&lt;/p&gt;
&lt;p&gt;Bottom  line... new developers should be forced to read this book.  Older  developers probably already know most of what it contains.  But it was nice to get some of this knowledge reiterated (much like how I re-read The Pragmatic Programmer every year or two just to get rejuvenated) and also have the case studies to back up the information with statistics.  It's one thing to do something a certain way because it works for you, and even better when it turns out that it works for the entire industry :)&lt;/p&gt;&lt;img src="http://newitup.com/aggbug/127.aspx" width="1" height="1" /&gt;</content>
        <wfw:comment>http://newitup.com/comments/127.aspx</wfw:comment>
        <slash:comments>69</slash:comments>
        <wfw:commentRss>http://newitup.com/comments/commentRss/127.aspx</wfw:commentRss>
        <trackback:ping>http://newitup.com/services/trackbacks/127.aspx</trackback:ping>
    </entry>
    <entry>
        <title>Linq To Sql Web App Lifetime Management - Take 1</title>
        <link rel="self" type="text/html" href="http://newitup.com/archive/2009/12/02/linq-to-sql-web-app-lifetime-management---take-1.aspx" />
        <id>http://newitup.com/archive/2009/12/02/linq-to-sql-web-app-lifetime-management---take-1.aspx</id>
        <published>2009-12-02T08:45:07-06:00:00</published>
        <updated>2009-12-02T08:45:07Z</updated>
        <content type="html">&lt;style type="text/css"&gt;&lt;![CDATA[csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: Consolas, &amp;quot;Courier New&amp;quot;, Courier, Monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ }  .csharpcode pre { margin: 0em; }  .csharpcode .rem { color: #008000; }  .csharpcode .kwrd { color: #0000ff; }  .csharpcode .str { color: #006080; }  .csharpcode .op { color: #0000c0; }  .csharpcode .preproc { color: #cc6633; }  .csharpcode .asp { background-color: #ffff00; }  .csharpcode .html { color: #800000; }  .csharpcode .attr { color: #ff0000; }  .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; }  .csharpcode .lnum { color: #606060; }]]&gt;&lt;/style&gt; I was asked to help another project team at work to come up with a good way to manage Linq To Sql data contexts on their project.  Their current situation is that they open and use a datacontext wherever needed, but often run into problems where they're trying to save entities with expired contexts or opening too many connections to the database to grab the same record multiple times.  They're not fully utilizing the datacontext's features such as the &lt;a href="javascript:void(0);/*1259763267838*/"&gt;Identity Map&lt;/a&gt; or &lt;a href="javascript:void(0);/*1259763303898*/"&gt;Unit Of Work&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
I haven't had much experience with Linq prior to being asked to help, but I knew the basics.  For the rest, I decided to do a bunch of blog reading on the subject to help out with my implementation.  My criteria for a good solution was the following:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight: bold;"&gt;Ease Of Use / Clean Syntax&lt;/span&gt;&lt;br /&gt;
I figured this one was self-explanatory.  First, I didn't want to get into a huge architecture if I didn't have to and furthermore, I figured that if it wasn't easy to implement and use, no one would want to do the work to implement it.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight: bold;"&gt;Unit Testable:&lt;/span&gt;&lt;br /&gt;
I like to do unit testing and wanted to be able to write tests that didn't actually hit the database.  I wanted to be able to write mock versions of the implementation instead for tests so I could control them during my tests.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight: bold;"&gt;Unit Of Work/Lifetime Management:&lt;/span&gt;&lt;br /&gt;
This was to solve the problem that they came to with me in the first place.  Microsoft, as well as common sense, indicate that you should really only have one datacontext around per request for web applications.  This seems to make sense since the datacontext already is built like a unit of work (it records all changes to entities, inserts and deletes and waits until SubmitChanges() to actually persist them to the database).&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight: bold;"&gt;Validation Of Entities:&lt;/span&gt;&lt;br /&gt;
Another concern the team had was how to validate entities before saving them.  Their current implementation was to create partial classes for each entity and create custom attributes to perform validation.  I did not include my solution as part of the prototype I came up, but I actually suggested they pull the validation out into separate Specification objects - this way, they can keep the entity classes to solely what Microsoft provides them and the Specification objects can be reused, as well as making more explicit the business rules around a valid entity - something I learned from reading Eric Evans' DDD book.&lt;br /&gt;
&lt;br /&gt;
What I came up with was pretty simple. I mostly just took a lot of what other bloggers were suggesting and stripped out a lot of stuff I didn't think was necessary at the moment.  Not that I felt others were over-complicating the matter, but they were showing examples of things they needed for their projects which may not necessarily be needed in this one.  And taking the YAGNI approach, I felt like I should keep it as simple as possible, knowing that I could add in the desired features later if necessary.&lt;br /&gt;
&lt;br /&gt;
So, finally, here is the design I came up with...&lt;br /&gt;
&lt;br /&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; UnitOfWork : IUnitOfWork&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;     &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; EntityClassesDataContext context;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt; &lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;     &lt;span class="kwrd"&gt;public&lt;/span&gt; UnitOfWork()&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;     {&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;          context = &lt;span class="kwrd"&gt;new&lt;/span&gt; EntityClassesDataContext();&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;     }&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt; &lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;     &lt;span class="kwrd"&gt;public&lt;/span&gt; Table&amp;lt;T&amp;gt; GetTable&amp;lt;T&amp;gt;() &lt;span class="kwrd"&gt;where&lt;/span&gt; T : &lt;span class="kwrd"&gt;class&lt;/span&gt;&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;     {&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt;          &lt;span class="kwrd"&gt;return&lt;/span&gt; context.GetTable&amp;lt;T&amp;gt;();&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;     }&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  14:  &lt;/span&gt; &lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  15:  &lt;/span&gt;     &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SubmitChanges()&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  16:  &lt;/span&gt;     {&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  17:  &lt;/span&gt;          context.SubmitChanges();&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  18:  &lt;/span&gt;     }&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  19:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;br /&gt;
This UnitOfWork class just wraps the DataContext and implements an IUnitOfWork interface which can then be used in the rest of the system, so that we can mock it during tests.  It just provides the ability to get a table (which can then be queried, or inserted to/deleted from) and run SubmitChanges().  I considered having SubmitChanges() be run automatically at the end of each request, but I felt like that was dangerous as you may not want all changes submitted - I want to make it more explicit and require programmers to call that function when they wanted their changes persisted.&lt;br /&gt;
&lt;br /&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; UnitOfWorkFactory&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;     &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; HTTP_CONTEXT_KEY = &lt;span class="str"&gt;"SFT.UnitOfWork.Factory.Context.Key"&lt;/span&gt;;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt; &lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;     &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnitOfWork GetUnitOfWork()&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;     {&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;          &lt;span class="kwrd"&gt;if&lt;/span&gt; (HttpContext.Current != &lt;span class="kwrd"&gt;null&lt;/span&gt;)&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;          {&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;               &lt;span class="kwrd"&gt;if&lt;/span&gt; (!HttpContext.Current.Items.Contains(HTTP_CONTEXT_KEY))&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;               {&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;                    HttpContext.Current.Items.Add(HTTP_CONTEXT_KEY, Activator.CreateInstance(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(UnitOfWork)));&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt;               }&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;               &lt;span class="kwrd"&gt;return&lt;/span&gt; (IUnitOfWork)HttpContext.Current.Items[HTTP_CONTEXT_KEY];&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  14:  &lt;/span&gt;          }&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  15:  &lt;/span&gt;          &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; Exception(&lt;span class="str"&gt;"No current HttpContext found."&lt;/span&gt;);&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  16:  &lt;/span&gt;     }&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  17:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;br /&gt;
This factory is used to get the current UnitOfWork which is stored in HttpContext's Items collection.  It's pretty simple.  If you ask for the current UnitOfWork and it hasn't been created for the current request yet, it creates it and puts into the Items collection.  Then, it returns it.  Otherwise, if it already exists, it returns the one that's in the Item's collection already.  From what I read, this should guarantee that you always use the single, per-request DataContext which means you take advantage of the Identity Map (instead of loading the same entity from the db multiple times) and have all your changes in a request tracked.&lt;br /&gt;
&lt;br /&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; DefaultPresenter(IDefaultView view) : &lt;span class="kwrd"&gt;this&lt;/span&gt;(view, UnitOfWorkFactory.GetUnitOfWork(), &lt;span class="kwrd"&gt;new&lt;/span&gt; DebtorRepository())&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt; &lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; DefaultPresenter(IDefaultView view, IUnitOfWork unitOfWork, IDebtorRepository repository)&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;{&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;     &lt;span class="kwrd"&gt;this&lt;/span&gt;.view = view;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;     &lt;span class="kwrd"&gt;this&lt;/span&gt;.unitOfWork = unitOfWork;&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;     &lt;span class="kwrd"&gt;this&lt;/span&gt;.repository = repository;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;br /&gt;
And this is how I used the factory in my prototype.  Dependency injection allows for unit testing because in the unit tests, I can use the 2nd constructor and pass in a mock of the IUnitOfWork, but in production, I can use the above constructor which calls on the UnitOfWork factory to get the concrete UnitOfWork class that wraps the Linq datacontext.&lt;br /&gt;
&lt;br /&gt;
I know that IoC containers would get me down to one constructor, but for the purposes of the prototype, I didn't want to do the extra work.  However, itt's probably something I would suggest if this is used in an actual project. &lt;br /&gt;
&lt;br /&gt;
The last thing which I won't post is that I use Repositories for getting data.  I do that cut down on the duplication of queries across the codebase and also to abstract out the Table classes that come with the datacontext since they're not easily mocked for testing.  I read about ways that you could mock them out and provide data from an in-memory data store during testing, but when I'm testing the presenters, I don't want to have to worry about all the overhead of setting that up in my test, so I'd rather just put it behind an IRepository interface.  When it comes time to test the Repository classes, I can focus on how to write the tables with an in-memory data collection.&lt;br /&gt;
&lt;br /&gt;
And that's it.  I would love some feedback as this is my first time taking up something like this.  Is there any obvious, or not-so-obvious flaw in this design that I'm missing?  Are there any ways it could be improved?  Your comments would be greatly appreciated.&lt;img src="http://newitup.com/aggbug/124.aspx" width="1" height="1" /&gt;</content>
        <wfw:comment>http://newitup.com/comments/124.aspx</wfw:comment>
        <slash:comments>72</slash:comments>
        <wfw:commentRss>http://newitup.com/comments/commentRss/124.aspx</wfw:commentRss>
        <trackback:ping>http://newitup.com/services/trackbacks/124.aspx</trackback:ping>
    </entry>
    <entry>
        <title>Delegates =&gt; Lambdas, Pt. 4:  .NET Helpers (The Final Episode)</title>
        <link rel="self" type="text/html" href="http://newitup.com/archive/2009/08/13/delegates--lambdas-pt.-4--.net-helpers-the-final.aspx" />
        <id>http://newitup.com/archive/2009/08/13/delegates--lambdas-pt.-4--.net-helpers-the-final.aspx</id>
        <published>2009-08-13T13:32:00-05:00:00</published>
        <updated>2009-12-02T08:09:23Z</updated>
        <content type="html">&lt;style type="text/css"&gt;&lt;![CDATA[
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: Consolas, "Courier New", Courier, Monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp { background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}

.csharpcode .lnum { color: #606060; }
]]&gt;&lt;/style&gt;
&lt;p&gt;&lt;span style="font-weight: bold;"&gt;&lt;span style="font-style: italic;"&gt;This is a series I created on my company's internal intranet for a few young developers.  However, I thought it might be useful to anyone, so I wanted to make it public.&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;     &lt;a href="../../../../archive/2009/08/13/delegates--lambdas-pt.-1-whats-a-delegate.aspx" title="Title of this entry." id="viewpost_ascx_TitleUrl"&gt;Delegates =&amp;gt; Lambdas, Pt. 1: What's A Delegate?&lt;/a&gt;     &lt;/li&gt;
    &lt;li&gt;     &lt;a href="../../../../archive/2009/08/13/delegates--lambdas-pt.-2-anonymous-methods--inline-delegates.aspx" title="Title of this entry." id="viewpost_ascx_TitleUrl"&gt;Delegates =&amp;gt; Lambdas, Pt. 2: Anonymous Methods == Inline Delegates&lt;/a&gt;     &lt;/li&gt;
    &lt;li&gt;     &lt;a href="../../../../archive/2009/08/13/delegates--lambdas-pt.-3-lambda-expressions.aspx" title="Title of this entry." id="viewpost_ascx_TitleUrl"&gt;Delegates =&amp;gt; Lambdas, Pt. 3: Lambda Expressions&lt;/a&gt;     &lt;/li&gt;
    &lt;li&gt;     &lt;a href="../../../../archive/2009/08/13/delegates--lambdas-pt.-4--.net-helpers-the-final.aspx" title="Title of this entry." id="viewpost_ascx_TitleUrl"&gt;Delegates =&amp;gt; Lambdas, Pt. 4:  .NET Helpers (The Final Episode)&lt;/a&gt;     &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;br /&gt;
&lt;/p&gt;
&lt;p&gt;Ok - this is the last part of my series about delegates and lambdas.  Finally.  But I wanted to mention a few helpers that .NET provides to make it easier to use delegates and lambdas in your code.&lt;/p&gt;
&lt;p&gt;If you remember back to the &lt;a href="http://newitup.com/archive/2009/08/13/delegates--lambdas-pt.-1-whats-a-delegate.aspx"&gt;first post&lt;/a&gt; of the series, I mentioned that to declare a delegate to be used as a parameter or anything else, you had to do this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;delegate&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; Filter(TeamDTO team);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Well - .NET makes it slightly less tedious with the use of three framework classes, namely Action&amp;lt;T&amp;gt;, Predicate&amp;lt;T&amp;gt; and Func&amp;lt;T&amp;gt;.  Let's look at an example of each.&lt;/p&gt;
&lt;h3&gt;Action&amp;lt;T&amp;gt;: &lt;/h3&gt;
&lt;p&gt;This class encapsulates a delegate that takes one parameter and does not return a value.  Meaning, it is a contract that specifies one input parameter, the type of which is specified as a generic, and a void return type.  This is useful for a variety of scenarios, but let me show you just one.&lt;/p&gt;
&lt;p&gt;If you've noticed, when you create a List&amp;lt;T&amp;gt;, one of the methods on that list that is built-in for .NET is ForEach(Action&lt;t&gt; action).  Using that, you can build for-each loops using delegates/lambdas.  See below:&lt;/t&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; List&amp;lt;TeamDTO&amp;gt; allTeams = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;TeamDTO&amp;gt;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;                                          {&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;                                              &lt;span class="kwrd"&gt;new&lt;/span&gt; TeamDTO(&lt;span class="str"&gt;"Flyers"&lt;/span&gt;, &lt;span class="str"&gt;"East"&lt;/span&gt;),&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;                                              &lt;span class="kwrd"&gt;new&lt;/span&gt; TeamDTO(&lt;span class="str"&gt;"Blackhawks"&lt;/span&gt;, &lt;span class="str"&gt;"West"&lt;/span&gt;),&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;                                              &lt;span class="kwrd"&gt;new&lt;/span&gt; TeamDTO(&lt;span class="str"&gt;"Blue Jackets"&lt;/span&gt;, &lt;span class="str"&gt;"West"&lt;/span&gt;),&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;                                              &lt;span class="kwrd"&gt;new&lt;/span&gt; TeamDTO(&lt;span class="str"&gt;"Capitals"&lt;/span&gt;, &lt;span class="str"&gt;"East"&lt;/span&gt;)&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;                                          };&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt; &lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;Action&amp;lt;TeamDTO&amp;gt; printTeam = x =&amp;gt; Response.Write(x.TeamName);&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;allTeams.ForEach(printTeam);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Or, you can just inline it all with a lambda expression like this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;allTeams.ForEach(x =&amp;gt; Response.Write(x.TeamName));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;By the way, &lt;strong&gt;Action&amp;lt;T&amp;gt;&lt;/strong&gt; also comes in a few additional flavors, those being &lt;strong&gt;Action&amp;lt;T1, T2&amp;gt;&lt;/strong&gt;, &lt;strong&gt;Action&amp;lt;T1, T2, T3&amp;gt;&lt;/strong&gt; and &lt;strong&gt;Action&amp;lt;T1, T2, T3, T4&amp;gt;&lt;/strong&gt;.  As you can probably guess, this just allows you to use them to define up to 4 input parameter types - the return value in all situations is still void.&lt;/p&gt;
&lt;h3&gt;Predicate&amp;lt;T&amp;gt;:&lt;/h3&gt;
&lt;p&gt;This is another .NET class representing another standard delegate situation.  This one takes one parameter and returns a boolean value.  This is actually PERFECT for our filter situation.  Instead of having to create a delegate like the one at the top of this post, we can use this in it's place, since it does the same thing (takes in one argument, it's generic, but we can specify we want it to be of type TeamDTO and returns a boolean value).  So let's see it in action:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IList&amp;lt;TeamDTO&amp;gt; SelectTeamsByFilter(IEnumerable&amp;lt;TeamDTO&amp;gt; teams, Predicate&amp;lt;TeamDTO&amp;gt; filter)&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;     var filteredTeams = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;TeamDTO&amp;gt;();&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;     &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (TeamDTO team &lt;span class="kwrd"&gt;in&lt;/span&gt; teams)&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;     {&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;          &lt;span class="kwrd"&gt;if&lt;/span&gt; (filter(team))&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;          {&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;               filteredTeams.Add(team);&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;          }&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;     }&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt; &lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt;     &lt;span class="kwrd"&gt;return&lt;/span&gt; filteredTeams;&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Compare this piece of code to the one in the first post of the series and you see that I just replaced the delegate object I created with the Predicate - why re-invent what .NET already has?&lt;/p&gt;
&lt;h3&gt;Func&amp;lt;T&amp;gt;:&lt;/h3&gt;
&lt;p&gt;This one actually comes in a bunch of different flavors and is arguably the most powerful.  And actually, if you look at the MSDN documentation, &lt;strong&gt;Func&amp;lt;T&amp;gt; &lt;/strong&gt;is actually not even the correct form of the delegate - but this is how it's used in conversation.  The actual name is &lt;strong&gt;Func&amp;lt;TResult&amp;gt;&lt;/strong&gt;.  And hopefully by now you're catching on and can guess what that means.  &lt;strong&gt;Func&amp;lt;TResult&amp;gt; &lt;/strong&gt;allows you to specify a delegate with no input parameters and a return value of &lt;strong&gt;TResult.&lt;/strong&gt;  Like &lt;strong&gt;Action&amp;lt;T&amp;gt;&lt;/strong&gt;, &lt;strong&gt;Func&amp;lt;TResult&amp;gt; &lt;/strong&gt;has variations that allow you to specify up to 4 input parameters, in addition to the return type.  So you have &lt;strong&gt;Func&amp;lt;TResult&amp;gt;, Func&amp;lt;T, TResult&amp;gt;, Func&amp;lt;T1, T2, TResult&amp;gt;, Func&amp;lt;T1, T2, T3, TResult&amp;gt; &lt;/strong&gt;and &lt;strong&gt;Func&amp;lt;T1, T2, T3, T4, TResult&amp;gt;.   &lt;/strong&gt;Keep in mind if you use these that the last value will be the return value in any situation.&lt;/p&gt;
&lt;p&gt;As a really simple example, imagine I wanted a function that printed all of the team names in a list.  Here it is:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;Func&amp;lt;TeamDTO, &lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; printTeamName = x =&amp;gt; x.TeamName;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;&lt;span class="kwrd"&gt;foreach&lt;/span&gt; (TeamDTO team &lt;span class="kwrd"&gt;in&lt;/span&gt; allTeams)&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;{&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;     printTeamName(team);&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;The first line defines a &lt;strong&gt;Func&amp;lt;T, TResult&amp;gt; &lt;/strong&gt;that accepts a TeamDTO object and returns a string.  Then the lambda shows that &lt;em&gt;x&lt;/em&gt; is the input parameter and on the other side of the =&amp;gt; is the return statement &lt;em&gt;x.TeamName&lt;/em&gt;.  The other part is just a for-loop which invokes the delegate.&lt;/p&gt;
&lt;p&gt;So that's it for my series on delegates and lambda expressions.  But it won't be the last time you hear about them.  A lot of the examples in these posts were scholastic in nature, but they probably left you thinking that aside from being neat, where was the benefit?  Where all of these helpers, and delegates in general, become really powerful is when you combine them with other features of .NET.  So expect to see more of these in future posts.  But hopefully these gave you a few ideas about where you could benefit from the use of delegates, or at least help your understanding about what exactly is going on when you type code into your IDE of choice.&lt;/p&gt;
&lt;p&gt;Any questions/comments/feedback? Feel free to comment any of the posts.&lt;/p&gt;&lt;img src="http://newitup.com/aggbug/123.aspx" width="1" height="1" /&gt;</content>
        <wfw:comment>http://newitup.com/comments/123.aspx</wfw:comment>
        <slash:comments>44</slash:comments>
        <wfw:commentRss>http://newitup.com/comments/commentRss/123.aspx</wfw:commentRss>
        <trackback:ping>http://newitup.com/services/trackbacks/123.aspx</trackback:ping>
    </entry>
</feed>
