<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>Heartysoft.com - Reverberations of .NET</title><link>http://www.heartysoft.com:80/</link><description>Heartysoft.com - Reverberations of .NET</description><item><title>Roughing It Session at the Canary Wharf Dot Net User Group</title><link>http://www.heartysoft.com:80/roughing-it-canary-wharf</link><description>&lt;p&gt;Here are the slides and code from my recent talk at the Canary Wharf Dot Net User Group (lots of code….few slides).&lt;/p&gt;  &lt;div id="__ss_12826363" style="width: 425px"&gt;&lt;strong style="margin: 12px 0px 4px; display: block"&gt;&lt;a title="Roughing It" href="http://www.slideshare.net/ashic/roughing-it"&gt;Roughing It&lt;/a&gt;&lt;/strong&gt;&lt;object id="__sse12826363" width="425" height="355"&gt;&lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=slides-120507035952-phpapp02&amp;amp;stripped_title=roughing-it&amp;amp;userName=ashic" /&gt;&lt;param name="allowFullScreen" value="true" /&gt;&lt;param name="allowScriptAccess" value="always" /&gt;&lt;param name="wmode" value="transparent" /&gt;&lt;embed name="__sse12826363" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=slides-120507035952-phpapp02&amp;amp;stripped_title=roughing-it&amp;amp;userName=ashic" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" width="425" height="355"&gt;&lt;/embed&gt;&lt;/object&gt; &lt;div style="padding-bottom: 12px; padding-top: 5px; padding-left: 0px; padding-right: 0px"&gt;View more &lt;a href="http://www.slideshare.net/"&gt;presentations&lt;/a&gt; from &lt;a href="http://www.slideshare.net/ashic"&gt;Ashic Mahtab&lt;/a&gt;.&lt;/div&gt;&lt;/div&gt;  &lt;p&gt;Code:&lt;/p&gt; &lt;p&gt;&lt;a href="https://github.com/ashic/RoughingItCanaryWharf"&gt;https://github.com/ashic/RoughingItCanaryWharf&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;Enjoy!&lt;/p&gt;</description><pubDate>Mon, 07 May 2012 09:05:09 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/roughing-it-canary-wharf</guid></item><item><title>Speaking at NxtGenUG Southampton</title><link>http://www.heartysoft.com:80/speaking-at-nxtgenug-southampton</link><description>&lt;p&gt;I'll be speaking on CQRS, Event Sourcing and related patterns at NxtGenUG Southampton on January 19.&lt;/p&gt;</description><pubDate>Sun, 15 Apr 2012 10:17:32 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/speaking-at-nxtgenug-southampton</guid></item><item><title>Speaking at NxtGenUG Coventry</title><link>http://www.heartysoft.com:80/speaking-at-nxtgenug-coventry</link><description>&lt;p&gt;I'll be speaking about CQRS, Event Sourcing and Related Patterns at NxtGenUG Conventry on June 26, 2012.&lt;/p&gt;</description><pubDate>Sun, 15 Apr 2012 10:16:57 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/speaking-at-nxtgenug-coventry</guid></item><item><title>Speaking at NxtGenUG Hereford</title><link>http://www.heartysoft.com:80/speaking-at-nxtgen-hereford</link><description>&lt;p&gt;I'll be speaking on CQRS, Event Sourcing and related patterns at NxtGenUG Hereford on January 09, 2012.&lt;/p&gt;</description><pubDate>Sun, 15 Apr 2012 09:30:09 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/speaking-at-nxtgen-hereford</guid></item><item><title>Yes, I Use a Text Editor for Demonstrating Code</title><link>http://www.heartysoft.com:80/yes-i-use-a-text-editor-for-demonstrating-code</link><description>&lt;p&gt;I was in Southampton recently for a talk titled “An Introduction to CQRS, Event Sourcing and their Benefits”. I’ve got some nice feedback suggesting people generally liked it. I also got some nice criticism – some to do with the focus of the talk (which I’ll cover in another post) but one particular one that brought up the issue of my coding in a text editor - &lt;/p&gt; &lt;p&gt;&lt;em&gt;“Dropping out many times to a text editor to write code that was never compiled let alone executed. What was that about? Why not use Visual Studio so you can compile and execute the code?”&lt;/em&gt;&lt;/p&gt; &lt;p&gt;It is definitely an interesting point and well worth addressing. Hence this blog post.&lt;/p&gt; &lt;h2&gt;A Brief Description of the Content&lt;/h2&gt; &lt;p&gt;The talk was about CQRS, Event Sourcing and the various benefits they can bring. It was about introducing the concepts and see how the orthogonal concepts can be useful from various angles – in implementing a bounded context in domain driven design, in conforming to SOLID principles and good OO practices, in achieving high scalability when needed, in writing good and stable tests etc. It covered a lot of ideas. And time was obviously limited. &lt;/p&gt; &lt;h2&gt;Why the Text Editor&lt;/h2&gt; &lt;p&gt;The focus of the talk was propagating the ideas. And showing how simple it is to implement those ideas. While simple, that still takes time. I could have pre-coded 15 samples and hit ctrl+F5 or CTRL+U, L and be done with it. However, I doubt that would have been useful in transferring the ideas. A running demo in certain cases is very useful. But it is not really that great in conveying the simplicity of implementing something.&lt;/p&gt; &lt;p&gt;I find Notepad++ to be an excellent tool to convey ideas related to coding. I’m not distracted by Visual Studio or Resharper constantly badgering me to fix my syntax or type in everything to make the code compilable. The freedom it gives (while maintaining nice indenting) means that I can focus on the idea I’m trying to express, rather than create an application in Visual Studio and do “code slides”. For example, the following code:&lt;/p&gt; &lt;p&gt;class LoggingHandle&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ctor(Logger logger, Action&amp;lt;object&amp;gt; next);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public void Handle(object cmd)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _logger.Log(cmd.ToString());&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _next(cmd);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;}&lt;/p&gt; &lt;p&gt;_bus.Register&amp;lt;SomeCommand&amp;gt;(x=&amp;gt; new LoggingHandler(_log, new SomeHandler().Handle));&lt;/p&gt; &lt;p&gt;That is enough to show how we can compose handlers. Does it compile? No. Does it need a bit more work to make it compile? Yes. Does it convey the idea? Yes. Then why do I need to take focus away from the main idea I’m trying to express and create running projects in Visual Studio? Typing that live takes about a minute. Going through VS project with all the implemented classes takes more than that. &lt;/p&gt; &lt;h2&gt;It’s not only for Demos&lt;/h2&gt; &lt;p&gt;Here’s a secret – I don’t use Notepad just for demos. I use it for real projects as well. If I’m faced with a particularly complicated problem that may have different approaches, I try them out in notepad. If I’m about to write a class that other classes may be using, I will sometimes start writing the method signatures in notepad to see how it looks, how much information is being appropriately hidden and what it “smells” like. In some cases, I even resort to pen and paper. Yes, tests are usually involved as well but this is at a pre-test-just-thinking phase. And I find it infinitely valuable. If I find it so, why would I not use the same thing to convey ideas during demoes?&lt;/p&gt; &lt;p&gt;Perhaps I’m a bit dumb but sometimes I find I need a buffer between my ideas and Visual Studio. And I find notepad to be a great one.&lt;/p&gt; &lt;p&gt;So, yes – dropping into a text editor to write the code that exists only to convey ideas and never gets compiled or executed? This is what that’s about.&lt;/p&gt;</description><pubDate>Thu, 15 Mar 2012 01:51:52 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/yes-i-use-a-text-editor-for-demonstrating-code</guid></item><item><title>Formatting JavaScript Date</title><link>http://www.heartysoft.com:80/formatting-javascript-date</link><description>&lt;p&gt;Formatting DateTime in C# is dead simple – just call ToString() passing in the format string you desire. Doing the same in JavaScript is annoyingly cumbersome. Today, I came across a nice little jQuery plugin that can carry out this mundane task. It’s the jQuery-dateFormat plugin and can be found at &lt;/p&gt;&lt;pre&gt;&lt;a href="http://archive.plugins.jquery.com/project/jquery-dateFormat"&gt;http://archive.plugins.jquery.com/project/jquery-dateFormat&lt;/a&gt;&lt;/pre&gt;
&lt;p&gt;Using it is quite simple:&lt;/p&gt;
&lt;p&gt;&lt;script src="https://gist.github.com/1548777.js?file=jqury-dateFormat"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;I can think of more than one time where this would've saved me some drudgery &lt;img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://www.heartysoft.com/Media/Default/Windows-Live-Writer/Formatting-JavaScript-Date_456/wlEmoticon-smile_2.png"&gt;&lt;/p&gt;</description><pubDate>Mon, 02 Jan 2012 00:27:23 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/formatting-javascript-date</guid></item><item><title>Agile Fragile</title><link>http://www.heartysoft.com:80/agile-fragile</link><description>&lt;p&gt;I’m going to indulge myself by having a nice old fashioned rant. The topic of choice is “Agile”. A few experiences and conversations of the recent past have compelled me to write something on this topic. So here goes nothing &lt;img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://www.heartysoft.com/Media/Default/Windows-Live-Writer/AgileFragile_D668/wlEmoticon-smile_2.png"&gt;&lt;/p&gt; &lt;p&gt;I’ve recently come across a quite senior person with an obscenely large number of years of experience during which time he has been involved in very large projects (think multi million pound) for very large organisations (think the likes of British Airways). He hasn’t ever worked in an Agile atmosphere. Now there’s nothing wrong in never having worked in an agile manner. However this individual has some very strong opinions about agile. In brief, his view seems to be that agile means “letting groups of people do their own thing and the &lt;strong&gt;hoping&lt;/strong&gt; all of it holds together”. And he is in a role where he spreads his knowledge to many many others. It appears that other people seem to have a similar viewpoint – agile has no discipline or process. It means “winging” it as you go along. It’s about not thinking and just doing. Seriously, where do people get these ideas? I find it quite remarkable that such FUD exists in 2011.&lt;/p&gt; &lt;p&gt;Agile, in many ways, is far more strict than all that CMMI waterfall-y nonsense of years past. Yes, there are many flavours but to say there’s no process to it is ridiculous. Those who practice TDD, CI, Continuous Delivery would all know about the rigour involved. I’ll just take TDD as a sample. If you’re doing strict TDD, you won’t be writing a single line of production code without a failing unit test. Think about the waterfall equivalent. Would you have test plans and “signed off” test cases that would achieve the same level of coverage? Probably not. You would be coding away at your hearts content only for weird errors to be found during the “testing” phase – at which point recovery may already be too difficult as a bunch of other things have been built in the mean time. In this case, who’s doing the “winging” and “hoping” it works.&lt;/p&gt; &lt;p&gt;The more there is a necessity of “hope”, the less agile you are. This is because you would be actively identifying problem points and bringing the pain forward – so that when it comes to deploying, integrating or whatever, you’re already prepared. You won’t have to “hope”. Yes, there’ll always be the unexpected and weird tangential cases. But an agile team will learn from that and cater for it the next time around. And they will do so immediately. They won’t wait for some board to approve some document put together by a non-coding architect who never really understood the problem as he was so far away from it.&lt;/p&gt; &lt;p&gt;Sure there are “agile” teams out there who do a lot of hoping and praying. Are they really agile? Or are they doing some sort of iterative development and calling it agile? Which brings me to the second part of my rant. &lt;/p&gt; &lt;p&gt;There seems to be another group that claim to be agile and think that because of that, there needs to be no planning at all. Even if there’s a train-wreck on the horizon that everybody can see coming, they seem to say “we’ll tackle the problem when we get there”. Just coz your agile doesn’t mean you don’t think? You’ve all got heads, right? Sure, you don’t design everything left right and centre before starting development but you at least need to think about the problems you’re likely to face or the common exceptional situation you need to cover. If you don’t, you’ll be in a constant state of flux, with more and more churn creeping up. And churn is waste. Agile looks to eliminate waste. Hence this is not agile.&lt;/p&gt; &lt;p&gt;Agile doesn’t mean that all you need to do is use a board of sorts and make things up as you go along. It represents a set of practices that can help improve quality, reduce waste and speed up delivery. It is more about adhering to the practices in order to achieve those benefits. If all you’re doing is adhering to the physically visible elements while your codebase is, and will remain, a stinking pile of shite and you have more and more waste coz nobody knows what they’re building then whatever it is – it’s not agile. It’s not about the board or Ninject or MVC or NUnit or SVN or TFS or Git. Focus too long on less important issues and you’ll quickly find yourself spending hours, days and weeks concerned with stuff that doesn’t really matter. It’s like trying to treat a headache induced from brain cancer with paracetamol. Are you focusing on processes and tools more than individuals and interactions? Sure, processes and tools are important but if all you’re interested in are “agile” processes and tools, surely you’ve lost a beat somewhere.&lt;/p&gt; &lt;p&gt;Yes – and I keep hearing this over and over – the agile manifesto says “Responding to Change”. And it’s very important. Detailed plans are seldom followed. But responding to change doesn’t mean blindly building something without thinking. It means being able to respond to change. If you go too fast without any planning at all, don’t stop to improve your design as you go along and keep doing it over and over again in the name of “Agile”, then you will soon find yourself in a monstrous ball of mud, ironically incapable of responding to the slightest change requested. Whether you have a Scrum board, Kanban flow thingy or whatever, and even if you have your daily 15 minutes going on an hour stand up meetings (where some people have the privilege of sitting!) – if you don’t have sustainable pace for the long run, then whatever you are, you’re not agile. &lt;/p&gt; &lt;p&gt;Every time I see people with these two views about agile, my immediate reaction is to say “That’s not Agile. I call that Fragile”. &lt;/p&gt;</description><pubDate>Thu, 24 Nov 2011 04:08:25 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/agile-fragile</guid></item><item><title>The Other Side of NuGet</title><link>http://www.heartysoft.com:80/the-other-side-of-nuget</link><description>&lt;p&gt;NuGet is a very nice addition to the .NET developers’ arsenal. It is a central place for every library and framework in .NET. It has pretty good tooling integrated into Visual Studio and the command line options are pretty sweet too. It can pull down specific libraries including their own dependencies saving the developer a lot of time and effort in figuring them out manually. For the continued growth of the open source .NET community, NuGet is pretty much something that should have happened years ago. Yet there are some things about NuGet you need to be careful about. &lt;/p&gt; &lt;h2&gt;Everything on NuGet is not shrink wrapped&lt;/h2&gt; &lt;p&gt;This may seem pretty obvious as its an amalgam of different libraries from many many different authors. Yet when using NuGet many people seem to forget that. When done properly, a NuGet package “just works”. Brilliant. Yet there are a number of reasons why a package may not “just work”. It could be that the package was created wrong. It could be that one of the dependencies forgot to mention a specific version and as such the latest version of that dependency would be fetched – possibly incompatible with the main package. It could be that the main package has an out-dated version specified. It could be that even with the latest version, there’s a glaring bug that makes the library unusable – it’ll get fixed eventually.&lt;/p&gt; &lt;p&gt;A lot of these problems stem from the fact that most packages are open source – some managed by a single person team. That’s not a bad thing. That’s what the OSS community thrives on. Yet if they weren’t on NuGet, we would find ourselves researching and evaluating the package more – trying to find chinks in the armour and in the process, get better understanding about the component. NuGet makes it quite easy to just do a search in the NuGet UI for some term, pull down a match into our project code and try to learn the library. What would we have done differently if we had not had NuGet? We would never have added an unknown library to our project. We would have created a separate throwaway project and experimented with the library. We would have judged its pros and cons and after careful evaluation, decided whether it’s good enough to go in. Just because you’re using NuGet should not mean you’re allowed to skip this step. Anyone can put anything on NuGet. Don’t think that just because it’s on NuGet, you don’t need to evaluate something.&lt;/p&gt; &lt;h2&gt;Dependency Hell&lt;/h2&gt; &lt;p&gt;Many people are wary about the number of dependencies they take on. Many think this is an unjust fear. Some argue that any bug in any of the dependencies can show up in your product. Using NuGet, it’s easier to “ignore” that fact when adding a package (even though the package explorer clearly shows the dependencies). There is another problem with the dependencies. If two packages have dependencies on different versions of the same package, you will run into issues. There’s little Microsoft or the NuGet team can do about this. You just need to be wary of this fact if you do use NuGet. That’s right – it’s your responsibility to judge the packages and as with the previous point, you should not skip this step.&lt;/p&gt; &lt;h2&gt;&lt;/h2&gt; &lt;h2&gt;Proxy and Network&lt;/h2&gt; &lt;p&gt;Where I work, we need to go through a proxy with credentials to access the central network and the internet. The network settings for VS seem abysmal. To connect we need to do these in order:&lt;/p&gt; &lt;p&gt;- Launch the VS Extension Manager&lt;br&gt;- Wait for it to timeout (90ish seconds)&lt;br&gt;- Click the link to enter credentials&lt;br&gt;- Enter credentials ticking the “remember” checkbox&lt;br&gt;- Close the extension manager&lt;br&gt;- Open NuGet package manager and use it.&lt;br&gt;&lt;/p&gt; &lt;p&gt;And if we close VS, we need to repeat the process again. Joy.&lt;br&gt;Yes, our network system is crap. And yes, we don’t have control over it. It takes 3 minutes or so to get to the NuGet packages. Surely this can be improved. &lt;/p&gt; &lt;p&gt;[Update: This is thankfully resolved…the NuGet window now displays the login prompt.]&lt;/p&gt; &lt;h2&gt;&lt;/h2&gt; &lt;h2&gt;References, Packages, Dlls, R#&lt;/h2&gt; &lt;p&gt;If you add every package to every project through NuGet, you’re fine. But if one project adds a dependency via NuGet and another project just uses the downloaded dlls, there’s a chance you’ll have problems on the central build. This may not sound like much but it can be. Resharper’s Alt + Enter will simply add a reference to the dll. In addition to that, NuGet adding packages could take a while (see previous point) depending on your network setup. These types of annoying pauses can decrease productivity significantly. &lt;/p&gt; &lt;h2&gt;Build Servers and NuGet&lt;/h2&gt; &lt;p&gt;With NuGet, comes the decision on whether or not to commit packages. Many people suggest that packages should not be committed to source control. NuGet has a nifty way of fetching the dependencies by a simple command line operation. Keeping the packages out of source control will mean quicker checkouts, right? I couldn’t disagree with this recommendation more. I believe that unless constrained by some very specific reason, dependencies should be in source control. This allows anybody who has the source code to build the project immediately regardless of whether or not they’re connected to the internet or a private NuGet server. Some people go as far as to put VMs with specific environment configurations in version control. Having to go through a secondary process to “update dependencies” on checkout is annoying and a waste of time. In addition, if another team member adds a new package to the project, other devs will have to run a command in order to get up to date. This can add up.&lt;/p&gt; &lt;p&gt;Does keeping the packages out of source control save you anything? Faster checkouts? Hah…you get a quicker checkout of the source code but you need to add those packages in anyway. Wouldn’t simply getting the dlls from source control be faster? Your dlls wouldn’t change that often if they’re in a lib folder. Hence, after the first checkout, you wouldn’t need to even think about it. And what about repeatability? You’re adding environmental dependencies (network, NuGet server etc.) that may or may not behave the same way year round. Just last week, NuGet was updated to v1.5. Until we updated the internal server to 1.5, we experienced problems using both the central NuGet server and our private NuGet server. This took time away from the devs. They were waiting for the bottleneck to clear up. We don’t like bottlenecks. Having the build server fetch packages from NuGet can be annoying if there are connectivity issues. Yes, caching helps. But if you add a new package, the server will need to connect to the internet. This is again an annoying delay. &lt;/p&gt; &lt;p&gt;Not committing packages means that the developers and the build server have to know about NuGet. What one guy does has to be done by others (be it through a simple command) after fetching the latest code. In the age of continuous delivery, this is just bizarre. I’m not saying don’t use NuGet. I’m saying use NuGet to fetch the dlls the first time (and when you need to update the packages) but commit the dlls in source control. Keep your build server free of NuGet and the network dependencies it brings. This will not slow you down. This will save you minutes every single day. Those minutes and the interruptions they bring do add up. What would happen if you did commit the dlls? Nobody on the team or the build server would need NuGet, a network connection or anything else to build. A few less things to worry about. &lt;/p&gt; &lt;p&gt;Great tools make your normal workflow faster , easier and quicker. NuGet is a great tool for adding those dependencies without having to go all sourceforge, github, bitbucket or codeplex crazy. But think about it – would you be fetching your dependencies from those places from your build server? No you wouldn’t. Adding NuGet to your build process would mean doing exactly that. At that point, you’re no longer automating a manual process, you’re adding a new step to your build – a step that has a dependency on NuGet itself, network connections, central servers and what not. It just occurred to me that this has an analogy with one of my passions – CQRS. In CQRS, you don’t wait for the user to request something and then go off to a huge central model to generate the result – rather you pre-process the result and return it when the user asks for it. This ensures that the user can get what they need even if there’s an issue connecting to the central server. Similarly, why go off traversing package servers and the interwebz when you can get avoid it? As Greg Young says – “Autonomy can be a powerful thing”. &lt;/p&gt; &lt;h2&gt;The Poor Guy on the Train &lt;/h2&gt; &lt;p&gt;There’s no golden rule for pretty much anything. But if your packages are seldom updated or new dependencies added then, consider what benefits you gain by forcing the NuGet dependency on everybody. Think of the guy who checks out code at the end of the day so that he can work during his 90 minute commute on a packed train. He somehow manages to find a seat, open up his laptop only to find that he forgot to run a pesky NuGet command line updater which connects to the office package server. And then he finds that the SVN or TFS monstrosity means he can’t even go back to his code before checkout and work on something else. He has to stare into the abyss for the remainder of his journey.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;NuGet is a great tool and a necessary one (as is OpenWrap but that’s another issue). Something like this from the first party was badly needed. And it does what it does quite well. But as far as checking in packages go, have a think and analyse if the NuGet dependency on your whole team is something that will work for you or against you. There is no right or wrong answer to this – do what’s best for your team.&lt;/p&gt;</description><pubDate>Thu, 27 Oct 2011 22:37:58 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/the-other-side-of-nuget</guid></item><item><title>DDD North 2011</title><link>http://www.heartysoft.com:80/ddd-north-2011</link><description>&lt;p&gt;One week after &lt;a href="http://www.heartysoft.com/ddd-belfast-2011"&gt;DDD Belfast&lt;/a&gt;, I was up in Sunderland for the first ever &lt;a href="http://developerdeveloperdeveloper.com/north/Default.aspx"&gt;DDD North&lt;/a&gt;. The session line-up looked fantastic and it geared up to be a fantastic day.&lt;/p&gt; &lt;h2&gt;My Session&lt;/h2&gt; &lt;h3&gt;Clean Up Your JavaScript Act&lt;/h3&gt; &lt;p&gt;I wasn’t expecting too much of a turnout for the session as Mark Rendle’s CoffeeScript was on at the same time. Apparently, I wasn’t the only one with that perception as Andrew mentioned scrambling in more and more chairs &lt;img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-winkingsmile" alt="Winking smile" src="http://www.heartysoft.com/Media/Default/Windows-Live-Writer/DDD-North-2011_D3/wlEmoticon-winkingsmile_2.png"&gt; I was surprised to see the room filled. Thanks to Plip overrunning his hyper-optimisation talk, I had to get started in a hurry. I &lt;em&gt;may &lt;/em&gt;have forgot to actually say who I was. &lt;/p&gt; &lt;p&gt;I was looking to cover three things in the talk. First, I would show unit testing with QUnit driven by Chutzpah – both in Visual Studio and as part of a build in TeamCity. I would then cover functional objects in JavaScripts ala Douglas Crockford. Lastly (given the time), I would show a very brief demo of Knockout – a JavaScript MVVM framework. Due to the time limit, I had to go very very fast. I would have liked to get into more details but I figured it would be more useful to give the audience a starting point to start investigating on their own. Judging by the reactions, I was introducing them to some new things – so that worked out quite well. &lt;/p&gt; &lt;p&gt;The official feedback seemed very positive overall. The one I appreciated most mentioned that they found the content of more immediate use than other ones. One was happy with it but raised a minor issue that it hurt his brain (“but worth it”!). My absolute favourite has to be the really really negative one I got:&lt;/p&gt; &lt;p&gt;&lt;em&gt;“I don't think I am really working with this set of technologies but it is very interesting”&lt;/em&gt;&lt;/p&gt; &lt;p&gt;The interesting part is that the abstract clearly mentioned unit testing JavaScript, QUnit, JavaScript objects and Knockout. I really appreciate somebody coming to a session that is irrelevant to them and then giving shite scores. Thank you.&lt;/p&gt; &lt;p&gt;It was very much code focused with live demonstrations. As such, there were very few slides. You can find them below:&lt;/p&gt;  &lt;div style="width: 425px" id="__ss_9684228"&gt;&lt;strong style="margin: 12px 0px 4px; display: block"&gt;&lt;a title="Clean up your javascript act" href="http://www.slideshare.net/ashic/clean-up-your-javascript-act"&gt;Clean up your javascript act&lt;/a&gt;&lt;/strong&gt;&lt;object id="__sse9684228" width="425" height="355"&gt;&lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=cleanupjsact-111013173245-phpapp01&amp;amp;stripped_title=clean-up-your-javascript-act&amp;amp;userName=ashic" /&gt;&lt;param name="allowFullScreen" value="true" /&gt;&lt;param name="allowScriptAccess" value="always" /&gt;&lt;embed name="__sse9684228" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=cleanupjsact-111013173245-phpapp01&amp;amp;stripped_title=clean-up-your-javascript-act&amp;amp;userName=ashic" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;/div&gt;  &lt;h2&gt;Other People’s Sessions I Attended&lt;/h2&gt; &lt;h3&gt;Behaviour Driven Development&lt;/h3&gt; &lt;p&gt;I went into this session with high expectations. This was my first time in an Ian Cooper session and I have been looking into Specification by Example ever since the book came out experimenting with various approaches. Ian covered the history of BDD quite nicely but I found it difficult to understand who the target audience was. He covered topics for pretty much all experience levels but thought there was too little for any particular one. He explained how BDD isn’t about any particular tool yet showed a lot of SpecFlow code. I do believe it would be an awesome day long talk but maybe targeting a particular level of maturity in the audience would have made it more interesting. Ian’s recent blog post on testing behaviour, not implementation explains the concept better.&lt;/p&gt; &lt;h3&gt;Tips and Tricks : Lightning Fast Pages&lt;/h3&gt; &lt;p&gt;Phil showed various subtle issues that can slow pages and various points to be aware of. The talk was very good, content rich (even though slide heavy) and went on and on and on and on…oi Plip – you almost made me miss my own session.&lt;/p&gt; &lt;h3&gt;Kanban : What is it and how can it help&lt;/h3&gt; &lt;p&gt;Nathan clearly explained how the Kanban process works (including various edge cases). There were some interesting questions and answers. I greatly enjoyed the talk. My only (very minor) criticism would be if he put forward the benefits a bit more – the talk lacked a bit of “why”. Very very good session to attend and would recommend to anybody who hasn’t done it yet.&lt;/p&gt; &lt;h2&gt;After Hours&lt;/h2&gt; &lt;p&gt;There was a brilliant English dinner arranged by Dev Express for 150 geeks. Scrumptious and awesome. Thanks guys. &lt;/p&gt; &lt;p&gt;Right, that’s the two DDDs wrapped up. I can now move on to blogging about tech stuff &lt;img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://www.heartysoft.com/Media/Default/Windows-Live-Writer/DDD-North-2011_D3/wlEmoticon-smile_2.png"&gt;&lt;/p&gt;</description><pubDate>Thu, 13 Oct 2011 23:22:40 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/ddd-north-2011</guid></item><item><title>DDD Belfast 2011</title><link>http://www.heartysoft.com:80/ddd-belfast-2011</link><description>&lt;p&gt;After repeated attempts to resume blogging, I think I’m pretty much determined to end my hiatus. And I’ll start off with my experience at DDD Belfast.&lt;/p&gt; &lt;p&gt;Apart from a Scott Gu special event last year, this was my first DDD event. The travel up to Belfast was a bit hectic&amp;nbsp; - the “journey” from the security gates to the EasyJet gates at Gatwick seemed like a mile long trek. Note to self: if flying out of Gatwick, leave an extra hour in your schedule. We were horrendously late but the pilot was kind enough to let us board minutes before take off. Surprisingly, the landing in Belfast has to be the best three point landing of any flight I’ve been on. Anyway…onto the geeky stuff.&lt;/p&gt; &lt;h2&gt;My Sessions&lt;/h2&gt; &lt;h3&gt;Code Contracts&lt;/h3&gt; &lt;p&gt;Mine was one of the first sessions. Due to some awesome weather on a Saturday morning, turnout was relatively low. There were 15-ish attendees in the session. Having a smaller audience meant some nice discussions about the pros and cons of Code Contracts. I tried to give a good idea of what Code Contracts is and how it may benefit their projects – be it greenfield or brownfield. I also put forward the common problems they may face and what they could do to overcome them. The slides from the session are provided below:&lt;/p&gt; &lt;div style="width: 425px" id="__ss_9637189"&gt;&lt;strong style="margin: 12px 0px 4px; display: block"&gt;&lt;a title="Code contracts" href="http://www.slideshare.net/ashic/code-contracts-9637189"&gt;Code contracts&lt;/a&gt;&lt;/strong&gt;&lt;object id="__sse9637189" width="425" height="355"&gt;&lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=codecontracts-111010190935-phpapp02&amp;amp;stripped_title=code-contracts-9637189&amp;amp;userName=ashic" /&gt;&lt;param name="allowFullScreen" value="true" /&gt;&lt;param name="allowScriptAccess" value="always" /&gt;&lt;embed name="__sse9637189" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=codecontracts-111010190935-phpapp02&amp;amp;stripped_title=code-contracts-9637189&amp;amp;userName=ashic" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;/div&gt; &lt;h2&gt;&lt;/h2&gt; &lt;h3&gt;CQRS and Event Sourcing&lt;/h3&gt; &lt;p&gt;This is the session I really wanted to take as it’s one of my primary fields of interest at the moment. The session was just after lunch and attendance was significantly higher. I believe I managed to fill the room. It was nice to see such interest in CQRS and Event Sourcing. I was also taking a risky move – a couple of days before the session, I decided to scrap my presentation and create a new one showing exactly how simple it is to use these patterns in even simple applications. There seems to be a negative vibe around CQRS suggesting that it’s only appropriate for large scale complex systems. While that is definitely an area where it can be applied, even simple systems can benefit from it. My goal was to put forward these benefits and provide an easier way to try it out. In order to do so, I created a usable (as in real apps) CQRS / ES mini-framework in exactly 250 lines of code – a file that you can simply drop in your project and start using. Sure, the file can be refactored further and it doesn’t to everything. But it is extendible and you should be able to bend it to your will. Creating the framework took less than a night’s coding – and considering I hadn’t previously used RavenDB before, it reflects exactly how simple the architecture really is. There’s far more to what it than what can be shown in a single hour and I shall be blogging about it in the coming days. Initially I had wanted to show just slide no. 5 after taking the decision to scrap the previous presentation. I ended up adding a few more. Like most of my talks, it’s more about the code than it is about slides. But if you want to see them, then here they are:&lt;/p&gt; &lt;div style="width: 425px" id="__ss_9637257"&gt;&lt;strong style="margin: 12px 0px 4px; display: block"&gt;&lt;a title="Cqrs, Event Sourcing" href="http://www.slideshare.net/ashic/cqrs-event-sourcing"&gt;Cqrs, Event Sourcing&lt;/a&gt;&lt;/strong&gt;&lt;object id="__sse9637257" width="425" height="355"&gt;&lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=cqrseventsourcing-111010192156-phpapp01&amp;amp;stripped_title=cqrs-event-sourcing&amp;amp;userName=ashic" /&gt;&lt;param name="allowFullScreen" value="true" /&gt;&lt;param name="allowScriptAccess" value="always" /&gt;&lt;embed name="__sse9637257" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=cqrseventsourcing-111010192156-phpapp01&amp;amp;stripped_title=cqrs-event-sourcing&amp;amp;userName=ashic" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;/div&gt; &lt;p&gt;I’m yet to receive the “official” feedback from the event but the vibe was quite good. I will be releasing the code in an upcoming (series of?) blog posts. Stay tuned &lt;img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://www.heartysoft.com/Media/Default/Windows-Live-Writer/2ec425e4f26f_81CB/wlEmoticon-smile_2.png"&gt;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;h2&gt;Other People’s Sessions I Attended&lt;/h2&gt; &lt;h3&gt;RefORM – Death to ORMs in .NET&lt;/h3&gt; &lt;p&gt;&lt;a href="http://yobriefca.se/"&gt;James&lt;/a&gt; (&lt;a href="http://twitter.com/#!/kouphax"&gt;@kouphax&lt;/a&gt;) did an excellent job of summing up all the Micro ORMs that have been popping up left, right and centre. He quickly covered the ones you hear about, their relative levels of abstraction, their pros and cons and showed us code samples. I quite enjoyed the talk.&lt;/p&gt; &lt;h3&gt;BDD with F#&lt;/h3&gt; &lt;p&gt;&lt;a href="http://www.trelford.com/blog/"&gt;Phillip&lt;/a&gt; (&lt;a href="http://twitter.com/#!/ptrelford"&gt;@ptrelford&lt;/a&gt;) told us about BDD and how “framework” agnostic it is. He then went on to show us his F# BDD framework called TickSpec. He showed how BDD is used in real projects and how TickSpec is nicer than other tools like SpecFlow. While I agree to the last statement, I’m not particularly fond of SpecFlow and if you feel the same, then take it with a (tiny) grain of salt. Regardless, the usefulness of BDD was clearly put forward.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;During the last session of the day, some attendees and speakers got together for a free for all talk which was quite fun. All in all, it was an excellent event. Kudos to &lt;a href="http://jackiepollock.co.uk/"&gt;Jackie&lt;/a&gt; (&lt;a href="http://twitter.com/#!/kievia"&gt;@kievia&lt;/a&gt;) who managed to put the event together in difficult circumstances.&lt;/p&gt;</description><pubDate>Tue, 11 Oct 2011 22:40:07 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/ddd-belfast-2011</guid></item><item><title>2011 MVP Hat Trick</title><link>http://www.heartysoft.com:80/2011-mvp-hat-trick</link><description>&lt;p&gt;Got this email today:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;"Congratulations! We are pleased to present you with the 2011 Microsoft&amp;reg; MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in ASP.NET/IIS technical communities during the past year."&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;That's three on the trot and it feels great to have done it before the 25 year milestone :)&lt;/p&gt;
&lt;p&gt;And so begins another year of contributing to the community. I have to thank Abhishek (my former MVP lead), Claire (my current lead), Microsoft and anybody in the community who helped, or was helped by, me. Right...back to business.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;</description><pubDate>Fri, 01 Jul 2011 22:32:41 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/2011-mvp-hat-trick</guid></item><item><title>My CQRS Session at the Canary Wharf Dot Net User Group</title><link>http://www.heartysoft.com:80/canary-wharf-cqrs</link><description>&lt;p&gt;About a couple of weeks ago, I presented some very basic CQRS and Event Sourcing concepts to the Canary Wharf Dot Net User Group. It was an interesting experience to say the least. About everybody there had heard of CQRS (hmmm), about a quarter knew a bit about how it works (wow) and only one guy there actually uses it (ah well). This confusing spread in the audience made it quite challenging as to which bits to focus on and what to consider “advanced”. [And I actually feel bad for the guy who uses it as he probably got zilch from the session!] With such a spread in the audience, the most effective part of any session turns out to be the Q&amp;amp;A part. And we had a very nice one with numerous questions – some of them turning into discussions. I’ll be blogging a bit about CQRS, Event Sourcing etc. in the coming weeks and will hopefully go into detail about some of the questions. As part of the session, I had a (purposefully) very simple demo using Ncqrs and ASP.NET MVC. It’s not a “best practices” thing but a simple app showing how simple it is to create a CQRS + Event Sourcing application with Ncqrs. (It’s also from an old build of Ncqrs – the current version would probably not work with the code but the changes required would be minimal. &lt;/p&gt; &lt;p&gt;&lt;a href="http://cqrscwdnug.codeplex.com/"&gt;The slides and code can be found here.&lt;/a&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;Any questions, discussions or just to get in touch, feel free to tweet / email / whatever. &lt;/p&gt;</description><pubDate>Mon, 20 Jun 2011 02:14:00 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/canary-wharf-cqrs</guid></item><item><title>ASP.NET MVC Gotcha – String as Model</title><link>http://www.heartysoft.com:80/aspnet-mvc-gotcha-string-model</link><description>&lt;p&gt;A very common task in ASP.NET MVC is to return a ViewResult from a controller Action. This is usually achieved by a simple:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;   
return View(“ViewName”, modelForTheView);    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;And this works fine…usually. Have you ever had a view where the model is simply a string? In that case, your code may look like this:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;   
var model = “some string”;    
return View(“ViewName”, model);    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;Only in this case, it won’t work. Don’t believe me? Try it. It’s going to show an obscure error message saying that it could not find the view or master / layout page for ViewName.cshtml [or aspx if you’re using that inferior view engine]. Yet if the model is anything but a string, it works perfectly. This can result in confusion, anger, despair, hair-pulling, keyboard pounding and more importantly wasted time. And if you ever find yourself doing any of those things, then the reason for the error will annoy you even further. You see, Controll.View() has a number of overloads. Two of them are as follows:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;   
View(String, Object)    
View(String, String)    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;And yes, they are different. The first one expects the model as the second parameter. The second one expects the MASTER/LAYOUT name as the second parameter. When you pass anything but a string as the second parameter, the first overload is triggered. When you pass a string, .NET sees that it matches the second overload and that match is “stronger” than the first. As a result, it calls the second overload. As a result, it will look for a master / layout with the same name as the data you’re passing to it and chances are, it won’t find it. And you’ll get that confusing error.&lt;/p&gt;  &lt;h2&gt;The Solution&lt;/h2&gt;  &lt;p&gt;The solution is quite simple. You could use the other overload:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;   
View(String, String, Object)    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;where the second parameter is the master / layout name and the third is the actual model whenever you have a View expecting a string in the model. Or you could use a named parameter:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;   
return View(“ViewName”, model: “some string”);    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;Or simply use a separate ViewModel class.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;The same principle applies to&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;&lt;pre class='brush:c#'&gt;     
View(Object)      
View(String)      
&lt;/pre&gt;&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;i.e. If you pass anything but a string as the first parameter, it’s considered the model and the view name is inferred from the executing action. If you pass only&amp;#160; a string, it’s taken to be the view name and the model is null.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h2&gt;Why This Annoys Me&lt;/h2&gt;  &lt;p&gt;With due respect, this design is simply bonkers to me. It seems like the MVC team wanted to add some flexibility but in the process, they introduced an open invitation for off by one errors. Suddenly the type of the model is dictating how the View method responds. Simply the fact that a call to:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;   
return View(“Index”, model)    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;can have two radically different consequences depending on what’s in the model variable is mindboggling. Besides, what benefit is there from having an overload of the View method that sets the master / layout? The same could easily be achieved by simply putting the master / layout name in Viewbag / ViewData and simply assigning it in the view. Assigning the master / layout in the view is not a good practice in general and should not be encouraged by having an overload of the View method which does exactly that while taking precedence over another overload that is far more commonly used [i.e. second parameter’s the model].&lt;/p&gt;  &lt;p&gt;That said, for good or for bad, the annoying overload is there in the framework. So if you have a string as the “model”,&amp;#160; be aware that what you think is the model may actually not be interpreted as such. &lt;/p&gt;</description><pubDate>Mon, 18 Apr 2011 23:25:00 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/aspnet-mvc-gotcha-string-model</guid></item><item><title>Ninja Coding: Composition over Inheritance–Even when Overriding</title><link>http://www.heartysoft.com:80/composition-when-overriding</link><description>&lt;p&gt;We’ve all heard it a million times – composition is favourable to inheritance. But inheritance can sometimes come with its own charms. One of its main attractions is to do some grunt work in a base class and have the ability to override that behaviour in a derived class. Framework developers favour an abstract base class as it leaves the potential to add features in the future without breaking all client code. The usual approach towards to polymorphism is achieved by declaring a method (or property) as virtual in the base class and overriding in the derived one(s). And this usually works out quite well (if you do find yourself using inheritance). This would typically look like this:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;    
public class Command     
{     
&amp;#160;&amp;#160;&amp;#160; public virtual void Validate()     
&amp;#160;&amp;#160;&amp;#160; {     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var validator = ServiceLocator.Get&amp;lt;Validator&amp;gt;();     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; validator.Validate(this);     
&amp;#160;&amp;#160;&amp;#160; }     
}     
    
