Blog
Laptop Rebuild - Essential Apps
When we last saw our hero, he had fallen victim to an evil plot to disable his computer’s ability to boot up. After great efforts at recovery, eventually he was forced to concede defeat to Vista and reinstall everything from scratch. Let’s return now to see what’s in store in the next chapter of our story, already in progress…
So, day 2 after my issue with Vista and I’m now at least able to use my laptop again for real work. However, it still is missing dozens of little things that I find useful, so I thought I’d catalog those here in the spirit of Scott and Jesse’s posts on useful tools and utilities. In my case, this is a running list of things I’m installing, in order, along with some commentary. Feel free to comment on anything you think I’ve left out.
Day 1 Basics
- Windows Vista Ultimate SP1 – Followed by about 40 immediate updates.
- Visual Studio Team Suite 2008 SP1
- Microsoft Office 2007 Ultimate SP1 – Followed by a bunch of updates, and switching from Windows Update to Microsoft Update so that Office automatically gets updated.
- FireFox 3
Basic Utilities
- Terminals – For all remote connection needs.
- Visio Professional 2007 – Often handy, and it’s on the same MSDN disc as Office 2007.
- Del.icio.us Bookmarks FireFox Addin – Makes Del.icio.us easy to use.
The following tools just stay in my C:\Util folder and get restored from my backup.
- DebugView
- Fiddler
- ProcessMonitor
- Reflector
- SpaceMonger
- LINQPad – xcopyable LINQ and SQL and Code Snippet Editor/Manager. Awesome!
Social Software (IM and Twitter)
- Pidgin – supports multiple IM clients and has some cool features like detecting when someone is writing an IM to you before they finish typing it.
- TweetDeck – Current favorite Twitter app. Follow me at @ardalis.
More Apps
- Foldershare – Awesome for sharing files between computers.
- Adobe Reader (or Foxit Reader) – for PDFs. Foxit installs and opens documents MUCH faster but occasionally has compatibility issues with Adobe.
- ClearContext – Makes filing things a breeze in Outlook.
- Flickr Uploadr – Makes uploading photos a breeze w/Flickr.
- Virtual CloneDrive – Trying this instead of Daemon Tools for ISO mounting. So far I like it.
- SQL Server 2008 – Had 2005 before, but figure now’s as good a time as any to upgrade. We’ll see if I still need SQLPrompt with it.
I still have a lot more to go but this is where I am with reinstalling by day 3. I still need an FTP client (FileZilla) and a bunch of other apps. Debating whether to install Plaxo again. Outlook is actually quite fast now that I just had it start with a fresh PST file, and I’m hoping to keep it that way since previously it was the slowest thing on my machine. We’ll see.
Stories Too Big - Vertical Slices
I have a client who lists as one of the key challenges with implementing agile practices with their teams as managing to define user stories that are valuable but not too big. This is actually a very common challenge, and one that we run into frequently ourselves at Lake Quincy Media and with other clients of NimblePros.
Naturally there are many books available on the subjects of extreme programming, agile software development, user stories, etc. and these are certainly worth reading. Additionally, an agile boot camp like HeadSpring’s can be an excellent way to fully immerse yourself in how things should be done, without the daily distractions of regular work. My first word of advice is that you read what the experts suggest, and consider attending a class from a well-respected trainer if you can do so.
That said, here is some simple, practical advice I’ve collected (from others) on the subject of writing useful stories. First, there’s an acronym that you can use as a test to measure how effective a particular user story is. This is taken from Bill Wake’s eXtreme Programming Explored book. He suggests that you INVEST in good user stories.
Good User Stories should be:
Independent
Negotiable
Valuable
Estimatable (or Estimable)
Small (more on small user stories)
Testable
I would further suggest that these attributes are most important only when the time comes to plan for the story in an iteration. That is, once it comes time to estimate the story and prioritize it as part of an iteration, it needs to exhibit the INVEST qualities. Prior to that point, it’s perfectly acceptable as a placeholder even if it’s big and vague – it can be broken down further when it’s closer to actually being done. This exemplifies the lean principle of putting off decisions until the last responsible moment. If you’re not going to get to the story next week, there’s no sense wasting time trying to estimate it or otherwise make it perfect. Things will change before you start work on it, which will make at least some of your work waste.
Large, vague user stories are known as Epics. It’s fine (even efficient) to have Epic stories in the backlog – it stops being fine once you begin an iteration. That’s when the rubber meets the road and the actual stories need to be extracted from the larger epic.
How Do You Break Up an Epic into Stories?
There are a lot of different ways one could attack this problem – and certainly more than one “right” way. If we take the “epic / story” metaphor too far, we could say that every story arc has an introduction, a climax, and a prologue and that in between there are many chapters and character development, etc. However, this viewpoint naturally imposes a serial constraint on the stories we develop, and would tend to lead to Story 1 which is required for Story 2 which is required for Story 3. This violates the first attribute in our INVEST acronym, which is that the stories should be Independent.
Bad Example
A real world example of this serial approach that delivers nothing until everything is in place would be to create stories based on logical tiers in the software. For instance, if you have a data-driven application consisting of UI, business tier, data access layer, and database (quite common), and for the sake of argument you have a hard dependency on each layer from the one above it (bad design, but quite common), then you might opt to write stories like this:
Story 1: Create the new DB Table
Story 2: Create the stored procedures
Story 3: Create the DAL to access the sprocs
Story 4: Create the business layer code that references the DAL
Story 5: Write the UI screen
You can think of each of these stories as addressing a horizontal layer in the application architecture. The problem with this is that it’s very difficult to start Stories 2-4 without the previous story being done. About the only parallelization you can easily achieve here would be the UI, and with strong coupling it would also be very difficult to test things along the way.
An Alternate Approach – Vertical Slices
An alternate approach is to break down the epic into stories that very small yet still valuable bits of vertical functionality. For instance, let’s say the initial story is for a user registration page that collects a lot of different data. There’s name data. There’s room for multiple addresses. There’s email and phone info. There’s some validation logic. Using the horizontal approach, someone might have generated the Registration Page user interface, and from there a data model, tables, sprocs, etc. If at any point someone got stuck, nothing would be ready to deliver and so none of the stories would be providing value until all of them were produced. Using vertical slices, this might break down like so:
Story 1: User can register and provide username and password.
Story 2: User can provide name data.
Story 3: User can provide an address.
Story 4: User can manage multiple addresses.
Story 5: User can add additional contact fields (phone, email, etc).
All of the stories most likely still depend on the first one in this case, and you’ll rarely be able to completely eliminate all dependencies between stories in an epic. But now it would be possible to develop all 5 stories independently. They might even be written using some kind of control (web, WPF, AJAX, doesn’t matter what UI technology) such that they would be simple to stitch together on a single UI page or kept separated to form some kind Registration Wizard multi-step process. And if the iteration ends and only Stories 1 and 2 are done? You ship it (or at least demo it to the customer) and get feedback earlier than you otherwise would have, which helps ensure that what you’re driving toward really is the correct solution.
Summary
As I mentioned, there are many ways to split epics into individual stories. The details of your application and other variables will influence what technique is best for the given situation. However, if you remember the key attributes of good user stories and focus on being able to deliver something, however small, of value to the customer as quickly as possible, you’ll very likely end up with stories that are about the right size.
Recently I picked up an HP MediaSmart EX470 Windows Home Server to help consolidate my files at home and to provide a simple backup solution. It’s been great and it’s an extremely economical way to get backups. You can hook it up with Amazon S3 using JungleDisk and get simple offsite backup of the files (but not the backups) easily and cheaply as well, and JungleDisk is just one of many plugins available. I recommend the 500GB version for the price, as you can pick up a 1.5TB hard drive to plug into one of the extra bays for under $150.
One of the many plugins for the WHS is a media streaming one that makes it very easy to use the WHS from your XBox 360. With this, it becomes trivial to use the XBox to browse pictures, watch slideshows, watch video clips, and play music. Sometimes the lag is pretty bad when the XBox is trying to load a list of items, but this is likely just due to my wireless network and the significant distance between my XBox and my router and WHS.
Suggestion 1: Support Streaming Video
As much as I love this, there is certainly room for improvement around the XBox’s media capabilities. First of all, as I mentioned in my previous post, you can download HD content for the XBox from the video marketplace, but the files are (as you would expect) quite large, and unfortunately you can’t start watching the movie until it’s been downloaded (or at least, I wasn’t able to start playing it after it had downloaded 20% over the course of half an hour the other day – I went to bed before it reached 100%). It would be great if the XBox video marketplace supported streaming downloads, as one of my commenters on another post reports the AppleTV does.
Suggestion 2: Consolidate XBox 360, WMP, Zune into Unified Media Story
I’d also like to improve the music playing experience. Currently, there is no way to save a playlist using the XBox interface unless the songs are stored on the XBox. It does support playlists on the media server it’s connecting to, but not Zune playlists. So if you’re a Zune user, you have to duplicate your playlists using Windows Media Player so that the XBox can use them, and you have to do all of this from your computer, not your XBox because the XBox can’t store playlists that include songs that aren’t on the XBox. It’s very uncoordinated in its current state, and not the kind of seamless application sharing that Microsoft is well-known for in other areas, such as Office. I’d really like to see some consolidation between Zune, Windows Media Player, and the XBox so that it’s much easier for these technologies to work together. Microsoft needs one ring to rule them all (and not the RROD).
Suggestion 3: Allow Upgrades to the XBox at Market Value
I can get a 1.5 TB hard drive for under $150. I can get a 2GB flash memory drive for $1.85!
Market Hard Drive Cost: $0.10 per GB
Market Flash Drive Cost: $0.92 per GB
Now, how much is for an XBox Hard Drive? Retail for the 120GB unit is $150, NewEgg has it right now for $135. How about a 2GB memory unit? Oh, wait, they don’t have those. 1GB? Nope. But you can get a state-of-the-art 512MB unit for just $40. My *phone* has more memory on its MicroSD card (300% more), and the MicroSD card is about 1/20th the size of the XBox memory card.
XBox Hard Drive Cost: $1.13 per GB (more than 10x market price)
XBox Flash Drive Cost: $80 per GB (more than 80x market price)
Apparently you can upgrade your hard drive yourself without being limited to a mere 120GB overpriced unit, as this PCWorld article shows. I’m not aware of a similar way to create a cheaper memory unit. Oh, and it’s also annoying that the XBox supports up to 4 players but only 2 memory units. What if all 4 people have XBox Live Accounts they want to use, with the profiles on their memory units?
Either Microsoft should put out supported upgrades for the hard drives and memory units that are at least in the same ballpark as market values (even 2x as expensive would be fine w/me, honestly, but 10x and 80x is a bit extreme), or, better yet, they should allow the use of standard electronics like USB flash drives and USB hard drives. I understand part of the reluctance to do this is to make hacking and cheating more difficult, so I would settle for the first option (and I’m sure Microsoft’s sales of these peripherals would be quite good, too).
Learning To Code with the Azure SDK - Show Me The Code
I’ve been working with Azure off and on since last summer, and like any new API or platform, there are hurdles involved with the learning curve. This is especially true for pre-release software that is rapidly changing and of course has neither official documentation nor much in the way of info on blogs or developer community sites like ASPAlliance.com. One of the ways I like to learn about projects these days is through testing. Ideally, the project will already have a suite of unit tests that I can run to confirm that it actually works at least as well as its creators expect it to, and then I can look at individual tests to discover how the creators of the API expect others to use it. Like many other developers, I usually don’t bother to read the official documentation (I’ve come to expect it will be lacking), preferring instead a “Show Me The Code (SMTC)” approach.
Show Me The Code
The big benefit of SMTC is that you don’t have to worry about whether or not the documentation was properly updated between the previous CTP release and the preview alpha CTP pre-release daily build you’re using now. You run the code, and if it does what it’s supposed to do, then you know you have a system that is more-or-less working and you can go from there. Most SDKs include samples to help you get started, with full source code, as obviously this is one of the best ways developers can quickly get up to speed with a new set of tools.
Azure’s SDK as of the January CTP ships with about 9 folders worth of samples, including a couple of HelloWorld projects, a PersonalWebSite, a CloudDrive demo that lets you map a drive to cloud storage, and more. If you want to take advantage of Azure Storage on your local machine, then you’ll most likely run the sample storage client API sample so you can get up to speed with it. It’s comprised of a console application that basically runs through a bunch of API exercises that demonstrate how to perform operations against Azure’s Blog, Queue, and Table storage options. If you run it, you end up with something like this:
Coupled with the actual source code, this is a great example of how to use Azure Storage. However, it’s not the best output and unless you watch it as it runs, you don’t really know what all this program actually did. Or if some pieces maybe failed. Or how to run just the part on deleting table entries. This is a good example of SMTC, but it falls short of being as expressive and approachable as it could be.
Unit Tests
I’m probably preaching the choir here when it comes to unit tests, but there are still about a bazillion developers out there who simply don’t get them. They don’t write them, they don’t run them, and they certainly don’t see the value in them. This is just one instance where I think unit tests are valuable, and that is as documentation. As a developer trying to learn an API or going through an SDK, I would much rather have an exhaustive suite of unit (and integration) tests than a .chm file or PDF with standard documentation (though of course having both would be ideal). With the unit tests, I have documentation I can execute. And I can do it for the whole system or just a tiny piece that interests me at the moment. I don’t have to try and set up a huge solution that came as a sample with the SDK – I can run just one test. Or I can look at just one test and, if it was written well, I can come quickly grasp how the System Under Test (SUT) is meant to be used.
Going back to the Azure SDK example with the StorageClientAPISample project, the Program.cs file in that project is 972 lines long. Here’s a small example of some of the code, showing how to create a Blob of text:
// write some text blobs
NameValueCollection nv1 = new NameValueCollection();
nv1["m1"] = "v1";
nv1["m2"] = "v2";
StringBlob hello1 = new StringBlob("hello.txt", "Hello World");
hello1.Blob.Metadata = nv1;
Console.WriteLine("Creating blob hello.txt");
PutTextBlob(container, hello1);
BlobProperties prop = container.GetBlobProperties("hello.txt");
Console.WriteLine("hello.txt content length = " + prop.ContentLength);
I’m sure the unit testers among you will agree that this would be a good candidate for a unit test (or in this case, since it really is talking to the storage service, an integration test). It’s possible that some future version of the Azure SDK (it’s not even Beta yet, I realize) will include a suite of unit tests, but Microsoft faces some challenges here with deployment. MSTest still is not xcopy deployable, and to date they’ve shown a fair amount of reluctance to use alternative open source tools like NUnit (though the ASP.NET MVC team has been more open in this regard than most other teams). Since I’m not on the Azure team but I do think such tests would be a valuable addition, I’ve suggested this to the team but I’ve also gone ahead and started an Azure Contrib project on CodePlex that will include such tests among its samples, as well as other Azure add-ons that don’t ship with the official SDK. Naturally I’ll be looking for additional project members as well as ideas for things to include in the project, though for now I don’t even have these tests set up so I don’t want to get too far ahead of myself.
Summary
Show Me The Code (SMTC) is a great way to learn. Tests are a great way to break up a lot of code into bite-sized pieces that are both easy to learn and easy to evaluate whether or not they’re working correctly. Microsoft should consider shipping tests instead of monolithic console applications with the SDK samples, for Azure as well as other frameworks they are developing, and they should consider making MSTest distributable or accepting the fact that tools like NUnit can serve this space well. Azure Contrib will soon provide some additional components of interest to Azure developers which are not part of the official SDK.
Outlook Send Mail Infinite Loop - Message in Outbox
Last week I encountered a problem with Outlook that I’m happy to report I’ve just solved. I found a bunch of things on the Interwebs that looked like they might be useful, but none of the fixes there did the trick for me (of the ones I tried – some fixes were more extreme than I wanted to attempt). Here are some resources that may help you if my fix does not:
- Outlook Send-Mail Infinite Loop
- Message stuck in Outbox
- How to troubleshoot mail stuck in Outbox in Outlook 2000
- Delete a stuck Read Receipt
- Download MDBVU32.EXE (see previous link for why)
- Forum with some tips for trying to delete messages
The Problem
I tried to send an email on Sunday and for whatever reason it got stuck in my outbox. It was italicized, and if I tried to open or delete it, it would inform me that Outlook was already trying to send the message and thus I couldn’t do anything to it. This was a minor annoyance, at first.
However, this became much more of an annoyance when Outlook would, from time to time, get into some kind of an infinite loop while trying to send messages. It would generate “Successful” account synchonrization messages over and over again (racking up hundreds of such messages per minute). Some of my online research suggested this might mean that my Address Book was out of sync with my contacts, but following the steps in that post revealed that this wasn’t my issue. While this loop was going on, Outlook was unusable and the Send/Receive dialog would flicker, taking focus from other windows, which basically forced me to close OULOOK.EXE from Task Manager.
I downloaded MDBVU32.EXE on the advice of some other blogs, which let me view my PST file and attempt to manipulate its contents. I was able to see the message in the outbox but attempting to delete it did nothing, and attempts to abort sending the message resulted in an error.
I tried switching to Offline mode, but that didn’t help. In fact, the infinite loop still occurred (I wasn’t really sure why it was still trying to connect to anything, but it was). Some of the possible solutions I’d found online suggested that I create a new PST file and delete all of my accounts and re-create them in the new PST file, and then move over my messages. That definitely seemed like overkill and really at that point I was starting to consider just giving up on Outlook altogether. Luckily, I found the solution today before resorting to anything that drastic.
The Solution
Thanks to Outlook guru Alon Brown, the solution was pretty straightforward. Restart Outlook in safe mode, switch to Offline mode, then restart Outlook in safe mode again (while still offline), and delete the message. This worked!
I’d tried safe mode, and I’d tried offline mode, but I hadn’t tried restarting Outlook with these settings in place. I’m not sure if it was necessary to be in safe mode each time or not, but those are the steps that worked for me. To get outlook into safe mode, simply browse to the path where OUTLOOK.EXE is located (e.g. C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE) and run it from the command prompt with the /safe switch. Then you should be able to navigate to the Outbox and delete any messages found there.
DevReach Online 2010 - Software Fundamentals
I just finished my DevReach Online presentation, A Whirlwind Tour of Software Development Fundamentals. In this 45-minute talk, I covered what I consider to be fundamental principles, patterns, and practices of software development, with a little bit of time for a demo at the end. The session was recorded and will be available on the DevReach Online web site soon. You can get my slides and demos from the talk here, though. I’ve also included some of the links from the talk to save you the trouble of hunting through the PowerPoint file.
18-19 October 2010, Sofia, Bulgaria
References
A Whirlwind Tour of Software Development Fundamentals - Slides and Demos
Clean Code by Robert C. Martin
Agile Principles, Patterns, and Practices in C# by Robert C. Martin and Micah Martin
Pluralsight On Demand Training
NimblePros agile consulting, training, and mentoring (virtual mentoring and training available)
Code Review Singleton Pattern Issues
One of my applications relies on a singleton pattern to create a single instance of a server which processes requests from many different ASP.NET handlers. It is created using pretty much standard Singleton code:
public static Context CreateContext()
{
return CreateContext(new ConfigurationFileSettings());
}
Recently, this server needed to be made aware of whether requests were coming into it via SSL or standard HTTP. The solution that was checked in (and which worked and passes local tests) is to create a new property of Context called IsSecureConnection, and to allow this to be passed into its public constructor like this:
public Context(ISettings settings,
bool isSecureConnection)
{
this.Settings = settings;
this.IsSecureConnection = isSecureConnection;
}
This is pretty much classic Dependency Injection and most of the time is what I would consider the right approach to the problem. However, in this case it fails to take into account how this object is used, because of the fact that it’s using a Singleton. And in this case nothing ever calls this constructor anyway – the actual solution that was applied instead only made use of the IsSecureConnection property (which was read/write).
The client code in the ASP.NET handlers that invokes the Context class looks like this (before adding any support for SSL):
Context engineContext = Context.CreateContext();
After adding support for SSL, this code became:
Context engineContext = Context.CreateContext();
engineContext.IsSecureConnection = isSecureConnection;
Looks fine, right? Run it through some tests – things behave as expected. SSL requests get routed to the Context object with IsSecureConnection = true. Regular HTTP requests get routed with IsSecureConnection = false. Stick a fork in it and ship it…
Global State and Static / Singleton Objects
The problem of course is that many different ASP.NET handlers are talking to the same exact instance of Context. In this particular application, this is taking place tens of times each second. So if you imagine that 49 requests come in during a given second over HTTP and 1 comes in over HTTPS, it’s quite likely that while the Context has had its IsSecureConnection property set to one value, it’s in the middle of processing another request.
The other issue here is that whether or not a given request is using SSL is a lower level concern to the Context object which is in essence a request manager. The only call that the handlers ever send to Context is something like this:
Response myResponse = engineContext.GetResponse(_myParamsDTO);
I’ve been reading a bunch of kanban and lean books recently as I work on my Pluralsight course on Introducing Kanban (not published yet – will link to it when it is). The most recent one I’ve finished is Scrumban, Essays on Kanban Systems for Lean Software Development, by Corey Ladas (I’m doing the reviews in LIFO order). I made a bunch of notes while reading this book, and it has a great deal of useful information. I read David Anderson’s Kanban book first, followed by Benson and Barry’s Personal Kanban. I think reading Scrumban last was definitely the right choice, though if I were recommending these books today I would most likely suggest someone start with Personal Kanban, as it’s the lightest weight of the three.
One thing that sets Scrumban apart from the other books is the narrative style and organization of the book. As it says in the title’s byline, this book is a collection of essays – there isn’t a great deal of cohesion or a consistent narrative guiding you through the book. It also tends to assume a fair bit of of knowledge on the part of the reader, which is one reason why I wouldn’t start off with this book if you’re just starting to learn about kanban and lean software development. I also don’t think the title is particularly fitting, since there is only one essay that deals with scrum and mentions the term scrumban in the whole book. I have a feeling the title was chosen mainly because it was short and would leverage the popularity of scrum to drive up book sales – whether this was the case or was successful I can’t say.
I found a great deal of value in the book, and it is certainly no rehash of the other two kanban titles listed above. There are some very important, basic concepts covered here such as the analogy of kanban tokens to money in one of the first essays. Corey does a great job of examining multiple different approaches to processes and showing their pros and cons. Things like methods for synchronizing different handoffs between related up- and downstream collaborators in a process are explained clearly and are honestly things I’d never given much thought previously. The book also does a great job of reinforcing the notion that time-boxed iterations are a stepping stone to an even more streamlined process. If you’ve ever considered the logical progression of moving from infrequent software builds, to having a daily build, to having continuous integration, you can see the same logic being applied to moving from large project phases and handoffs (e.g. waterfall) to many smaller and iterative iterations (sprints), to continuous software delivery and one piece flow (ideal).
One criticism I do have of the book is that it often didn’t define new terms and acronyms as they were introduced. I noted a bunch of them:
There were probably more that I missed because I was already familiar with the term, and of course it’s possible some of these were covered somewhere in the book and I missed them, but these were my “google these later” notes. The links above are the result of my google-fu after-the-fact.
The latter 2/3 of the book shows a bunch of different ways to model processes using task boards, and the effects of each of these designs. The analysis from these areas of the book are easily worth the price of the whole book, considering how much time they’ll save you if you’re just getting started. The book doesn’t propose one right way to go about implementing such systems, but it does a very good job of showing the pros and cons of a number of approaches.
Overall, I thought the book had some great information, but could have been organized better. I would give it 3 or 4 stars on Amazon and would recommend other books first, but if you’ve read the others and still want to learn more, there’s some great information here.
Updating Blog to Orchard and Switching Domains
So, yesterday I posted a review of the new Asus Ultrabook and, as has become rather predictable lately, the virtual web server hosting my Graffiti-powered blog started having 100% CPU for quite a while after the post went live. Now, I don’t get *that* much traffic, but apparently something with my configuration of Graffiti, the server, and the traffic that I do get is enough for it to bring that server to its knees. And Graffiti, great though it was years ago, just had to go.
I opted to go with Orchard for several reasons. I’d been on the fence between Orchard and WordPress, but after using WordPress for some other one-off projects over the last 18 months, I’ve grown disenchanted with it. While I did find that it was very cheap to find hosting for WordPress, I also found that these cheaper hosts were (shockingly) not as responsive as I was used to, and also since WordPress is to blogging as Windows has been to PCs, it also is the target of loads of automated hacks, and it didn’t take long before the WordPress accounts I had set up on these shared hosts were compromised. After cleaning them up multiple times only to have the problems recur, I decided I’d just avoid the whole problem by using Orchard (the blogging equivalent of buying a Mac). I’m hosting my new blog with Cytanium.com, which is run by the same awesome folks who run ORCSWEB hosting, but is set up better for a personal site like this.
Orchard is incredibly easy to get set up, has loads of extensions, and also happens to use the platform, language, and design approach that I prefer (in this case, .NET, C#, and MVC). There’s a great introductory course on Pluralsight (intro module is free) by my fellow NimblePros employee Kevin Kuebler, too, if you’d like some help getting started. Migrating to Orchard was fairly straightforward. I used John Papa’s blog series on migrating from Graffiti to Orchard as my primary guide, and it was a huge help. The data migration involved pulling the data out of Graffiti into BlogML, and then sucking in the BlogML back into Orchard. I cleaned up the code for doing this a bit, though the comments are still all wrapped in <p>…</p>, so use John’s script to fix that. The latest version of the GraffitiToBlogML code should be here.
I’m hoping to get Disqus set up for my comments soon (using this tool to import from BlogML to WXR), as well as to migrate my old blog data from AspAdvice.com, ArmyAdvice.com, and asp.net/blogs, so that all of my blogging for the last decade can all live here. And hopefully this new account will perform better than the old one – I know I was losing visitors who came to my old site and found it unresponsive and left. If you’re reading this, thanks for sticking with me! :)
Hi, I'm Steve Smith. I go by Ardalis online because, well, you'd understand if your name was Steve Smith.
This is now the fifth place I've had a blog, if you don't count my initial home page and articles on ASPAlliance.com, which were somewhat blog-like but preceded the term. Unlike my past blog moves (from the ASP.NET/blogs site to AspAdvice.com/blogs and my ArmySteve.com / ArmyAdvice.com/blogs/ArmySteve blogs, and then from there to SteveSmithBlog.com), this time I'm pulling everything into one place. So far I only have the most recent stuff here, but soon you should see content dating back to 10 years ago, all in one easy to find location.
If you're here, you've found my blog. You may also wish to stalk me via other means:
Here's some more info on me, which is slightly outdated at the moment (Jan 2012).
Steve Smith is currently a Senior Architect with The Code Project and CTO of Lake Quincy Media, which he co-founded in 2005. He also founded and continues to run ASPAlliance.com, a popular resource for Microsoft programmers. He is a Microsoft Regional Director, an ASP.NET MVP (profile), an INETA Speaker, and an ASPInsider. He's written or contributed to several books on ASP.NET and related topics and is a frequent speaker at industry conferences such as DevConnections and TechEd. Steve also founded and organizes the Hudson Software Craftsmanship group in Hudson, Ohio, where he and his wife Michelle also own office space and she manages their agile consulting company, NimblePros.com.
Steve is a US Army veteran who served in Iraq as a combat engineer platoon leader tasked with finding and destroying unexploded ordnance and clearing IEDs. He received his honorable discharge as an army Captain in 2005 and is now happy to be 100% a civilian.
Steve lives in Ohio with his wife and business partner Michelle, their daughter Ilyana, and son Nikita. When he's not trying to keep up with his business or technology, Steve enjoys games, bicycling, and karate.
History
In January 2012 I moved my blog from SteveSmithBlog.com to Ardalis.com, which is shorter, more memorable, and lines up with my twitter alias.
In July 2008 I moved my blog from AspAdvice.com/blogs/ssmith to my own domain, SteveSmithBlog.com. I'm keeping all the old content at the old blog, as well as my previous Army blog that I kept while I was in Iraq in 2004.
Asus Zen Ultrabook First Impressions
Last week a received a new Asus UX31E Zenbook Ultrabook laptop computer, which I’ve been putting through the paces. I’d like to write up my thoughts on the unboxing and my initial impression of the machine, and I’ll write more in a few weeks once I’ve had some more time to use it. Overall, I really like it so far. It’s thin, light, shiny, and feels solidly put together. It’s also extremely fast to start up and has a very reasonable active use battery life and a better sleep/standby battery life than any laptop I’ve ever owned.
Unboxing
I got my Asus Zenbook Ultrabook on Amazon, so of course it came in an Amazon box. Inside the Amazon box was the Asus box:
And inside the Asus shipping box is the actual Zenbook packaging:
After removing a bit of shrink wrap, this box opens to reveal the Zenbook and its accessories:
After a bit of unpacking and cleaning up some of the Russian nesting doll style boxes, the components look like this:
The laptop is incredibly thin. Here it is compared to a thin Bic pen on my desk:
It comes with a magnetic clasp carrying sleeve, which I really like. It’s handy to slide the Zenbook in and out of, and it has a nice texture and feel to it, in addition to feeling pretty durable (though it’s too early to say how well it holds up to real usage). Because it’s so thin, the Zenbook doesn’t have ports for Ethernet and VGA, opting instead to support only thinner ports like USB and micro-HDMI. It comes with a small accessory bag and two adapters:
- A USB to Ethernet/RJ-45 adapter
- A micro-HDMI to VGA adapter
I do have two small complaints about the accessories. Firstly, I wish it came with an HDMI adapter, since our office projector supports HDMI. That said, I wouldn’t want to give up the VGA adapter, since that’s still the universal standard for projectors everywhere. Secondly, the accessory bag, while compact and stylishly a match for the larger Zenbook sleeve, does not actually fit into the sleeve. Likewise, the power adapter certainly doesn’t fit into the sleeve, so you’ll certainly still need some kind of proper laptop bag or backpack to hold these things. It would have been nice if the sleeve somehow could be just as slick and portable as it is now while still somehow being able to hold the adapters and/or the accessory bag, but I suspect those two desires are simply incompatible with real-world space constraints.
To support standard HDMI output from the Zenbook, I’ll most likely pick up one of these HDMI Female to Micro HDMI Mail Adapters for under $3.
The front and back of the Zenbook are very simple. The smooth finish is great to look at and has a nice, slick feel to it. The sleeve, again, is a nice addition to the package, as I’m sure it will protect the Zenbook from fingerprints and accidentally slipping from my fingers in transit.
The power adapter is light and the connector the the Zenbook itself is tiny. I think it’s smaller than a standard 3.5mm headphone jack, though I haven’t measured it or tried to plug my headphones into the power port of the laptop (yet). I certainly appreciate having a light power supply, since I’ve had laptops in the past with power bricks that weighed (literally) more than the Zenbook itself (I’m looking at you, Alienware).
Once you open up the machine, it has a nice-sized screen, a huge trackpad, built-in speakers on the inside of the screen’s hinge, a webcam, and the same smooth metal finish found on the outside case.
Starting For The First Time
The Zenbook comes with Windows 7 Home Premium 64-bit. It also has the Bing Bar installed automatically, but this is the only “crapware” that seems to come preinstalled on the device. I left the Bing Bar running for almost a day before it annoyed me enough to remove it (I did try to give it a fair chance).
Once you’ve started, you’ll see some information about Instant On, which theoretically is a unique Asus technology that saves power and speeds boot time for the computer. I turned it on and the default desktop widget that displays expected Standby Time doubled as a result.
Asus also has an automatic update service running, which is set up nearly identically to Windows Update. You’ll want to make sure you get the latest drivers via Asus Update, as I have heard of others having issues that were resolved by these updates. One common issue I’ve seen relates to the trackpad. It’s different from others I’ve used, as it is both more sensitive to touch and by default somewhat slower (in terms of how fast the mouse pointer moves on the screen based on how far you move your finger – adjustable in Windows). The left and right “buttons” are actually just regions on the touchpad, too, and so occasionally I’ve accidentally dragged things as I was trying to click. These are I’m sure just things I need to get used to. I’ve also read others’ complaints about the keyboard. It, too, is different from most laptop keyboards I’ve used, but I haven’t had any problems with it, and I’m a relatively fast touch typist. It requires some getting used to, just like riding a new and unfamiliar bicycle, but once you’re acclimated to it, it’s fine in my so far limited experience.
The one other oddity I noticed so far is that the power button is placed where the Delete button usually goes (and the delete key is just to the left of the power key). I almost, once, hit the power button while going for the delete key. I’m pretty sure it just would have gone to sleep (which it does quite quickly) and I’d have simply had to wake it back up (also very quick), but I caught myself and have had no issue with remembering where the del key is since.
Disclosure of Material Connection: I received one or more of the products or services mentioned above for free in the hope that I would mention it on my blog. Regardless, I only recommend products or services I use personally and believe my readers will enjoy. I am disclosing this in accordance with the Federal Trade Commission’s 16 CFR, Part 255: “Guides Concerning the Use of Endorsements and Testimonials in Advertising.”
Here’s another review of the Zenbook on CNET you may find interesting if you read this far. I agree with their sentiment, “who doesn't want a thin, unibody metal lightweight laptop that starts fast and has a great battery life?”
Run Your Unit Tests in Parallel to Maximize Performance
If you’re at all serious about testing, at some point you’re going to have a rather large suite of tests that need to run, and you’ll find that your builds are taking longer than you would like because of how long the tests run. For example, consider this suite of 24 tests, each one of which looks like this one:

