Thursday, February 24, 2011

More Book Reviews

Continuing with more reviews I’m horribly overdue on…

Agile Coaching by Rachel Davies and Liz Sedley. Published by Pragmatic Press, ISBN 1934356433.

I’m amazed that this book covers so may critical topics so well and in such a short length! It’s a terrific book that can help guide you to building highly effective teams regardless of whether you’re a professional coach or team lead.

The book is formatted in four major sections (Coaching Basics, Planning as a Team, Caring About Quality, and Listening to Feedback), each with a few chapters around areas fundamental to good teams. The chapters are comprised of short sections working through details on things like good user stories, hijacked standup meetings, or defining what “Done” means.

I love the concise, easy-to-read style of the authors, and the content in the book is extremely helpful. They hit all the obvious topics, but they also lay out common tough issues like driving change in your organization, keeping meetings effective, and helping resolve team issues of culture and respect. Coaching’s easy when everything’s easy – but the real world requires great coaches to deal with tough problems and this book’s a tremendous help in that aspect.

I also love the authors focusing on issues that are so core to my own notions of great software teams: effective team environments, concise and simple user stories, listening to your teams, and fostering scads of communication. It was also great seeing an entire section of three chapters devoted to software quality, but then I may be a bit biased in that direction…

This book gave me a number of highly useful insights and made me re-think some approaches to common problems I see. It’s a great addition to my bookshelf.

Agile Retrospectives by Esther Derby and Diana Larsen. Published by Pragmatic Press, ISBN 0977616649.

I’ve been a firm believer in retrospectives for a number of years. I’ve used them on many projects in my last two jobs and the benefits have been tremendous. This book is a great help for me in tuning up and improving how retrospectives work.

The writing is extremely concise, well-done, and in a great tone. The authors cover the basics of retrospectives (Set the Stage, Gather Data, Generate Insights, Decide What to Do, and Close the Retrospective), but then head off into a number of other critical topics.

I really enjoyed the authors not shying away from dealing with potentially tough emotional parts of retrospectives. You’ll find short, extremely helpful tips on dealing with the occasional shouters, criers, stompers-off, etc. Retrospectives can be intense, and too many books skip over the unfortunate reality that on occasion you may have some drama to work through. Derby and Larsen don’t shy away; they’re practical in their advice.

Agile Retrospectives also emphasizes teams need to find a retrospective formula that works for them. They offer up a number of different approaches (fishbones, brainstorming, etc.) and lay out situations where those are helpful. (The section on fishbones was particularly helpful to me.) They also have a section on how to run longer post-release or post-project retrospectives – a horse of a completely different color.

Overall this has been a tremendously useful book, and I’ll continue to pull it off my shelf to brush up.

Friday, February 18, 2011

Increase A Disk’s Size in a VMWare VM

I occasionally need a larger disk in one of my VMWare VMs, and I always forget how to do it. I’m writing this post to save myself time the next time I need to do it!

Problem: You need a larger disk in one of your VMWare VMs.

Solution: Expand the disk first in VMWare, then inside the guest OS use Disk Management to extend the disk. (Of course this is somewhat centric to Windows 200*, Vista, or Windows 7 guest OSes. Steps 1-4 apply are the same regardless of your guest OS.)

Note: You can’t extend volumes in VMWare if the VM has any snapshots.

  1. Shut down the guest OS.
  2. Delete any snapshots of the system (VMWare | VM | Snapshots | Snapshot Manager | Delete)
  3. From the VM’s settings screen, select the disk you need to resize, then use Utilities | Expand

  4. Select the new disk size, click OK and go get lunch. It’s not a fast operation. (Impatient? Grips, dude. Think of what’s going on and listen to some Kenny while you do some yoga breathing exercises.)

  5. Start up the guest OS, log on, and start server manager, then select Storage | Disk Management.
  6. Notice the partition you just expanded now shows extra available space. Right click the drive and select Extend.

  7. Walk through the wizard and confirm everything looks as it should

  8. Bask in the joy that you don’t have to fool around with building a new VM with a larger hard disk.

Tuesday, February 15, 2011

