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.

February 2009 - Posts

  • March's Toolbox Column Now Online

    My Toolbox column in the March 2009 issue of MSDN Magazine is available online. The March issue of MSDN Magazine has a focus on the Web and my reviews in Toolbox  follow suit and include:

    • The Ajax Data Controls Project - The Ajax Data Controls (ADC) project is an ASP.NET AJAX extension that marries the ease of the server-centric development model with the performance of the client-centric development model. ADC is a collection of controls that displays data in an Ajax-enabled web page. You can add the ADC to your page like you would any other web control, and set their properties through the Properties window. However, you work with the ADC controls programmatically via JavaScript. The net result is that the ADC result in significantly less markup between partial page postbacks than the built-in Web controls in an UpdatePanel, but provide a similar page developer experience.
    • Fiddler - an HTTP traffic analyzer is a must-have tool for web developers. Such tools provide a clear picture of the low-level HTTP traffic coursing between the client and server. Moreover, such tools can be quite helpful in debugging or generating a pre-canned HTTP request (for testing server-side functionality) or response (when testing client-side functionality). My favorite HTTP traffic analyzer is Fiddler, a free tool created by Eric Lawrence. Check it out.
    • Blogs of Note:
      • Rick Strahl - Rick is an old-school FoxPro developer and ASP.NET developer who regularly shares his experiences, insights, tips, and tricks on his blog. Rick's blog posts primarily focus on Web topics, including ASP.NET, jQuery, AJAX, and Silverlight.
      • Sam Larbi - Sam pens one of my favorite blogs, My Secret Life as a Spaghetti Coder. Sam works as a jack of all trades developer, dabbling in both Web and desktop applications and languages ranging from C++ to ColdFusion to C# and ASP.NET. Along with posts about specific technologies, Sam also routinely writes about the non-technology-related aspects of being a developer, including topics like meetings, working with others, personal development, and so on.

    The Bookshelf section reviewed jQuery in Action by Bear Bibeault and Yehuda Katz. An excerpt follows:

    Due to JavaScript's increasing importance in Web development, several frameworks have been created. One of the most popular ones is jQuery, a free, open-source, cross-browser JavaScript framework created by John Resig. (In fact, Visual Studio 2010 will ship with the jQuery library, making it even easier for ASP.NET developers to get started with jQuery.) ... jQuery in Action (Manning, 2008) ... is a great resource for leaning the ins and outs of jQuery and for mastering its terse and flexible syntax. jQuery in Action assumes the reader is already familiar with JavaScript and wastes no time covering the basics of the language. Instead, it starts with a quick introduction to the motivation behind jQuery and jQuery fundamentals and then moves on to using jQuery to accomplish common tasks. (Some of the more advanced JavaScript concepts that are used by jQuery are covered in an appendix.)

    Enjoy! - http://msdn.microsoft.com/en-us/magazine/dd483223.aspx

    As always, if you have any suggestions for products, blogs, or books to review for the Toolbox column, please send them to toolsmm@microsoft.com.

  • What Are The “Never Events” for Software Quality?

    ekg Recent talk centered on software quality got me thinking of “never events”. The “never events” in health care are defined by the National Quality Forum to identity serious problems in the quality of a health care facility.  A “never event” has to be:

    • Measureable
    • Mostly preventable
    • Have serious implications (like death or disability)

    Here are some examples of these events from the list of 28 defined by the NQF:

    These are not events that never occur, but events that should never occur. Humans will make mistakes, but a high quality hospital will have fewer occurrences of “never events” than a hospital with low standards.

    I wonder if we could ever find consensus on a set of “never events” for software development. Perhaps we could start with the “Top 25 Most Dangerous Programming Mistakes”, except not all of these are preventable,  or at least easily preventable. Plus, the list is focused on dangerous programming mistakes. I’ve always felt that configuration management practices are a leading indicator of software quality, and a couple “never events” come to mind immediately: 

    • A team should never find itself incapable of retrieving the exact source files used to produce a build of the software.
    • A team should never find a build deployed with manual changes made outside of source control. 

    What “never events” can you think of? Remember: measureable, preventable, and serious.

  • Thoughts on the Code Contracts Preview for .NET 4.0

    A new Code Contracts preview is now available on DevLabs. Code Contracts will be part of the base class library in .NET 4.0 (included in mscorlib), and facilitate a Design by Contract programming approach. You can describe pre-conditions, post-conditions, and object invariants.

    The Code

    Let’s borrow a couple ideas from Matt’s DbC post (he was using Spec#, which was a precursor) to see what Code Contracts will look like.

    public void Run()
    {
        TargetResult result = LaunchMissle(new Target());
    }
    
    public TargetResult LaunchMissle(Target target)
    {
        Contract.Requires(target != null);
        Contract.Ensures(Contract.Result<TargetResult>() != null);
    
        return new TargetResult();
    }
    

    In the LaunchMissle method we are using static methods on the System.Diagnostics.Contracts.Contract class to define a pre-condition (the target reference cannot be null), and a post-condition (the return value cannot be null). You can allow these contracts to verify not only the runtime behavior of your software, but you can also allow a static analysis tool to verify these contracts during builds. The following screen shot is from the new Code Contracts tab in the project options:

     

    code contract options

    Static analysis will find two problems when it analyzes the following code:

    public void Run()
    {
        TargetResult result = LaunchMissle(BuildTarget());
    }
    
    Target BuildTarget()
    {
        return new Target();
    }
    
    public TargetResult LaunchMissle(Target target)
    {
        Contract.Requires(target != null);
        Contract.Ensures(Contract.Result<TargetResult>() != null);
    
        return null;
    }
    

    The “return null” line in LaunchMissle is an obvious violation of the method’s contract, and the static analyzer will tell us so. However, it will also tell us that the pre-condition (target != null) is unproven. This is because the BuildTarget method doesn’t include a contract that guarantees it’s behavior. We could fix that with the following code:

    Target BuildTarget()
    {
        Contract.Ensures(Contract.Result<Target>() != null);
        return new Target();
    }
    

    This example demonstrates how enforcing a contract in one location can have a ripple effect on your code – which is something that becomes really painful if you’ve ever dealt with checked exceptions or generic constraints. Nevertheless, I’m still pretty optimistic about DbC in .NET. Built-in DbC constructs would have been in my top 3 list of “things to have in C#” 5 years ago. TDD has re-order my list dramatically, but I still feel DbC will still be a good addition and useful in some specific scenarios. 5 years ago I would have liberally applied contracts everywhere. Currently I’m thinking they’ll be best put to use on system boundaries.

    MSIL Rewriting, TDD

    One of the interesting features of Code Contracts is that it includes a MSIL rewriter (ccrewrite.exe) that post-processes an assembly to change the intermediate language instructions emitted by the compiler. I hope this elevates MSIL re-writing from a black art to a more mainstream technology that we can benefit from in the future. Re-writing could enable a number of cool scenarios in .NET, like AOP. I can’t help thinking that the Entity Framework team might have delivered POCOs in V1 if AOP was held in more regard.

    Another great feature of Code Contracts is that you can turn static analysis on and off on a per project basis. I believe this will be important to anyone practicing TDD and BDD. You can see the issues in the comments of Matt’s post that I linked to earlier. Some people believe contracts eliminate the need for certain tests, and some people don’t.

    I’ve done some thinking on this issue and I don’t want a contract to force a compiler error in my test.  For example, imagine a unit test that would pass null as the parameter to LaunchMissle. Static analysis can flag this as a problem because it violates the LaunchMissle contract. Should I delete the test? I vote no. Fortunately, it looks like I’ll be able to turn off static analysis when building my test project. TDD and BDD are a design process and I’ll write the test before I ever write the contract, and I feel that the eventual writing of the contract shouldn’t invalidate my unit tests. They have contracts and tests serve orthogonal purposes. As Colin Jack commented in Matt’s post:

    What I'm saying is that yes the compiler will warn me and that I love, however I'd also want the option of being able to write a spec that ensures a particular contract is in place (if I do X I get Y). If I can't do that then refactoring of the code (not the specs) becomes less safe.


    There are many more great features in the preview. Download the bits to check them out, or RTFM. Will Code Contracts be something you use in .NET 4.0?

  • 3 talks you should watch

    Below are some of the talks that I really enjoyed over the last couple of years, these are all language agnostic and focus on general development practices and techniques. So take some time and watch these great talks:

    What Makes Code Beautiful - Marcel Molina

    This is a great talk that I saw at RubyConf 2007. Some of the interactive pieces in the beginning don't come across as well in the video, but it is well worth it to get through that part. Marcel compares the historical definitions of beauty and how they can be applied to code.

    Aristotle and the art of software development - Jonathan Dahl

    I really enjoyed this talk, the main take away for me was that programming rules and morals are so similar. Once we think of them in this way it makes alot more sense on how we should approach them.

    Writing Code that Doesn't Suck - Yehuda Katz

    This was a great talk that covered the need to focus on your external interfaces, especially when it comes to your tests.

    -James

  • Creating and Consuming Syndication Feeds in ASP.NET 3.5

    Do you run a website that routinely publishes new content? If so, does your site offer a syndication feed? A syndication feed is an XML file that summarizes the most recently published content and is commonly used in blogs, news sites, sports sites, social networking sites, and other content producing websites to provide a machine-readable format of the latest content. For the longest time the .NET Framework did not include built-in support for syndication feeds, meaning that if you needed to generate a syndication feed or parse the syndication feed from another site you either needed to:

    The good news is that syndication functionality was added to the .NET Framework version 3.5, namely with the addition of the classes in the System.ServiceModel.Syndication namespace. This namespace includes a classes that model a syndication feed and the items that compose the feed, along with classes for formatting a syndication feed into either RSS 2.0- or Atom 1.0-compliant XML. (RSS 2.0 and Atom 1.0 are the two leading syndication feed format standards.)

    For more information, check out my latest article on DotNetSlackers.com, which looks at creating and consuming syndication feeds using these new classes in the .NET Framework 3.5 from an ASP.NET application: How to Create a Syndication Feed For Your Website.

    Happy Programming!

  • What's the Best Way to Format a Title for a Blog Post, Article, or Tutorial?

    If you are writing an article, blog post, or tutorial about a feature of ASP.NET or the .NET Framework, how do you format the title? For example, say that you are writing a blog entry about grouping data using ASP.NET's ListView control. Which of these titles is most appropriate?

    1. Grouping Data Couldn't Be Easier!
    2. Group Data Using the ListView Control
    3. ASP.NET's ListView Control Makes Groupnig Data Easy
    4. Learn How to Group Data Using the ListView Control in ASP.NET 3.5

    I think title (1) is the worst of the four because it provides no context. It could be a blog entry about grouping data in Excel, a look at using SQL's GROUP BY clause, or an article not even related to computers. Granted, the body of the blog post would make it crystal clear, but from an SEO perspective and when considering that the title it what appears in the search engine results, a more descriptive title would seem to be preferred.

    Title (2) does a good job mentioning the feature to be discussed (grouping data) and the control to be used (the ListView). However, it still lacks context, especially if there is some other technology stack that has a control with the same name. (See the postscript below for more discussion on why noting the technology can be important.)

    Title (3) mentions the goal / feature (grouping data), the control being demonstrated (the ListView), and the framework (ASP.NET), but it makes no mention of the ASP.NET version. The ListView control was added to ASP.NET version 3.5, so a developer using ASP.NET version 2.0 might not realize that this technique doesn't apply to her until she gets half way through the blog post.

    That leads us to title (4), which gives a complete and thorough description. And this is the title format I've migrated to over the years. For example, my current article series on 4Guys about the ListView is titled: Using ASP.NET 3.5's ListView and DataPager Controls, with subtitles explaining what each installment of the article series covers, as in: Using ASP.NET 3.5's ListView and DataPager Controls: Grouping By a Data Field. However, over time I've found one problem with this most descriptive title: including the version number makes sense and seems like a good idea when covering some new feature in the latest version of ASP.NET, but it unnecessarily dates the article. Because ASP.NET versions are additive, the technologies present in ASP.NET 2.0 are still around in ASP.NET 3.5, which is great from a developer's perspective. But if you include the verison number in the article it makes it sound like the feature in question is now antequated or that it no longer applies to the latest version.

    Take the following article title, for example: Health Monitoring in ASP.NET 2.0. Health Monitoring was introduced in ASP.NET 2.0 and does not exist in ASP.NET 1.x, hence the rationale for adding the version number in the title. But today we are using ASP.NET 3.5. Health Monitoring still exists and is still used in ASP.NET 3.5 applications, but that article title makes it sound like Health Monitoring is something specific to 2.0. I worry that someone who sees that title in Google's search results will say, “I'm using ASP.NET 3.5, so that article is not relevant to me“ and instead choose to read an article that's titled, “Learn How to Use ASP.NET's Health Monitoring“ because it makes no mention of ASP.NET 2.0.

    Given all of this, I am torn between title formats (3) and (4), and I'm now leaning more to (3) than (4). Including the version number is useful when writing about a technology that will be in the next version of ASP.NET or is in the just-released version of ASP.NET, but it becomes a liability as time marches on and new versions of ASP.NET are released. Perhaps the ideal approach would be to change the title over time. That is, name the article Health Monitoring in ASP.NET 2.0 when ASP.NET 2.0 first comes out, but knock off the version number and change the title to Health Monitoring in ASP.NET when ASP.NET 3.5 is nearing release.

    Thoughts?

    P.S.: Regarind title (2) and omitting the framwork context... During the ASP.NET 1.x days I wrote an 18-part article series on 4Guys titled An Extensive Examination of the DataGrid Web Control. There is also a DataGrid control that can be used in WinForms applications. Despite having the same name, the DataGrid controls in the ASP.NET and WinForms differ substantially when it comes to binding data to the control, adding paging and sorting features, and so on. Long story short, during the ASP.NET 1.x days I'd get an e-mail or two a week from WinForms developers who had questions about the WinForms DataGrid control. It was clear that some had read the article, realized that the focus was on the ASP.NET DataGrid, but asked their question anyway, hoping I could help, while others clearly did not read a word of the article. Perhaps a more descriptive title: An Extensive Examination of the ASP.NET DataGrid Web Control would have reduced the number of these e-mails.

    P.S.S.: I'm sure that if you e-mail a blogger or author of an article with a question, you do so in a very courteous and kind manner and realize that you are, in essence, asking for free help from a stranger who likely has other tasks and duties that demand his attention. Moreover, I'm sure you understand if said author or blogger cannot respond to your query, or responds with a, “Sorry, I'm too busy to help,“-type message. But there are people who somehow expect that you are there to be their free, private consultant and programmer, and get surly if you don't answer their question post haste. I bring this up because writing the above aside reminded me of one of the most vitriolic e-mails I ever got from a reader was from a guy who had a question about the WinForms DataGrid control. I had explained to him that there were differences between the ASP.NET and WinForms DataGrid, and that I was not familiar with the WinForms DataGrid and therefore couldn't be of help, and got back one of the nastiest e-mails I've ever received about how they were indeed alike and that I just didn't want to help him and was being all sorts of words I don't want to write here for fear that your workplace's Internet filter will flag my site. The point is (and there is a point in here somewhere, I'm sure), is that the next time you run into one of these types of people, feel free to smack them on the back of their head for me.

  • Erlang: List Comprehensions

    One of the most challenging things about learning a new language isn't just learning how to do something, but more importantly learning the best way to do something. "Best" in this context is of course very subjective, but for me it not only means correctness but also readability, brevity, and following what is the normal convention for writing code in that language. Erlang has lots of ways to do things. I am working on a small solution where I am pulling messages back from Amazon SQS and processing them in Erlang. Here is a piece of code I initially wrote to handle looping through the list of messages and processing each of them:

     process_messages(H|T, SQS) ->
       process_message(H, SQS),
       process_messages(T, SQS.
     
     process_messages([], SQS) ->
       ok.
     
     process_message(Message, SQS) ->
       %%process message here.
    

    I was showing Mark this code and it struck him as strange, the process_messages function is just going through every item in the list and passing it to the process_message function, so a perfect case for map. So I rewrote the code using the lists:map function:

     process_messages(List, SQS) ->
       lists:map(fun(X) -> process_message(X, SQS) end, List).
     
     process_message(Message, SQS) ->
       %%process message here.
    

    This is much nicer and reads better, I could even inline this code if I wanted to but I like the descriptiveness of having a function named process_messages. But, this can be even more descriptive using a list comprehension:

     process_messages(List, SQS) ->
       [process_message(X, SQS) || X 
       %%process message here.
    

    An even simpler line of code and once you get comfortable reading list comprehensions it makes much more sense.

    (found a nice Erlang Brush for Syntax Highlighter over here)

  • Mapping Objects with AutoMapper

    At the end of last year I finished a project that required a fair amount of object-to-object mapping. Unfortunately, Jimmy Bogard didn’t release AutoMapper until this year, so I had to write a pile of object-to-object mapping goo on my own.

    AutoMapper is a convention based mapper. Let’s say you have an object implementing an interface like this…

    public interface IPatientDetailView
    {
        string Name { get;  set; }
        IEnumerable<Procedure> Procedures { get;  set; }
        // ...         
    }
    

    …but all of the data you need to pump into the object is in a different type:

    public class PatientDetailData
    {
        public string Name { get; set; }
        public IEnumerable<Procedure> Procedures { get;  set; }
        // ...
    
    }
    

    With AutoMapper you just need a one time configuration:

    Mapper.CreateMap<PatientDetailData, IPatientDetailView>();

    Then moving data over is ridiculously easy:

    Mapper.Map(patientData, patientView);

    AutoMapper has a number of neat tricks up its sleeve. The flattening feature, for instance, can move data from a hierarchical object graph to a “flattened” destination. But what if your property names don’t match? Then you can take advantage of a fluent API to describe how AutoMapper should move the data. For example, moving data from the following type …

    public class ProcedureData
    {
        public string PatientName { get; set; }
        public IEnumerable<Procedure> Procedures { get;  set; }
        // ...
    
    }
    

    … will require a bit of configuration for AutoMapper to know where to put the patient name:

    Mapper.CreateMap<ProcedureData, IPatientDetailView>()
            .ForMember(destination => destination.Name,
                       options => options.MapFrom(
                            source => source.PatientName));
    

    For other AutoMapper features it’s best to peruse the tests. There are extensibility hooks, like custom formatters and resolvers, and support for different profiles. Check it out.

  • Learning Erlang

    Last year I saw Kevin Smith do a presentation at the local raleigh.rb group on this fascinating little language called Erlang. Erlang is a functional language that is dynamically typed. Its true power is that it makes concurrency, one of the most difficult programming problems, extremely easy. One statement that really says it all to me is this:

    In Erlang spawning a new process is as easy and cheap as creating an object in an object oriented language.

    The presentation peaked my interest and I dabbled with Erlang when I had time last year. I went to a couple of the local Erlang hack nights, I started reading the Programming Erlang book, and I checked out the prag prog screencasts (also by Kevin Smith).

    Last week I went to a great 2-day training class on Erlang put on by Kevin down in Carborro at the co-working facility there. This class impressed me for a couple of reasons:

    1) I feel like I finally understand Erlang and I can actually start a project using it.

    2) I normally hate training classes, but this one was actually very effective. It put the focus on writing erlang code in labs, but the labs were just a problem and you had to figure out how to solve it. They weren't the classic step by step labs that are just mindless instruction following, you really had to stretch your knowledge of the language and what you had learned to complete these labs. I enjoyed it so much that I am actually considering trying to put together a training course and becoming a trainer is one of the things I never wanted to do.

    With all this knowledge I have started an interesting little project with Erlang. I am attempting to re-write the reporting section of Adzerk (the software that runs Ruby Row and The Lounge) using Erlang. I have been meaning to separate the reporting piece from the rest of the application (especially from a database perspective) for sometime and this gives me a great excuse. Erlang will make it easy for me to make my reporting system near time, advertisers and publishers will be able to see impressions and clicks seconds after they happen instead of the day after like how it currently works. (I know you could accomplish this in just about any technology, but Erlang makes it easier to do this and to scale in the ways I want to).

    So if you are looking for a new language to pick up this year I would encourage you to try out Erlang. I plan on using it more and more and will be posting interesting tools or tricks I find to this blog.

    -James

  • New Publishers joining The Small Publishers Room

    This was originally posted over on the Zerk Media blog but I wanted to cross-post it here since I think everyone should be subscribed to these blogs.

    Over the last month or so a number of new publishers have joined the Small Publishers Room. With some of our members moving to The Silverlight Room there was room to take on additional publishers. Here are the new additions:

    Corey Haines is currently a freelance developer and journeyman, traveling around to pair-program with other developers.

    Dave Bost is a Developer Evangelist with Microsoft and co-host of the Thirsty Developer Podcast.

    Mark Harrison is a Solutions Architect at Microsoft UK - and a pre-sales Technical Product Specialist for Office Platform with a key focus on customer solutions for Content Management, Collaboration, Portal and Search.

    John Sheehan is a .NET developer based in St. Paul, MN who specializes in building web applications with ASP.NET MVC, C#, jQuery and SubSonic.

    I am thrilled to have these influential developers and bloggers join The Lounge.

    -James

  • Blogs are the Most Important Innovation of the 21st Century

    A case could be made that blogs and blog hosting websites like WordPress and Blogger are, so far, the most important innovation of this century, technological or otherwise. Prior to the advent of blogs, publishing online was a task reserved for the computer savvy. Sure, sites like Geocities and Tripod lowered the barrier, but still required a good deal of work and at least a passing familiarity with HTML. It wasn't until blogs that the average person - my mom, my grandfather, etc. - could, with a few points and clicks of the mouse, get their thoughts, feelings, and information out to an audience of, potentially, billions. In mathematics there is the concept of different cardinalities of infinity. While both the set of integers and the set of real numbers are inifinite sets, there are 'more' items in the set of real numbers. It's a 'bigger' infinity, if you will. In a similar vein, both e-mail and blogs shrink the world and allow people who may be vast distances apart to communicate with one another instantly, but blogs go a step beyond e-mail (or the telephone or fax machines) in that it allows for one-to-many communications. With an e-mail message you can send urban legends and corny jokes to your aunt in Baltimore, but with your blog you can share them with the world at large.

    Blogs have had a very profound affect on society as a whole. They have democratized the publishing process and made the idea of citizen journalism a reality and, in doing so, they have quickly neutered industries that were flourishing a mere 10 years ago. Why buy a newspaper when you can get your information online? Why pick up a copy of Sports Illustrated when you can read more interesting and in-depth articles written by ex-GMs, current athelets, and impassioned fans? And what's the motivation to purchase a programming book when there are countless developers sharing their tips and tricks, what works and what doesn't, on their blogs each day? Of course, there are benefits to be had by big box newspaper and magazines and having content presented on pieces of paper. Print media is not dead, but it has been relegated to a niche market, and blogs are a big reason why.

    Blogs have also had a profound impact on the Web 2.0 landscape, namely in the areana of syndication. Ten years ago content syndication was in its infancy. Blogs were the first application that used syndication - Dave Winer invented RSS in 1997 to syndicate content from his blog, Scripting News. As the popularity of blogging grew, the RSS standard matured, the Atom standard was created, and non-blog sites started embracing syndication. Today, virtually every website that produces content on a regular or semi-regular schedule provides a syndication feed. We have blogs to thank for that development.

    It may seem like an over-exaggeration to say that blogs have had such a profound impact, but consider this - how do you think my daughter will react when I tell her, 15 years hence, that there was a time in my life when only people who were 'computer experts' could publish content online. I think she'll be flabbergasted, and I think that surprise and disbelief she'll have is a testament to how important an innovation blogging has been.

  • Why Would I Create A Custom LINQ Operator?

    Here are three different reasons:

    1. For an operation that doesn’t exist.
    2. For readability.
    3. For performance.

    An example for reason #1 is Bart De Smet’s ForEach operator. While you are on Bart’s blog, you can read about the pros and cons of a ForEach in his comments.

    An example for reason #2 would be a custom join operator. Let’s say we are joining an object collection of employees to an object collection of departments.

    var employeeAndDepartments =
        employees.Join(departments,
                       employee => employee.DepmartmentID,
                       department => department.ID,
                       (employee, department) =>
                           new
                           {
                               Employee = employee,
                               Department = department
                           });
    

    The Join operator with extension methods is a little unwieldy. You need three lambda expressions: one to specify the employee key, one to specify the department key,  and one to specify the result. To make the query itself a bit more readable you could define a custom Join operator that knows how to join employees and departments.

    public static IEnumerable<EmployeeDepartmentDTO> Join(
                 this IEnumerable<Employee> employees,
                      IEnumerable<Department> departments)
    {
        return employees.Join(departments,
                              employee => employee.DepmartmentID,
                              department => department.ID,
                              (employee, department) =>
                                  new EmployeeDepartmentDTO
                                   {
                                       Employee = employee,
                                       Department = department
                                   });
    }                                             
    

    Not pretty, but it drastically cleans up code in other places:

    var employeeAndDepartments = employees.Join(departments);

    Reason #3 is performance. Generally speaking, you'll write an operator for performance when you know something that LINQ doesn't know.A good example is in Aaron Erickson’s i40 (Indexed LINQ) library. i40 features an IndexableCollection type that can drastically increase the performance of LINQ to Object queries (think table scan versus index seek). Imagine having a huge number of objects in memory and you commonly query to find just one.

    var subject = subjects.Where(subject => subject.ID == 42)
                          .Single();
    

    With i40 you can create an index on the ID property.

    var subjects = /* ... */
                    .ToIndexableCollection()
                    .CreateIndexFor(subject => subject.ID);
    /* ... */
    var subject = subjects.Where(subject => subject.ID == 42)
                          .Single();

    If you are using the i40 namespace, you’ll get a special i40 Where operator that takes advantage of the indexes built into the IndexableCollection.

    //extend the where when we are working with indexable collections!
    public static IEnumerable<T> Where<T>
    (
      this IndexableCollection<T> sourceCollection,
      Expression<Func<T, bool>> expr
    )
    {
        // ... source from IndexableCollectionExtension.cs
    }

    What custom operators have you made?

  • More LINQ Optimizations

    Not every optimization is a performance optimization. Imagine trying to get this XML:

    string xml = 
        @"<people>
            <Person>
              <property value=""John"" name=""firstName""/>
              <property value=""Dow"" name=""lastName""/>
              <property value=""john@blah.com"" name=""email""/>
            </Person>
            <Person>
              <property value=""Jack"" name=""firstName""/>
              <property value=""Dow"" name=""lastName""/>
              <property value=""jack@blah.com"" name=""email""/>
            </Person>
          </people>";
    
    

    Into objects of this type:

    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
    }
    

    A brute force solution would look like the following:

    var xmlDoc = XDocument.Parse(xml);
    var records =
        from record in xmlDoc.Descendants("Person")
        select new Person
        {
            FirstName = (from p in record.Elements("property") 
                        where p.Attribute("name").Value == "firstName"
                        select p.Attribute("value").Value).FirstOrDefault(),
            LastName = (from p in record.Elements("property") 
                        where p.Attribute("name").Value == "lastName"
                        select p.Attribute("value").Value).FirstOrDefault(),
            Email = (from p in record.Elements("property")
                     where p.Attribute("name").Value == "email"
                     select p.Attribute("value").Value).FirstOrDefault(),
    
        };
    

    It works - but it’s ugly. It would be better if the code looked like this.

    var records =
        from record in xmlDoc.Descendants("Person")
        select new Person
        {
            FirstName = record.Property("firstName"),
            LastName = record.Property("lastName"),
            Email = record.Property("email")
        };
    

    Which just requires a bit of extension method magic.

    public static string Property(
        this XElement element, string name)
    {
        return
            (from p in element.Elements("property")
             where p.Attribute("name").Value == name
             select p.Attribute("value").Value).FirstOrDefault();
    }
    

    Is the code faster? Probably not – but until it’s certain that we have a performance problem, it’s better to optimize for readability.

  • Moonlight 1.0 Release

    I am excited to announce that Novell today released version 1.0 of Moonlight, and is making it available for download at no cost with support for most major Linux distro’s (including openSUSE, SUSE Linux Enterprise, Fedora, Red Hat, and Ubuntu). For those unfamiliar with it, Moonlight is a joint effort between Novell and Microsoft of an open-source implementation of Silverlight for Linux.

    My team has worked closely with Miguel de Icaza and his team on the project.  We are also shipping the Microsoft Media Pack – which is a set of licensed media codecs that enable playback for all Silverlight compatible media (wmv, wma, mp3, etc.), as a free download for Linux users who run Moonlight.

    Moonlight enables Linux users to view Silverlight content and Silverlight applications.  Recently the official Presidential Inauguration Committee broadcast the inauguration of President Barack Obama using Silverlight.  Over 50,000 viewers using Linux installed Moonlight and watched the event live using it.  Miguel de Icaza and the volunteers behind Moonlight made a tremendous effort to make sure that Linux users were able to watch the broadcast of the inauguration, even though the official release of Moonlight was still a few weeks away.

    image

    I am really excited about the awesome work Miguel and his team at Novell have done, and we’re looking forward to seeing Moonlight 2 (a Silverlight 2 compatible implementation with .NET support) which the team is hard at work on. For more details on the Moonlight 1.0 release, check out Miguel’s blog post on it.

    Thanks,

    Scott

  • Due Diligence and Code Comments

    Due diligenceThis is the silly tale of a strange due diligence process I experienced. It happened several years ago but I couldn’t talk about it at the time. 

    I’ve been on both sides of the technical due diligence table, and I’ve always felt that being reviewed is easy – you simply tell the truth when asked about the software and how it’s built. Anything else can get you into trouble. It is the reviewer who has the difficult job. Someone wants to buy or invest in a company and they are depending on you to help determine the fair value. You have to look at the development methodology, the design, the architecture, the configuration management practices, the licenses, and basically ferret out any problems and risks to ensure the company is a good investment.

    A few years ago I was on the receiving end of the review. The first thing the guy wanted to do was open up a source code file. I pick one and open it on the screen. The conversation goes like this:

    Him: I don’t see any comments in the code.

    Me: Nope!

    Him: Ok, let’s take a look at this file. Hmm, I don’t see any comments in here, either!

    Me: Umm .. no .. no comments.

    Him: Ok, let’s take a look at this file here. Well, well, well. It doesn’t look like you guys write any comments at all!

    Me: Honestly - we try to avoid commenting code.

    Him (horrified): What? How on earth does anyone know what the code is doing?

    Me (stunned): Well, we figure out what the code is doing .. by  .. um .. reading .. the  .. code.

    There are people who believe that all code should be accompanied by comments (an undergrad professor come to mind), but by the turn of the century I had hoped that most people understood comments to only be used as a “here be dragons” sign. If you are depending on comments to make code consumable - you’ve already lost the battle. Sure, there are exceptions for exceptional code – like code written to work around platform bugs, code optimized for speed, and the comments that feed javadoc and intellisense for a public API, but for the most part code that requires comments to make itself maintainable is bad code. This isn’t a recent trend. The Elements Of Programming Style said in 1978:

    Don’t comment bad code – rewrite it.

    Eventually the business deal fell through, but it wasn’t due to the lack of comments. The company walked away from the money the investors were willing to offer. A due diligence process, like a job interview, works in both directions. In this case the competency of the due diligence team didn’t instill the confidence needed to sell them a piece of ownership.


  • Announcing the Silverlight Room

    This was originally posted over on the Zerk Media blog but I wanted to cross-post it here as well since that blog is pretty new.

    I am thrilled to announce the launch of the Silverlight Room in the Lounge. The room started serving ads in the middle of January with Telerik being the first advertiser to take advantage of this very targeted advertising opportunity. I am very proud of the group of publishers who helped to launch this room, it is made up of a couple of publishers who moved from the Small Publishers Room as well as publishers new to The Lounge. Here is our "starting lineup":

    Tim Heuer is a Program Manager with the Silverlight team at Microsoft and writes a very popular blog filled with great information.

    Shawn Wildermuth is a well-known blogger and Microsoft MVP who runs the Silverlight Tour which offers comprehensive Silverlight training.

    Jeff Blankenburg is a developer evangelist with Microsoft who is personally very passionate about UX.

    Josh Holmes is a RIA Architect Evangelist with Microsoft focused on building and educating the dev partners with a Rich Internet Application offering in Central Region.

    Corey Schuman .NET developer who concentrates on combining an object-oriented software development approach with a stellar UI experiences.

    Terence Tsang writes the Shine Draw blog which compares Silverlight and Flash by posting various samples and source code.

    Laurent Bugnion is the author of "Silverlight 2 Unleashed" and frequently writes about Silverlight and web development on his blog.

    I am very excited about this room and expect it to grow throughout this year to include all the top sites and bloggers who focus on Silverlight.

    -James

  • Keyboard Thoughts

    Jeff Atwood recently replaced his keyboard, a Microsoft Natural Keyboard 4000, with... a new Microsoft Natural Keyboard 4000.

    I mentioned my beloved Microsoft Natural Keyboard 4000, which is pretty much the holy grail of keyboards to me. Some people don't care for the non-split spacebar, and the way the keys have a fair bit of resistance -- but that's never bothered me. If you're into the whole ergonomic split layout thing, as I obviously am, it's difficult to go wrong with the Natural 4000. That's why I'm replacing my old keyboard with the very same model.

    I am also a (mostly) satisfied user of the Microsoft Natural Keyboard 4000. My only complaint has to do with the function keys and function key remapping. For starters, the function keys are not as big as they were in old school keyboards. I cut my teeth on keyboards where the function keys were square shaped. However, the function keys on the Microsoft Natural Keyboard 4000 are almost half as tall as they are wide. But what's more frustrating is that, like many Microsoft keyboards, the function keys (F1-F12) perform some alternate action if the Function Lock option is disabled. (You can toggle the Function Lock by pressing the F Lock key, which is immeidately to the right of F12.) About once a month the Function Lock status will toggle magically. I know for a fact I'm not pressing it. I don't know if some program can toggle it, or if they keyboard has a short circuit, or if my forceful typing somehow jiggles the F Lock key. Regardless, about once a month I find that my function keys aren't working and the reason is because the Function Lock has been disabled.

    This function mapping also annoys Jeff, who lists three bad keyboard design decisions:

    • Mangling the Home Key Cluster
    • Using a Non-Standard Arrow Key Cluster
    • Remapping the Function Keys

    I have another item to add to the list - keyboards that break from the norm of having the lower left key be the Ctrl key. Too many laptops do this, placing the Fn key in the lower left corner and the Ctrl key to its immediate right.

    The Ctrl key is one of the most oft-used keys for people who prefer to keep their hands on the keyboard and off the mouse, as it's the key that typically denotes a keyboard shortcut, including the most essential ones: Copy, Paste, Cut, Open, Save, Print, Undo, and Redo. It is almost tantamount to moving the space bar, or the Enter or Tab keys. Almost. Which is why it is baffling that this keyboard layout is still in use and is not some footnote in the history of flawed design, like Microsoft Bob and VRML.

  • Thoughts on AJAX Preview 4 and JSINQ

    ASP.NET AJAX 4.0 is adding client-side templates. You can bind data in the browser using declarative markup, imperative JavaScript code, or mix and match both approaches. The purely declarative approach looks like the following:

    <body xmlns:sys="java script:Sys"
    xmlns:dataview="java script:Sys.UI.DataView"
    sys:activate="*">
        <ul id="departmentManagerList" 
                class="sys-template"
                sys:attach="dataview"
                dataview:serviceuri="DepartmentService.svc"
                dataview:query="GetAllDepartments">
            <li>{{ Manager.Name }}</li>
        </ul>

    That code is everything you need to invoke an AJAX-enabled WCF service (specifically the GetAllDepartments method of DepartmentService.svc), and bind the results to a list. Some of the binding markup looks foreign inside the HTML, and when I read it a little voice in my head says: “JavaScript should be unobtrusive”. I reply and say “that is not JavaScript”, and the voice says “but it’s still ugly”. I have to agree, but there is an alternative we’ll look at in just a moment.

    Anyone who has used XAML binding extensions for Silverlight or WPF will notice a number of similarities in the AJAX 4 bits. For example, both use curly braces inside the item template to denote the path to the source property for binding (in the above code we’re drilling into a department object and pulling out a manager’s name property). The AJAX libraries will take care of replicating the data inside of <li> tags. Also, there are similar binding modes (one way, two way, and one time), and the concept of an IValueConverter for each binding (ConvertFrom and ConvertBack functions can inject custom logic at bind time).

    The AJAX 4 libraries support hierarchical data binding (for master detail scenarios) and can update a binding when the underlying data changes. However, this is one place where AJAX and XAML land differ. In XAML land we use INotify* interfaces to raise change events, whereas AJAX provides a Sys.Observable class that can “mixin” functions on a target object that allow you to ultimtaely catch property change notifications, but you must use Sys.Observable.setValue to see the notifications. Infinities Loop has the scoop on this behavior.

    Imperative Code and JSINQ

    Instead of purely declarative code, one can instantiate a DataView and write some JavaScript code to grab and process data. Since there doesn’t appear to be any pre or post request events we can hook from the DataView (which would be nice), this also gives us a chance to manipulate data from a web service before binding. The HTML will look cleaner:

    <body>
        …    
        <ul id="departmentManagerList" class="sys-template">
            <li>{{ Manager.Name }}</li>
        </ul>

    And we need to write a bit of code during load:

    var view = $create(Sys.UI.DataView, {}, {}, {},
                      $get("departmentManagerList"));
    
    var service = new DepartmentService();
    service.GetAllDepartments(function(result) {
        view.set_data(filterAndSortDepartments(result));
    });

    What is filterAndSortDepartments? It’s a function that uses JSINQ – LINQ to objects for JavaScript.This isn't part of ASP.NET AJAX 4.0, but a CodePlex hosted project.

    function filterAndSortDepartments(departments) {
        
        return new jsinq.Enumerable(departments)
                           .where(function(department) {
                             return department.Employees.length > 1;
                         }).orderBy(function(department) {
                             return department.Name;
                         }).toArray();
    }
    

    JSINQ has complete coverage of all the standard LINQ query operators, including join, group, groupJoin, any, all, and aggregate. The above code was written with the “extension method” syntax style, and rather makes me wish that JavaScript could take the lead from C# 3.0 lambda syntax and allow function definitions without keywords. JSINQ also offers comprehension query syntax:

    function filterAndSortDepartments(departments) {
        var query = new jsinq.Query('\
                            from department in $0 \
                            where department.Employees.length > 1 \
                            orderby department.Name \
                            select department \
                        ');
        query.setValue(0, new jsinq.Enumerable(departments));
        return query.execute().toArray();
    }
    

    In this case the declarative code is easier on the eyes, but like most declarative code it’s impossible to debug if something goes wrong. There are lot’s of possibilities when using the combination of these two libraries. Give JSINQ a try in the JSINQ playground

  • Accessing the DropDownList Control's SelectedIndex or SelectedValue Properties Selects the First ListItem

    I was recently helping a colleague squash a bug that had popped up on a page that involved a DropDownList. Specifically, an HttpException was being thrown with the error message Cannot have multiple items selected in a DropDownList. This exception is raised, as the message notes, if a DropDownList contains multiple ListItems whose Selected properties are set to true.

    The page in question had a DropDownList whose values were populated from a web service on the first page load. Shortly after this population code was a foreach loop that looped through the items in the DropDownList looking for a ListItem whose value matched a user-specific setting. The first such ListItem found had its Selected property set to true before exiting the loop. The code (in the Page_Load event handler) looked something like this:

    if (!Page.IsPostBack)
    {
        ... Populate MyDropDownList ...
     
        ... More Code ...
     
        foreach(ListItem li in MyDropDownList.Items)
            if (li.Value.StartsWith("some value specific to the user visiting the page"))
            {
                li.Selected = true;
                break;
            }
    }

    This error was perplexing because while there was some code that occurred between the population of the DropDownList, when the appropriate ListItem was selected, and when the page was rendered, none of that code set the Selected property to true or assigned a value to the DropDownList's SelectedIndex or SelectedValue properties. To unearth the cause of this error I fired up the debugger and set a breakpoint at the point where the DropDownList was populated. I then put the following statements in the Watch window:

    • MyDropDownList.Items[0].Selected
    • MyDropDownList.Items[1].Selected
    • MyDropDownList.Items[2].Selected
    • ...

    I wanted to see what items became selected and when. As I was stepping through the code, things started to unfold as I expected. After the DropDownList was populated all of the Items[i].Selected values returned false. But then in the code between where the DropDownList was populated and when a ListItem was selected based on the user's settings, there was a call to a method further down in the code-behind class. That method did not set the DropDownList's SelectedIndex or SelectedValue properties so I stepped over it thinking that it couldn't be the cause of my problems. But as I stepped over the method call the MyDropDownList.Items[0].Selected value in the DropDownList changed to true!

    I went to look at the code in that method I had just stepped over. This method was (among other things) showing or hiding a Panel on the page based on whether the first DropDownList item was selected. It had code like:

    if (MyDropDownList.SelectedIndex == 0)
        SomePanel.Visible = true;
    else
        SomePanel.Visible = false;

    But here's the rub - merely reading the value of the DropDownList's SelectedIndex property (or SelectedValue) causes the first ListItem in the DropDownList to be selected! This kind of makes sense, I guess. Unlike a ListBox there's always an item in the DropDownList that is selected. What's confusing is that the MyDropDownList.Items[0].Selected property is not true when the data is first bound to the DropDownList, but only after the SelectedIndex or SelectedValue properties are accessed. If these properties had not been read in the method that was called then my code in the Page_Load event handler would have worked as expected and without error.

    You can see how the first DropDownList item gets auto-selected when the SelectedIndex property is accessed by examining the SelectedIndex property code using Reflector:

        1 public override int SelectedIndex
        2 {
        3     get
        4     {
        5         int selectedIndex = base.SelectedIndex;
        6         if ((selectedIndex < 0) && (this.Items.Count > 0))
        7         {
        8             this.Items[0].Selected = true;
        9             selectedIndex = 0;
       10         }
       11         return selectedIndex;
       12     }
       13     set
       14     {
       15         base.SelectedIndex = value;
       16     }
       17 }

    Note lines 6-10. If the selected index is not set and if there are one or more items in the DropDownList then the first item is automatically selected (line 8)! In short, the first item of the DropDownList was being silently selected between the time the DropDownList was populated and the foreach loop that set the Selected property of some other ListItem based on the user's settings. Hence the resulting Cannot have multiple items selected in a DropDownList exception during rendering of the DropDownList. (Because the DropDownList's SelectedValue property reads the SelectedIndex property, accessing the SelectedValue property also has the side-effect of selecting the first DropDownList item.)

    I fixed this by adding a loop that enumerates the DropDownList Items collection just before the foreach loop, setting each ListItem's Selected property to false.

    if (!Page.IsPostBack)
    {
        ... Populate MyDropDownList ...
     
        ... More Code ...
     
        foreach(ListItem li in MyDropDownList.Items)
            li.Selected = false;
            
        foreach(ListItem li in MyDropDownList.Items)
            if (li.Value.StartsWith("some value specific to the user visiting the page"))
            {
                li.Selected = true;
                break;
            }
    }
  • The DefaultButton Property - News To Me!

    Back in January I created and shared??a custom server control called RedirectButton that was designed to be used in scenarios where the user is taken to a different page when a Button is clicked. It's a common scenario that virtually every ASP.NET developer has implemented at one time or another. The typical pattern for implementing such behavior is to add a Button to the page and create a Click event handler that executes a Response.Redirect(url). If the redirect incorporates some input from the user, then this pattern is expanded to include the addition of a TextBox or some other control to the page and a Response.Redirect(url) statement that includes this control's value in the querystring.

    The RedirectButton control was designed to account for two shortcomings of this pattern:

    • Eliminate the extra round trip to the server (the postback that does nothing more than send back a Response.Redirect).
    • If there is an associated TextBox where the user enters some value and that is transmitted via the querystring, you need to worry about what happens if the user presses the Enter key while focused in this TextBox. There's a postback, most likely, but what Button is considered clicked? This issue becomes more apparent if you have several TextBoxes on a page, each with a Button, that, when clicked, takes the user to some other page passing along the related TextBox's value through the querystring.

    Turns out the second shortcoming isn't a shortcoming of the TextBox or the Button or ASP.NET in general, but a shortcoming of my knowledge of the tools at my disposal. Turns out that you can implement such behavior using a standard Button by simply placing it (and the associated TextBox) into a Panel control and setting the Panel's DefaultButton property to the ID of the Button control. (Thanks to??alert 4Guys reader Vinod Soni for pointing this feature out to me.)??Doing so renders the following markup:

    onkeypress="BLOCKED SCRIPTreturn WebForm_FireDefaultButton(event, 'buttonId')">
    ?????? ...
    ??????

    The Panel renders the

    , which includes an onkeypress client-side event handler. The WebForm_FireDefaultButton function is added to the page automatically through a JavaScript include and is executed everytime there is a key press in the
    . If the user hits Enter (keycode 13) while not in a multi-line TextBox, then the default button is ???clicked.??? The full script for this function follows:

    function WebForm_FireDefaultButton(event, target) {
    ?????? if (event.keyCode == 13) {
    ?????????????? var src = event.srcElement || event.target;
    ?????????????? if (!src || (src.tagName.toLowerCase() != "textarea")) {
    ?????????????????????? var defaultButton;
    ?????????????????????? if (__nonMSDOMBrowser) {
    ???????????????????????????? defaultButton = document.getElementById(target);
    ?????????????????????? }
    ?????????????????????? else {
    ?????????????????????????????? defaultButton = document.all[target];
    ?????????????????????? }
    ?????????????????????? if (defaultButton && typeof(defaultButton.click) != "undefined") {
    ?????????????????????????????? defaultButton.click();
    ?????????????????????????????? event.cancelBubble = true;
    ?????????????????????????????? if (event.stopPropagation) event.stopPropagation();
    ?????????????????????????????? return false;
    ?????????????????????? }
    ?????????????? }
    ?????? }
    ?????? return true;
    }

    What's more, you can also set the default button for an entire form. The HtmlForm class has a DefaultButton property as well. The DefaultButton??properties for the form and Panel??were added in ASP.NET 2.0; it is not available in 1.x applications. In other words, this functionality has been present in the framework since 2005 -??it took four years for me to learn about it, and I work on ASP.NET applications daily and??spend time in Reflector and in the documentation several times per week. I find that there are many such ASP.NET features and control properties that fall into this camp (another example - I didn't discover Health Monitoring until nearly two years after ASP.NET 2.0 was released).??What explains this? Perhaps it's a commentary on my continuing education into the .NET world and a hint that I need to explore other avenues for learning and dedicate more time and effort to such tasks,??and I'm willing to accept??that that is part of the reason, but another factor is??the sheer size of the .NET Framework and??the wealth of features that are added, and the speed and frequency with which new features and frameworks and technologies are unveiled.

  • New T-SQL 2008 Syntax

    If you are using Microsoft SQL Server 2008 there are some cool new additions to the T-SQL syntax that can help save you a few keystrokes. For example, with T-SQL 2008 you can now (finally) assign a value to a variable when it is declared, like so:

    DECLARE @ThisIsLikeSo int = 1984

    Rather than having to put the declaration and assignment on two separate lines.

    T-SQL 2008 now includes the standard shorthand operators that have been standard in C++/Java/C# and were added to VB several years ago, things like +=, *=, -=, and so on.

    But the neatest new T-SQL syntax is row constructors, which provides a terse syntax for declaring a set of records and are not unlike object initializers in higher-level languages. Want to insert four records into a table? In the past you'd have to write four separate INSERT statements, but with row constructors you can write one INSERT statement with four row constructors in the VALUES part:

    -- Add four records to the Employees table 
    INSERT INTO Employees(Name, Email, Salary) 
    VALUES('Scott',
    'scott@example.com', 50000.00),  
          ('Jisun',
    'jisun@example.com', 225000.00),  
          ('Alice',
    'al@example.com', 75000.00),  
          ('Sam',
    'sam@example.com', 45000.00) 

    My latest monthly tip at DotNetSlackers.com summarizes the new T-SQL 2008 features that will help you write more terse stored procedures, UDFs, and ad-hoc scripts: More Concise T-SQL with SQL Server 2008.

This Blog

Syndication

Powered by Community Server, by Telligent Systems
'