public class SomeDerivedCommand : Command     
{     
&amp;#160;&amp;#160;&amp;#160; public override void Validate()     
&amp;#160;&amp;#160;&amp;#160; {     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //some other validation logic     
&amp;#160;&amp;#160;&amp;#160; }     
}     
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;While this works quite well in a lot of cases, one area where this is annoying is unit testing. Say you have a class that has the following method:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;    
public class SomeCommandHandler     
{     
&amp;#160; public void Handle(SomeDerivedCommand command)     
&amp;#160; {     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; command.Validate();     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //do other stuff     
&amp;#160; }     
}     
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;and you wished to unit test the Handle method. You first wish to test how the Handle method would behave if the command.Validate() failed. You have a number of options:&lt;/p&gt;  &lt;p&gt;1. Mock a command with a mocking tool. This adds a dependency, might have more-than-desired syntax, usually requires the method to be mocked to be virtual or the reference be an interface.   &lt;br /&gt;2. Actually create a valid command for the test and an invalid command for another test. This is tedious and more importantly, if the validation logic for the command changes, you’ll have to go back and change tests which are not testing the validation logic. This means brittle tests and is quite bad (usually).    &lt;br /&gt;3. Write a manual mock.&lt;/p&gt;  &lt;p&gt;Now option 3 usually involves writing a derived class and overriding. Since this is a few lines of code for a test, this is mostly avoided in favour of a tool like moq, fake-it-easy or similar. With one simple step we can make this much simpler.&lt;/p&gt;  &lt;h2&gt;Functional Override&lt;/h2&gt;  &lt;p&gt;Let’s refactor the code, but this time with a somewhat functional approach:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;   
public class Command    
{    
&amp;#160;&amp;#160;&amp;#160; public Action Validate { get; protected internal set; }
  &amp;#160;&amp;#160;&amp;#160; public Command()   
&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Validate = _Validate;    
&amp;#160;&amp;#160;&amp;#160; }
  &amp;#160;&amp;#160;&amp;#160; private void _Validate()   
&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var validator = ServiceLocator.Get&amp;lt;Validator&amp;gt;();    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; validator.Validate(this);    
&amp;#160;&amp;#160;&amp;#160; }    
}
  public class SomeDerivedCommand : Command   
{    
&amp;#160;&amp;#160;&amp;#160; public SomeDerivedCommand()    
&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Validate = _SomeOtherValidationLogic;    
&amp;#160;&amp;#160;&amp;#160; }
  &amp;#160;&amp;#160;&amp;#160; private void _SomeOtherValidationLogic()   
&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //do other validation here    
&amp;#160;&amp;#160;&amp;#160; }    
}
  public class SomeCommandHandler   
{    
&amp;#160; public void Handle(SomeDerivedCommand command)    
&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; command.Validate();    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //do other stuff    
&amp;#160; }    
}    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;We haven’t changed much – just converted Validate in the command class to an Action as opposed to a virtual method. The derived class can still override the base class behaviour. If overriding behaviour is not something the derived class wants to do, it doesn’t have to do anything. &lt;/p&gt;  &lt;h2&gt;Hang on…that’s more code…what’s the benefit?&lt;/h2&gt;  &lt;p&gt;Let’s revisit the scenario where we were testing the SomeCommandHandler class’ Handle method. To create a valid command, we can simply do this:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;   
var stubCommand = new SomeDerivedCommand();    
stubCommand.Validate = () =&amp;gt; { };    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;And for an invalid command, we can do this:   &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;   
var stubCommand = new SomeDerivedCommand();    
stubCommand.Validate = () =&amp;gt; { throw new SomeException(); };    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;No mocking tools, no derived classes for stubbing out a parameter – so much nicer. And any code that’s calling Validate() will continue to build.&lt;/p&gt;  &lt;p&gt;Another benefit you get is that you can now have a library of functional elements (Action, Func, Predicate) and hook them up in the base class and “override” them is derived classes simply by setting a property in the constructor. So even though you’re specifying default functionality in the base class, you have a more flexible approach when overriding behaviour.&lt;/p&gt;  &lt;h2&gt;Gotchas&lt;/h2&gt;  &lt;p&gt;If you haven’t noticed yet, the Validate Action has a protected internal setter. This means derived classes OR classes in the same assembly can set it. The reason I’m allowing internal mutator is because I would have the test project able to access the internal symbols in the main project. For this I would simply need to set [assembly:InternalsVisibleTo(..)]. That way, the test assembly will be able to set the Action. This does mean encapsulation is broken within the main assembly but judging by the fact that it’s composing behaviour, I’m willing to accept that. If you don’t like that, just make the mutator protected and not internal. You’ll lose the stubbing benefit but you will still get the benefits of composition (use reusable libraries of functional elements as mentioned in the last section). &lt;/p&gt;</description><pubDate>Thu, 17 Mar 2011 18:08:45 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/composition-when-overriding</guid></item><item><title>ViewBag can be good…honestly</title><link>http://www.heartysoft.com:80/ViewBag-can-be-goode280a6honestly</link><description>&lt;p&gt;A lot of people seem to have an allergic reaction towards anything not “strongly typed”. They abhor ViewBag and resent ViewData[“key”] for passing values from the controller to the view. They write viewmodels that aggregate a few other viewmodels or worse, use inheritance to generate complex hierarchies. And in order to try and keep all that clean, they use design patterns and what not to achieve “compile time checking”, “testability” and a few other mirages of “good code”. Maybe I like leaning over the edge a bit, but I really can’t understand why something that is to be a data carrier has to be part of something that’s as complex (if not more) than a trivial application’s domain. Here are some of the drawbacks of strongly typing all viewmodel data:&lt;/p&gt;  &lt;h2&gt;Hideous hideous chaining&lt;/h2&gt;  &lt;p&gt;If you have viewmodel classes that encapsulate other viewmodel classes, your view will like have code like:&lt;/p&gt;  &lt;p&gt;Model.MemberAddressVM.X.Y.WhatNot&lt;/p&gt;  &lt;p&gt;Granted the effects can be mitigated by using partials, RenderAction and other stuff; and this is not the main problem.&lt;/p&gt;  &lt;h2&gt;Using hierarchies&lt;/h2&gt;  &lt;p&gt;If you use a base viewmodel class and set some default stuff further up the hierarchy (in an ApplicationController base class or something), you won’t get (much of) the chaining problem, but you will tightly couple the behaviour for all controllers that share the same base. In many cases, the viewmodel data is only for the specific view and meaningless for the others. Anytime we favour inheritance, we should stop and think whether the coupling is worth it.&lt;/p&gt;  &lt;h2&gt;Extra burden&lt;/h2&gt;  &lt;p&gt;Right, so if we choose the aggregated viewmodel approach, we take on a great deal of responsibility. We need to create the wrapper class, pass in parameters via the ctor, do the newing up in the controller, write tests to verify…while sometimes all of that can be useful, in many cases it’s not. Consider this example:&lt;/p&gt;  &lt;p&gt;A member has many addresses. The /member/rooney/addresses page has a list of addresses and a button named “create new”. Clicking the button shows a jquery iframe popup which handles the create form. The form needs to know about the member’s id (to know which member the new address would belong to). The grid showing all addresses for the user needs an IEnumerable&amp;lt;Address&amp;gt;. So just to pass in MemberId to the addresses page, (if we were using an aggregate viewmodel) our viewmodel would be like this:&lt;/p&gt;  &lt;p&gt;MemberAddressesViewModel    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; - MemberId     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; - IEnumerable&amp;lt;MemberAddress&amp;gt;&lt;/p&gt;  &lt;p&gt;or even &lt;/p&gt;  &lt;p&gt;MemberAddressesViewModel    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; - MemberId     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; - MemberAddressGridViewModel&lt;/p&gt;  &lt;p&gt;where the latter would just wrap an IEnumerable&amp;lt;MemberAddress&amp;gt;.&lt;/p&gt;  &lt;p&gt;We would then have controller code like:&lt;/p&gt;  &lt;p&gt;var gridItems = db.GetAll&amp;lt;Address&amp;gt;().Where(x=&amp;gt;x.MemberId == memberId);    &lt;br /&gt;var model = new MemberAddressesViewModel(memberId, new MemberAddressGridViewModel(gridItems));     &lt;br /&gt;return View(model);&lt;/p&gt;  &lt;p&gt;And I won’t bother writing the test for that.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h2&gt;False sense of doing it right&lt;/h2&gt;  &lt;p&gt;Many think that only using strongly typed vms is the “right” and “proper” way of doing things. They assume that since it’s strongly typed and “driven” by intellisense, it must be right. This is far from the case…at best it just gives you syntactic validation. If you accept that as enough, you run the risk of having semantic errors. If MemberId and LegacyMemberId were both present in the viewmodel and somebody used MemberId to create a link to the member’s legacy data, chances are that’s still wrong, although intellisense and view compilation would let that pass. Even with all those additional indirections, something as simple as which Id should be used go through. When using ViewBag, it’s quite likely that you would double check if you’re using the right thing as it’s loosely typed and you know it can be prone to errors. When using the strongly typed version, after having dedicated vm code, tests to cover it and seeing it pass intellisense, you might accept that simply using the MemberId to generate a link on a member details page may be enough. This shouldn’t be the case and you should be doing UI testing – but if you’re doing that, any errors with the ViewBag version would also get caught. So apart from seeing the cool intellisense, are you really gaining any benefit?&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h2&gt;&lt;/h2&gt;  &lt;h2&gt;But ViewBag isn’t statically checked…that’s bad, right?&lt;/h2&gt;  &lt;p&gt;Is it? Well, I can understand where lack of static checking might be alarming (I still like C# over ruby), but there are cases where the ceremony needed to achieve the static checking means a lot more work with very little gain. In the previous example, We could have left the index page’s model to be of type IEnumerable&amp;lt;MemberAddress&amp;gt; and simply passed in MemberId in ViewBag. Sure, we wouldn’t have got compile time checking and our controller (and view) would build even if the ViewBag.MemberId were not passed in to the controller. The controller side of things could be rectified with a single unit test [ ((long)(ViewBag.MemberId)).ShouldEqual(5) ] – you achieve the same “notification” of the controller not working, you just get it one step later (at unit test time and not at build time). This would be a concern only if you accept code that fails unit tests as “complete”. I don’t, hence it’s not a problem for me. Loss of testability? I don’t think so.&lt;/p&gt;  &lt;p&gt;As for the view side of things – yes, you won’t be able to do Model.MemberId, rather you’ll be doing ViewBag.MemberId. Other than that, the difference is quite minimal. You’d still UI test the page to ensure that the correct variable is getting set properly and if not, it’ll get caught.&lt;/p&gt;  &lt;h2&gt;Benefits of using ViewBag for some data&lt;/h2&gt;  &lt;p&gt;Apart from the example mentioned above, ViewBag is quite useful when passing bits of data to the view that aren’t related to the immediate functionality of the view. For example, widget data or navigation data can be set up in a base controller and put in the ViewBag. If you were to use strongly typed viewmodels, you would have to adhere to a hierarchy of viewmodel classes which would add complexity and rigidity. Anything that doesn’t quite fit into your existing vm hierarchy will be an annoyance and may require time and effort in maintaining your one true viewmodel tree. All that work to pass in some trivial data not directly related to the immediate functionality of the view – seems like a waste. If you set the secondary bits of data via the ViewBag, this becomes so much simpler. And I’m all for simplification. This does mean you’ll need to check whether or not a controller is setting the appropriate ViewBag entry via a unit test. But one test vs all that complexity – it’s really a no brainer for me.&lt;/p&gt;  &lt;h2&gt;So you’re saying not to use strongly typed viewmodels?&lt;/h2&gt;  &lt;p&gt;No I’m not. I’m all for strongly typed viewmodel for the data that is of immediate concern to the view’s functionality. For example, on a EditMember page, the MemberDetails might be the viewmodel. However, NavigationItems, WidgetData, CountryDropDownListItems etc. do not contribute directly to the MemberDetails editing feature. As such, I would put those bits in viewbag while keeping the view’s type as MemberDetails (as opposed to a MemberDetailsWithNavigationAndWidgetAndCountryItemsViewModel). You can see a bit of this in the default project template as well – they set the page’s title in ViewBag and display it in the master from ViewBag. &lt;/p&gt;</description><pubDate>Sun, 13 Mar 2011 05:47:22 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/ViewBag-can-be-goode280a6honestly</guid></item><item><title>Introducing MSMSpec</title><link>http://www.heartysoft.com:80/Introducing-MSMSpec</link><description>&lt;p&gt;&lt;a href="http://msmspec.codeplex.com/"&gt;http://msmspec.codeplex.com/&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;MSMSpec is a T4 based tool that can generate MSTest code to extend your MSpec (Machine.Specifications) tests so that they can run under anything that runs MSTest. This means all the Visual Studio testing features become available for your MSpec tests without the need for Resharper, TDD.NET or setting up an external tool. This can be useful in scenarios where you need to / require / are forced to use certain technologies.&lt;/p&gt;  &lt;h2&gt;Features&lt;/h2&gt;  &lt;p&gt;MSMSpec is a single T4 file that you can add to the root of a class library project that has a reference to Machine.Specifications.dll. The T4 template will scan through the project and identify classes that have MSpec components in them (It, Because, Establish, Cleanup, Ignore). It will mark such classes as partial and create a nested *.mstest.cs file adding a corresponding partial class. The corresponding class will have MSTest attributes on methods which will get called when MSTest runs. If you manually add the T4 file, I would recommend unloading and reloading the project (or simply closing and opening VS). This would enable the testing buttons in visual studio. MSMSpec should work with class hierarchies in tests.&lt;/p&gt;  &lt;h2&gt;&lt;/h2&gt;  &lt;h3&gt;&lt;/h3&gt;  &lt;h2&gt;Installing without NuGet&lt;/h2&gt;  &lt;p&gt;Make sure your project is a C# class library project and already has a reference to Machine.Specifications.dll. Then simply add MSMSpec.tt to the root of your project. Unload and reload the project (or close and open VS) to access the test buttons.&lt;/p&gt;  &lt;h2&gt;Installing via NuGet&lt;/h2&gt;  &lt;p&gt;PM&amp;gt; Install-Package MSMSpec&lt;/p&gt;  &lt;p&gt;or simply search for MSMSpec using the NuGet GUI.&lt;/p&gt;  &lt;p&gt;Unload and reload the project (or close and open VS) to access the test buttons.&lt;/p&gt;  &lt;h2&gt;Requirements&lt;/h2&gt;  &lt;p&gt;VS2010, C#, .NET 4.0 only for now.&lt;/p&gt;  &lt;h2&gt;Limitations&lt;/h2&gt;  &lt;p&gt;MSpec behaviours are not supported. They will be ignored in the current version (and I’m not personally a fan of MSpec behaviours – they result in having to jump around to see all that a test does). It should work with source control systems but hasn’t been fully tested with TFS (yet). Merc / git users should be fine.&lt;/p&gt;  &lt;h2&gt;Tips&lt;/h2&gt;  &lt;p&gt;1. Be sure to install the VS extension Chirpy (&lt;a href="http://chirpy.codeplex.com/"&gt;http://chirpy.codeplex.com/&lt;/a&gt;). This will allow you to run the T4 on every build automagically. This can help resolve many source control issues (for TFS) and also ensure you’re generating the latest MSTest stuff for your MSpec test before testing. With Chirpy installed, go to Tools &amp;gt; Options and set the following:&lt;/p&gt;  &lt;p&gt;&lt;a href="/media/default/images/chirpy.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="chirpy" border="0" alt="chirpy" src="/media/default/images/chirpy_thumb.png" width="858" height="488" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Chirpy will not only auto run T4 files, it can help with css, allow less syntax, has a closure compiler etc.&lt;/p&gt;  &lt;p&gt;2. The MSMSpec T4 generates a nested MSMSpec.cs file that has a TestExecutionHelper class in it. This class is used in the *.mstest.cs files to work around MSTest’s weird test execution order. If you have two test projects where one references the other, this might be a problem as both projects may have this file. In this case, simply open up one MSMSpec.tt file and find the line (near the top):&lt;/p&gt;  &lt;p&gt;&lt;em&gt;const bool ShouldGenerateHelper = true;&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;Set that flag to false and the helper won’t get generated.&lt;/p&gt;  &lt;h2&gt;&lt;/h2&gt;  &lt;h2&gt;Show me ze codez&lt;/h2&gt;  &lt;p&gt;You can find MSMSpec at &lt;a href="http://msmspec.codeplex.com/"&gt;http://msmspec.codeplex.com/&lt;/a&gt; – if you think you can improve it, please feel free to do so. &lt;/p&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;</description><pubDate>Sun, 06 Mar 2011 21:35:00 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/Introducing-MSMSpec</guid></item><item><title>Introducing SeleniuMspec</title><link>http://www.heartysoft.com:80/Introducing-SeleniuMspec</link><description>&lt;p&gt;Happy new year to you all. And to celebrate, I’ve just published my first codeplex project. SeleniuMspec is a template that you can use to generate MSpec BDD tests from Selenium IDE. I’ve been using both Selenium and MSpec for a while now and thought this might save a few seconds when writing some integration tests.&lt;/p&gt;  &lt;p&gt;I’d welcome any ideas / help on improving it. Check it out at &lt;a href="http://seleniumspec.codeplex.com"&gt;http://seleniumspec.codeplex.com&lt;/a&gt;&lt;/p&gt;</description><pubDate>Mon, 03 Jan 2011 15:02:29 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/Introducing-SeleniuMspec</guid></item><item><title>Ninja Coding: Code Comments and Self Explanatory Code</title><link>http://www.heartysoft.com:80/ninja-coding-code-comments</link><description>&lt;p&gt;It’s been a while since I last blogged and thought I would get back into the habit by starting off a new category of posts. The title for this category is “Ninja Coding” and will cover topics from software craftsmanship and better design to very simple tricks and tricks. Today, we will be visiting code comments.&lt;/p&gt;  &lt;p&gt;When I was starting out with programming many many moons ago, the wiser elders I learnt from and the books I read seemed to suggest proper professional code is always properly commented so that a new user (or yourself coming back a few months later) could easily understand the intent of the code. It is a practice that generally seems like a good idea and a lot of people practice it. And I was one of them.&lt;/p&gt;  &lt;p&gt;I guess there are many examples of companies that comment their code aggressively. Few even talk of Microsoft having comments in their code and tools like StyleCop that bring up issues if code isn’t commented “properly”. Lately though, I’m veering more and more away from comments.&lt;/p&gt;  &lt;p&gt;Have I gone mad? Probably, but that’s a different issue ;)&lt;/p&gt;  &lt;h1&gt;&lt;/h1&gt;  &lt;h2&gt;Why I don’t like comments&lt;/h2&gt;  &lt;p&gt;The main reason I’m trying to avoid commenting my code is the concept of self explanatory code. Code should be self explanatory – anyone reading the code should understand what’s going on (given some domain knowledge, of course). Relying on comments to explain what’s going on is hardly a good idea. Code is going to change far more often than comments getting updated. No matter how vigilant your team is, this is bound to happen. At best, this can result in slightly outdated comments. At worst, stale comments may be entirely misleading to what the code is actually doing. Let’s take a look at a quick example from code from a certain company based in Redmond. XmlDocument has a Load method which has a number of overloads, one them being:&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="/media/default/images/XmlDocument.jpg"&gt;&lt;img title="XmlDocument" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="111" alt="XmlDocument" src="/media/default/images/XmlDocument_thumb.jpg" width="685" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The parameter name suggests it’s looking for a file whereas the comment immediately below it specifies a URL. Only by looking at the detailed comment for filename can we ascertain that the parameter can be either. I’m forced to have to read the entire comment to have to know what’s going on. I’d rather not have to. But this is only part of the problem here. Microsoft later introduced Linq to Xml. The new API also has a Load method and one of its (many) overloads look like this:&lt;/p&gt;  &lt;p&gt;&lt;a href="/media/default/images/XDocument.jpg"&gt;&lt;img title="XDocument" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="139" alt="XDocument" src="/media/default/images/XDocument_thumb.jpg" width="559" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Hmm…this time the parameter name reads uri and the comment reads file. The detailed comment this time is slightly less useful – a URI string that references the file. Granted all Xml documents can be thought of as files but the obvious lack of consistency is what troubles me the most. Will it through an exception if a parameter named uri is not an http uri? Will it through if a parameter named filename is passed an http uri? In cases like this, the only real solution seems to be some throwaway code to actually test what’s going on. Had there been methods like LoadFromFile or LoadFromUri, it would have been much more obvious.&lt;/p&gt;  &lt;h2&gt;So, err…no comments?&lt;/h2&gt;  &lt;p&gt;Please note, however, I’m not advocating simply removing all comments. I’m suggesting that self explanatory code is better than using comments to convey intent. If the code itself isn’t self explanatory, then having no comments is far far worse. Let’s go over another quick example, this time from CTP5 of Entity Framework Code First. The DbContext class’s Database property has a very nice CreateIfNotExists method. While the method itself is a nice feature, let’s have a look at its signature:&lt;/p&gt;  &lt;p&gt;&lt;a href="/media/default/images/Create.jpg"&gt;&lt;img title="Create" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="101" alt="Create" src="/media/default/images/Create_thumb.jpg" width="224" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Hmm..the method returns a bool. (And there are no detailed comments either explaining what that bool is for). What does the bool represent? Does it signify that there was not a database and it successfully created it? Does it mean that there is already a database present no recreation is unnecessary? Would it return false if there was already a database present or if an exception was thrown? Will a failure to create a database throw an exception, or simply return false? [On another note, Database.Delete() also returns a bool. Will it do pokemon exception handling and return false in case of errors?] So many questions…and there aren’t comments explaining anything. Will these comments be added in RTM? In that case, will a team of people (who might not have been the developers) go through the code and do their best to put comments in? And even then, will the comments explain everything accurately? And even then, how much will the programmer have to read after hitting “Database.” to understand what his code is going to do? &lt;/p&gt;  &lt;p&gt;In this case, the code is not conveying intent / meaning and there are no comments either. Comments for intellisense might be added in the RTM (I mean, it is a CTP still, right?). And even if they aren’t, there are going to be some official guidance, samples etc. that will show users how to use the library. While this is not ideal, it is something Microsoft can get away with (most of the time) – their libraries are going to be used in the same manner by developers worldwide and implicit customs will be (or become) the “standard”. Anyone learning to use these libraries will put themselves through the pain of having to learn these idioms. That is a luxury the creators of .NET have – it is not one developers in companies should indulge themselves in. &lt;/p&gt;  &lt;h2&gt;An example of self explanatory code&lt;/h2&gt;  &lt;p&gt;Let us look at the following code:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;   
    