If you run 24 of these, it’s going to take about 24 seconds, by default:

Now of course it’s important to keep your unit tests and integration tests separate and to know which is which, but even once you’ve done that, anything you can do to speed up your test execution times is going to be a big help to your productivity. Slow builds due to slow tests kill productivity:
One simple way you can speed up your tests is to run them in parallel. Doing so with MSTest is actually extremely easy to do, although it’s not at all obvious how to do it, since the setting you need to adjust is hidden away and has no user interface exposed. The really cool thing is that, after you make the change, even if you don’t use the Visual Studio built-in test runner, your tests will run in parallel.
Enabling Parallel Testing in MSTest
Like most of the settings used by MSTest, the setting you need to tweak to enable parallel unit test execution is in the .testsettings file that you’re using. In a brand new test project, you should have a Local.testsettings file, like this one:

If you open this file and click through the various settings boxes, you won’t find anything there related to test parallization. Go ahead and look. Ok, satisfied now? Good, let’s move on.
Now, if you right-click on the file and open it with an XML Editor, you’ll find some more interesting settings.

Here’s the default XML file:
If you go click on the <Execution> element, and attempt to add an attribute to it, you should get some Intellisense/statement completion, showing you what the acceptable attributes are:

In this case, the option you want is parallelTestCount. If you simply set it to 0, the system will automatically choose a number of parallel tests equal to the number of cores detected on your system. In my case, I have a 4-core machine, so it will use 4 cores. Save the file.
Note: Typically at this point if you re-run your tests, they will continue to run one-at-a-time. The .testsettings files are cached and are not read immediately when you make changes to them. I’ve had success getting them to update by going to the Test View window and hitting the Refresh button there, but if that fails you could simply try closing Visual Studio and re-opening it and your project.
Run your tests again. Here’s a screenshot showing them running in the Visual Studio test runner. You can see there are 4 tests In Progress at the same time:

