When Virtual Server 2005 R2 SP1 was released it included the VHDMount tool – that came with a DLL to allow you to control it programmatically. Unfortunately we were rather light with the documentation / sample code for this. So today I would like to show you how to drive VHD mounting from managed code.
To do this I will be creating a small application called ‘VHDMounter’. It will have a simple user interface like this:
To help with tracking things in the code I have named the TextBox "VHDTextBox" and the buttons "MountButton" and "UnmountButton" respectively. Once the basic user interface is built here is the code that you need to drive the application:
Let us have a dig into what is happening here:
- The first thing to do is to create an enum for VHD_FLAGS. This information is grabbed directly from the VHDMount.h file in the vhdmount directory from where Virtual Server is installed.
- Next you need to create interop code for ‘MountVHD’ and ‘UnmountVHD’ on vhdmount.dll. Note that while I am doing a full path reference to the copy of vhdmount.dll that is included with my installation of Virtual Server – you probably just want to make a local copy of this file for your project (also note that the Virtual Server EULA does grant you redistribution rights if you want to include this in a formal product).
- Finally hookup some basic code for click events on MountButton and UnmountButton to try and mount / unmount the virtual hard disk specified in VHDTextBox. In this code I do not do any checking on the text that I am passing to vhdmount.dll because I am lazy and vhdmount.dll does a very good job of checking the validity of the string anyway. The result code will always be ‘0’ if the operation is successful. Any other result code means a failure of some kind. To look up the meaning of a result code go to here: http://msdn2.microsoft.com/en-us/library/ms681382(VS.85).aspx
Two final things to be aware of:
- This code was written using Visual Studio 2008 – I make no guarantees of compatibility with other versions of Visual Studio.
- In order for this code to work it needs to be running with Administrative privilege. You can manually launch with administrative privilege – or you can manifest it to require administrative privilege. You can read how to do this with Visual Studio 2008 here: http://www.danielmoth.com/Blog/2007/08/uac-settings-in-vb.html