public class BusinessException : Exception    
{    
&amp;#160;&amp;#160;&amp;#160; public BusinessException(string message) : base(message)    
&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160; }    
}    
    
public class Calculator    
{    
&amp;#160;&amp;#160;&amp;#160; public double Divide(double a, double b)    
&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //is the divisor 1    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; if (b == 1)    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //divisor is one, simply return the dividend    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return a;    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }    
    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //is the divisor zero    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; if (b == 0)    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //throw business exception for divide by zero    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; throw new BusinessException(&amp;quot;divisor cannot be zero&amp;quot;);    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }    
    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //divide for other divisors    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return a / b;    
&amp;#160;&amp;#160;&amp;#160; }    
}    
    
&lt;/pre&gt; &lt;/p&gt;  &lt;p&gt;Never mind the trivialness of the code or how better it could have been implemented mathematically. The code is quite simple, yet it requires a certain knowledge on the reader’s part to understand what’s going on (what’s the meaning of 1 and 0?). The code may be refactored as follows:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;   
public class Calculator    
{    
&amp;#160;&amp;#160;&amp;#160; public double Divide(double dividend, double divisor)    
&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; if (ShouldReturnTheDividend(divisor))    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return dividend;    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }    
    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; if (IsAttemptToDivideByZero(divisor))    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ThrowDivideByZeroException();    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }    
    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return DivideForOtherDivisors(dividend, divisor);    