Of course, you can also set the value to a number that exceeds the number of (apparent) cores on your system. I’ve gotten it to work with as many as 16 on one machine, but on the one I’m working on now, it fails once it exceeds 5 cores. According to a friend of mine, there is a hotfix available that fixes this bug and allows VS2008/VS2010 to use this setting with a parallelTestCount > 5, and apparently this already works in some environments without this hotfix (such as my laptop). Likewise, I was able to run tests in parallel using ReSharper’s test runner on my laptop, but on this desktop machine running the latest 6.1 version of R# it is only running one test at a time.
Nonetheless, if you set the value to 5 and run my suite of 24 1s tests, the entire suite executes in about 5 seconds. That’s an 80% reduction in total test time, which is pretty amazing, and of course this number gets even bigger if you make it larger (assuming you have the hardware to support it).
Caveats
You need to be using MSTest. This doesn’t work with NUnit.
You may need to be using the Visual Studio built-in test runner. I had it working with the ReSharper test runner, but it’s not working now on this machine, so YMMV.
You may not be able to exceed <Execution parallelTestCount="5">. If you need to do so, contact Microsoft support for the hotfix. If it’s a publicly available link, please link to it in the comments below.
Your tests should be thread-safe and side effect free. This rules out most integration tests (what’s the difference between unit tests and integration tests?). You also need to be very careful about any use of global state. Here’s simple example of a test suite that passes when run sequentially but fails when run in parallel (click to open in new window):
Summary
Especially as CPUs continue to ship with greater and greater numbers of cores, rather than faster clock speeds, the ability to take advantage of the potential performance of these systems will depend on our ability to perform operations in parallel. One area in which MSTest currently has the lead on alternatives like NUnit is in parallel test execution, and I hope that the next version of Visual Studio improves upon this feature and makes it more discoverable and addresses some of the current issues it suffers from. I have confirmed that the XML attribute and test runner behavior in the Visual Studio 11 CTP distributed at the BUILD conference in September 2011 work just as they do today in VS2010.
You can view and download the sample code from its BitBucket Mercurial Repository here.
Unit Test or Integration Test and Why You Should Care
There remains a fair bit of confusion about what constitutes which kind of test. Many developers are fairly new to testing, and tend to call any tests of their code “unit tests” even when they’re dealing with something substantially larger than a unit. The tools don’t really help much here, since the various test runner frameworks all call themselves unit test frameworks, and the various test runners themselves almost universally refer to the tests they run as “unit tests” whether they are or not. For instance, Visual Studio 2010 starts every new Test Project with a class called UnitTest1 and lets you add a new Unit Test, but nowhere does it mention Integration Tests, Acceptance Tests, Smoke Tests, etc, as you use the same code templates to create each of these.
Visual Studio 2010

