This blog as moved to: http://nerditorium.danielauger.com/

This Blog Has Moved

I've revamped this blog at a new location. Please visit it at:
http://nerditorium.danielauger.com

I will eventually move posts from this blog over to the new one, and hopefully figure out some sort of way to do redirects for the more popular posts.

Your ASP.NET.* Project is Not Just Your UI Layer



In this post by Jimmy Bogard about “dealing with non-transactional operations that must happen if some transaction succeeds,” the often embraced, but sometimes criticized, Session Per Request pattern (aka Transaction Per Request), came under fire in the comments.
image
I’ve had this conversation with other developers who have raised similar concerns before, and the reason brought up against going with this pattern is based off of the notion that the “Web” project must not orchestrate or indirectly know about the other layers of the application because it is the “UI” layer.
The fact is, that the web project houses two conceptual layers:
  1. It houses the UI layer for the application.
  2. It houses the entry point / bootstrapping for the infrastructure of the application. It is the application.
I am perfectly fine with the plumbing of the web project directly managing transactions. Some part of the application must manage this, and I a believe that the it should be pushed as far out to the seams of the application platform as possible.

All Paths to a Sitefinity Image are not Equal



Recently, while doing a performance pass through a Sitefinity 4 application, I noticed that a public facing page had an unusually slow load time. Of course, the first thing I did was open up Firebug to see where the time was being spent. To my surprise, the majority of the time was spent waiting for the initial response from the server. After a little digging, I narrowed down the time-sink to a custom widget that pulled images from a Sitefinity image album. In particular, the query to figure out which images to display was the source of slothness.

A few things to note:

  • There were about 250 image albums in the CMS (all but 5 or so of them were empty at the time of discovery, however).
  • There were roughly 30 images in the album we were querying against.
  • When the original query was written, there were only a few images in the system, and that is why the issue wasn’t apparent right when the query was written.

Here’s an approximation of the original call to retrieve the images through the Sitefinity API:

In this bit of code, we are querying for all images that belong to the image album named “Foo”. Note that the query is structured in a way where we query through the image object to determine what album it belongs to.

The above query took about 2 seconds to return roughly 30 Sitefinity Image objects. This would not do. Therefore, I took to tweaking the query. I tried several different things while maintaining the original approach, but since Sitefinity’s LINQ provider isn’t a complete implementation, I couldn’t make much headway.

I eventually decided to rethink the approach and query for the images by going in through the album instead of going through the image object.

This reduced the query time down to about .2 seconds.

Matt Chat–The YouTube Channel You Should be Watching if You Played Video Games in the 80s or 90s



mattChat

Nerd service announcement:

If you played video games in the 80s and/or 90s and have never heard of, or watched Matt Chat, you you are in for a treat. One of my friends aptly described it as, “Behind the Music for vintage video games.”

Matt Barton (College Professor and Author) debuted Matt Chat in February 2009 with a low-production-quality, but loving, retrospective of SSI’s classic AD&D CRPG, “Pool of Radiance.” Since then, Matt has produced an additional 100 episodes, and has made leaps-and-bounds in production value. In addition to his editorial retrospectives, Matt began doing interviews with game developers around episode 40.

To whet your appetite, here is a listing of the first 101 episodes of Matt Chat :

