BusinessRx Community

Dedicated to the advancement of software, technology and the people who devote their lives to it.

Welcome to BusinessRx Community Sign in | Join | Help
in Search

BusinessRx Reading List

These blog entries are written by industry experts and leaders. We consider this content to be a good read for any software developer or web technologist.

September 2008 - Posts

  • jQuery and Microsoft

    jQuery is a lightweight open source JavaScript library (only 15kb in size) that in a relatively short span of time has become one of the most popular libraries on the web.

    A big part of the appeal of jQuery is that it allows you to elegantly (and efficiently) find and manipulate HTML elements with minimum lines of code.  jQuery supports this via a nice "selector" API that allows developers to query for HTML elements, and then apply "commands" to them.  One of the characteristics of jQuery commands is that they can be "chained" together - so that the result of one command can feed into another.  jQuery also includes a built-in set of animation APIs that can be used as commands.  The combination allows you to do some really cool things with only a few keystrokes.

    For example, the below JavaScript uses jQuery to find all <div> elements within a page that have a CSS class of "product", and then animate them to slowly disappear:

    As another example, the JavaScript below uses jQuery to find a specific <table> on the page with an id of "datagrid1", then retrieves every other <tr> row within the datagrid, and sets those <tr> elements to have a CSS class of "even" - which could be used to alternate the background color of each row:

    [Note: both of these samples were adapted from code snippets in the excellent jQuery in Action book]

    Providing the ability to perform selection and animation operations like above is something that a lot of developers have asked us to add to ASP.NET AJAX, and this support was something we listed as a proposed feature in the ASP.NET AJAX Roadmap we published a few months ago.  As the team started to investigate building it, though, they quickly realized that the jQuery support for these scenarios is already excellent, and that there is a huge ecosystem and community built up around it already.  The jQuery library also works well on the same page with ASP.NET AJAX and the ASP.NET AJAX Control Toolkit.

    Rather than duplicate functionality, we thought, wouldn't it be great to just use jQuery as-is, and add it as a standard, supported, library in VS/ASP.NET, and then focus our energy building new features that took advantage of it?  We sent mail the jQuery team to gauge their interest in this, and quickly heard back that they thought that it sounded like an interesting idea too.

    Supporting jQuery

    I'm excited today to announce that Microsoft will be shipping jQuery with Visual Studio going forward.  We will distribute the jQuery JavaScript library as-is, and will not be forking or changing the source from the main jQuery branch.  The files will continue to use and ship under the existing jQuery MIT license.

    We will also distribute intellisense-annotated versions that provide great Visual Studio intellisense and help-integration at design-time.  For example:

    and with a chained command:

    The jQuery intellisense annotation support will be available as a free web-download in a few weeks (and will work great with VS 2008 SP1 and the free Visual Web Developer 2008 Express SP1).  The new ASP.NET MVC download will also distribute it, and add the jQuery library by default to all new projects.

    We will also extend Microsoft product support to jQuery beginning later this year, which will enable developers and enterprises to call and open jQuery support cases 24x7 with Microsoft PSS.

    Going forward we'll use jQuery as one of the libraries used to implement higher-level controls in the ASP.NET AJAX Control Toolkit, as well as to implement new Ajax server-side helper methods for ASP.NET MVC.  New features we add to ASP.NET AJAX (like the new client template support) will be designed to integrate nicely with jQuery as well. 

    We also plan to contribute tests, bug fixes, and patches back to the jQuery open source project.  These will all go through the standard jQuery patch review process.

    Summary

    We are really excited to be able to partner with the jQuery team on this.  jQuery is a fantastic library, and something we think can really benefit ASP.NET and ASP.NET AJAX developers.  We are looking forward to having it work great with Visual Studio and ASP.NET, and to help bring it to an even larger set of developers.

    For more details on today's announcement, please check out John Resig's post on the jQuery team blog.  Scott Hanselman is also about to post a nice tutorial that shows off integrating jQuery with ASP.NET AJAX (including the new client templating engine) as well as ADO.NET Data Services (which shipped in .NET 3.5 SP1 and was previously code-named "Astoria").

    Hope this helps,

    Scott

  • A Twist on the Monty Hall Problem

    Steve Smith has posted a couple of interesting probability problem solvers on his blog recently. His most recent one is a twist on the Monty Hall problem. I mentioned the Monty Hall problem and its solution in an earlier blog entry of mine, For Some Probability Problems, Seeing Can Be Believing:

    When facing a particularly tough probabilty problem sometimes it helps to sit down and draw out the possible outcomes for the given scenarios. In doing so, things that may otherwise seem very complex boil down to a very apparent solution or explanation.

    A great example of simplicity through diagraming is the Monty Hall problem, which goes like this: You are a contestant on the TV game show, Let's Make a Deal and are presented with three doors. Behind one door there is a luxury car. Behind the other two doors there is a poster of a car. The game show host asks you to pick a door. After choosing one, the game show host reveals one of the other doors that has a poster behind it and then asks you if you want to change your door choice to the other unopened door. What is the best strategy?”

    The answer is that you should change the door you had selected, because there's a 2/3 probability that the door you did not select houses the luxury car. In other words, there is a 2/3 probability that the door you picked has the remaining poster. The solution seems backwards. It seems paradoxical that the door the host reveals to have a poster of a car could have any influence on your initial selection. But if you sit down and draw out the various probabilities you can see that there's there are more good outcomes if you make the switch than if you hold fast to your initial choice. The following diagram was created by Rick Block; here, instead of a poster of a car you get a goat. Same difference.

    Steve's most recent puzzle asks what would happen if instead of a single contestent in the Monty Hall problem there were multiple participants:

    I take 3 plain envelopes and put a $100 bill inside one of them, seal them, and give one to you, one to Bob, and one to Carrie, at random.  Then I randomly ask one of you to open an envelope - for the sake of argument let's say I choose Carrie.  Carrie opens her envelope to reveal that it is empty.  Now I offer you the choice to trade envelopes with Bob - should you trade? And now I ask Bob the exact same question.  Should he trade?

    As written, Steve's problem isn't that interesting. If he is randomly choosing one envelope to open then there is no advantage to be gained by changing or not changing your envelope. Now, if Steve were to reword the problem as follows (as I believe was his intention), then things are a bit more interesting:

    I take 3 plain envelopes and put a $100 bill inside one of them. I then let you choose one, and then give the other two to Bob and Carrie.  I then open one of the envelopes (Carrie's or Bob's) knowing that it is empty. Now I offer you the choice to trade envelopes with Bob - should you trade? And now I ask Bob the exact same question.  Should he trade?

    There is a big difference between these two questions. In the first one, everything is random; in the second one, the host (Steve Smith) knowingly opens one of the envelopes that is empty. It's also important that the host is forced to open Bob or Carrie's envelope, and cannot attempt to open yours.

    The answer to this problem can be worked out the same way as the traditional Monty Hall problem - by putting pen to paper and drawing out the probability tree, although I used the name Cal instead of Carrie. (See the full size image...) 

    As you can see, your odds are maximized if you get your hands on your contestant's envelope, while your opponent's best bet is to keep his envelope. Therefore, whoever gets to make the final change is the person with the best odds.

    Another tool for determining how a probability puzzle works out is through empirical means. You can oftentimes write a terse program that simulates the problem at hand thousands of times and tallies up the various outcomes. I created such a program in C#.

        1 for (int iter = 0; iter < ITERATIONS; iter++)

        2 {

        3     int moneyPos = rnd.Next(3);

        4     int bucketChoice = 2;

        5     int openDoor = rnd.Next(2);

        6     if (moneyPos == openDoor)

        7         openDoor = 1 - openDoor;

        8     int oponentsPos = 1 - openDoor;

        9 

       10     bool makeSwap = rnd.Next(2) % 2 == 0;

       11     bool otherContestantMakesSwap = rnd.Next(2) % 2 == 0;

       12 

       13     if (makeSwap)

       14     {

       15         tmp = bucketChoice;

       16         bucketChoice = oponentsPos;

       17         oponentsPos = tmp;

       18     }

       19 

       20     if (otherContestantMakesSwap)

       21     {

       22         tmp = bucketChoice;

       23         bucketChoice = oponentsPos;

       24         oponentsPos = tmp;

       25     }

       26 

       27     // See if we won

       28     if (bucketChoice == moneyPos)

       29     {

       30         if (makeSwap && otherContestantMakesSwap)

       31             numberOfWinningsWhenSwappingAndContestantSwaps++;

       32         else if (makeSwap && !otherContestantMakesSwap)

       33             numberOfWinningsWhenSwappingAndContestantStays++;

       34         else if (!makeSwap && otherContestantMakesSwap)

       35             numberOfWinningsWhenStayingAndContesstantSwaps++;

       36         else

       37             numberOfWinningsWhenStayingAndContesstantStays++;

       38     }

       39     else if (moneyPos == oponentsPos)

       40     {

       41         if (makeSwap && otherContestantMakesSwap)

       42             numberOfContestantWinsWhenYouSwapAndContestantSwaps++;

       43         else if (makeSwap && !otherContestantMakesSwap)

       44             numberOfContestantWinsWhenYouSwapAndContestantStays++;

       45         else if (!makeSwap && otherContestantMakesSwap)

       46             numberOfContestantWinsWhenYouStayAndContestantSwaps++;

       47         else

       48             numberOfContestantWinsWhenYouStayAndContestantStays++;

       49     }

       50 }

       51 

       52 // Summarize results

       53 Console.WriteLine("Percentage of Wins When Swapping and Contestant Swapping: {0}", Convert.ToDecimal(numberOfWinningsWhenSwappingAndContestantSwaps) / Convert.ToDecimal(ITERATIONS));

       54 Console.WriteLine("Percentage of Wins When Swapping and Contestant Stays: {0}", Convert.ToDecimal(numberOfWinningsWhenSwappingAndContestantStays) / Convert.ToDecimal(ITERATIONS));

       55 Console.WriteLine("Percentage of Wins When Staying and Contestant Swapping: {0}", Convert.ToDecimal(numberOfWinningsWhenStayingAndContesstantSwaps) / Convert.ToDecimal(ITERATIONS));

       56 Console.WriteLine("Percentage of Wins When Staying and Contestant Stays: {0}", Convert.ToDecimal(numberOfWinningsWhenStayingAndContesstantStays) / Convert.ToDecimal(ITERATIONS));

       57 Console.WriteLine("");

       58 Console.WriteLine("Percentage of Contestant Wins When Swapping and Contestant Swapping: {0}", Convert.ToDecimal(numberOfContestantWinsWhenYouSwapAndContestantSwaps) / Convert.ToDecimal(ITERATIONS));

       59 Console.WriteLine("Percentage of Contestant Wins When Swapping and Contestant Stays: {0}", Convert.ToDecimal(numberOfContestantWinsWhenYouSwapAndContestantStays) / Convert.ToDecimal(ITERATIONS));

       60 Console.WriteLine("Percentage of Contestant Wins When Staying and Contestant Swapping: {0}", Convert.ToDecimal(numberOfContestantWinsWhenYouStayAndContestantSwaps) / Convert.ToDecimal(ITERATIONS));

       61 Console.WriteLine("Percentage of Contestant Wins When Staying and Contestant Stays: {0}", Convert.ToDecimal(numberOfContestantWinsWhenYouStayAndContestantStays) / Convert.ToDecimal(ITERATIONS));

    I set ITERATIONS to 50,000 and let 'er rip. The following output confirmed my initial assumptions:

    Percentage of Wins When Swapping and Contestant Swapping: 0.08266
    Percentage of Wins When Swapping and Contestant Stays: 0.16618
    Percentage of Wins When Staying and Contestant Swapping: 0.16482
    Percentage of Wins When Staying and Contestant Stays: 0.08318

    Percentage of Contestant Wins When Swapping and Contestant Swapping: 0.16754
    Percentage of Contestant Wins When Swapping and Contestant Stays: 0.08386
    Percentage of Contestant Wins When Staying and Contestant Swapping: 0.08262
    Percentage of Contestant Wins When Staying and Contestant Stays: 0.16914

    As you can see, your chances of winning are best when you swap and your contestant stays or when you stay and your contestant swaps - namely, when you get your hands on your contestant's envelope. Your contestant, however, does best when he hangs onto his envelope, either by having you both stay or both change.

  • In Memoriam to My Nephew, Matthew O'Bryant

     My nephew, Matthew O'Bryant, was one of the two US military personnel that was killed in the terrorist bombing of the Pakistan Marriott last weekend.  He was a great kid (22 years old) and he will be missed very much by his wife, brother and sisters, parents, the rest of our family, and his many friends.

    http://www.wkrg.com/local/article/local_sailor_killed_in_pakistan_bombing/18566/
    http://www.myfoxgulfcoast.com/myfox/pages/News/Detail?contentId=7499322&version=2&locale=EN-US&layoutCode=TSTY&pageId=3.2.1
    http://www.al.com/news/press-register/metro.ssf?/base/news/1222247795109040.xml&coll=3

     

  • Silverlight 2 Release Candidate Now Available

    This evening we published the first public release candidate of Silverlight 2.

    There are still a small handful of bugs fixes that we plan to make before we finally ship.  We are releasing today's build, though, so that developers can start to update their existing Silverlight Beta2 applications so that they'll work the day the final release ships, as well as to enable developers to report any last minute showstopper issues that we haven't found internally (please report any of these on the www.silverlight.net forums).

    Important: We are releasing only the Silverlight Developer Runtime edition (as well as the VS and Blend tools to support it) today, and are not releasing the regular end-user edition of Silverlight.  This is because we want to give existing developers a short amount of time to update their applications to work with the final Silverlight 2 APIs before sites are allowed to go live with it.  There are some breaking changes between Beta2 and this RC, and we want to make sure that existing sites can update to the final release quickly once the final release is out.  As such, you can only use the RC for development right now - you can't go live with the new APIs until the final release is shipped (which will be soon though).

    You can download today's Silverlight Release Candidate and accompanying VS and Blend support for it here.  Note that Expression Blend support for Silverlight 2 is now provided using Blend 2.0 SP1.  You will need to install Blend 2.0 before applying the SP1 service pack that adds Silverlight 2 support.  If you don't already have Blend 2.0 installed you can download a free trial of it here.

    Beta2->RC API Updates

    Today's release candidate includes a ton of bug fix and some significant performance optimization work.

    Today's release candidate also includes a number of final API tweaks designed to fix differences between Silverlight and the full .NET Framework.  Most of these changes are relatively small (order of parameters, renames of methods/properties, movement of types across namespaces, etc) although there are a number of them.  You can read this blog post and download this document to get a listing of the known API breaking changes made from the Beta2 release. 

    We have updated the styles of the controls shipped with Silverlight, and have also modified some of the state groups and control template names they use.  When upgrading from Beta2 you might find it useful to temporarily remove any custom style templates you've defined, and get your application functionality working using the RC first - and then after that works add back in the styles one style definition at a time to catch any rename/behavior change issues with them.

    If you find yourself stuck with an question/issue moving from Beta2 to the RC, please report it on the www.silverlight.net forums (Silverlight team members will be on there helping folks).  If after a day or two you aren't getting an answer please send me email (scottgu@microsoft.com) and I can help or connect you with someone who knows the answer.

    New Controls

    Today's release candidate includes a bunch of feature additions and tweaks across Silverlight 2, as well as in the VS and Blend tools targeting it. In general you'll find a number of nice improvements across the controls, networking, data caching, layout, rendering, media stack, and other components and sub-systems.

    Over the next few months we will be releasing a lot of new Silverlight 2 controls (more details on these soon).  Today's release candidate includes three new core controls - ComboBox, ProgressBar, and PasswordBox - that we are adding directly to the core Silverlight runtime download (which is still only 4.6MB in size, and only takes a few seconds to install):

    At runtime these controls by default look like:

    The ComboBox in Silverlight 2 supports standard DropDownList semantics.  In addition to statically defining items like above, you can also use databinding with it.  For example, we could define a "Person" class like below:

    And the add a ComboBox to a page like so:

    And then write the below code to databind a collection of Person objects to the ComboBox (by setting its ItemSource property):

    At runtime our simple app will then display the data-bound Person names (note that we set the DisplayMemberPath property on the ComboBox above to display the "Name" value from our Person objects):

    We could then implement a SelectionChanged event handler like below to run code when a person is selected from the ComboBox:

    Notice above how we can retrieve a reference to the selected "Person" object from the databound ComboBox using the ComboBox's "SelectedItem" property. 

    We can then call the MessageBox.Show() helper method (new in the RC) to display a modal dialog box that displays some details about our selected person:

     

    New Control Skins

    The final release of Silverlight 2 will have a much more polished set of default control template skins than those that were in Beta1 and Beta2.  Our goal with the default control templates is to have a look that is professional and attractive, can be used in the majority of applications as-is (without requiring you to author custom style templates), and which is also easily tweakable using Expression Blend.

    Today's RC build has skins that are close to the final look we plan to ship (there are a few final tweaks we are doing post RC on the focus color of controls, as well as to tighten up and tweak a few issues in some of the control templates).  Below is the default look for the DataGrid, RadioButton, CheckBoxes, and the DatePicker controls with today's RC build:

    Note that the DatePicker control above allows users to type in a date (with a masked edit to ensure it is a valid date), or they can click the calendar icon to the right of the textbox and select the date using a popup Calendar control:

    One of the most powerful features of Silverlight and WPF, of course, is the ability for designers and developers to completely customize the look and feel of any control.  This goes beyond simple styling of colors and fonts - you can literally completely change the visual UI of a control, as well as customize its behavior (for example: add animation) without writing any code.

    Within Expression Blend, simply right-click on any Silverlight control and choose the "Edit Control Parts" sub-menu to open and edit its control template:

     

    When in control template editing mode, you can manipulate any sub-element of a control (for example: a checkbox's inner content), as well as customize each "state" its in (notice the states pane circled in red below).  This allows designers to customize what the control looks like in individual states (for example: checked, unchecked, mouseover, etc).  Silverlight will then automatically handle animating the control from state to state depending on the user action:

    You can learn more about how Silverlight's Visual State Model works from my previous blog post here

    Previous releases of Silverlight often rendered graphics on sub-pixel locations - which could cause lines and shapes to sometimes appear "fuzzy".  The RC of Silverlight has a new features called "layout rounding" that causes the layout system to round the final measure of a control to an integer ("pixel snapping"), which results in crisper lines and fewer rendering artifacts.  This feature is now on by default, and helps make applications look nicer.

    Summary

    The final release of Silverlight is not that far off now.  It has been a pretty amazing project that has come a long way in a pretty short amount of time.

    If you have existing Beta2 applications, please start getting them ready for the final release - as once we release Silverlight 2, users that have existing beta releases installed will automatically be upgraded to use the final version.  Testing your application out with the release candidate will ensure that you can easily update your applications and have them ready within hours of the final release.

    Let us know if you find issues with today's release candidate, and please make sure to post them on the forums on http://www.silverlight.net.

    Hope this helps,

    Scott

  • Raleigh Alt.Net Beer Users Group

    I am happy to announce that this Thursday (9/25) will be the first meeting of the new Raleigh Alt.Net Beer Users Group, or Alt.bug for short. The basic idea is just to go hang out and discuss whatever comes up. We might consider setting topics for future meetings, but for this first meeting we are just going to see what happens. I have already confirmed that Derik, Dug, and Jayme will be coming and hopefully many more will show up as well.

    The meeting will be at O'Malleys Tavern (Guinness and Red Oak on tap) and start around 6:00 PM and go till whenever, hope to see you there.

    -James

  • Transferring Large Files

    Every couple of weeks or so I seem to have a need to transfer (or receive) a relatively large file to another colleague or client. It might be a database zipped up into a 50 MB file, artwork totalling hundreds of megabytes, or various DLLs and source code. Over the course of my career I have used the following techniques for transferring data:

    • E-mail - the most straightforward technique for sharing data. The major con is that many email providers reject attachments over a certain threshold, usually in the 2-10 MB range. Also, e-mail is inherently insecure, making it a non-ideal medium for transferring sensitive data like passwords, credit card numbers, social security numbers, and so on.
    • Upload/Download from a Website - if you have write access to a website you can always upload the data to share and then send a URL to the file(s). The downside here is that you need a website. Security also requires a few extra steps - you need to have some mechanism to only allow the intended recepient from downloading the article.

      Side story: Back in 2002 Microsoft released Web Matrix, which later became Visual Web Developer Express Edition. Prior to announcing the release Microsoft and asp.netPRO Magazine asked me to write an overview of the tool to be included in the asp.netPRO edition that came out right when the product was released officially. There were a group of other ASP.NET folks at the time who also knew about this project and were invited to review my article. I distributed it by putting the article up on a website and provided this group a link to download the article. A couple days later I left for a short vacation during which I did not check e-mail or phone messages.

      The day I left town one of the reviewers leaked the article to Neowin.net, which linked directly to the URL on my website. Shortly after the link was published on Neowin.net I started getting e-mails and phone calls from Scott Guthrie asking me to take down the link. Of course, I did not get these messages until a few days later upon return from my vacation.

      I never did find out who leaked the link/article. I guess it didn't really matter in the end, and it wasn't the article on my server that caused the leak as someone else sent in the link to Neowin.net and they could have just as easily sent the Microsoft Word document. But still, I was rather red-faced when having to explain to the guys at Microsoft why the article was accessible to anyone on the Net and why it took so long to get the article down once it had been compromised.
    • Use a Third-Party Service - there are a plethora of web-based services that are built to allow large files to be transferred between two individuals. Most work by you uploading a file to a site, where it is stored temporarily. You then e-mail the recipient a link to download the attachment. I have used the free service TransferBigFiles.com many times and heartily recommend them. You could also use DropBox and place the file to share in the Public folder. The benefit of this approach is that you don't need a website; however, the security concerns remain. In fact, you might consider the security concerns even (slightly) greater because you are now adding an intermediary into the equation (the folks at TransferBigFiles.com or at DropBox).
    • Physically Deliver the Data - the most secure option is the physically deliver the data - put it on a thumb drive or burn it to a DVD and then mail or hand deliver the data. This approach takes the most work, but is the most secure, especially if you hand deliver the data. And if you are transferring extremely large amounts of data - terrabytes, let's say - this approach would likely be the fastest.

      I used this approach 8 years ago when transferring large amounts of information between myself and a publisher. At the time I only had dial-up access. When the publisher needed to send me several hundred megabytes worth of materials - mostly artwork from previous editions - it was more efficient to mail me a CD. I also had a student in one of my Web Services class, must have been four years ago or so, whose company was running computer simulations that would output several GBs worth of data per test run. To send the day's test data to another facility they would plug in an external hard drive, copy over the data, and then use a mail carrier to overnight deliver the drive. I wonder what techniques they use today.

    How do you share large files with others?

  • September Lounge Update

    August was a great month for The Lounge, with Scott joining the network the web publishers room hit an all-time high of 1.7 Million impressions in the month. To start out this month I have moved Sam Allen who runs the excellent site DotNetPerls from the Small Publishers Room to the Web Publishers Room. Sam has been writing some excellent articles and has been rewarded with great traffic.

    I am thrilled to announce that I will be handling sponsorship for the Herding Code Podcast. I am convinced that podcast sponsorships are a great opportunity for advertisers and I love supporting the great content and conversations that I hear on the podcasts I work with. Herding Code is also joining the Small Publishers Room to run display advertising on their site.

    I have also added a number of other new publishers to the Small Publishers Room, we are now up to 26 publishers in that room!

    Ben Hall has been on my radar for quite some time as he is a member of the team building my favorite unit testing tool (MbUnit) and also does a great job writing about unit testing, build tools, and much more.

    I have known Scott Reynolds virtually for awhile and finally met him at CodeStock. Right after joining The Lounge he ended up joining the great folks over at LosTechies so not sure how long this blog will be in The Lounge, but thankfully LosTechies is a member as well so we aren't really losing Scott.

    Alvin Ashcraft has been writing an excellent daily link post and has also started to write some quality articles, he will make another great addition to the room.

    September is going to be an exciting month for The Lounge, I hope to launch another new room in the next couple of weeks as well as launching a side-project that is related to The Lounge in some ways. Should be able to announce both very soon.

    -James

  • NHaml-Users Google Group

    Since NHaml has broken out of MvcContrib (which is a great decision I think, I hate contrib projects in general since they are very hard to maintain) there isn't a great place to ask questions about using NHaml so I went ahead and created a NHaml-Users Google group.

    -James

  • Search Your Site Using Google's Custom Search Engine

    Remember when people used to debate what search engine was the best among the bunnch? Do you remember back in the day when Yahoo! differentiated itself from other search engines by having actual human beings catalog, summarize, and rate large swaths of the World Wide Web? Today, search is a commodity. It's ubiquitous. Web surfers expect there to be a search box and expect accurate results returned in the blink of an eye. Because of these expectations, it's now more important than ever that your website offers search. I don't care if the site has only five static web pages that only get updated once in a blue moon, you still need search.

    The good news is that Google offers free tools for quickly and easily adding search to your site. With Google's Custom Search Engine (CSE) you can add search to your site within a matter of minutes. All it takes is configuring a few settings and then copying and pasting a snippet or two of HTML and JavaScript into your site. A couple of months ago I used CSE to add search to this blog. You can find the search interface in the upper right hand corner of every page or by visiting the Search page.

    To learn how to add a search engine to your site using CSE check out my latest article on DotNetSlackers: Implementing Search in ASP.NET with Google Custom Search.

    Site Note: Another technique for making your site more searchable is to create an OpenSearch provider. By adding a simple XML file to your website you can have your site searchable through the search box that's baked into the user interface of browsers like Internet Explorer and Firefox. Learn more about this technique by reading: Helping Visitors Search Your Site By Creating an OpenSearch Provider.

     

  • Three's Company, Too

    I try to keep this blog tightly focused on technical issues, but I wanted to share this happy bit of news: on September 1st my wife gave birth to our daughter, Alice Mitchell. Mom & baby are healthy and happy.

    If you'd care to read a bit more about this, I've blogged about it on my personal blog, ScottOnLife.com: Then There Were Three.

  • What’s Wrong With This Code? (#20)

    Mike had to model answers. Yes or no answers, date and time answers - all sorts of answers. One catch was that any answer could be “missing” or could be “empty”. Both values had distinct meanings in the domain. An interface definition fell out of the early iterative design work:

    public interface IAnswer
    {
        bool IsMissing { get; }
        bool IsEmpty { get; }
    }
    

    Mike was prepared to implement a DateTimeAnswer class, but first a test:

    [TestMethod]
    public void Can_Represent_Empty_DateTimeAnswer()
    {
        DateTimeAnswer emptyAnswer = new DateTimeAnswer();
        Assert.IsTrue(emptyAnswer.IsEmpty);
    }
    

    After a little work, Mike had a class that could pass the test:

    public class DateTimeAnswer : IAnswer
    {       
        public bool IsEmpty
        {
            get { return Value == _emptyAnswer; }
        }
    
        public bool IsMissing
        {
            get { return false; } // todo 
        }
    
        public DateTime Value { get; set; }
    
        static DateTime _emptyAnswer = DateTime.MinValue;
        static DateTime _missingAnswer = DateTime.MaxValue;
    }
    

    After sitting back and looking at the code, Mike realized there were a couple facets of the class he didn’t like:

    • A client of the class needed to know which values of DateTime were used internally to represent empty and missing answers.  
    • The class felt like it should produce immutable objects, and thus the set-able Value property felt wrong.

    Mike returned to his test project, and changed his first test to agree with his idea of how the class should work. Mike figured adding a couple well known DateTimeAnswer objects (named Empty and Missing) would get rid of the magic DateTime values in client code.

    [TestMethod]
    public void Can_Represent_Empty_DateTimeAnswer()
    {
        DateTimeAnswer emptyAnswer = DateTimeAnswer.Empty;
        Assert.IsTrue(emptyAnswer.IsEmpty);
    }
    

    Feeling pretty confident, Mike returned to his DateTimeAnswer class and added a constructor, changed the Value property to use a protected setter, implemented IsMissing, and published the two well known DateTimeAnswer objects based on his previous code:

    public class DateTimeAnswer : IAnswer
    {       
        public DateTimeAnswer (DateTime value)
        {
            Value = value;
        }
    
        public bool IsEmpty
        {
            get { return Value == _emptyAnswer; }
        }
    
        public bool IsMissing
        {
            get { return Value == _missingAnswer; }
        }
    
        public DateTime Value { get; protected set; }
        public static DateTimeAnswer Empty = new DateTimeAnswer(_emptyAnswer);
        public static DateTimeAnswer Missing = new DateTimeAnswer(_missingAnswer);
        static DateTime _emptyAnswer = DateTime.MinValue;
        static DateTime _missingAnswer = DateTime.MaxValue;    
    }
    

    Mike’s test passed. Mike was so confident about his class he never wrote a test for IsMissing. It was just too easy – what could possible go wrong? Imagine his surprise when someone else wrote the following test, and it failed!

    [TestMethod]
    public void Can_Represent_Missing_DateTimeAnswer()
    {
        DateTimeAnswer missingAnswer = DateTimeAnswer.Missing;
        Assert.IsTrue(missingAnswer.IsMissing);
    }
    

    What went wrong?

  • ASP.NET MVC Preview 5 and Form Posting Scenarios

    This past Thursday the ASP.NET MVC feature team published a new "Preview 5" release of the ASP.NET MVC framework.  You can download the new release here.  This "Preview 5" release works with both .NET 3.5 and the recently released .NET 3.5 SP1.  It can also now be used with both Visual Studio 2008 as well as (the free) Visual Web Developer 2008 Express SP1 edition (which now supports both class library and web application projects).

    Preview 5 includes a bunch of new features and refinements (these build on the additions in "Preview 4").  You can read detailed "Preview 5" release notes that cover changes/additions here.  In this blog post I'm going to cover one of the biggest areas of focus with this release: form posting scenarios.  You can download a completed version of the application I'll build below here.

    Basic Form Post with a Web MVC Pattern

    Let's look at a simple form post scenario - adding a new product to a products database:

     

    The page above is returned when a user navigates to the "/Products/Create" URL in our application.  The HTML form markup for this page looks like below:

    The markup above is standard HTML.  We have two <input type="text"/> textboxes within a <form> element.  We then have an HTML submit button at the bottom of the form.  When pressed it will cause the form it is nested within to post the form inputs to the server.  The form will post the contents to the URL indicated by its "action" attribute - in this case "/Products/Save".

    Using the previous "Preview 4" release of ASP.NET we might have implemented the above scenario using a ProductsController class like below that implements two action methods - "Create" and "Save":

    The "Create" action method above is responsible for returning an html view that displays our initial empty form.  The "Save" action method then handles the scenario when the form is posted back to the server.  The ASP.NET MVC framework automatically maps the "ProductName" and "UnitPrice" form post values to the method parameters on the Save method with the same names.  The Save action then uses LINQ to SQL to create a new Product object, assigns its ProductName and UnitPrice values with the values posted by the end-user, and then attempts to save the new product in the database.  If the product is successfully saved, the user is redirected to a "/ProductsAdded" URL that will display a success message.  If there is an error we redisplay our "Create" html view again so that the user can fix the issue and retry.

    We could then implement a "Create" HTML view template like below that would work with the above ProductsController to generate the appropriate HTML.  Note below that we are using the Html.TextBox helper methods to generate the <input type="text"/> elements for us (and automatically populate their value from the appropriate property in our Product model object that we passed to the view):

    Form Post Improvements with Preview 5

    The above code works with the previous "Preview 4" release, and continues to work fine with "Preview 5".  The "Preview 5" release, though, adds several additional features that will allow us to make this scenario even better. 

    These new features include:

    • The ability to publish a single action URL and dispatch it differently depending on the HTTP Verb
    • Model Binders that allow rich parameter objects to be constructed from form input values and passed to action methods
    • Helper methods that enable incoming form input values to be mapped to existing model object instances within action methods
    • Improved support for handling input and validation errors (for example: automatically highlighting bad fields and preserving end-user entered form values when the form is redisplayed to the user)

    I'll use the remainder of this blog post to drill into each of these scenarios.

    [AcceptVerbs] and [ActionName] attributes

    In our sample above we implemented our product add scenario across two action methods: "Create" and "Save".  One motivation for partitioning the implementation like this is that it makes our Controller code cleaner and easier to read.

    The downside to using two actions in this scenario, though, is that we end up publishing two URLs from our site: "/Products/Create" and "/Products/Save".  This gets problematic in scenarios where we need to redisplay the HTML form because of an input error - since the URL of the redisplayed form in the error scenario will end up being "/Products/Save" instead of "/Products/Create" (because "Save" that was the URL the form was posted to).  If an end-user adds this redisplayed page to their browser favorites, or copy/pastes the URL and emails it to a friend, they will end up saving the wrong URL - and will likely have an error when they try and access it later.  Publishing two URLs can also cause problems with some search engines if your site is crawled and they attempt to automatically traverse your action attributes.

    One way to work around these issues is to publish a single "/Products/Create" URL, and then have different server logic depending on whether it is a GET or POST request.  One common approach used to-do this with other web MVC frameworks is to simply have a giant if/else statement within the action method and branch accordingly:

    The downside with the above approach, though, is that it can make the action implementation harder to read, as well as harder to test. 

    ASP.NET MVC "Preview 5" now offers a better option to handle this scenario.  You can create overloaded implementations of action methods, and use a new [AcceptVerbs] attribute to have ASP.NET MVC filter how they are dispatched.  For example, below we can declare two Create action methods - one that will be called in GET scenarios, and one that will be called in POST scenarios:

    This approach avoids the need for giant "if/else" statement within your action methods, and enables a cleaner structuring of your action logic.  It also eliminates the need to mock the Request object in order to test these two different scenarios.

    You can also optionally now use a new [ActionName] attribute to allow the method name implementation on your controller class to be different than that from the published URL.  For example, if rather than having two overloaded Create methods in your controller you instead wanted to have the POST method be named "Save", you could apply the [ActionName] attribute to it like so:

    Above we have the same controller method signature (Create and Save) that we had in our initial form post sample.  The difference, though, is that we are now publishing a single URL (/Products/Create) and are automatically varying the handling based on the incoming HTTP verb (and so are browser favorites and search engine friendly).

    Model Binders

    In our sample above the signature of the Controller action method that handles the form-post takes a String and a Decimal as method arguments.  The action method then creates a new Product object, assigns these input values to it, and then attempts to insert it into the database:

    One of the new capabilities in "Preview 5" that can make this scenario cleaner is its "Model Binder" support.  Model Binders provide a way for complex types to be de-serialized from the incoming HTTP input, and passed to a Controller action method as arguments.  They also provide support for handling input exceptions, and make it easier to redisplay forms when errors occur (without requiring the end-user to have to re-enter all their data again - more on this later in this blog post). 

    For example, using the model binder support we could re-factor the above action method to instead take a Product object as an argument like so:

    This makes the code a little more terse and clean.  It also allows us to avoid having repetitive form-parsing code scattered across multiple controllers/actions (allowing us to maintain the DRY principle: "don't repeat yourself").

    Registering Model Binders

    Model Binders in ASP.NET MVC are classes that implement the IModelBinder interface, and can be used to help manage the binding of types to input parameters.  A model binder can be written to work against a specific object type, or can alternatively be used to handle a broad range of types. The IModelBinder interface allows you to unit test binders independent of the web-server or any specific controller implementation.

    Model Binders can be registered at 4 different levels within an ASP.NET MVC application, which enables a great deal of flexibility in how you use them: 

    1) ASP.NET MVC first looks for the presence of a model binder declared as a parameter attribute on an action method.  For example, we could indicate that we wanted to use a hypothetical "Bind" binder by annotating our product parameter using an attribute like below (note how we are indicating that only two properties should be bound using a parameter on the attribute):

    Note: "Preview 5" doesn't have a built-in [Bind] attribute like above just yet (although we are considering adding it as a built-in feature of ASP.NET MVC in the future).  However all of the framework infrastructure necessary to implement a [Bind] attribute like above is now implemented in preview 5. The open source MVCContrib project also has a DataBind attribute like above that you can use today.

    2) If no binder attribute is present on the action parameter, ASP.NET MVC then looks for the presence of a binder registered as an attribute on the type of the parameter being passed to the action method.  For example, we could register an explicit "ProductBinder" binder for our LINQ to SQL "Product" object by adding code like below to our Product partial class:

    3) ASP.NET MVC also supports the ability to register binders at application startup using the ModelBinders.Binders collection.  This is useful when you want to use a type written by a third party (that you can't annotate) or if you don't want to add a binder attribute annotation on your model object directly.  The below code demonstrates how to register two type-specific binders at application startup in your global.asax:

    4) In addition to registering type-specific global binders, you can use the ModelBinders.DefaultBinder property to register a default binder that will be used when a type-specific binder isn't found.  Included in the MVCFutures assembly (which is currently referenced by default with the mvc preview builds) is a ComplexModelBinder implementation that uses reflection to set properties based on incoming form post names/values.  You could register it to be used as the fallback for all complex types passed as Controller action arguments using the code below:

    Note: the MVC team plans to tweak the IModelBinder interface further for the next drop (they recently discovered a few scenarios that necessitate a few changes).  So if you build a custom model binder with preview 5 expect to have to make a few tweaks when the next drop comes out (probably nothing too major - but just a heads up that we know a few arguments will change on its methods).

    UpdateModel and TryUpdateModel Methods

    The ModelBinder support above is great for scenarios where you want to instantiate new objects and pass them in as arguments to a controller action method.  There are also scenarios, though, when you want to be able to bind input values to existing object instances that you own retrieving/creating yourself within the action method.  For example, when enabling an edit scenario for an existing product in the database, you might want to use an ORM to retrieve an existing product instance from the database first within your action method, then bind the new input values to the retrieved product instance, and then save the changes back to the database.

    "Preview 5" adds two new methods on the Controller base class to help enable this - UpdateModel() and TryUpdateModel().  Both allow you to pass in an existing object instance as the first argument, and then as a second argument you pass in a security white-list of properties you want to update on them using the form post values.  For example, below I'm retrieving a Product object using LINQ to SQL, and then using the UpdateModel method to update the product's name and price properties with form data.

    The UpdateModel methods will attempt to update all of the properties you list (even if there is an error on an early one in the list).  If it encounters an error for a property (for example: you entered bogus string data for a UnitPrice property which is of type Decimal), it will store the exception object raised as well the original form posted value in a new "ModelState" collection added with "Preview 5".  We'll cover this new ModelState collection in a little bit - but in a nutshell it provides an easy way for us to redisplay forms with the user-entered values automatically populated for them to fix when there is an error.

    After attempting to update all of the indicated properties, the UpdateModel method will raise an exception if any of them failed.  The TryUpdateModel method works the same way - except that instead of raising an exception it will return a boolean true/false value which indicates whether there were any errors.  You can choose whichever method works best with your error handling preferences.

    Product Edit Example

    To see an example of using the UpdateModel method in use, let's implement a simple product editing form.  We'll use a URL format of /Products/Edit/{ProductId} to indicate which product we want to edit.  For example, below the URL is /Products/Edit/4 - which means we are going to edit the product whose ProductId is 4:

    Users can change the product name or unit price, and then click the Save button.  When they do our post action method will update the database and then show the user a "Product Updated!" message if it was successful:

    We can implement the above functionality using the two Controller actions methods below.  Notice how we are using the [AcceptVerbs] attribute to differentiate the Edit action that displays the initial form, and the one that handles the form post submission:

    Our POST action method above uses LINQ to SQL to retrieve an instance of the product object we are editing from the database, then uses UpdateModel to attempt to update the product's ProductName and UnitPrice values using the form post values.  It then calls SubmitChanges() on the LINQ to SQL datacontext to save the updates back to the database.  If that was successful, we then store a success message string in the TempData collection and redirect the user back to the GET action method using a client-side redirect (which will cause the newly saved product to be redisplayed - along with our TempData message string indicating it was updated).  If there is an error either with the form posted values, or with updating the database, an exception will be raised and caught in our catch block - and we will redisplay the form view again to the user for them to fix.

    You might wonder - what is up with this redirect when we are successful?  Why not just redisplay the form again and show the success message?  The reason for the client-redirect is to ensure that if the user hits the refresh button after successfully pressing the save button, they don't resubmit the form again and get hit with a browser prompt like this:

    Doing the redirect back to the GET version of the action method ensures that a user hitting refresh will simply reload the page again and not post back.  This approach is called the "Post/Redirect/Get" (aka PRG) pattern.  Tim Barcz has a nice article here that talks about this more with ASP.NET MVC.

    The above two controller action methods are all we need to implement in order to handle editing and updating a Product object.  Below is the "Edit" view to go with the above Controller:

    Useful Tip: In the past once you started added parameters to URLs (for example: /Products/Edit/4) you had to write code in your view to update the form's action attribute to include the parameters in the post URL.  "Preview 5" includes a Html.Form() helper method that can make this easier.  Html.Form() has many overloaded versions that allow you to specify a variety of parameter options.  A new overloaded Html.Form() method that takes with no parameters has been added that will now output the same URL as the current request. 

    For example, if the incoming URL to the Controller that rendered the above view was "/Products/Edit/5", calling Html.Form() like above would automatically output <form action="/Products/Edit/5" method="post"> as the markup output.  If the incoming URL to the Controller that rendered the above view was "/Products/Edit/55", calling Html.Form() like above would automatically output <form action="/Products/Edit/55" method="post"> as the markup output.  This provides a nifty way to avoid having to write any custom code yourself to construct the URL or indicate parameters.

    Unit Testing and UpdateModel

    In this week's Preview 5 drop the UpdateModel methods always work against the Request object's Form post collection to retrieve values.  This means that to test the above form post action method you'd need to mock the request object in your unit test. 

    With the next MVC drop we'll also add an overloaded UpdateModel method that allows you to pass in your own collection of values to use instead.  For example, we would be able to use the new FormCollection type in preview 5 (which has a ModelBuilder that automatically populates it with all form post values) and pass it to the UpdateModel method as an argument like so:

    Using an approach like above will allow us to unit test our form-post scenario without having to use any mocking. Below is an example unit test we could write that tests that a POST scenario successfully updates with new values and redirects back to the GET version of our action method.  Notice that we do not need to mock anything (nor do we have to rely on any special helper methods) in order to unit test all the functionality in our controller:

    Handling Error Scenarios - Redisplaying Forms with Error Messages

    One of the important things to take care of when handling form post scenarios are error conditions.  These includes cases where an end-user posts incorrect input (for example: a string instead of a number for a Decimal unit-price), as well as cases where the input format is valid, but the business rules behind the application disallow something from being created/updated/saved (for example: making a new order for a discontinued product).

    If a user makes a mistake when filling out a form, the form should be redisplayed with informative error messages that guide them towards fixing it.  The form should also preserve the input data the user originally entered - so that they don't have to refill this manually.  This process should repeat as many times as necessary until the form successfully completes.

    Basic Form Entry Error Handling and Input Validation with ASP.NET MVC

    In our product edit sample above we haven't written much error handling code in either our Controller or our View.  Our Edit post action simply wraps a try/catch error handling block around the UpdateModel() input mapping call, as well as the database save SubmitChanges() call.  If an error occurs, the controller saves an output message in the TempData collection, and then returns our edit view to be redisplayed:

    With earlier preview releases of ASP.NET MVC the above code wouldn't be enough to deliver a good end-user experience (since it wouldn't highlight the problem, nor preserve user input if there was an error).

    However, with "Preview 5" you'll find that you now get a decent end-user error experience out of the box with just the above code.  Specifically, you'll find that when our edit view is redisplayed because of an input error it now highlights all input controls that have problems, and preserves their input for us to fix:

    How, you might ask, did the Unit Price textbox highlight itself in red and know to output the originally entered user value?

    "Preview 5" introduces a new "ModelState" collection that is passed as part of the "ViewData" sent from the Controller to the View when it renders.  The ModelState collection provides a way for Controllers to indicate that an error exists with a model object or model property being passed to the View, and allows a human friendly error message to be specified that describes the issue, as well as the original value entered by the end-user.

    Developers can explicitly write code to add items into the ModelState collection within their Controller actions.  ASP.NET MVC's ModelBinders and UpdateModel() helper methods also automatically populate this collection by default when they encounter input errors.  Because we were using the UpdateModel() helper method in our Edit action above, when it failed in its attempt to map the UnitPrice TextBox's "gfgff23.02" input to the Product.UnitPrice property (which is of type Decimal) it automatically added an entry to the ModelState collection.

    Html helper methods inside the View by default now check the ModelState collection when rendering output.  If an error for an item they are rendering exists, they will now render the originally entered user value as well as a CSS error class to the HTML input element.  For example, for our "Edit" View above we are using the Html.TextBox() helper method to render the UnitPrice of our Product object:

    When the view was rendered during the error scenario above the Html.TextBox() method checked the ViewData.ModelState collection to see if there were any issues with the "UnitPrice" property of our Product object, and when it saw that there was rendered the originally entered user input ("gfgff23.02") and added a css class to the <input type="textbox"/> it output:

    You can customize the appearance of the the error css classes to look however you want.  The default CSS error rule for input elements in the stylesheet created in new ASP.NET MVC projects looks like below:

    Adding Additional Validation Messages

    The built-in HTML form helpers provide basic visual identification of input fields with issues.  Let's now add some more descriptive error messages to the page as well.  To-do this we can use the new Html.ValidationMessage() helper method in "Preview 5".  This method will output the error message in the ModelState collection that is associated with a given Model or Model property.

    For example: we could update our view to use the Html.ValidationMessage() helper to the right of the textboxes like so:

    Now when the page renders with an error, an error message will be displayed next to the fields with problems:

    There is an overloaded version of the Html.ValidationMessage() method that takes a second parameter that allows the view to specify an alternative text to display:

    One common use case is to output the * character next to the input fields, and then add the new Html.ValidationSummary() helper method (new in "Preview 5") near the top of the page to list all the error messages:

    The Html.ValidationSummary() helper method will then render a <ul><li></ul> list of all the error messages our ModelState collection, and a * and red border will indicate each input element that has a problem:

    Note that we haven't had to change our ProductsController class at all to achieve this.

    Supporting Business Rules Validation

    Supporting input validation scenarios like above is useful, but rarely sufficient for most applications.  In most scenarios you also want to be able to enforce business rules, and have your application UI cleanly integrate with them.

    ASP.NET MVC supports any data layer abstraction (both ORM and non-ORM based), and allows you to structure your domain model, as well as associated rules/constraints, however you want.  Capabilities like Model Binders, the UpdateModel helper method, and all of the error display and validation message support are explicitly designed so that you can use whatever preferred data access story you want within your MVC applications (including LINQ to SQL, LINQ to Entities, NHibernate, SubSonic, CSLA.NET, LLBLGen Pro, WilsonORMapper, DataSets, ActiveRecord, and any other).

    Adding Business Rules to a LINQ to SQL Entity

    In the sample above I've been using LINQ to SQL to define my Product entity and perform my data access.  So far, the only level of domain rules/validation that I am using on my Product entity are those inferred by LINQ to SQL from the SQL Server metadata (nulls, data type and length, etc).  This will catch scenarios like above (where we are trying to assign bogus input to a Decimal).  However, they won't be able to model business issues that can't be easily declared using SQL metadata.  For example: disallowing the reorder level of a product to be greater than zero if it has been discontinued, or disallowing a product to be sold for less than what our supplier price is, etc.  For scenarios like these we need to add code to our model to express and integrate these business rules.

    The wrong place to add this business rule logic is in the UI layer of our application.  Adding them there is bad for many reasons.  Among others it will almost certainly lead to duplicated code - since you'll end up copying the rules around from UI to UI and from form to form.  In addition to being time-consuming, there is an excellent chance doing so will lead to bugs when you change your business rule logic, and you forget to update it everywhere. 

    A much better place to incorporate these business rules is at your model or domain level.  That way they can be used and applied regardless of what type of UI or form or service works with it.  Changes to the rules can be made once, and picked up everywhere without having to duplicate any logic.

    There are several patterns and approaches we could take to integrate richer business rules to the Product model object we've been using above: we could define the rules within the object, or external from the object.  We could use declarative rules, a re-usable rules engine framework, or imperative code.  The key point is that ASP.NET MVC allows us to use any or all of these approaches (there aren't a bunch of features that require you to always do it one way - you instead have the flexibility to reflect them however you want, and the MVC features are extensible enough to integrate with almost anything).

    For this blog post I'm going to use a relatively simple rules approach.  First I'm going to define a "RuleViolation" class like below that we can use to capture information about a business rule that is being violated within our model.  This class will expose an ErrorMessage string with details about the error, as well as expose the primary property name and property value associated with it that is causing the violation:

    (note: For simplicity sake I'm only going to store only one property - in more complex applications this might instead be a list so that multiple properties could be specified).

    I will then define an IRuleEntity interface that has a single method - GetRuleViolations() - which returns back a list of all current business rule violations with that entity:

    I can then have my Product class implement this interface.  To keep the sample simple I'm embedding the rule definition and evaluation logic inside the method.  There are better patterns that you can use to enable reusable rules, as well as to handle more complex rules. If this sample grew I'd refactor the method so that the rules and their evaluation where defined elsewhere, but for now to keep this simple we'll just evaluate three business rules below like so:

     

    Our application can now query the Product (or any other IRuleEntity) instance to check its current validation status, as well as retrieve back RuleViolation objects that can be used to help present UI that can guide an end-user of the application to help fix them.  It also allows us to easily unit test our business rules independent of the application UI.

    For this particular sample I am going to choose to enforce that our Product object is never saved in the database in an invalid state (meaning all RuleViolations must be fixed before the Product object can be saved in the database).  We can do this with LINQ to SQL by adding an OnValidate partial method to the Product partial class.  This method will get called automatically by LINQ to SQL any time database persistence occurs.  Below I'm calling the GetRuleViolations() method we added above, and am raising an exception if there are unresolved errors.  This will abort the transaction and prevent the database from being updated:

    And now in addition to having a friendly helper method that allows us to retrieve RuleViolations from a Product, we have enforcement that those RuleViolations must be fixed before our database is ever updated.

    Integrating the above Rules into our ASP.NET MVC UI

    Once we've implemented our business rules, and exposed our RuleViolations like above, it will be relatively easy to integrate it into our ASP.NET MVC sample.

    Because we added the OnValidate partial method to our Product class, calling northwind.SubmitChanges() will raise an exception if there are any business rule validation issues with a Product object that we are trying to save.  This exception will abort any database transactions, and will be caught in our catch block below:

    The one extra line of code we'll then add to our error catch block is some logic to call a UpdateModelStateWithViolations() helper method defined below.  This method retrieves a list of all rule violations from an entity, and then updates a ModelState collection with appropriate model errors (including references to the properties on our entity object that caused them):

    Once we do this, we can re-run our application.  Now, in addition to seeing input format related error messages, ASP.NET MVC's validation helpers will also display our business rule violations as well. 

    For example, we could set the unit price to be less than a $1, and try to set the Reorder level to be -1 (both values are legal from an input format perspective - but both violate our business rules).  When we do this and hit save we'll see the errors show up in our Html.ValidationSummary() list, and the corresponding textboxes will be flagged:

    Our business rules can span multiple Product properties.  For example: you might have noticed above that I added a rule that said that the reorder level can't be greater than zero if the product is discontinued:

    The only changes we needed to make to our "Edit" view template throughout this entire business rules process has been to add two more Product properties (Reorder and Discontinued) to the file:

    Now we can add any number of additional business validation rules we want to our Product entity, and we do not need to update the Edit view nor the ProductsController in order to have our UI support them.

    We can also unit-test our model and business rules separately from our Controller and View.  We can unit-test our URL routing separately from our Controller, Views and Models.  And we can unit test our Controller separately from our Views.  All of the scenarios shown in this blog post will support unit testing without requiring any mocking or stubbing to be used.  The end result are applications that are easily testable, and which can support a nice TDD workflow.

    Summary

    This post has provided a quick look at how form post scenarios work with ASP.NET MVC Preview 5.  Hopefully after reading it you have a better sense of how you handle form and input entry scenarios using a MVC model.  You can download a completed C# version of the application I built above here.  I will post a VB version a little later this week (it is unfortunately 4:30am while I'm typing this and I need to hop on a plane in a few short hours and have not started packing yet).

    Important: If you don't like the MVC model or don't find it natural to your style of development, you definitely don't have to use it.  It is a totally optional offering - and does not replace the existing WebForms model.  Both WebForms and MVC will be fully supported and enhanced going forward (the next release of ASP.NET WebForms will add richer URL routing features, better HTML markup/client-side ID/CSS support, and more).  So if after reading the above post you think "hmm - that doesn't feel natural to me", then both don't worry, and don't feel like you should or need to use it (you don't). 

    In my next post on MVC I'll cover how to integrate AJAX into your ASP.NET MVC applications. 

    Hope this helps,

    Scott

  • Quick Update

    I've received a number of (very nice) emails recently asking if I was ok - since my blog has been silent the last few weeks (and much of the summer). 

    Just to address people's concerns - I'm alive and well. :-)  I've just been on vacation the last 6 weeks, and have unfortunately not had free time to post (I've been changing a lot of diapers). 

    I am still on vacation another week before I officially return to work.  I did get a chance to write up a quick post this weekend that covers some of the new ASP.NET MVC Preview 5 features, though, that will hopefully provide some interim reading until I can resume a more regular posting schedule over the next month when I get back into the office.

    Thanks,

    Scott