Deleting Browser Cookies with Fiddler

Problem: Internet Explorer 8 won’t clear out authentication credentials and keeps signing you on to a site with a set of undesired creds. In this instance, you’ve likely told Internet Explorer to remember a user’s logon creds for a site with Windows authentication turned on. You want to log on to that same site with different user credentials, but you can’t get IE to bring back up the user logon dialog. Clearing out all browser data (Tools | Internet Options | Browsing History | Delete | check all boxes, clear Preserve favorite website data) doesn’t solve the issue.

Solution: Use Fiddler to delete the browser’s cookie header. Start Fiddler and use Tools | Automatic Breakpoints | Before Request. Open IE and navigate to the bothersome site. Click on the last entry in the sessions pane, then right click on the Authorization cookie in the right Headers pane and select Remove Header.

Flip back to IE and clear out all browser data again (Tools | Internet Options | Browsing History | Delete | check all boxes, clear Preserve favorite website data) .

Now switch back to Fiddler and click Run to Completion in the lower left pane.

At this point you should be presented with the familiar login dialog.

Tuesday, February 08, 2011

Fixing Blogger’s Bad Formatting of Code Snippets

Problem: Your code snippet fomatting in Blogger looks like poo – extra line breaks “helpfully” injected by Blogger leave your snippets with more whitespace than a third grader’s resume.

Solution: From a forum post by Daniel Carrarini on MSDN: Go to your Blogger’s control panel and select Settings | Formatting. Then change Convert Line Breaks from Yes to No.

Voila!

Monday, February 07, 2011

Quick Script for Building .sln Files With Configurations

Repeatedly typing out msbuild command lines with configuration switches (release, debug) and clean/regular, FTL.

Here’s a quick Ruby script to let you specify –d, –r, –c for debug, release, and clean, respectively. –d and –r are mutually exclusive, but you need one.

Oh! the joy of optparse. Dunno how many times I’ve written a command line parser for just this sort of use case. Love how well this works OOB.

require 'optparse'
 
def process_command_args
    $options = {}
 
    opts = OptionParser.new 
    opts.banner = "Usage: build [options]"
 
    opts.on( "-r", "--release", "release configuration" ) do
        $options[:releaseconfig] = true
    end
 
    opts.on( "-d", "--debug", "debug config" ) do
        $options[:debugconfig] = true
    end
 
    opts.on( "-c", "--clean", "clean build" ) do
        $options[:clean] = true
    end
    
    opts.on("-h", "--help", "Display this screen") do
        puts opts
        exit
    end
 
    opts.parse(ARGV)    
    
    if ($options[:releaseconfig].nil? && $options[:debugconfig].nil?)
        puts "Red pill or blue, your choice. Try -d or -r.ac"
        puts opts
        exit
    end
    
    if ($options[:releaseconfig] && $options[:debugconfig])
        puts "Make up your mind: release OR debug, not both"
        puts opts
        exit
    end
 
end
 
 
def do_the_work
    if $options[:releaseconfig]
        $config= "release"         
    end
 
    if $options[:debugconfig]
        $config = "debug"         
    end
    
        
    $sln = Dir.glob("*.sln")
    if ($sln.length > 1)
        puts "More than one .sln file here. Can't figure it out, bailing."
        exit
    end
    
    $command = "msbuild " + $sln[0] + " /p:configuration=" + $config 
    
    if $options[:clean]
        $command += " /t:clean"
    end
    
    system($command)
    
end
process_command_args()
do_the_work()

Tuesday, February 01, 2011

Beware “the Meeting Guy”

If you want an effective project team, then you need to ensure everyone on the team is able to make the right things happen. This is especially important on projects which are in critical phases or are suffering through a painful spot with your clients/stakeholders. You can’t get through tough spots in a project if members of that team have to constantly run back to their supervisory chain to get approval for every decision, or if they can’t help you get roadblocks out of the way.

Sometimes it’s apparent that a member of the team was put there for no other reason than to have a token presence at the table. That member has no authority to make decisions and is unable to commit to anything because they’re constantly having to go elsewhere to get approval for fundamental actions. There’s a great term used to describe these people: “The Meeting Guy.” (Or “The Meeting Gal” if you prefer.)