1: Pool of Radiance
2: Myst
3: Defender of the Crown
4: M.U.L.E.
5: Elite
7: The Sims
8: The Secret of Monkey Island
9: The Oregon Trail
10: Lemmings
11: Civilization
12: Metroid
13: Adventure
14: The Lost Vikings
15: The PLATO Computer System
16: Lode Runner
17: Ultima VII, The Black Gate
18: Summer Games
19: Gauntlet
20: Worms and Artillery Games
21: Super Mario Kart
22: Deja Vu, Uninvited, Shadowgate, and MacVentures
23: Planescape Torment
24: Star Control II and the Spacewar Legacy
25: Knights of the Old Republic
26: David Crane's Ghostbusters
27: Autoduel
28: Maniac Mansion
29: Wizardry
30: Fallout
31: A Rockstar Ate My Hamster
32: Tomb Raider
33: Jade Empire
34: System Shock 2
35: Alone in the Dark
36: Starcraft
37: Syndicate
38: Legacy of the Ancients
39: World of Warcraft Part One
39: World of Warcraft Part Two
40: Sword of Fargoal with Jeff McCord
41: The History of Cinemaware with Bob Jacob
42: Dragon Age Origins
43: Archon
44: Ralph Baer, the Father of Videogames
45: Rogue
46: Choose Your Own Adventure with R.A. Montgomery
47: Quest for Glory
48: Dungeons of Daggorath
49: Nancy Drew featuring Jessica Chiang
50 Part 1: Leisure Suit Larry featuring Al Lowe
50 Part 2: Leisure Suit Larry featuring Al Lowe
51: Interview with John Romero (Early Days)
52: Wolfenstein 3D with John Romero
53: Doom with John Romero
54: Quake with John Romero
55: Daikatana with John Romero
56: Ocarina of Time
57: Tunnels of Doom
58: Heroes of Might and Magic
59: The Settlers
60: X-COM, UFO Defense
61: Sid Meier's Pirates
62: Chris Avellone's Early Days
63: Planescape Torment with Chris Avellone
64: Sean Cooper's Early Days
65: Syndicate with Sean Cooper
66: Fallout with Tim Cain, Pt. 1
67: Fallout with Tim Cain Pt. 2
68: Arcanum and More with Tim Cain
69: Howard Scott Warshaw's Early Days
70: ET and Yar's Revenge with Howard Scott Warshaw
71: The Bard's Tale
72: Deus Ex
73: The Dig
74: Dune II
75: Interview with Megan Gaiser and Rob Riedl of Her Interactive
76: King's Quest
77: Darklands
78: Arnold Hendrick Interview Pt. 1
78: Interview with Arnold Hendrick Pt. 2
78: Interview with Arnold Hendrick Pt. 3
79: Scott Adams' Early Days
80: Adventureland with Scott Adams
81: Questprobe and More with Scott Adams
82: Interview with Rebecca "Burger" Heineman Pt. 1
83: Rebecca Heineman Pt. 2
84: Rebecca Heineman Pt. 3
85: Rebecca Heineman Pt. 4
86: Bard's Tale IV and Wasteland II with Rebecca Heineman
87: Twilight Scene it with Don Kurtz (censored)
88: The Donimator Gets His
89: Bard's Tale and Wizardry with Brian Fargo
90: Wasteland and Fallout with Brian Fargo
91: The Fall of Interplay with Brian Fargo
92: Mail Order Monsters
93: Scratches and Asylum with Agustín Cordes
94: Interview with Agustín Cordes Pt. 2
95: Skylanders and more with Paul Reiche and Fred Ford
96: Star Control and More with Paul Reiche and Fred Ford
97: The Horde and More with Fred Ford and Paul Reiche
98: Scott Miller Interview Pt. 1
99: Duke Nukem with Scott Miller
100: Scott Miller will Live Forever
101: Baldur's Gate

My Sister Always Said I’d Turn Out to be a Nerd

smokingNerdToday was a good day. As mentioned previously, I’ve been looking for a new career opportunity for the past month-and-a-half or so. My journey came to a head yesterday when I received two fantastic job offers. I’m happy to report that I have accepted an offer to join 
the Nerdery as a Software Engineer. I’m looking forward to working with this group of people who are way smarter than I am, and for the chance to grow with this unique company.

Additionally, I’ve been reflecting on the overall job search experience. I am very aware of how lucky I am to have rubbed shoulders with many insanely smart and experienced professionals. I really appreciate the time everyone took to meet with me. Life is good.

Full Stack Interview Coding Challenges

Challenge AcceptedIt’s been seven years since I was last looking for a job, so I’m not sure if this is a new trend or not: Over half the companies I’ve started the interview process with have given me time-unlimited full-stack coding challenges as part of the interview process. I just completed my third one in two weeks and I thought I’d share my thoughts about this practice in general.

Challenge Requirements
Here are highly condensed versions of the requirements for each challenge:

Company A:

  1. Create an ASP.NET MVC application that consists of one page that allows users to add, remove, and rate movies. Movie ratings are to be indicated with a star rating control similar to what Netflix uses.
  2. Create a Javascript widget that a user can host on their blog which pulls and displays their movie ratings from the application.

Company B:

Create an ASP.NET MVC website that allows users to upload and view images. If the image is more than 500 pixels wide, or 700 pixels tall, downsize the image to the maximum allowed size, but maintain the aspect ratio. All images should be stored on the server, including the original image when images are resized.

Company C:

Create an ASP.NET application (Webforms or MVC) that allows users to add and vote on Xbox game titles for the company break room. Users can only vote once a day, and they cannot vote on the weekends. Any user can mark a game as owned, in which case it ends up on a list of owned games. The titles and votes will be stored / retrieved via a set of WCF services that are provided for you. In addition to sending the code in for review, submit a URL to a running copy of the application.

What I Liked About the Process

First off, I really liked that these companies wanted to see code. I think far too many places hire developers without seeing a line of code. True, you can determine what somebody is capable of through conversation (especially at senior / expert levels), but I think it’s a pretty big risk. Some people are really good at talking, and / or look good on paper when in truth they don’t know what they are doing.

