After searching the web for information, I have managed to create a service which, depending on the command line, can install or uninstall itself, or just run as an application.
However, the uninstalling code isn't working correctly.
The related code:
Private Function UnInstallService(ByVal args As String(), ByRef errMsg As String) As Boolean
Dim si As New ServiceInfo
If (Not GetServiceInfo(args, si)) Then
errMsg = "Error..."
Return False
End If
If (Not IsServiceInstalled(si.Name)) Then
errMsg = "Error..."
Return False
End If
Try
Dim installer As ServiceProcessInstaller = GetServiceInstaller(si)
Dim stateSaver As IDictionary = New Hashtable
Try
installer.Uninstall(stateSaver)
Catch e As exception
errMsg = "Error..."
Return False
End Try
Catch e As exception
errMsg = "Error..."
Return False
End Try
End Function
Private Function GetServiceInstaller(ByVal si As ServiceInfo) As ServiceProcessInstaller
Dim installer As ServiceInstaller = New ServiceInstaller()
Dim pInstaller As New ServiceProcessInstaller
pInstaller.Context = New InstallContext("", si.CommandLine)
installer.Description = si.Description
installer.DisplayName = si.DisplayName
installer.ServiceName = si.Name
installer.StartType = ServiceStartMode.Automatic
If (si.Account = "LocalSystem") Then
pInstaller.Account = ServiceAccount.LocalSystem
ElseIf (si.Account = "LocalService") Then
pInstaller.Account = ServiceAccount.LocalService
ElseIf (si.Account = "NetworkService") Then
pInstaller.Account = ServiceAccount.NetworkService
Else
pInstaller.Account = ServiceAccount.User
pInstaller.Password = si.Password
pInstaller.Username = si.Account
End If
pInstaller.Context.Parameters("assemblypath") = si.FullPath
pInstaller.Installers.Add(installer)
installer.Parent = pInstaller
Return pInstaller
End Function
It throws a NullReferenceException in the call to installer.Uninstall The code for installation is exactly the same, except for checking if the service is installed, and calling installer.Install and then installer.Commit instead of Uninstall. I'm passing it exactly the same parameters.
Any idea?