ReSharper and most other add-in test runners follow the same convention – if you ran run it as a test on your code, it’s probably going to be referred to as a Unit Test.
ReSharper 6.1

So what constitutes a unit test, and what constitutes an integration test? What about other kinds of tests beyond these two? There’s a decent StackOverflow answer related to this topic, which lists several kinds of tests and their definitions. Here is what it has to say about Unit Tests and Integration Tests, specifically:
-
Unit test: Specify and test one point of the contract of single method of a class. This should have a very narrow and well defined scope. Complex dependencies and interactions to the outside world are stubbed or mocked.
-
Integration test: Test the correct inter-operation of multiple subsystems. There is whole spectrum there, from testing integration between two classes, to testing integration with the production environment.
I have my own definition of a unit test, which is that it’s a test that only tests a single path through a single method. More importantly, it’s a test that has zero dependencies on infrastructure, or on code outside of your control. Unit tests should run fast – as in very, very fast – because they aren’t touching file systems, databases, networks, email servers, system clocks, etc. They run your code. Period. If you have code that has dependencies, you need to remove them when running your unit tests, typically by using mocks, fakes, or stubs. I’ve written before about dependencies, if you’re not sure what I mean:
If you have a test that depends on any of the dependencies listed in the above posts, then you have an integration test. Integration tests are great and necessary, but they’re generally at least an order of magnitude slower than unit tests, and as such you’re going to be able to run far fewer of them in a given amount of time. Therefore, you want to write as many unit tests as you can, and write integration tests for things unit tests can’t do (like actually testing your infrastructure and interactions between components). Basically, you want to follow the Test Pyramid, just like in the United States people are encouraged to eat based on the Food Pyramid (with one key difference being that the Test Pyramid is probably better advice and is less controversial).