Secondly, I really enjoyed doing these challenges. They’ve helped me from getting rusty during this period of unemployment. Additionally, I had to learn at least one thing for each of the applications. For company A’s challenge, I had to learn how to create a widget that used JSONP. For company B’s challenge I had to learn to resize an image while keeping its aspect ratio using only the core .NET framework. For company C’s challenge, I learned how to use the MVCContrib Grid and the jquery.dataTable plugin. I also learned and used AppHarbor to host the application.

What I didn’t Like or was Uncomfortable With During the Process

Finding time to do all three of these within a couple of weeks was a little rough. I did find the time, but part of me was wondering if the companies were wondering why I hadn’t turned the challenge in yet. In reality they didn’t know that I was working on three of them simultaneously. This is something I probably should have communicated to them.

The thing I was most uncomfortable with was that I felt like I had more than enough rope to hang myself with in terms of doing things that weren’t wrong per say, but that the reviewer might frown upon due to personal taste. One thing that I was really torn on was how C# 2/3/4 idiomatic I should make my code. Taking advantage of generics, lambdas, linq, anonymous types, etc… could cause the code to look like gibberish to the reviewer if he or she is still writing code in C#1 style. On the flip side, I felt that I would look like I was stuck in the past if I didn’t write modern C#. I’m not sure that finding the middle ground is the right thing to do in this case either as it could look inconsistent.

Along the same lines, I found it very difficult to decide on the right level of architectural complexity to use. These apps were all a bit more than trivial, so I could have gone either way with the complexity. As with idiomatic C#, I found myself wondering if the reviewer was going to think I was oversimplifying or overcomplicating things. Additionally the reviewer may actually want me to overcomplicated things a bit to show what architectural patterns I know. 

These two issues are things that usually get sorted out when you hash over ideas with people in person, but I found it difficult to know who my audience was when given nothing but a set of requirements.

Final thoughts

All-in-all, I thought it was a positive and enjoyable experience. If I’m ever in the position to help with hiring again, I would probably really push hard for code samples to be part of the process. However, I probably wouldn’t give such open ended challenges. I’d probably give multiple smaller and more focused problems.

.NET Dependency Management in a Pre-Nuget World


This post is an attempt to capture how my previous team dealt with dependency / package management. The team, at its largest point, consisted of about 15 developers. There were roughly 200 3rd party dlls, and roughly 150 internal dlls in the dependency mix. No single app needed all 350 dlls, but groups of these dlls were common to applications in the same domain space of the enterprise. 3rd party dlls were things such as the MS Enterprise Library, image conversion libraries, desktop scanner interop libraries, etc… Internal dlls were things such as common utility libraries, WCF service contracts, DTOs etc…

Until the recent development of projects such as Nuget and OpenWrap, dependency management in .NET has been a big problem. The larger a development group’s topology is, the more of a pain point it is. Because this is the case, a lot of teams don’t even realize they are going to have issues until the pain is upon them. Additionally, I think the complexity of describing the problem has helped to keep package management as an elephant in the .NET room for a long time.

Since there has been abundant discussion on this issue lately, I’m going to skip describing the problems with dependency management and get straight into what we tried over the years, and what the final solution ended up being. It’s important to note that my team used TFS (2008) for source control because some of the steps we took were in response to TFS’ weaknesses.

First attempt ending in Failure:

  • Manage all 3rd party dlls by putting them in a [sln]/bin folder (tracked by TFS).
  • Manage all internal dependencies as shared projects across multiple slns.
I’m sure some of you are already cringing after reading the last bullet point, but you’ll have to admit it is the first solution that comes to mind to a lot of developers. Additionally, it is a very simple solution. The biggest issue with this solution is with sharing a project over several slns. Unfortunately, any bit of code in those shared projects is easily changeable from multiple slns; therefore it is very easy to break several slns in one fell swoop. Secondly configuration management goes out the window because every time a sln is compiled, each shared project gets a new version that bypasses any sort of change management.

Second attempt ending in failure:

  • Manage all 3rd party and internal dlls by putting them in a [sln]/bin folder.
This solution complicates things slightly (in a positive way) by requiring each sln to use a proper release of all internal dlls; therefore you are able to have some degree of configuration management. However, this solution failed for us because of one simple fact: TFS does not track binaries well. We never ran into this weakness with the first solution because all of the 3rd party dlls were set-and-forget. They never changed after setting the initial reference. The internal dlls however, would change daily, or even hourly. At first this seemed like the perfect solution, however all sorts of strange errors started occurring. One person would get latest and everything would work, but another person would get latest and have errors. TFS simply could not tell if you needed a new version of the dlls in the /bin folder. Sadly, even a “clean all" and "get specific version" didn't fix things a lot of the time.

Third attempt ending in Success:

  • Build a custom package management system.