I’ve run in to this a couple times in my career, and it’s never pleasant. You need someone to bust through impediments, and instead you’re saddled with someone who never delivers on anything because they can’t make anything happen. The Meeting Guy may be a wonderful, happy person, but at the end of the day they’re an impediment to the success of your project.

Having The Meeting Guy on your team is frustrating because your project’s progress suffers. Worse yet, this may be a dangerous sign of a lack of commitment from your client or stakeholder: they may not care enough about the project to fully support it. The worst of all situations might have someone seeking to actively sabotage the effort by saddling the project with a Meeting Guy – thankfully a situation I’ve never run in to.

Identifying the Meeting Guy

Sometimes it’s obvious right away if The Meeting Guy is on your team; other times it may take a few iterations/releases/weeks or an outright crisis to unmask the person. Daily standups are the biggest help in determining if you’re saddled with a Meeting Guy. Is someone on the team regularly missing commitments with reasons like “I’m waiting on <x> to give me approval for <y>,” or “We’re blocked on that while I coordinate with <z>?” Potential Meeting Guy.

Note that I said “regularly.” Stuff happens, and not everyone can get every roadblock instantly out of the way. Meeting Guys/Gals are repeat offenders.

Dealing with the Meeting Guy

There are no easy answers when you’re stuck with The Meeting Guy. You have to get communication flowing to find out what the real issue is – because The Meeting Guy is a symptom, not a root cause.

You need to have a frank, open  discussion with your project’s stakeholders and potentially with the project’s executive sponsors. Take a breath and leave your frustrations behind. Approach the conversation from the business value aspect: “We’re not able to deliver the amount of value we should be because we’re not able to get through roadblocks in a timely fashion. Having the right people committed to the team will help us deliver more quickly.”

What’s the Root Cause?

You also need to step back and re-evaluate the need for the project. If stakeholders and sponsors won’t get the right people at the table, is there actually a real need for the project? Perhaps the business environment has changed and the project isn’t as high a priority any more. That’s not an easy topic to bring up with the people responsible for the project, but it’s a hard question that you need to get answered. Again, approach it from the business value aspect: “If the business situation’s changed so much, maybe we should stop this project and figure out a better place to spend our time and effort. What other cool things can we do for the business?”

Never, ever approach these conversations with a demanding mindset or tone. Yes, you need to clearly identify impediments and risks, but you can’t slip over in to metaphorical hostage taking or blackmail!

These are tough conversations to have with the people and organizations responsible for the project, but you must have them. Something is preventing you from delivering the best business value to the client/organization/stakeholders. Find the root cause, solve it, and focus on helping your organization/clients get the best value for their money!

Friday, January 28, 2011

Catching Up on Book Reviews

It’s been a long time since I’ve written up reviews on anything from my book pile. Here’s an overdue catch up post with short reviews of several books I’ve read over the last six months or so.

Growing Object-Oriented Software, Guided By Tests by Steve Freeman and Nat Price. Pub Addison-Wesley, ISBN 0321503627.

The first part of this book seemed scattered, jumping all over the place and making a lot of reference to things which weren’t defined until later in the book. However, once you get used to the style, this book jumps off a cliff and hits a lot of great topics, and hits them in depth.

Tooling, design, culture, methodologies – it’s all covered, and it’s covered fairly well. I particularly enjoyed the authors carrying the same detailed, practical example through the book. Too many software books use trivial examples specific to one topic. Freeman and Price evolve an “Auction Sniper” as they go through the book; the consistency is a great asset.

I also enjoyed the authors speaking emphatically about using acceptance tests as the starting point for features, not just unit tests. There’s an important differentiation between acceptance and unit tests, and the authors specifically call out acceptance tests “using only terminology from the application’s domain” – speaking to the feature’s business driver, not the underlying technology.

Also as critical to me is the authors’ emphasis on keeping the test side of the codebase clean. Your tests ARE production code. Treat them with the same approach about solid design and refactoring as you treat the code you’re deploying to your customers.