Basically, you want a lot more servings of Unit Tests in your daily diet than Integration Tests, and remember that UI tests, being the most expensive and usually the most brittle, are a sometimes food.
How Can You Tell if a Test is a Unit Test or an Integration Test?
Here are some quick questions you can use to qualify your tests. There may be some exceptions to these rules, but these are generally good guidelines. It’s usually a good idea to separate your unit and integration tests, either as separate projects/assemblies, or at least using separate categories, so that you can run them separately. You’ll want to run the unit tests all the time, and they should be fast enough that doing so isn’t too painful. You’ll want to run the integration tests as often as you can bear to do so, but often these take long enough to run that you don’t want to run them with every compile or before every check-in.
Q: Does the System Under Test (SUT) require an installed and configured and available database in order to run the test successfully?
A: If yes, then it’s an Integration Test
Q: Does the SUT talk to the file system?
A: If yes, then it’s an Integration Test
Q: Does the SUT reference configuration files directly?
A: See previous question. It’s an Integration Test.
Q: Does the SUT reference a service over the network?
A: If yes, then it’s an Integration Test
Q: Does the test take more than 10ms to execute?
A: If yes, it’s very likely an Integration Test, or at the very least it may be possible to refactor it to run faster.
Q: Does the SUT send emails as part of the test execution, even via a local SMTP server like smtp4dev?
A: If yes, then it’s an Integration Test.
Q: Does the SUT depend on the system clock? Are there certain days of the week or times of day when it would behave differently?
A: If yes, then it’s an Integration Test.
Q: Does the test make use of a mocking framework?
A: If yes, then it’s likely a Unit Test. Generally you shouldn’t need to mock much in your integration tests, or you risk not actually testing your system.
References
MSDN describes Unit Testing and Integration Testing if you’d like an “official” Microsoft source
“What is Unit Test, Integration Test, Smoke test, Regression Test?”
Last week I presented two half-day workshops at CodeMash’s PreCompiler on Wednesday (with Brendan Enrick), and a session on ASP.NET MVC 4 on Thursday. CodeMash 2012 was an amazing conference and I’d like to personally thank the organizers as well as the attendees of my own events for making it such a great event. I’ll post a separate write-up with my experiences shortly – for now I just need to get my slides and demos posted for folks who want them.
Beginning Software Craftsmanship
The morning PreCompiler was on Beginning Software Craftsmanship, and included some presentations on software craftsmanship, deliberate practice, testing, and pairing. We had about 25 people in attendance, which was just about perfect for the room we had. Unfortunately, we had a tiny little 6’ screen to present on, but we made it work and thankfully most of this workshop involves hands-on coding, not watching slides. The group worked through the Prime Factors kata several times, and then the String Calculator kata. You can download the Beginning Software Craftsmanship slides, katas, and the FizzBuzz demo that Brendan and I worked through here.
Intermediate Software Craftsmanship
In the afternoon PreCompiler, we continued delving into software craftsmanship and practice, with an emphasis on writing quality code. There was a quick repeat presentation on why software craftsmanship and practice are important, which was good since the afternoon session was standing room only with over 50 people in it at one point, so there were many new faces in addition to folks from the morning session. Brendan and I presented one lecture on refactoring and SOLID principles to set up the next kata, the Gilded Rose refactoring kata. This kata starts with some existing working code, which we provided in several different languages from online sources:
- http://github.com/professor/GildedRose Ruby
- http://github.com/NotMyself/GildedRose C#
- http://github.com/wouterla/GildedRose Java
The intent of this kata is to practice your refactoring skills, and also to practice working with legacy code that has no test coverage and is in fact very difficult to get under test. Working in pairs, the teams sought to implement the new feature requested in the kata while following the constraints and attempting to improve the overall design of the code (by, for instance, making it more DRY and applying the SOLID principles).
Following the Gilded Rose kata, we worked through the Greed kata, which implements the rules of a simple dice game. Included in the download below are several implementations of this kata in C#, including one that uses a rules engine that allows new rules to be added while following the Open/Closed Principle (no changes need to be made to the scoring logic classes).
Download the Intermediate Software Craftsmanship slides, katas, and demos here.
A Lap Around ASP.NET MVC 4
On Thursday I gave a morning session on ASP.NET MVC 4. Unfortunately, I wasn’t able to talk about some of the new features that were under development due to NDA restrictions. However, that kind of changed about 30 minutes before my talk when Scott Hanselman announced several of the previously private features that were coming to MVC 4, namely integration of Web API directly into MVC and a few new project templates, including a single-page application template. Look for more info on these topics on Scott’s blog and/or from the Gu himself, soon.
My session focused on the new mobile features, recipes, and async features of MVC 4. You can find my Lap Around ASP.NET MVC 4 slides and demos here.
Hope you enjoyed CodeMash and I look forward to seeing you again soon. Feel free to follow me on twitter (@ardalis) to join the conversation!
“The reports of my death have been greatly exaggerated.” – Mark Twain
Today, Silverlight 5 is released and available for download! The Release Candidate has been around for some time, and many of us were expecting the release in November. Well, here it is, November 39th, and it’s here! Here are some of the things that are New or Improved in Silverlight 5:
- Binding Improvements, including ICustomTypeProvider, Binding in Style Setters, DataContextChanged Event, and Custom Markup Extensions
- Support for the XNA 3D API for 3D graphics
- 3D Render Targets
- 3D surface composition settings
- 3D multi-sample anti-aliasing
- Other improvements to the Graphics Stack
- Hardware decoding for H.264 media
- Low-latency sound effects (good for games)
- Variable Speed Playback and Trick-play (great if you want to listen to podcasts at high speed)
- Text Improvements
- Text Tracking and Leading
- Linked and Multi-column Text
- OpenType Support
- Better OS integration
- P/Invoke support
- Multiple Window support
- Full file system access (in full trust)
- Default Filename support in Open/Save FileDialogs
- 64-bit browser support in Windows
- Power awareness (don’t sleep while movie is playing, for instance)
- Performance Improvements
- Faster Parser
- Multi-Core JIT compilation (improved start-up time)
- Double-Click (and n-click) support
- PivotViewer control
- ComboBox type-ahead search
- Printing improvements
- Tasks from Task Parallel Library
Pete Brown has a great write-up of these and more features. There is another, official list of What’s New in Silverlight 5 available on the Silverlight.net site. You can learn more at http://silverlight.net/learn, or from Pete’s book, Silverlight 5 in Action.
There’s a great site for finding extension methods, ExtensionMethod.net. I don’t believe either of these came from there, and I’ve not (yet) submitted them there, but here are a couple of extensions on IEnumerable<T> that I’ve found useful recently.
ForEach<T>
The first one is simply a method that allows you to easily iterate over a sequence and perform an action on it. This is a pretty commonly useful extension method, so much so that it’s now included in .NET 4.0 out of the box. But if you’re using an older version of the framework, this is one you can roll yourself.
public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (T item in items)
{
action(item);
}
}
ContainsAny<T>
If you have a collection, you can test for whether it contains an item by using the .Contains(T item) extension method. However, this only works for single instances of an item. What if you have a set of items and you need to know if that set contains any elements of a second set of items? For that, you want to use ContainsAny(), which you can use with either a params collection (specify each item inline) or with an enumerable parameter. Here are the methods:
public static bool ContainsAny<T>(this IEnumerable<T> sequence, params T[] matches)
{
return matches.Any(value => sequence.Contains(value));
}
public static bool ContainsAny<T>(this IEnumerable<T> sequence, IEnumerable<T> matches)
{
return matches.Any(value => sequence.Contains(value));
}
And here are some passing unit tests that demonstrate how these are used:
[TestFixture]
public class ContainsAnyShould
{
[Test]
public void ReturnTrueGivenMatchInItemCollection()
{
var testList = new List<string>() { "A", "B", "C" };
var filterList = new List<string>() { "C", "D", "E" };
Assert.IsTrue(testList.ContainsAny(filterList));
}
[Test]
public void ReturnFalseGivenNoMatchInItemCollection()
{
var testList = new List<string>() { "A", "B", "C" };
var filterList = new List<string>() { "D", "E" };
Assert.IsFalse(testList.ContainsAny(filterList));
}
[Test]
public void ReturnTrueGivenMatchInParamCollection()
{
var testList = new List<string>() { "A", "B", "C" };
Assert.IsTrue(testList.ContainsAny("C", "D", "E"));
}
[Test]
public void ReturnFalseGivenNoMatchInParamCollection()
{
var testList = new List<string>() { "A", "B", "C" };
Assert.IsFalse(testList.ContainsAny("D", "E"));
}
View HTML Source of Email in GMail and Google Apps
If you’re working on creating a pleasant-looking HTML email template for your site’s newsletter, you’ll want to test it out on the major email clients, including Outlook and GMail. For instance, if you get The Code Project’s Insider Daily News in your GMail inbox, it will look something like this:
Now, if you view the source for this page, you’ll get something that’s less than useful. The whole thing looks like a giant <script> block and has no relation to the HTML that was in your email template. Of course, the interface uses frames (iframes), and depending on your browser you can also view the frame source:

Which will yield this:

How useful!
If you *actually* want to see the HTML markup for an email as it was received by the mail server, the way to do that in GMail or Google Apps is to click the triangle icon in the upper right of the message, and select Show Original:

This will open up a new browser window or tab, with the full email content, including the headers. Something like this, perhaps:

All that and *still* no HTML! But we’re almost there. If you look at the last line of the headers in the image above, you can see that in this case the message says it has Content-Transfer-Encoding: base64. That means that long mess of characters in the body of the message is base64-encoded, which further means that we can easily decode it using any base64 decoder. You can write your own, but there are numerous online tools that will decode base64 for you, including this one I found after a quick search. Simply cut and paste everything below (but not including) the Content-Transfer-Encoding: base64 line into the box on the page and click the button and you should see your decoded, beautiful, actual HTML of your email message. What could be easier than that?

Now just copy the output to Notepad or your HTML editor of choice and you should be ready to make whatever tweaks you and your design team would like.
Inner Fields and Lazy Initialization in C#
Using lazy initialization in C#, a class’s state is set up such that each property’s get method performs a check to see if the underlying field is null. If it is, then it calculates or populates the field before returning it. This is a very simple and common approach, but it requires that the class follows a convention of only accessing the field via the property. Unfortunately, there are no language features that can enforce this, so it’s possible for errors to creep in. Here’s an example of this approach working correctly:
public class Order
{
// other properties
private Customer _customer;
public Customer Customer
{
get
{
if (_customer == null)
{
_customer = new Customer();
}
return _customer;
}
}
public string PrintLabel()
{
return Customer.CompanyName + "\n" + Customer.Address;
}
}
Now here’s where this approach can break down. Consider the same class as above, but with a rewritten PrintLabel() method:
public string PrintLabel()
{
return _customer.CompanyName + "\n" + _customer.Address;
}
This code will still compile just fine, but now will very likely result in a NullReferenceException when it attempts to access properties of the _customer, which may not yet be initialized. The solution to this would be to control access to the _customer member. We’ve already set its access to private, though, which is as restrictive as we can make it. We could force it to be initialized by moving the work into the class’s constructor, but then we’re losing the benefits of lazy initialization. I wonder if it wouldn’t be useful to do something like this instead:
public class Order
{
// other properties
private Customer _customer;
public Customer Customer
{
get
{
if (_customer == null)
{
_customer = new Customer();
}
return _customer;
}
}
public string PrintLabel()
{
string result = _customer.CompanyName; // probably results in a NullReferenceException
return result + "\n" + Customer.Address; // ok to access Customer
}
}
One approach that can be used with the relatively new Lazy<T> type is this one (thanks to Jose Romanie for pointing this out):
public class Order
{
public Order()
{
_customerInitializer = new Lazy<Customer>(() => new Customer());
}
// other properties
private Lazy<Customer> _customerInitializer;
public Customer Customer
{
get
{
return _customerInitializer.Value;
}
}
public string PrintLabel()
{
string result = Customer.CompanyName; // ok to access Customer
return result + "\n" + _customerInitializer.Value.Address; // ok to access via .Value
}
}
I like this approach, and I’m generally a fan of Lazy<T>. It might eliminate the need for the private backing field idea for properties, as it does provide a means of enforcing the initialization even if the backing field is accessed from within the class. The only downside is that you need to work with a Lazy<T> instead of a T, but within the class it’s probably not a bad thing for this detail to be exposed. Thoughts?
RazorEngine Performance and Template Caching
I’ve been using RazorEngine on a project and have been impressed with its simplicity and ease-of-use. However, the performance of the application isn’t quite where I need it to be, and I was pretty sure the issue was with how I was using RazorEngine, especially since I could anecdotally see that the processor consumption on the machine running the app was quite high, and looking at the running tasks it was clear that most of that was a result of csc.exe (C# compiler) activity.
A bit of searching found this discussion thread on codeplex regarding the re-compiling of existing templates. The issue is a known one with version 2.1, which is the current release and what I’m using. However, I talked to Matthew Abbott (aka Antaris) via his blog where he recently discussed what’s coming in RazorEngine v3, and that led me to go ahead and pull the latest pre-release RazorEngine v3 code out of GitHub.
From there it was pretty trivial to get my code working with the new bits. Fortunately I’d created an interface ITemplateParser and implemented a RazorEngineTemplateParser, and this latter class was the only one I needed to change to use the new API. I created a couple of nearly identical unit tests, with the key difference being when they make the call to parse the template. The caching version provides the same name for the template with each call, while the non-caching one provides a new Guid string as the template name, ensuring a cache miss.
I don’t have any fancy graphs to show off, since all I did was run a 2-minute load test of each unit test with 5 users and no think time using Visual Studio 2010’s load test runner. The results were pretty significant, though, and corresponded with the performance I was seeing in my actual application (about 1 request per second on one thread):
5 Concurrent Users, Non-Cached
5 Tests/Second
5 Concurrent Users, Cached
1600 Tests/Second
Install Application as Service on Windows Server 2008
You can use the sc.exe command to install an EXE as a service on Windows Server 2008. There’s a good article on creating an application that can easily run as either a console app or as a service here. From an administrator command prompt, the syntax is something like this:
sc \\servername create MyService.ServiceName binpath= d:\services\Foo\Foo.exe displayname= MyService.ServiceName
Note that for this particular utility, the command line options include the “=” sign in them, so you must have no space before the “=” and you must have a space after the “=”. Also the server name must be preceded by \\ to work.
Assuming it works, you should see something like this:
As you can see from the help message above, the SC.EXE utility can be used for much more than simply creating services, but this is something I’ve had to use it for more than once (and hence I’m blogging it since it’s not necessarily easy to search for).


“The reports of my death have been greatly exaggerated.” – Mark Twain