Our custom package management system worked thusly: We created a network share. For each logical release (i.g. MS EntLib, Internal.Common.Util) we created both a [networkShare]\[package]\LatestRelease folder and a [networkShare]\[package]\Release_[version number] folder. We then created a console EXE with a bunch of options that would: 1) go and grab all of the latest dlls for all projects and dump them into one pre-defined “latest” folder on the developer PC and 2) Recreate the “releases” tree structure on the developer PC. This way, developers have the ability to drink from the fire-hose (the latest folder) or go for set releases (from the releases folder tree). TFS is not tracking dlls at all. Rather, we are relying on an absolute path file reference. Additionally, calling this executable becomes a build task on the CI server.

This solution isn't perfect. Namely, it relies on developers to remember to run the executable from time to time. Additionally, there are potentially some versioning scenarios that could occur between packages that expect a different versions of sub dependencies. However that issue never manifested itself in our environment.

Nuget is not the final answer for teams using TFS
I've been following the Nuget dev list closely, and Nuget is considered to be a development time dependency resolver only, not a build time resolver. This means that if you use TFS to track your Nuget package folders, you could still run into dll versioning issues.

Update (4/17/2011)
Nuget team member David Ebbo has blogged that functionality has been added to allow use of Nuget without committing the packages folder to source control.http://blog.davidebbo.com/2011/03/using-nuget-without-committing-packages.html

Update (4/30/2011)
According to Phil Haack, Nuget is going to be getting official support for non-committed packages: http://haacked.com/archive/2011/04/27/feedback-request-for-using-nuget-without-committing-packages.aspx



I know that many of us have had to face this problem, therefore I'd really enjoy hearing about how you addressed this issue.


Moving On

Yesterday was a tough day. I resigned from my position of seven years as a Developer / Analyst for the Office of the Minnesota Secretary of State.

Over the past couple of months, the development group has gone through several reorganizations. Yesterday another reorganization happened, including a substantial software platform shift. I did not feel this shift was good for my career, nor was it something I wanted to participate in. Additionally, I think the days of in-house software development for government agencies are coming to an end at light speed. Therefore, with heavy heart, I felt it was time for me to go. Up until recently, it was the most enjoyable job of my career. I wish my former coworkers the best of luck, and I look forward to hearing their war stories as time goes on.

The Case of Web Deploy 2.0 and the Missing MSDeploy.exe


This week, I decided to install the newly released Web Deploy 2.0 on my machine at work. I already had Web Deploy 1 on my machine, so I decided to uninstall that first before installing 2.0. After the installation I begain getting the following error when trying to execute VS2010 created web deployment packages from the command line:

Error:  The system was unable to find the specified registry key or value
msdeploy.exe is not found on this machine. Please install Web Deploy before exe
cute the script.
Please visit http://go.microsoft.com/?linkid=9278654
=========================================================
=========================================================

Of course the first thing I did was validate that MSDeploy was indeed installed with Web Deploy 2.0. It was. I then tried adding MSDeploy's location to the path environment variable. No dice. I then tried reinstalling Web Deploy 2.0. Still no luck. After trying some other things I cracked open the deployment package's cmd file and found this:
@rem ---------------------------------------------------------------------------------
@rem if user does not set MsDeployPath environment variable, we will try to retrieve it from registry.
@rem ---------------------------------------------------------------------------------
if "%MSDeployPath%" == "" (
for /F "usebackq tokens=2*" %%i  in (`reg query "HKLM\SOFTWARE\Microsoft\IISExtensions\MSDeploy\1" /v InstallPath`) do (
if "%%~dpj" == "%%j" ( 
set MSDeployPath=%%j
))

For whatever reason, Web Deploy 2.0 did not add either of these items during install. I ended up adding the MSDeployPath environment variable, and all was good.

Programming is a Craft


Here are my initial thoughts after reading: Programming is not a Craft

“craft -noun 1. an art, trade, or occupation requiring special skill, esp. manual skill: the craft of a mason." (dictionary.com)

“In English, to describe something as a craft is to describe it as lying somewhere between an art (which relies on talent) and a science (which relies on knowledge). In this sense, the English word craft is roughly equivalent to the ancient Greek term techne." (wikipedia.com)

In my opinion, on a whole, software development is a combination of craft and primitive engineering (which is slowly emerging as a true engineering discipline). The term craft usually means how something was made, not what was made or the perceived value of the end result by the layman. One of the commenters on the original post mentioned carpentry as a craft that may not always be defined by the value placed on the end product by the layman. In this vein, I will also mention that witchcraft is considered a craft.

One of the hallmarks of craft is that that it is filled with heuristics and folklore. Much of the work of today's software developer is squarely within this realm. More often than not, there is no clear-cut way to solve a problem. We craft a solution based off of our experiences and the folklore we encounter. It is worth noting that I consider blogs, google searches, MSDN, visits at a coworker's desk, irc, and stackoverflow.com to be sources of folklore.

I must say that I do agree with much of the post, but I think the terminology that is presented is incorrect. I think it would have been wiser to say that software development is most often not an art, and ego has no place in it.

I also have to concede that in hindsight, I believe that the software craftsmanship manifesto was a bad idea. I recently learned there was a period of time when it was being debated if there should be clause in it to forbid using anything (tools, languages, etc...) that was not OSS. In my opinion the manifesto only serves to force a definition on something that needs no additional definition.

The Mythology of Commodore Told in about 15 Minutes by Jim Butterfield

jimbutterfield-centrefold

 

 

 

 

 

 

 

I was cleaning up the data drive on my computer tonight and I came across this gem, which is also hosted on blip.tv:





Many of us owe our career to Butterfield, and the father of the 65XX - Chuck Peddle.
If you are interested in the history of Commodore, please check out Brian Bagnall’s: Commodore: A Company on the Edge.

 

Getting RVM to Work when GVim is Launched from Ubuntu's Menu


If you want to use GVim as your Ruby editor in Ubuntu (and most likely any other Gnome based distro), you've probably found out that your .bashrc file is not read when launching GVim from the Gnome menu. This means that your RVM paths are not available in the scope of apps launched from the menu. However, when launching apps from the menu, the launcher can access your .profile file. That being the case, here is a quick work-around for this issue:

1) Add the following code to your ~/.profile file:
# This loads RVM into the session scope of the launcher.
[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"
2) Create a script that you can use to start up GVim. Example ~/Apps/GVim/gvimstart.sh. In this script, place the following:
#!/bin/bash
source ~/.profile 
gvim
3)Right click on the applications menu and choose "Edit Menus". Then find your GVim launcher and point the command entry to your script.