&amp;#160;&amp;#160;&amp;#160; }    
    
&amp;#160;&amp;#160;&amp;#160; private static bool ShouldReturnTheDividend(double divisor)    
&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return divisor == 1;    
&amp;#160;&amp;#160;&amp;#160; }    
    
&amp;#160;&amp;#160;&amp;#160; private static bool IsAttemptToDivideByZero(double divisor)    
&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return divisor == 0;    
&amp;#160;&amp;#160;&amp;#160; }    
    
&amp;#160;&amp;#160;&amp;#160; private static void ThrowDivideByZeroException()    
&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; throw new BusinessException(&amp;quot;divisor cannot be zero&amp;quot;);    
&amp;#160;&amp;#160;&amp;#160; }    
&amp;#160;&amp;#160;&amp;#160; 
&amp;#160;&amp;#160;&amp;#160; private static double DivideForOtherDivisors(double dividend, double divisor)    
&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return dividend / divisor;    
&amp;#160;&amp;#160;&amp;#160; }    
}    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;The refactorings are quite simple, yet see how much readable the code in the Divide() method has become. The reader can simply read through the code and understand what’s going on. If they need to alter the code somewhat, it’d be clear which portion is doing what. And when changes are made, nobody has to worry about updating comments.&lt;/p&gt;  &lt;h2&gt;So, err…no comments at all?&lt;/h2&gt;  &lt;p&gt;There are situations when comments can be useful. Every public API / library needs to be understandable and usable. How the API should be used needs to be conveyed to the user of the API / library. This requires communication and this can be done through documentation. Documentation does not necessarily mean separate files. In fact, I can think of many things that can be used for this task. First and foremost, the names of classes, methods, parameters etc. can convey intent. This would be the very first stage of documentation. Effort should be taken so that this stage is enough to convey all intent. Another form of documentation could be a suite of unit tests. They themselves are an example of how the code is intended to be used. Examples can also serve as documentation. Lastly, separate files can also be used to describe the API / library. A feature of VS is xml comments – these can be used to generate separate files (and also intellisense) for documenting. If you do find that separate files are the only way of getting your message across, only then would those xml comments come in handy. Note that these comments are only for generating separate documentation and will need to be kept in sync. Yes, they can also be used to generate intellisense, but even then – if the name of a class, method or entity can reflect the intent, further reading of intellisense descriptions would become redundant. Forcing other people to read your intellisense comments is making others pay for your sloppiness.&lt;/p&gt;  &lt;p&gt;Simply put, if you feel the need for comments in explaining to your team (or future self) what you’re code is doing, consider refactoring the code by renaming stuff or moving code into methods with names that reflect what you wanted to convey via the comment. For public APIs where you’re trying to communicate something to a third party that will not have the source code, try to name classes, methods, parameters etc. in such a manner that comments won’t be necessary. If the intent is still ambiguous, only then succumb to commenting and ensure the API is properly documented – via xml documentation, separate documents, examples or simply a suite of unit tests.&lt;/p&gt;  &lt;h2&gt;What about StyleCop&lt;/h2&gt;  &lt;p&gt;StyleCop is a tool that can be used to enforce coding styles in a team. It is configurable and by default it enforces the rules in accordance with Microsoft’s Framework Design Guidelines. While that’s all good, you need to think about whether or not you’re building a framework for public consumption (like the .NET framework). And also the fact that your team might not have the resources to keep comments updated and in sync(and even if you do, things might slip through the net – as we saw in the xml example earlier). StyleCop is simply a tool to ensure a certain style of coding within a team. Personally, if it were a choice between self explanatory code and more points on the default StyleCop rules, I’d choose self explanatory code any day. A better option might be to set up StyleCop rules to enforce no comments in non-public code!&lt;/p&gt;</description><pubDate>Mon, 20 Dec 2010 02:06:41 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/ninja-coding-code-comments</guid></item><item><title>ASP.NET MVC 3 CTP1 View Improvements</title><link>http://www.heartysoft.com:80/aspnet-mvc-3-ctp1-view-improvements</link><description>&lt;p&gt;ASP.NET MVC 3 CTP1 has introduced many improvements, not least of which is in the View. This screencast explores the improvements in the View, specially looking at the awesome new ViewEngine – Razor. It covers Razor syntax, layouts, templates, issues with namespaces etc. It also looks at the new dynamic viewmodel and shows how it can be used to clean up view code. It's just over 45 minutes long and we do go into a little depth. Hope you enjoy it :)&lt;/p&gt;  &lt;div&gt;&lt;iframe height="500" src="/videos/Mvc3Ctp1ViewImprovements/default.html" frameborder="0" width="740" scrolling="no"&gt;&lt;/iframe&gt;&lt;/div&gt;  &lt;p&gt;&lt;em&gt;PS: This is my first ever screencast. If you have any tips regarding recording, hosting video etc. I'd be happy for pointers. &lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;PPS: I recently was invited to take a session on ASP.NET MVC 3 CTP1 for the virtual techdays hosted by Microsoft India recently. I got about 2 days notice and due to communication problems resulting in my gaining access to the virtual meet 30 minutes into a one hour session, I had to cut it way short. I later discovered that I had my monitor set to its 1920x1200 native resolution, so I don't think anyone got anything visual out of it. I was surprised I got a 6.71 (out of 9) rating from the attendees – I was expecting something like 1 or 2 ;). I hope this video makes up for at least part of that dreadful session.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;PPPS: The video doesn't seem to be progressive-downloading in Chrome. I'll try to fix this tomorrow. For now, please use IE or FF.&lt;/em&gt;&lt;/p&gt;</description><pubDate>Wed, 15 Sep 2010 16:12:40 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/aspnet-mvc-3-ctp1-view-improvements</guid></item><item><title>Selecting ListView Items with CheckBoxes</title><link>http://www.heartysoft.com:80/Selecting-ListView-Items-with-CheckBoxes</link><description>&lt;p&gt;Often we need to enable users to select multiple items from a ListView control and do a batch operation on them. While the ListView control does enable selection, it only supports selecting one row (item) at a time. This article shows a nice, easy and reusable way to enable multiple selection with checkboxes.&lt;/p&gt;  &lt;h3&gt;The Project&lt;/h3&gt;  &lt;p&gt;I've created a very simple &amp;quot;Empty ASP.NET WebForms Application&amp;quot; and added a standard Default.aspx page. I've created an App_Data folder and added a database called PeopleDB.mdf into it. The database consists of one simple table holding the Id, Name and AwesomePoints of a number of people* and also if they are attending some event. We want to list them in a simple ListView with pagination, and be able to select some of them and set all of the selected people's AwesomePoints in one go. We also want to be able to select some other people and set the boolean stating whether or not they're attending.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;*these people are purely fictional and any resemblance to real people are entirely coincidental ;)&lt;/em&gt;&lt;/p&gt;  &lt;h3&gt;The Page Layout&lt;/h3&gt;  &lt;p&gt;The page layout is fairly simple. It's ugly and OMG I'm using tables for layout – help – the Earth is gonna explode…yeah right. At least it's apparent what needs doing. We show a list of people and provide checkboxes for each row to select the person for either batch update of their AwesomePoints or batch update of their IsAttending value. At the end of the page, we provide controls to actually carry out the batch updates. Here's the page body's markup so far:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:xml'&gt;    
    
