Wednesday, September 23, 2009

Unit Tests for registry read fails in Visual Studio on 64 bit machines

My my my...
A hotch potch of Windows Server 2008 and Visual Studio 2008 on a 64 bit machine killed my 3-4 hours today...

So here's the deal
I've a method in one of my dlls which reads a certain value from a sub key of HKEY_LOCAL_MACHINE\SOFTWARE Then i wrote a unit test to test this method. Turns out it fails to read the Registry. I was amazed because registry entry did exist in the registry. After struggling for about an hour or so i decided to write a console application to test the method. And the method worked :O. So now i was in a situation where a method works from the console application while fails from a unit test.

I thought that its a permissions issue so i gave full trust to both the assemblies i.e. unit test assembly and the assembly i was testing. Even that didn't help.
Looking at the task manager of the system i saw that the unit tests run under a process call VSTestHost.exe. So next i tried to give full trust to this exe however that's not possible since it is a win32 exe.

A relook at the Task Manager showed me that the process runs under VSTestHost.exe*32 means a 32 bit process running on a 64 bit OS. Nothing suspicious about it in the first look. However if you look at the nodes below HKEY_LOCAL_MACHINE\SOFTWARE in the registry you see a node called Wow6432Node and that made me think. After some search i figured out that if you run a 32 bit process on a 64 bit machine and try to read the subkeys of HKEY_LOCAL_MACHINE\SOFTWARE The registry reads are actually directed to HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node. So i made an entry in this node and it worked.

Lesson :- Be careful while working with registries if you depend on registry for your program to work.

Happy coding :)


1 comment:

Murtaza said...

finally you unravelled the mystery ...!! WOW!!