I am, by no means, a Gnome expert, so please let me know if you are aware of a better solution.

Happy coding!

Learn WPF for Free


In my last WPF related post I spoke a bit about my WPF learning experience. I was fortunate enough to have an MSDN Universal subscription and any book I wanted via my employer as I went down the path. Unexpectedly, I recently received an email from a reader who wanted to learn WPF on a budget of $0.00. After thinking for a bit, I came to the conclusion that WPF can be learned without spending any money (assuming you have a computer that can run the tools). Below is a roadmap on how to do so.

Get the tools for free

Visual Studio Express, which is able to create WPF apps can be found here:
http://www.microsoft.com/express/Windows/

If you need any other tools, such as SQL Server Express, you can most likely find them via the Web Platform Installer here: http://www.microsoft.com/web/downloads/platform.aspx

Learn the Framework

Between MSDN and the community, there is more than enough well-written documentation out there to help one become an expert on the WPF framework itself. In his book, “Advanced MVVM”, WPF expert, Josh “The Maestro” Smith, recommends the following documents to come up to speed with the WPF framework:

Introduction to WPF: http://msdn.microsoft.com/en-us/library/aa970268.aspx
WPF Architecture: http://msdn.microsoft.com/en-us/library/ms750441.aspx
A Guided Tour of WPF: http://joshsmithonwpf.wordpress.com/a-guided-tour-of-wpf/
Customize Data Display with Data Binding and WPF: http://msdn.microsoft.com/en-us/magazine/cc700358.aspx
ItemsControl: ‘I’ is for the Item Container: http://drwpf.com/blog/2008/03/25/itemscontrol-i-is-for-item-container/

A lot of the information in the above links is difficult to absorb, but I think it is very worthwhile to go through the material, and work through the examples, at least once. If some of the documents are unclear, you can always go back to them as you learn more and need more clarification.

Learn MVVM

Many people blow off MVVM as “the latest popular design pattern”, but learning MVVM is essential to working with WPF. This is because MVVM is a natural pattern to use considering the way databinding works with WPF. Yes, you can write WPF apps using tried-and-true code-behind and click event handlers like people did with winforms, but you’ll be doing yourself a disservice.

When learning MVVM, the first place to look is this very simple video by the Jason “The Enigma” Dolinger, where he explains what MVVM is, and what the pattern’s strengths are: http://blog.lab49.com/archives/2650

The next place I would look is the “MVVM In the box” training by Karl “The Educator” Schifflett:
http://karlshifflett.wordpress.com/2010/11/07/in-the-box-ndash-mvvm-training/

As a lesson summary, an in-depth overview of MVVM written by Josh Smith can be found here: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Apply what you’ve learned

While there is no WPF “best practices” sample that I am aware of, I think the following can get one to see how WPF fits into an application architecture.

Building a Desktop TO-DO application with NHibernate: http://msdn.microsoft.com/en-us/magazine/ee819139.aspx
Understanding the MVVM Pattern: http://live.visitmix.com/MIX10/Sessions/EX14
Build Your Own MVVM Framework: http://live.visitmix.com/MIX10/Sessions/EX15

