Trying to start a new service - but having a permission problem - c#

The error:
I get a popup window when trying to manually start the windows service. It says:
Windows could not start the XXX
service on Local Computer. Error:
1069: The service did not start due to
a logon failure.
Post-build events:
There are 2 Windows services in the solution and they have the same post-build events:
REM C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe /u "$(TargetPath)"
REM C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe /i /username=.\administrator /password=blabla "$(TargetPath)"
But for some reason it's only the first service that is installed during debug-build mode. The other is not (despite similar post-build events). So I manually used the InstallUtil with the administrator login and blabla password from the post-build events. That did install it, but one is installed with "Log On As = Local System" (works!) and the other has "Log On As = .\administrator" (does not work!).
I guess that's what triggers the error. Why the difference? Is there another install going on the solution build somewhere? It should be said that it is a solution consisting of 47 projects.

I'm 99% sure that you can solve this by granting the Log on as service privilege to the administrator user.

Related

how to have a windows service self update?

All the solutions I can find on this topic are very old and none of them appear to answer my question...
I am trying to create a windows service that can self update (or auto update by some external trigger). In the past, I had created a windows service that was installed with InstallShield and we were able to update auto update the service in a hacky way by making the service write a batch script to the local machine and then run the batch script, which would stop the service, overwrite the service executable and other files with the new ones, and restart the service. This surprisingly worked.
However, I have updated the service to use InstallUtil.exe and this auto update script no longer works... I assume it's something to do with the way InstallShield handles the service install vs how InstallUtil does it... but I can only make guesses as I don't fully understand what each is doing to the registry.
Since I can't just overwrite the files and restart the service with the InstallUtil method, I thought I'd write a batch script that runs sc.exe to stop the service, uninstall it entirely, write the new files, install the new service files, and then start it... unfortunately, I can't seem to get sc.exe to run from a windows service automatically because it requires admin permissions... I tried to force it to self-elevate to admin using this snippet, but it doesn't appear to work as a service (it works fine if I run it from command line not as a service)
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)
Does anyone know how I can cause a windows service to self update? I can look into updating to a .NET Core Worker service if there is some method of self update in .NET Core that I'm unaware of... Any ideas are much appreciated... it really shouldn't be this hard to accomplish...
For reference, here is the batch script I am currently using (ignore odd variables and such as I am dynamically replacing some of them, it works great when launched manually, just doesn't work when the service tries to run it):
#echo off
setlocal enableextensions enabledelayedexpansion
::make sure to run whole script as admin (this restarts scripts as admin if not already in admin mode)
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)
pushd %networkDirectory%
::stop running service
for /F "tokens=3 delims=: " %%H in ('sc query %serviceName% ^| findstr " STATE"') do (
if /I "%%H" NEQ "STOPPED" (
net stop %serviceName%
if errorlevel 1 goto :stop
)
::delete existing service after stopping
sc delete %serviceName%
)
:: install updated service files
set "releaseDir=%networkDirectory%\Release"
set "programFilesCopyDir=%ProgramFiles%\{_companyDirectory}\%serviceName%\Release"
:: copy service Release dir to local system program files
xcopy "%releaseDir%" "%programFilesCopyDir%" /S /Y /Q
::execute the install
pushd "%programFilesCopyDir%"
CALL %serviceName%.exe --install
::start service
sc start %serviceName%
For anyone else trying to accomplish this that stumbles on this... I ended up finding a solution. I use the same script posted in my question above, but I wrote code to set up a scheduled task with Windows Task Scheduler. The scheduled task runs the above script as a one time scheduled task. This works like a charm.
I used this NuGet package to write the Task Scheduler code I needed:
https://www.nuget.org/packages/TaskScheduler/2.8.20?_src=template