This isn’t a simple 100-level book. The authors dive deep in to design, practices, and lifecycle. They do it well enough that they’ll hook newcomers to testing as well as teach accomplished folks new things too.

Great read.

Cooking for Geeks by Jeff Potter. Pub by O’Reilly, ISBN 0596805888.

OK, this book is just plain fun. The recipes are straight-forward and tasty, and it’s terrific to dive deep in to how and why food transforms itself during the cooking process.

Potter covers everything from Calibrating Your Instruments to creating your own sous vide immersion cooker. Along the way you’ll learn about how leaveners work, discover a new taste factor you may not have known of (Umami), figure out some key time/temperature figures critical to food safety, and get exposed to some interesting molecular gastronomy.

The writing style is exceedingly well-done. Potter does a great job walking readers through the recipes and the science behind them – and it’s extremely apparent that he’s writing about something he loves.

I’m a very serious, very accomplished home cook and I got a tremendous amount out of this book. More importantly, I had scads of fun reading it.

Apprenticeship Patterns by Dave H. Hoover and Adewale Oshineye. Pub by O’Reilly, ISBN 0596518382.

Short, concise, well-written, highly useful. Other books such as Chad Fowler’s The Passionate Programmer cover similar things, but this book sits absolutely well in that company.

This book is a series of very short articles (“patterns”) around specific things you can do to guide and improve your career as a software craftsman. The articles all follow the same template: discuss the context of an environment/situation you’re in, lay out a problem you need to solve, then offer up a solution for you to apply to that problem. Many of the articles are interwoven, linking common ideas or useful concepts.

This book echoes a number of things in Passionate Programmer like the concepts of being the worst in your group (work with folks that are a LOT better than you so you’ll learn more), but it’s a very worthwhile read on its own.

Apprenticeship Patterns is particularly nicely done in that the authors don’t push a specific path they expect you to follow. They lay out a number of options and encourage you to find the path that works best for you.

I also GREATLY appreciated the authors being pragmatic over dogmatic in their approach to software craftsmanship. Certain zealots in the craftsmanship movement have completely lost site of the primary purpose of our trade: delivering value to customers. In their section “Craft over Art” he authors specifically and emphatically point out that we need to deliver “value to customers over advancing your own self-interests.” They don’t promote getting sloppy with one’s work, but emphasize doing your work well while keeping the folks in mind who are writing the checks.

All in all, this is a solid read.

Tuesday, January 25, 2011

Convert a HyperV Image to VMWare

Problem: You have the physical files for a Hyper-V virtual machine and you need to convert it to VMWare. (Maybe you’ve downloaded one of Microsoft’s demo systems such as their SharePoint 2010 Information Worker Evaluation VM.)

Solution: If you have access to HyperV, load the image in HyperV and use VMWare’s stand alone converter. It’s awesome. Point it at your HyperV server, select the server, and the converter does the rest.

If you don’t have access to HyperV, all is not lost.

Option 1: Install Virtual PC, create a new virtual system, use the VHD from the image you have. Start that system up in VPC, ensure it’s running, shut it down, then use VMWare’s Import feature to read the .vmc file Virtual PC created. (VMWare’s Import will deal with .vmc files from VPC, but not the .xml or .exp files from HyperV.)

Unfortunately, the image I was trying to import wouldn’t come up in VPC, so I was left with the less elegant, funky sledgehammer approach of

Option 2: Grab WinImage, a nifty piece of shareware that lets you convert a VHD directly to a VMDK – the format VMWare uses. Download it, install it, launch it, use Disk | Convert Virtual Hard Disk image. Select the source VHD, choose to use a fixed or dynamic target disk type, then give it the name and location of the target VMDK. (See the very nice HOWTO.)

Now you can create a new VMWare image and use the existing VMDK. The VMDK’s format is from an older version of VMWare, but VMWare will nicely upgrade it for you.

Power on your VM and bask in your geeky awesomeness.

Then go pay for WinImage because they’ve saved your bacon and you should throw some money their way. That’s how shareware works, folks.