Not strictly MVVM, but worth looking at as application and framework samples:

PRISM: http://compositewpf.codeplex.com/
Caliburn Micro: http://caliburnmicro.codeplex.com/
Caliburn Micro Soup To Nuts Series: http://caliburnmicro.codeplex.com/documentation
MVVM Light: http://mvvmlight.codeplex.com/

Keep Learning

Read Blogs! Search out WPF related blogs. There are enough out there to fill your news reader every day. Pete “6510” Brown  puts out a Windows Client roundup frequently which is a good starting point.

Read and participate in the knowledge dump at http://stackoverflow.com/questions/tagged/wpf.
At first you may find that some of the questions are the same things you are wondering about. After awhile, you will find that you can answer some of the questions. As you answer questions, you’ll reinforce what you’ve learned.

Share

Software development is still largely a folklore based discipline. It is your duty to share what you have learned in the best way you know how.

Katamari Code


We’ve all worked on projects where the codebase is a mess. Here are a couple of common messy codebase analogies I’ve heard over the years:

The House of Cards Codebase:

The Jenga Codebase:

Although I can appreciate the above analogies, more often than not, I think Beautiful Katamari is the most appropriate analogy.

Time Until Productivity In WPF


kingkongtorso One of the things I see over-and-over-again when reading about teams that are deciding if they should adopt WPF or not is the fear of the learning curve, and the worry that they will not be productive for a huge period of time. Given that I’ve recently become productive in WPF myself, I thought I would talk about my experience in this area.


A little background about myself: I would consider myself to be your average mid-30 year old ALT.NET developer. I got my start programming BASIC and 65xx assembly as a kid in the early 80s on a Commodore 64, got my first programming job doing Java in the late 90s, and started using ASP.NET in the late 1.0 beta days. Programming is one of my hobbies, but I am not the type that stays up all hours of the night working on my pet OSS project. I am also not a “computer scientist” or language wonk. However, I am passionately interested in software craftsmanship. S.O.L.I.D. is prominent in my tool belt.

My attention was first turned to WPF in the early fall of 2008. My group was facing a large desktop project. The question came up as to if we should go with Winforms or WPF. No one on the team had any practical Winforms experience, so the initial reaction was that we should go with WPF since Microsoft had made it clear that it was the future of Windows desktop development. However, we all had heard rumblings about how difficult WPF was. That being the case, each member of the team created a very small drag-and-drop application to test the waters. The general consensus was that if you ignored the more advanced features of WPF, it was just as easy as Winforms drag-and-drop + code behind development. Mind you, we did not want to do that sort of development, but it became apparent that that style of development would be equally painful using either framework. Note that at this time, I really had no idea how to make a real application using WPF, but I did understand the very basic concept of how XAML markup changed the game from Winforms development.

Estimated time spent learning WPF during this period: 8 hours.

After the initial decision making process, I returned to ASP.NET and WCF development. The WPF project didn’t really get started until spring 2009. I was not slated to work on the project, but I was enlisted to help decide the preliminary architecture. Once I was given that task, I began to look around for application frameworks, or at the very least, some patterns that had momentum behind them. At this time, I learned about the MVVM pattern via the still insightful Jason Dolinger video. It really seemed to click in my mind so I began looking for an application framework to support this pattern. I did not find a mature application framework per say, but I did come across PRISM. There were a few other budding frameworks at the time, but PRISM was way ahead of the game. Therefore, we decided to go with PRISM using the MVVM presentation pattern on the client side of the application. Once that decision was made, I was back off the project and doing other things. I did however start following a few WPF blogs at this time, but I did not do any WPF coding.

Estimated time spent learning WPF during this period: 8 hours.
Total estimated time: 16 hours.

This July, my schedule freed up and I was put on the project 50% of my time. I was tasked with a reporting interface that had to show a list of available reports and then dynamically show parameter UI elements depending on which report was selected.

As soon as I was assigned to the project, I got a copy of WPF in Action with Visual Studio 2008. I read the book half the day during my work week, and then a few hours each night at home. As someone who learned programming through type-in programming, I made sure that I recreated all of the samples myself. Also at this time, I grabbed the latest version of PRISM and took a peek at the examples.

Estimated time spent learning WPF during this period: 30 hours.
Total estimated time: 46 hours.

The first week of actual development was pretty brutal. MVVM was not the problem. PRISM was not the problem. XAML and databinding is where I was banging my head against the wall. It kind of worked like HTML, and it kind of didn’t. That first week was pretty aggravating, but pretty much every problem I encountered was just an internet search away.

Estimated time spent learning WPF during this period: 30 hours.
Total estimated time: 76 hours.

I became productive after that first week. I’ll be the first to admit that I don’t intimately know how WPF works behind the scenes (like I do with ASP.NET). However, I do think that I became productive within a reasonable amount of time.