Windows Service - UnauthorizedAccessException Error when Installing Service (C#)

So I am trying to create a service using C# in Visual Studio 2017 and I keep getting an error when I try to install it.
Right now, I don't even have anything in my service, I just want to be able to install the service. I created a new Project in Visual Studio 2017 using the Windows Service (.NET Framework) template under Visual C# > Windows Desktop. I then added the installer via Right Click > Add Installer. For serviceProcessInstaller1, I set the account to LocalSystem. And...that's it!
Now, I try to install it. I open up command prompt (run as administrator) and I do
InstallUtil ServiceTest.exe
Things start off smoothly, but then I get a message:
"An exception occured during the Install phase.
System.UnauthorizedAccessException: Attempted to perform an
unauthorized operation."
What could be generating this message?
I've googled and tried the following things:
Ensure I run command prompt as administrator.
Assign Full Control to
the project folder to my admin account.
Configure permissions to Full
Control for admin account in the security log of regedit.
Log into my
computer as an administrator (rather than regular user) and run it
that way.
Despite these things, I keep getting the same error. What else could I be doing wrong? Would really appreciate some advice!
Note: I am trying to install this service locally on my computer.
Edit: Per request, here are the logs. I named my project "FailedService", by the way, since I can't get it to work!
InstallUtil.InstallLog
Running a transacted installation.
Beginning the Install phase of the installation.
See the contents of the log file for the C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe assembly's progress.
The file is located at C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.InstallLog.
An exception occurred during the Install phase.
System.UnauthorizedAccessException: Attempted to perform an unauthorized operation.
The Rollback phase of the installation is beginning.
See the contents of the log file for the C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe assembly's progress.
The file is located at C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.InstallLog.
The Rollback phase completed successfully.
The transacted install has completed.
FailedService.InstallLog
Installing assembly 'C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe'.
Affected parameters are:
logtoconsole =
logfile = C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.InstallLog
assemblypath = C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe
Installing service Service1...
Creating EventLog source Service1 in log Application...
Rolling back assembly 'C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe'.
Affected parameters are:
logtoconsole =
logfile = C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.InstallLog
assemblypath = C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe
Restoring event log to previous state for source Service1.
I was FINALLY able to resolve this issue. I was able to get to the bottom of it by using SysInternal's Process Monitor. I opened up the program and had it take logs for InstallUtil.exe. From there, I began to search for any logs that said "Access Denied". As I sorted through them, I noticed something interesting: it was trying to create a registry key, but it kept failing!
So I went into the registry and created a key named "ServiceTest". After that, I ran the InstallUtil command again, and it worked!
If anyone else is having trouble, the solution is to create a key named after your process name in the following location:
HKLM\System\CurrentControlSet\Services\EventLog\Application\
Enter the full path to installUtil & your service binary in an elevated prompt, that could do.

cannot uninstall a windows service: "...cannot be deleted, because it's equal to the log name."

I need to uninstall a Windows Service I have created, but I get this error using the "Uninstall or change program" program in windows:
Error. An exception occurred while
uninstalling. This exception will be
ignored and the uninstall will
continue. However, the application
might not be fully uninstalled after
the uninstall is complete. -> The
event log source '111 My Service'
cannot be deleted, because it's equal
to the log name.
Then I click "OK" and the program remains listed in the list of installed programs. What is worse, I cannot install a new version of it. The windows installer says that another version of this product is already installed and I should uninstall it first. How do I get rid of this program?
Update Here is what is happening when I run InstallUtil.exe /u command on it.
The uninstall is beginning. See the
contents of the log file for the
C:\MyService.MyService. assembly's progress. The file
is located at
C:\MyService.MyService.InstallLog.
Uninstalling assembly
'C:\MyService.MyService.exe'. Affected
parameters are: logtoconsole =
assemblypath = C:\MyService.exe
logfile =
C:\MyService.MyService.InstallLog
Removing EventLog source 111 My
Service. An exception occurred during
the uninstallation of the
System.Diagnostics.EventLogInstaller
installer.
System.InvalidOperationException: The
event log source '111 My Service'
cannot be deleted, because it's equal
to the log name. An exception occurred
while uninstalling. This exception
will be ignored and the uninstall will
continue. However, the application
might not be fully uninstalle l is
complete.
The uninstall has completed. An
exception occurred while uninstalling.
This exception will be ignored and the
uninstall will continue. However, the
application might not be fully
uninstalle l is complete.
Try to execute next command in cmd:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe /u "c:\myservice.exe"
The second option is:
sc delete <service name>
After running the line above you can try to remove the service branch as well in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services.
The accepted answer didn't work for me.
What worked is open regedit in administrator mode and find the service and delete it.
I had the exact same problem (and nothing in the selected answer worked).
Surprisingly, what fixed the problem was (using the standard "Uninstall or change program" or "Programs and Features" windows dialog) right-clicking on the program and choosing repair (this was apparently successful), and then uninstalling.
This just happened to me and the solution above didn't work where you run the InstallUtil.exe or delete the service. I had initially set up my service with the "LocalSystem" security context, and it was installed with that. I later changed the security context to "User" and recompiled the service executable and tried to uninstall the old service. The error messages were coming up that are described here, and once I went and changed the security context back to "LocalSystem" I could fully uninstall.
In other words, you might want to uninstall your old service with the executable it was created with rather than a newer one with possible modifications.

Installing C# Windows Service on Windows 7

I have a batch file that I have been using to install my C# Windows Services for awhile now, never had a problem until Windows 7. I have attempted to run the batch file with Administrator privileges. I have attempted to run the command prompt with admin privs, navigate to the windows service EXE and run InstallUtil there. Still doesn't work.
After reading some other suggestions I tried moving my files out of the /bin folder and running them from another location but that also didn't work.
The batch file looks like this
#ECHO OFF
REM The following directory is for .NET 2.0
set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727
set PATH=%PATH%;%DOTNETFX2%
echo Installing IEPPAMS Win Service...
echo ---------------------------------------------------
InstallUtil /i IEPPAMS_WinService1.exe
echo ---------------------------------------------------
echo Done.
and I have a install log file that I dump info to. If I just double click the .bat file I get
Running a transacted installation.
Beginning the Install phase of the
installation. See the contents of the
log file for the
C:\Users\Justin\Desktop\service
test\IEPPAMS_WinService1.exe
assembly's progress. The file is
located at
C:\Users\Justin\Desktop\service
test\IEPPAMS_WinService1.InstallLog.
An exception occurred during the
Install phase.
System.InvalidOperationException:
Cannot open Service Control Manager on
computer '.'. This operation might
require other privileges. The inner
exception
System.ComponentModel.Win32Exception
was thrown with the following error
message: Access is denied.
The Rollback phase of the installation
is beginning. See the contents of the
log file for the
C:\Users\Justin\Desktop\service
test\IEPPAMS_WinService1.exe
assembly's progress. The file is
located at
C:\Users\Justin\Desktop\service
test\IEPPAMS_WinService1.InstallLog.
The Rollback phase completed
successfully.
The transacted install has completed.
When I run the .bat file with admin privileges nothing is written to the log file, and the service is still not installed.
Any thoughts? Is there a new way to install services in Windows 7?
Right click on the batch file and run it as Administrator.
You are most likely running into battle with the new security model (User Account Control) from Windows Vista and Windows 7. Even if you are running as an account that has Admin rights you will still need to elevate to do some (most) administrative activities. (Yes it is possible to disable this feature, but don't)
UAC (MSDN)
UAC (Wikipedia)
InstallUtil (MSDN)
Edit... The correct commandline is InstallUtil YourApp.exe. The /i does not look to be a vaild switch for InstallUtil.
So I was able to fix the problem by typing in the command line the entire path to InstallUtil and it worked. So after navigating to the folder that had my EXE I typed the following:
C:\Windows\Microsoft.NET\Framework\v4.0.21006\installutil.exe
IEPPAMS_WinService1.exe
Not sure why I have to do that in Windows 7 now when I never had to in XP, but oh well. Thanks for all the suggestions!
When I run the .bat file with admin privileges nothing is written to the log file, and the service is still not installed.
First off, you HAVE to run as admin permissions.
Second, when you "Run as Administrator", it actually changes the directory to c:\windows\system32 as the initial directory ( no idea why ), which would probably explain why running as admin causes no log file. Manually change to the path IEPPAMS_WinService1.exe resides in that the start of your script.

Uninstall Command Fails Only in Release Mode

I'm able to successfully uninstall a third-party application via the command line and via a custom Inno Setup installer.
Command line Execution:
MSIEXEC.exe /x {14D74337-01C2-4F8F-B44B-67FC613E5B1F} /qn
Inno Setup Command:
[Run]
Filename: msiexec.exe; Flags: runhidden waituntilterminated;
Parameters: "/x {{14D74337-01C2-4F8F-B44B-67FC613E5B1F} /qn";
StatusMsg: "Uninstalling Service...";
I am also able to uninstall the application programmatically when executing the following C# code in debug mode.
C# Code:
string fileName = "MSIEXEC.exe";
string arguments = "/x {14D74337-01C2-4F8F-B44B-67FC613E5B1F} /qn";
ProcessStartInfo psi = new ProcessStartInfo(fileName, arguments)
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true
};
Process process = Process.Start(psi);
string errorMsg = process.StandardOutput.ReadToEnd();
process.WaitForExit();
The same C# code, however, produces the following failure output when run as a compiled, deployed Windows Service:
"This action is only valid for products that are currently installed."
Additional Comments:
The Windows Service which is issuing
the uninstall command is running on
the same machine as the code being
tested in Debug Mode. The Windows
Service is running/logged on as the
Local system account.
I have consulted my application logs
and I have validated that the
executed command arguments are thhe
same in both debug and release mode.
I have consulted the Event Viewer
but it doesn't offer any clues.
Thoughts? Any help would be greatly appreciated. Thanks.
Step 1: Check the MSI error log files
I'm suspicious that your problem is due to running as LocalSystem.
The Local System account is not the same as a normal user account which happens to have admin rights. It has no access to the network, and its interaction with the registry and file system is quite different.
From memory any requests to read/write to your 'home directory' or HKCU under the registry actually go into either the default user profile, or in the case of temp dirs, c:\windows\temp
I've come across similar problems in the past with installation, a customer was using the SYSTEM account to install and this was causing all sorts of permission problems for non-administrative users.
MSI log files aren't really going to help if the application doesn't appear "installed", I'd suggest starting with capturing the output of MSIINV.EXE under the system account, that will get you an "Inventory" of the currently installed programs (or what that user sees installed) http://blogs.msdn.com/brada/archive/2005/06/24/432209.aspx
I think you probably need to go back to the drawing board and see if you really need the windows service to do the uninstall. You'll probably come across all sorts of Vista UAC issues if you haven't already...
Thanks to those offering help. This appears to be a permissions issue. I have updated my service to run under an Administrator account and it was able to successfully uninstall the third-party application. To Orion's point, though the Local System account is a powerful account that has full access to the system -- http://technet.microsoft.com/en-us/library/cc782435.aspx -- it doesn't seem to have the necessary rights to perform the uninstall.
[See additional comments for full story regarding the LocalSystem being able to uninstall application for which it installed.]
This is bizarre. LocalSystem definitely has the privileges to install applications (that's how Windows Update and software deployment in Active Directory work), so it should be able to uninstall as well.
Perhaps the application is initially installed per-user instead of per-machine?
#Paul Lalonde
The app's installer is wrapped within a custom InnoSetup Installer. The InnoSetup installer, in turn, is manually executed by the logged in user. That said, the uninstall is trigged by a service running under the Local System account.
Apparently, you were on to something. I put together a quick test which had the service running under the LocalSystem account install as well as uninstall the application and everything worked flawlessly. You were correct. The LocalSystem account has required uninstall permissions for applications in which it installs. You saved the day. Thanks for the feedback!

Categories

Resources