Friday, January 21, 2011

VMWare Full-Screen Display Oddities

Problem: In VMWare 6.x and 7.x I constantly run in to the problem where I set the VM to full screen mode and then have the cursor in the VM go completely bonkers – clicking anywhere in the VM causes the cursor to shoot to the upper left corner. Occasionally a number of items on the screen will get selected.

Solution (sort of): Toggle the VM to multiple-monitor mode, minimize VMWare, maximize it again, and finally switch back to single-monitor mode. It’s ugly, but it works.

Monday, January 17, 2011

SharePoint 2010: Can’t Access Site Collection or Site Features

Problem: You get the infamous, unhelpful error message screen in SharePoint 2010 (“Click here to troubleshoot problems with SharePoint Foundation”) when trying to access Site Actions | Site Settings | Manage site features (or Site collection features).

Error logs show entries from the w3wp.exe process, usually entries such as “System.IO.IOException: The file or directory is corrupted and unreadable” followed by other exceptions with “...Context.RunAsProcess(CodeToRunElevated secureCode)” as their entry.

Solution: I checked the app pool for my SharePoint web app and found it was running with Network Service. For whatever reason, that account wasn’t given read access to SharePoint’s 14 hive (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14) during installation or site collection creation.

It’s hacky, and I’ve not done a lot of validation, but simply granting Network Service read/write/modify privs to this folder solved my problem.

IMPORANT NOTE: This was on a dev box. I’ll dig deeper before doing the same on a production system. You should too!

CodeMash 2011 Wrap Up

CodeMash 2011 is in the can and I’m mostly recovered after a weekend at the Kalahari and several naps yesterday.

Behind the scenes we organizers had a number of issues that gave us a load of last-minute grief, but hopefully we did a good enough job that most of those issues never leaked out in to public.

One of the big things we’ll refactor for next year is our approach to keynoters. Every year in the previous conferences we’ve had the same basic setup: 20 – 30 minutes for attendees to get their food prior to the keynoter kicking off their talk. This let us hold meal periods to 90 minutes, enabling us to not lose an additional breakout session right after keynoters. This also enabled us to get three great keynoters each conference, something I don’t think any other conference around does.

This arrangement has worked extremely well in the past; however, this year attendees made it clear by their Tweets and especially their behavior during the keynotes that they wanted a better separation of meals and keynotes. As a result next year we’ll likely drop down to one single keynote following a longer meal period. We’ll lose one additional breakout timeslot, but it will give everyone more time to deal with the logistics of getting though the food lines. I’m personally saddened by the loss of the two additional keynoter slots, but we need to follow what our attendees are pushing for.

Note on the food lines: Unfortunately, we had two meals that were quite honestly train wrecks regarding long lines at the buffets. I’ll personally take the hits on these due to some miscommunications with the venue’s catering folks regarding timing. This is the first time in five conferences we’ve ever had this problem. I covered the issues with the Kalahari’s awesome staff during the post-conference wrap up with them. Please trust me: the problem of grossly backed up buffet lines will never happen again. Ever.

Note on the Thursday lunch “keynote”: It wasn’t a keynote. This was specifically a special launch event. We thought it was a wonderful opportunity to have something of a global impact showcased at CodeMash. We’d be happy to consider other vendors approaching us for future events of a similar nature. We’ll also work harder to ensure everyone understands the differentiation between launches and keynotes.

We’re also going to consider refactoring the notion of allowing family members to eat with the attendees. As was very obvious, CodeMash has been extremely limited in venue space the last couple years – the dining hall is completely full with attendees, so there’s no physical space for family members or guests to eat meals alongside the attendees. Previously it’s also been a nightmare to deal with the separate billing required to cover food costs.Thankfully two things have happened that remove a couple significant roadblocks.

First, our move to Eventbrite for ticketing has GREATLY reduced the headaches associated with our registration system. We should be able to handle the mechanics around separate meal-only tickets now. Secondly, the Kalahari is adding on new construction that jumps their conference space from the current 18,000 square feet to well over 120,000 square feet. As a result, we’ll have physical space to seat a lot more folks. We won’t turn CodeMash in to a huge 5,000 attendee conference, but we certainly should have the space for attendees and guests to chow down together.