&amp;lt;body&amp;gt;     
&amp;#160;&amp;#160;&amp;#160; &amp;lt;form id=&amp;quot;form1&amp;quot; runat=&amp;quot;server&amp;quot;&amp;gt;     
&amp;#160;&amp;#160;&amp;#160; &amp;lt;div&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;asp:ListView runat=&amp;quot;server&amp;quot; DataKeyNames='Id' ID='lvPeople' ItemPlaceholderID='ph1'&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;LayoutTemplate&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;table&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;thead&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;tr&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;th&amp;gt;Name&amp;lt;/th&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;th&amp;gt;Awesome Points&amp;lt;/th&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;th&amp;gt;Is Attending&amp;lt;/th&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;th&amp;gt;Select for Updating Awesome Points&amp;lt;/th&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;th&amp;gt;Select for Updating Attendee Status&amp;lt;/th&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/tr&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/thead&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;tbody&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;asp:PlaceHolder runat=&amp;quot;server&amp;quot; ID='ph1' /&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/tbody&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/table&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/LayoutTemplate&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;ItemTemplate&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;tr&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;td&amp;gt;&amp;lt;%# Eval(&amp;quot;Name&amp;quot;) %&amp;gt;&amp;lt;/td&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;td&amp;gt;&amp;lt;%# Eval(&amp;quot;AwesomePoints&amp;quot;) %&amp;gt;&amp;lt;/td&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;td&amp;gt;&amp;lt;%# Eval(&amp;quot;IsAttending&amp;quot;) %&amp;gt;&amp;lt;/td&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;td&amp;gt;&amp;lt;asp:CheckBox runat=&amp;quot;server&amp;quot; ID='chkAwesomePoints' /&amp;gt;&amp;lt;/td&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;td&amp;gt;&amp;lt;asp:CheckBox runat=&amp;quot;server&amp;quot; ID='chkAttending' /&amp;gt;&amp;lt;/td&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/tr&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/ItemTemplate&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/asp:ListView     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;div&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;asp:DataPager ID=&amp;quot;DataPager1&amp;quot; runat=&amp;quot;server&amp;quot; PagedControlID='lvPeople' PageSize='5'&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;Fields&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;asp:NumericPagerField /&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/Fields&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/asp:DataPager&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/div&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;br /&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;table border='none'&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;tbody&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;tr&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;td&amp;gt;Set Awesome Points to: &amp;lt;asp:TextBox runat=&amp;quot;server&amp;quot; ID='txtAwesomePoints' /&amp;gt;&amp;lt;/td&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;td&amp;gt;&amp;lt;asp:Button Text=&amp;quot;Update Awesome Points&amp;quot; runat=&amp;quot;server&amp;quot; /&amp;gt;&amp;lt;/td&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/tr&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;tr&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;td&amp;gt;Set Attendee Status to: &amp;lt;asp:CheckBox runat=&amp;quot;server&amp;quot; ID='chkAttending' /&amp;gt;&amp;lt;/td&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;td&amp;gt;&amp;lt;asp:Button Text=&amp;quot;Update Attending Status&amp;quot; runat=&amp;quot;server&amp;quot; /&amp;gt;&amp;lt;/td&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/tr&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/tbody&amp;gt;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;/table&amp;gt;     
&amp;#160;&amp;#160;&amp;#160; &amp;lt;/div&amp;gt;     
&amp;#160;&amp;#160;&amp;#160; &amp;lt;/form&amp;gt;     
&amp;lt;/body&amp;gt;     
    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;Notice that I've set the DataKeyNames fo the ListView to Id. I'll explain this part later.&lt;/p&gt;  &lt;h3&gt;&lt;/h3&gt;  &lt;h3&gt;&lt;/h3&gt;  &lt;h3&gt;The DataSource&lt;/h3&gt;  &lt;p&gt;We have the ListView, we now need to add a datasource. I could easily use a SqlDataSource or whatever else I want. But since I'll be updating the database as well, I'll just add an Entity Framework model to the project (and use an EntityDataSource control to populate the ListView). Right click the project in solution explorer and select &amp;quot;Add New Item&amp;quot;. I chose ADO.NET Entity Data Model from the popup and name it PeopleModel.edmx.&lt;/p&gt;  &lt;p&gt;&lt;a href="/media/default/images/1_adding_EF.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="1_adding_EF" border="0" alt="1_adding_EF" src="/media/default/images/1_adding_EF_thumb.png" width="831" height="577" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;From the next window, I select &amp;quot;Generate From Database&amp;quot;. I get an option to select the connection to be used. Since I don't have one to the mdf file in App_Data, I select &amp;quot;New Connection&amp;quot;. I ensure that the &amp;quot;Microsft SQL Serv Database File (SqlClient)&amp;quot; is selected and I &amp;quot;Browse&amp;quot; to my .mdf file in the App_Code folder. You could obviously use other databases and you'd configure the connection here. Finishing this dialog takes you back to the previous one, where you can click &amp;quot;Next&amp;quot;. &lt;/p&gt;  &lt;p&gt;&lt;a href="/media/default/images/2_EF_connection.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="2_EF_connection" border="0" alt="2_EF_connection" src="/media/default/images/2_EF_connection_thumb.png" width="633" height="565" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The next window gives you options of selecting a subset or all of the tables, sprocs and views in the target database. We're only interested in the People table, so select it and click &amp;quot;Finish&amp;quot;.&lt;/p&gt;  &lt;p&gt;&lt;a href="/media/default/images/3_select_table.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="3_select_table" border="0" alt="3_select_table" src="/media/default/images/3_select_table_thumb.png" width="570" height="509" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;And that's it – our EF4 model is done. Let's now add an EntityDataSource to the page.To do this, add the following markup right after the ListView:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:xml'&gt;    
    