Looking back, I can safely say it took me about 80 hours to go from expert ASP.NET programmer to productive WPF programmer.  That being said, I do not know how long it would have taken me to go from expert ASP.NET programmer to productive Winforms developer. Something tells me it wouldn’t have been a number that would have made us use Winforms instead of WPF.

Should .NET Auto Properties Have Unit Tests?


testing_scaled

Should .NET auto properties be unit tested? It is very easy to argue that testing auto properties falls into the “testing the .NET framework” smell and is a waste of time. However, experience has shown me otherwise. This is something that I’ve gone back and forth on many times since auto properties were introduced. For the time being, I think I’ve reached a conclusion. That conclusion is yes.

 

I typically do two types of testing: 1) Test Driven Design, and 2) Test while/after unit testing. Let’s consider these two scenarios.

When doing test driven design, there is no question. You should write tests for your auto properties. Test driven design is not about testing; it’s about design. The rule of thumb is that you don’t write any code without a test dictating its need. Case closed (in general).

Things get trickier when doing test while/after unit testing. This type of testing is more about creating a test harness. When writing tests after the fact, I know that the property is implemented using auto properties. Therefore, if I am taking a white box approach, I know that my implementation of the encapsulated property is simply the .NET framework. Following that line of thought, testing auto properties is testing the .NET framework. However, I tend to view test while/after testing as a test harness of the public contract. This is black box testing. A public property is an encapsulation, and therefore it should be tested. It’s not uncommon for an auto property to be converted into a regular property as an application lives on. I’d have to say that I would want a test there to capture any publicly facing change in that encapsulation.

Persistence Ignorant Lazy Loading For Your Hand-Rolled DAL In .NET 4.0 Using Lazy<T>


This post is a brief update to the .NET 3.5 article I posted about P.I. lazy loading. The only major change I have made to the code is to use the new Lazy<T> class that was introduced in .NET 4.0. This considerably cleans up the LazyLoadingList<T> class from the previous post.

Here is the new LazyLoadingList<T>:
public class LazyLoadingList<T> : IList<T>
{
private Lazy<IList<T>> _lazyList;

public LazyLoadingList(Lazy<IList<T>> lazyList)
{
_lazyList = lazyList;
}

#region Implementation of IEnumerable

public IEnumerator<T> GetEnumerator()
{
return _lazyList.Value.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return _lazyList.Value.GetEnumerator();
}

#endregion

#region Implementation of ICollection<T>

public void Add(T item)
{
_lazyList.Value.Add(item);
}

public void Clear()
{
_lazyList.Value.Clear();
}

public bool Contains(T item)
{
return _lazyList.Value.Contains(item);
}

public void CopyTo(T[] array, int arrayIndex)
{
_lazyList.Value.CopyTo(array, arrayIndex);
}

public bool Remove(T item)
{
return _lazyList.Value.Remove(item);
}

public int Count
{
get
{
return _lazyList.Value.Count;
}
}

public bool IsReadOnly
{
get
{
return ((ICollection<T>)_lazyList.Value).IsReadOnly;
}
}

#endregion

#region Implementation of IList<T>

public int IndexOf(T item)
{
return _lazyList.Value.IndexOf(item);
}

public void Insert(int index, T item)
{
_lazyList.Value.Insert(index, item);
}

public void RemoveAt(int index)
{
_lazyList.Value.RemoveAt(index);
}

public T this[int index]
{
get
{
return _lazyList.Value[index];
}
set
{
_lazyList.Value[index] = value;
}
}

#endregion
}


Here are the changes to the invoking code:
public class CompanyDAO : ICompanyDAO
{
List<Company> _companiesInDatabase = new List<Company>
{
new Company(){Name = "ACME"},
new Company(){Name = "Hardees"}
};

#region Implementation of ICompanyDAO

public Company GetByName(string name)
{
// Write to console to demonstrate when loading is happening
Console.WriteLine("---Loading Company---");

// Pretend we are calling / mapping from a store procedure
var company = _companiesInDatabase.Where(x => x.Name == name).First();


// Create / add the lazily loaded collection
if (company != null)
{
var lazyLoader = new Lazy<IList<Employee>>(
() =>
{
var employeeDAO = new EmployeeDAO();
return employeeDAO.GetByCompanyName(name).ToList();
}
);

company.Employees = new LazyLoadingList<Employee>(lazyLoader);
}

return company;
}

#endregion
}


The full source can be found here: http://github.com/dauger/BlogSamples

How to fail at ORM

NoORM


Let's face it: if trends continue, some form of ORM will be a fact of life at most .net organizations that develop business / enterprise software. Microsoft isn't playing games this time with Entity Framework. They mean for it to succeed. Additionally, at the time of writing this, NHibernate has been downloaded 391,024 times from sourceforge alone (there is more than one place to download it from). This being the case, I’m going to give everyone a few pointers to ensure that their first attempt at ORM fails.

