Thu, December 20, 2007, 12:48 PM under
dotNET |
MobileAndEmbedded
When the Windows Mobile Managed APIs were introduced they made use of a new underlying Windows CE 5 feature (that WM 5.0 is based on):
volatile registry keys (see dwOptions).
Volatile keys are also available on normal/desktop/server Windows. In a nutshell, volatile registry keys do not survive an OS reboot so anything you write there is not persisted the next time you restart. The obvious question at this point is: Does the
managed registry API support volatile keys? The answer is "no" for both the full .NET Framework and the .NET Compact Framework. Let's explore an UNSUPPORTED solution for both platforms.
On the surface without too much digging it appears that the native RegCreateKeyEx is wrapped by
RegistryKey.CreateSubKey. So for the BCL team to add support for volatile keys to the managed API, one way would be to add a new overload to CreateSubKey that accepts our desire for volatileness and at the point it calls RegCreateKeyEx it passes in REG_OPTION_VOLATILE instead of 0 which is what the implementation does now (i.e. a change of one line of code).
But since we are not the BCL team and we cannot edit the library's code, we can create a helper static method to do that job for us. Maybe that method would live in the static Program class with a signature something like this:
public static RegistryKey CreateSubKey(this RegistryKey rk, string subkey, bool isVolatile)
{
if (!isVolatile)
{
return rk.CreateSubKey(subkey); // i.e. no change
}
else
{
// call our own method since we cannot change the framework's
return MothCreateVolatileSubKey(rk, subkey, RegistryKeyPermissionCheck.Default);
}
}
Note on the above:
1. I've made the method an
extension method which means that we can call it in either of these two ways (the first being more natural):
RegistryKey rk1 = Registry.CurrentUser.CreateSubKey("my vol", true);
RegistryKey rk2 = Program.CreateSubKey(Registry.CurrentUser, "my vol", true);
2. As you can imagine the implementation of
MothCreateVolatileSubKey is a simple duplication of the implementation of the existing framework method with 2 differences:
a) Where the framework's implementation passes 0 as the 4th argument to the native RegCreateKeyEx, we will pass REG_OPTION_VOLATILE.
b) Wherever the framework's implementation calls private/internal methods we will have to use reflection to access them (unless you fancy duplicating all of that too;)).
Yes, I know the above is very ugly, very unsupported and very much a hack. I have created a VS2008 solution with the above that you can use to test it out at your own risk. It contains two projects, one for NETCF to run on your Windows Mobile and one for the desktop.
It is quite possible that by running the code from the project your machine will be wiped clean and that your monitor will go up in flames after transferring all your money out of your bank account. You have been warned!So, at your own risk,
get the VS2008 projects here.