&amp;lt;asp:EntityDataSource runat=&amp;quot;server&amp;quot; ID='edsPeople'     
&amp;#160;&amp;#160;&amp;#160; ConnectionString=&amp;quot;name=PeopleDBEntities&amp;quot;     
&amp;#160;&amp;#160;&amp;#160; DefaultContainerName=&amp;quot;PeopleDBEntities&amp;quot; EnableFlattening=&amp;quot;False&amp;quot;     
&amp;#160;&amp;#160;&amp;#160; EntitySetName=&amp;quot;People&amp;quot;&amp;gt;&amp;lt;/asp:EntityDataSource&amp;gt;     
    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;(If you're using the webforms designer to hook up the datasource, be sure to compile the project before attempting to do so. Without a recompile, the required metadata would not be available to the user.)&lt;/p&gt;  &lt;p&gt;Next, set the DataSourceId of the ListView to match the Id of the EntityDataSource:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:xml'&gt;    
    
&amp;lt;asp:ListView runat=&amp;quot;server&amp;quot; ID='lvPeople' DataKeyNames='Id' ItemPlaceholderID='ph1'&lt;strong&gt; DataSourceID='edsPeople'&lt;/strong&gt;&amp;gt;     
    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;At this point, we can run the page to see this:&lt;/p&gt;  &lt;p&gt;&lt;a href="/media/default/images/4_initial_results.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="4_initial_results" border="0" alt="4_initial_results" src="/media/default/images/4_initial_results_thumb.png" width="741" height="253" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;h2&gt;&lt;/h2&gt;  &lt;h3&gt;&amp;#160;&lt;/h3&gt;  &lt;h3&gt;The ListView Extension&lt;/h3&gt;  &lt;p&gt;Add a folder called Extensions and in it, create a class called ListViewExtensions with the following code:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;    
    
public static class ListViewExtensions     
{     
&amp;#160;&amp;#160;&amp;#160; public static List&amp;lt;DataKey&amp;gt; GetSelectedDataKeys(this ListView control, string checkBoxId)     
&amp;#160;&amp;#160;&amp;#160; {     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return control.Items.Where(x =&amp;gt; IsChecked(x, checkBoxId))     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; .Select(x =&amp;gt; control.DataKeys[x.DisplayIndex])     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; .ToList();     
&amp;#160;&amp;#160;&amp;#160; } 
  &amp;#160;&amp;#160;&amp;#160; private static bool IsChecked(ListViewDataItem item, string checkBoxId)    
&amp;#160;&amp;#160;&amp;#160; {     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var control = item.FindControl(checkBoxId) as CheckBox;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; if (control == null)     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return false;     
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } 
  &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return control.Checked;    
&amp;#160;&amp;#160;&amp;#160; }     
}     
    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;This class is the heart of what we're trying to do. It basically finds the checkbox with the Id passed in and returns the DataKey of every item in the ListView that has said checkbox checked. Remember the DataKeyNames property of the ListView that we set earlier? This is where that comes in. You can pass the names of the properties of each data item that you wish to have access to later on to the DataKeyNames. In our case, we only need the Id property, as such we passed in &amp;quot;Id&amp;quot;. If for some reason, we wanted the AwesomePoints property too, we'd pass in &amp;quot;Id, AwesomePoints&amp;quot;. Notice that our extension method returns a list of DataKeys. What is a DataKey? It's basically an object that holds the values of the properties mentioned in DataKeyNames. It has two properties – Value and Values. Value hold the value of the first data key property. So, if we had passed in &amp;quot;Id, AwesomePoints&amp;quot;, Value would hold the value of the Id property for the associated item. Values on the other hand has an ordered dictionary. You would then find the value of the Id property in Values[0] and the value of the AwesomePoints property in Values[1] and so on.&lt;/p&gt;  &lt;h3&gt;Putting it to Work&lt;/h3&gt;  &lt;p&gt;We'll now add two handlers for the two button click events:&lt;/p&gt;  &lt;p&gt;&lt;pre class='brush:c#'&gt;   
    
