So, EnvDTE.Solution.AddXXX and EnvDTE.ProjectItems.AddXXX methods return Nothing "by design"…

These days I am working on some Visual Studio automation to perform unit testing against some features of my MZ-Tools add-in. I know I should have done this long time ago, but I never found the time or willingness to do it until last week. And since then I am thrilled because while the cost of writing code to test an application can make unit testing arguable, if you have to test your add-in against four Visual Studio versions and soon five versions, it clearly pays off, specially if you are a perfectionist like me that do a lot of code refactoring (with the risk of breaking something) to get better code.

Unit testing add-ins poses some challenges since the add-in DLL must be hosted inside the VS IDE, likely its classes and methods are not public, the add-in needs a solution to be tested against it, etc. I will try to blog about all this in a few weeks when I have time again (I’ll travel to Japan tomorrow for two weeks) but for now suffice to say that I am automating Visual Studio to make the tests to create the (disposable) solution, projects, files and sample code that they will use, rather than depending on already created solutions (which should be in different format for each VS version). And one thing that I have found while automating Visual Studio is that the EnvDTE.Solution.AddFromTemplate and EnvDTE.ProjectItems.AddFromTemplate methods return null (Nothing in VB.NET) in VS 2005 or higher rather than the created EnvDTE.Project or EnvDTE.ProjectItem.

I hardly remembered that I read about this in the Working with Visual Studio 2005 book (which despite its misleading name is about creating add-ins). Checking the MSDN documentation yesterday I saw that Ed Dore (from MS) explained it in the Community Content section, and when I was about to write a MZ-Tools article about it, I have found that I already had one about this back in 2006:

PRB: Solution.AddXXX and ProjectItems.AddXXX methods return Nothing (null)
http://www.mztools.com/Articles/2006/MZ2006019.aspx

Needless to say, I think it is a pity this loss of functionality introduced by VS 2005 due to changes in the wizard/templates mechanism. If only one file is created, it should return it. If more than one file is created, it should return the main one (such as Form1.cs rather than Form1.Designer.cs). Or if all that is not possible with the exising methods, provide new AddFromTemplate2 methods that return a collection of added files. All that is better than returning nothing and forcing the developer to guess the added file iterating the collection or using the OnItemAdded event.

BTW, using the AddFromTemplate methods is very tricky across Visual Studio versions and across languages in the same version. I will try to write an entry about this on the plane to post when I am online again :-)