Here are my tips to insure ORM adoption failure (in no particular order):

Consider the ORM’s SQL engine as a replacement for SQL knowledge. The whole point behind ORMs is so that I don’t have to write or understand SQL right? WRONG!

Consider the ORM’s SQL engine to be a black box. I got back the correct dataset, so this must be the best SQL the ORM can produce right? WRONG! Most ORMs will create drastically different SQL depending on how the object query is structured.

Don’t get more than a skin deep understanding of the ORM. If you run into a brick wall with a bit of behavior from the ORM, you can follow two paths. You can A) learn about the finer points of the ORM to resolve the issue, or B) rip the ORM out of your application. The latter is the outcome I’ve seen more often than not. A classic example of this is the N+1 select issue where the app calls the database in a loop. ORMs have things such as eager loading, multi-queries, and future queries to avoid extra trips to the database. However, it’s best to ignore the existence of those features if you want to fail at ORM.

Use ORM generated schema without manually tweaking it. Many ORMs will happily create a schema for the developer just how they specified it, and index free. Ideally you shouldn’t use generated schema at all once you are up and running. A DBA should be creating a schema using relational theory. However, if you want to fail, it’s best to just used that generated schema.

Use the ORM for 100% of your data access.
Most ORMs allow for dropping into prepared SQL, stored procedures, and even db function calls. However, it’s best to ignore this functionality if you want to fail.

Maintain OO purity at all costs.
Does fetching your aggregate root cause an 11 table join? So be it.

Cut the DBA out of the development process.
The whole point of ORM is to cut out the DBA right? WRONG! The DBA should be just as active with helping to craft the data access strategy as they would with a hand rolled data access layer. Cutting the DBA of the picture is a recipe for failure.

Don’t profile your application.
If you want to fail, it’s best to find out if you have have created a SQL nightmare once you hit production. NHProf, EFProf, L2SProf, and SQL Profiler are your friends. Ignore them to fail.

I hope you find these tips helpful. I’d like to hear about any other tips for ORM failure you might have.

Possibly The Most Important C# Interview Question


brain_resized


The Problem

Recently I was reviewing some code at work that was written by a senior developer that had left the organization. I saw something along these lines that set off a huge red flag in my head:

Address newAddress = customer.Address;
newAddress.LineOne = "122 SongbirdLane"; // more changes etc...
customer.Address = newAddress; // RED FLAG!

Although the above code technically works, I took it as a warning sign indicating that the developer probably didn’t understand how references work. Sadly, my suspicions were confirmed after I dug through some more code. Even worse, the application was littered with hacks to fix areas where this misunderstanding manifested problems.

Yes ladies and gentlemen, there are people out there that have been doing C# development since .NET 1.0 that don’t have a functional mental model of how the language works. I wish I could say this was the first time I’ve run into this. Sadly, I’ve run into it several times over the years.

The Solution

It is very easy to weed these people out during the interview process by asking a very simple interview question. That question is:

What does the following program output to the command line?


public class Person
{
public string Name { get; set; }
}

class Program
{
static void Main(string[] args)
{
Person joe = new Person();
joe.Name = "Joe";

Person tim = joe;
tim.Name = "tim";

Console.WriteLine(joe.Name);
Console.WriteLine(tim.Name);

int myNumber = 666;

DoSomething(myNumber);

Console.WriteLine(myNumber);
}

private static void DoSomething(int someNumber)
{
someNumber = 777;
}
}

The trick is that you have to ask it to every developer, no matter how many years they have under their belt.

Speeding Up Cassini In Vista And Windows 7

I was doing some ASP.NET MVC work this evening on my new supa-fast Windows 7 machine using the built-in Visual Studio Cassini webserver. For some odd reason, it was taking a few seconds for my tiny pages to resolve / render. I was using Chrome, so I decided to try Firefox. Firefox was just as slow. I then tried using IE and it performed with the speediness I was used to on my old XP install. I did some digging, and I came across the solution to the problem in two places:

http://www.wagnerdanda.me/2009/12/asp-net-development-server-slow-on-windows-vista7-with-firefox-or-chrome/
http://stackoverflow.com/questions/1416128/my-local-host-goes-so-slow-now-that-i-am-on-windows-7-and-asp-net-mvc

It turns this is an issue with ipv6 and resolving localhost on Vista and Windows 7. The fix is very easy – you simply need to uncomment the localhost entry in your  C:\Windows\System32\drivers\etc\hosts file by changing this:

# localhost name resolution is handled within DNS itself.
#    127.0.0.1       localhost

to:

# localhost name resolution is handled within DNS itself.
     127.0.0.1       localhost

You may need to run your text editor as administrator in order to save the changes.