To be clear: Guests during mealtimes isn’t a done deal, but we’re certainly going to have a hard look at it.

OK, so on to a few things I consider highlights of CodeMash 2011 – and I have a much different view of things I personally find successful than most other attendees.

  • The waterpark party. Wow. I figured a few hundred folks would be down in the waterpark. Instead, when I finally got down there at 11:30pm to check on the status of things I saw a waterpark filled with happily screaming people. And that was the adults! Kids were having even more fun! This will definitely be on the list for future events. (I’d fear for my personal safety and health if I dropped it off the list.)
  • The Wednesday night band. There’s an amazing story behind The Womack Family Band and Chris Castle showing up, but I’ll leave that for another post or you can ask me in person. Chalk it up to the amazing great karma CodeMash seems to have picked up over the years.
  • Open spaces. This year’s open spaces were, to me, the most successful yet. We’ve had more sessions on the board in previous years, but this year the conversations in the Grand Hall were all intense, highly engaged, passionate discussions. It was just awesome to see those going on.
  • My Wednesday at midnight (appropriately) dive in to “Are You A Werewolf?” I was physically wiped out and emotionally drained after a long, stressful day when Steve Smith and others in one of the game rooms hollered at me to join the game. That 45 minutes of fun got my head back on right and gave me the kick to roll through the rest of the conference. Many thanks, folks!
  • KidzMash. Another “Wow.” Melissa Insko took off with this and added on a whole second day of activities. Lots of great stuff going on there, and I’m so happy she and Darrell Hawley did such an amazing job lining up fun things for the kids and families.
  • The attendees. CodeMash is great because we get great speakers to show up and deliver great content, but CodeMash is awesome because we have an amazing crowd of attendees who show up excited about learning and ready to get engaged with new ideas and people they’d otherwise never reach out to. Thanks to all of you!
  • On a closing note, I have to thank the amazing crew who puts on CodeMash. A large number of newcomers to CodeMash don’t understand that the conference is organized and executed completely by volunteers – and a tiny crew of them at that. I’ve heard of similarly-sized events having volunteer staff of 30 – 100 staffers. We do CodeMash every year with SEVEN, plus a couple on-site helpers.

    The core organizing committee, aside from myself, are:

    All youse folks are awesome, and it’s amazing to work with you again and see you do tremendous things. (Want more details on how cool these folks are? Read my post from last year I am not CodeMash.)

    Monday, January 03, 2011

    CodeMash 2011 is Nearly Here!

    Thanks to Joe Fiorini, I have an awesome countdown tool that helps me know exactly how close CodeMash 2011 is!

    It’s been an amazing run putting CodeMash together this year. We’ve had an amazing turnout from sponsors (we sold out of physical spots!), the best sessions from the best speakers of any CodeMash so far, an amazing lineup of PreCompiler workshops, and of course we are still a bit shell shocked that we sold out in 3.5 days. The screenshot of the CodeMash newsfeed says it all: registration open, registration closed.

    There are a huge number of things I’m looking forward to at this year’s CodeMash, but here are a few of my personal favorites in no particular order:

    • Chatting Selenium with Adam Goucher
    • Getting inspired by Chad Fowler’s keynote
    • Sitting in Mike Eaton’s Going Independent PreCompiler workshop
    • Working through a few of the exercises in the Coding Dojo put on by the smart folks at Nimble Pros
    • Seeing happy young geeks in the KidzMash sessions
    • Wandering around at the afterhours CodeMash only waterpark party
    • Enjoying some time chatting with my various community hommies who I don’t see anywhere near enough
    • Absorbing all the tremendous positive energy exuded from all the attendees – it’s this energy that recharges me and keeps me rolling for another year!

    I hope to see you there! If not, hopefully at the 2012 event!

    Wednesday, December 29, 2010

    Twitter.com/JimHolmes == “Sorry, that page doesn’t exist!”

    In case you’re looking for me on Twitter, I’m not.

    Twitter turned in to a massive time sink for me (and I didn’t have time to sink in the first place), and I was letting myself vent way too many frustrations there. It was time to take my own advice: “Enough griping, enough bitching already. Roll up your sleeves already and get to work.”

    ‘Nuff said.

    WinDirStat–Nice Disk Space Usage Visualizer

    Hard disks are cheap and greatly ease the past pain of having to manage free space, but that’s not the case for me: I have a small-ish Crucial C300 128GB Solid State Drive as my C: volume in my work laptop. It’s been absolutely awesome for working with the various VMWare virtual servers I deal with on a daily basis. The speed on the SSD goes to 11.

    The only downside is I have to be very careful about free space on the SSD. SSDs need breathing room to deal with various low-level things (go read Wikipedia’s article on them for a great overview), so I try to keep things fairly tidy and clean up unneeded files regularly.

    One of the best tools I’ve found to help me with this is WinDirStat, a free GPL tool. No installation, just download and throw in a util folder somewhere. Launch it via SlickRun to be really cool.

    You get an easy to understand UI with clear indicators where your space pain points are.

    Besides, I’m a tool whore and this is yet another great thing for me to play with.

    Wednesday, December 22, 2010

    HTTP 500 Errors With Invalid Request Format After Upgrading Site to .NET 4.0

    Problem: After upgrading an ASP.NET site to 4.0 you get HTTP 500 errors with exceptions when Javascript is making web service calls: “System.InvalidOperationException: Request format is invalid: application/json; charset=utf-8.” You’ve used IIS Manager to change the application pool to specify .NET 4.0 but the problem persists.

    Solution: Change to the 4.0 framework folder (C:\Windows\Microsoft.NET\Framework64\v4.0.30319 in my case) and run aspnet_regiis.exe. You’ll need to determine which option you want – check the help before running and determine what you need.

    For whatever reason, simply changing the application pool’s version value in IIS Manager didn’t work. Using the big hammer of aspnet_regiis.exe fixed things up.

    Duplicated Setup Code in Your Tests? Refactor to a Factory!

    Your test code is production code. Treat it the same way. Don’t let cruft build up, and follow good software engineering principles – like Don’t Repeat Yourself (DRY).

    I was looking through some test code the other day and found a great opportunity to refactor out some common behavior to a factory. I do this quite often in the test frameworks I build – shove off responsibility for data and object creation to a factory so I can keep things much clearer in my tests.

    In this case, we’re testing a parser class that creates reports based on an XML file. A number of tests check the parser’s handling of malformed XML or missing elements. The basic pattern below is repeated across eight or nine tests: hardwire an XML string in the test, feed that to the parser, then check if appropriate errors and messages are generated by the parser.

       1: var reportXml =
       2:     @"<report version='4.0'>
       3:             <key>FiscalYearByBrowser</key>
       4:             <description>Shows cool stuff.</description>
       5:             <connectionString>TelligentAnalyticsAnalysisServer</connectionString>
       6:             <query>
       7:                select some SQL-fu from a magic place and return unicorns
       8:             </query>
       9:       </report>";
      10:  
      11: _report = ReportParser.Parse(reportXml);

    This is repetitious, duplicated, copied cruft. Small joke there. Moreover, it’s not readily apparent what the XML snippet’s intent is. I have to read the entire XML, then mentally unwind what I know of the structure to figure out that, oh, this snippet is actually missing the title element.

    Compare the above with this section of refactored code:

       1: _report = ReportParser.Parse(TestReportFactory.GetWithoutTitle());

    The implementation of the TestReportFactory isn’t overly important [1]; what’s important here is that duplicated behavior should be pushed out to a common area, regardless of whether it’s in the system under test or your test code itself.

    Your tests are production code. Treat them as such!

    (NOTE: Some folks, particularly the Really Smart Guy Jeremy D. Miller, make the absolutely solid case that you should never sacrifice readability in your tests for the sake of cutting duplication. It’s good to push duplicated behavior out if you can keep your tests completely clear. It’s not ok to push behavior up to base classes or elsewhere if your test turns into a vague skeleton. Readability trumps everything else.)

    [1] The TestReportFactory simply builds up a string of XML, creates an XElement from that, then uses XElement.remove() or XAttribute.remove() to drop elements or attributes as needed. The entire class is pasted below. Yes, there are a number of other ways to skin this cat. I could make things a bit more dynamic, but this worked for what I needed right now. And yes, I drove design and implementation of this factory with a separate set of tests I wrote first…

       1: internal class TestReportFactory
       2: {
       3:     private static string _reportOpen = @"<report version='4.0'>";
       4:     private static string _key = @"<key>FiscalYearByBrowser</key>";
       5:     private static string _title = @"<title>Fiscal Year by Browser</title>";
       6:  
       7:     private static string _description =
       8:         @"<description>Shows page views per browser (IE, FireFox, etc..)
       9:          for each fiscal year.</description>";
      10:  
      11:     private static string _connectionString =
      12:         @"<connectionString>TelligentAnalyticsAnalysisServer</connectionString>";
      13:  
      14:     private static string _query =
      15:         @"<query>
      16:             select non empty [Time].[Fiscal Year].Members on columns,
      17:             non empty [Dim Browser].[Browser Name].Members on rows
      18:             from [Evolution Reporting]
      19:          </query>";
      20:  
      21:     private static string _chartTypes =
      22:         @"<chartTypes>
      23:                                 <add type=""fancy 3d chart"" />
      24:                                 <add type=""plain 2d chart"" />
      25:                               </chartTypes>";
      26:  
      27:     private static string _reportClose = @"</report>";
      28:  
      29:  
      30:     public static string GetValidXml()
      31:     {
      32:         XElement doc = CreateValidReportXElement();
      33:         return doc.ToString();
      34:     }
      35:  
      36:     private static XElement CreateValidReportXElement()
      37:     {
      38:         var _outgoing = new StringBuilder();
      39:         _outgoing.Append(_reportOpen);
      40:         _outgoing.Append(_key);
      41:         _outgoing.Append(_title);
      42:         _outgoing.Append(_description);
      43:         _outgoing.Append(_connectionString);
      44:         _outgoing.Append(_query);
      45:         _outgoing.Append(_chartTypes);
      46:         _outgoing.Append(_reportClose);
      47:         XElement doc = XElement.Parse(_outgoing.ToString());
      48:         return doc;
      49:     }
      50:  
      51:  
      52:     internal static string GetWithoutQuery()
      53:     {
      54:         return CreateXmlStringWithoutElement("query");
      55:     }
      56:  
      57:     private static string CreateXmlStringWithoutElement(string elementName)
      58:     {
      59:         XElement doc = CreateValidReportXElement();
      60:         XElement element = doc.Element(elementName);
      61:         element.Remove();
      62:         return doc.ToString();
      63:     }
      64:  
      65:  
      66:     internal static string GetWithoutKey()
      67:     {
      68:         return CreateXmlStringWithoutElement("key");
      69:     }
      70:  
      71:     internal static string GetWithoutDescription()
      72:     {
      73:         return CreateXmlStringWithoutElement("description");
      74:     }
      75:  
      76:     internal static string GetWithoutConnectionString()
      77:     {
      78:         return CreateXmlStringWithoutElement("connectionString");
      79:     }
      80:  
      81:     internal static string GetWithoutChartTypes()
      82:     {
      83:         return CreateXmlStringWithoutElement("chartTypes");
      84:     }
      85:  
      86:     internal static string GetWithoutTitle()
      87:     {
      88:         return CreateXmlStringWithoutElement("title");
      89:     }
      90:  
      91:     internal static string GetWithoutVersion()
      92:     {
      93:         XElement doc = CreateValidReportXElement();
      94:         XAttribute ver = doc.Attribute("version");
      95:         ver.Remove();
      96:         return doc.ToString();
      97:     }
      98:  
      99:     internal static string GetInvalidXml()
     100:     {
     101:         return "<report>";
     102:     }
     103: }
     104:  

    Subscribe (RSS)

    The Leadership Journey