protected void UpdateAwesomePointsButton_Click(object sender, EventArgs e)    
{    
&amp;#160;&amp;#160;&amp;#160; var selectedKeys = lvPeople.GetSelectedDataKeys(&amp;quot;chkAwesomePoints&amp;quot;);    
&amp;#160;&amp;#160;&amp;#160; var selectedIds = selectedKeys.Select(x =&amp;gt; new Guid(x.Value.ToString())); 
  &amp;#160;&amp;#160;&amp;#160; if (selectedIds.Count() &amp;gt; 0)   
&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var targetPoints = int.Parse(txtAwesomePoints.Text);    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var db = new PeopleDBEntities(); 
  &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; db.People.Where(x =&amp;gt; selectedIds.Contains(x.Id))   
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; .ToList()    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; .ForEach(x =&amp;gt; x.AwesomePoints = targetPoints); 
  &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; db.SaveChanges();   
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; lvPeople.DataBind();    
&amp;#160;&amp;#160;&amp;#160; } 
  }    
    
protected void UpdateAttendeeStatusButton_Click(object sender, EventArgs e)    
{    
&amp;#160;&amp;#160;&amp;#160; var selectedKeys = lvPeople.GetSelectedDataKeys(&amp;quot;chkAttending&amp;quot;);    
&amp;#160;&amp;#160;&amp;#160; var selectedIds = selectedKeys.Select(x =&amp;gt; new Guid(x.Value.ToString())); 
  &amp;#160;&amp;#160;&amp;#160; if (selectedIds.Count() &amp;gt; 0)   
&amp;#160;&amp;#160;&amp;#160; {    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var targetValue = chkAttending.Checked;    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var db = new PeopleDBEntities(); 
  &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; db.People.Where(x =&amp;gt; selectedIds.Contains(x.Id))   
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; .ToList()    
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; .ForEach(x =&amp;gt; x.IsAttending = targetValue); 
  &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; db.SaveChanges();   
&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; lvPeople.DataBind();    
&amp;#160;&amp;#160;&amp;#160; }    
}    
    
&lt;/pre&gt;&lt;/p&gt;  &lt;p&gt;All we've done here is used our extension method to get the datakeys of the selected items in the ListView and have updated those items accordingly. Granted there's no validation or anything fancy going on – hey, this is a demo – it shows how we can know which items of a ListView have been selected.&lt;/p&gt;  &lt;h3&gt;Source&lt;/h3&gt;  &lt;p&gt;You can download the source by &lt;a href="http://cid-9d8a7728356393b1.office.live.com/self.aspx/.Public/code/ListViewSelectionDemo.zip" target="_blank"&gt;clicking here.&lt;/a&gt;&lt;/p&gt;</description><pubDate>Sat, 14 Aug 2010 04:57:28 GMT</pubDate><guid isPermaLink="true">http://www.heartysoft.com:80/Selecting-ListView-Items-with-CheckBoxes</guid></item></channel></rss>