We have built a Windows Service that is running on client's machines, which occasionally downloads a newer version of itself, and then performs a self-update: installs a new service, starts it, stops the old one, and eventually deletes it. The service cannot stop itself directly and do other stuff, so it spins another executable, which does some of the work. getting this right is tricky, and this is particularly bad when the newer service is built using a newer .Net Framework (such as the recent switch from .Net 2.0 to .net 4.0). The problem is that a .Net 2.0 library cannot operate on a .Net 4.0 service.
Now, one approach would be to have the older version of the service spin a helper program which comes with the newer version, but ... what if the behavior of it HAS to change in a breaking way? I feel safer about not mixing up the versions, even if some things usually stay the same - helps to keep the design complexity down.
Now, there appears to be a .Net version-neutral way of operating on Windows Services: the sc.exe
tool: http://support.microsoft.com/kb/251192
I wonder if it is indeed the silver bullet that I was seeking. Now, because I will be calling this guy programmatically, and checking for errors, then I might as well use an API for this. Ideally I would have one native C++ project, which compiles to a native exe, which interfaces with SC.exe. Is this possible? If not, then how can I go about locating sc.exe on different computers? They could be 32-bit or 64-bit, and running any version of Windows starting with Win XP SP2/3.
Let me know if you have questions about my question, or some ingenious idea, or an answer to the exact question that I posed here.
Edit: If I try to install a 4.0 service using 2.0 code, I get the same error as if I do:
> C:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe MyService4.exe
Microsoft (R) .NET Framework Installation utility Version 2.0.50727.4927 Copyright (c) Microsoft Corporation. All rights reserved.
Exception occurred while initializing the installation: System.BadImageFormatException: Could not load file or assembly 'file:///[path]\MyService4.exe' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded..