Windows Service Fails To Start Through ManagedInstallerClass But Succeeds Through InstallUtil - c#

I have created a windows service in Visual studio 2012 (c#) that needs to be started after install. I have read so many articles and StackOverflow questions but none got it working.
In the main function, I have:
static void Main(string []args)
{
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
}
I have registered AfterInstall event of the service.
private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
using (ServiceController sc = new ServiceController(serviceInstaller1.ServiceName))
{
sc.Start();
}
}
I'm logged in as an administrator. When I run the .exe file (as administrator), it tries to installs the service (keeps it in starting status for 2 minutes) but fails to start it. When I run in debug mode, I get an exception on sc.Start(). The log file says:
System.InvalidOperationException: An exception occurred in the OnAfterInstall event handler of System.ServiceProcess.ServiceInstaller.
The inner exception System.InvalidOperationException was thrown with the following error message: Cannot start service Database Convertor on computer '.'.
The inner exception System.ComponentModel.Win32Exception was thrown with the following error message: The service did not respond to the start or control request in a timely fashion.
I tried to change LocalService account to LocalSystem with no success.
Then I tried changing the main function too
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
and when I installutil convertor.exe, it successfully installs and starts the service (but I need to start it through the program).
Why it starts the service when installing through installutil and why it throws an exception when I manually call installhelper?

Try removing everything in the OnStart function in the service and see if it starts successfully, if it starts then debug the onStart function (You can user Debugger.Attach())
Best of luck

Related

Application does not exit when an error happening on systemd

So I developed an application using .net-core, I run this software on a linux machine as a daemon service using systemd. Now the problem is that when an error happen in the app, it enters in a "limbo", infact each activity of the application is logged using Console.WriteLine and I can see this log typing that command on linux machine: journalctl -fu app.service.
When the error happen the log doesn't write anything, but at the same time the application keep running and this is really strange because I setup the service with the following configuration:
[Unit]
Description = Daemon service
[Service]
ExecStart = /usr/bin/dotnet /home/my username/Desktop/publish/SimpleApp.dll
WorkingDirectory= /home/foo/Desktop/publish
Restart = always
RestartSec = 3
[Install]
WantedBy = multi-user.target
as you can see the Restart = always should restart the app when an error is raised. When an exception is raised the method Error() write the error inside a file and then kill the software in the following way:
public void Error(Exception ex)
{
File.WriteAllText("error.txt", ex.ToString());
Environment.Exit(1);
}
Must be some problem on Environment.Exit with the Linux environment, or I did something wrong calling Environment.Exit. There are other ways to close an application like this which run as system service?
Thanks
Try the following:
public void Error(Exception ex)
{
File.WriteAllText("error.txt", ex.ToString());
throw new Exception ("This is a test to see if restart is working");
}

Could not start Windows Service, Error 1064

I wrote a Windows Service to run on Win10, and it worked perfectly fine until I decided to change it a bit. I rewrote some logic, tested it in both Debug and Release configurations, and everything was fine. Then I uninstalled the current version of the service using installutil.exe /u %servicename.exe% and reinstalled it again using installutil.exe %servicename.exe%.
For some reason, this new version cannot start, and it crashes with Error 1064. This is the full error text:
Windows could not start %servicename% service on Local Computer. Error 1064: An exception occurred in the service when handling the control request.
The last time I installed this service, I ran into some difficulties, but quickly fixed them by changing the Log On properties. This time, it is not working. Please help with this issue.
Thanks.
Update 1
Here are my Main() and OnStart() service methods:
Main()
static void Main()
{
#if DEBUG
var service = new SalesforceToJiraService();
service.OnDebug();
Thread.Sleep(Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new SalesforceToJiraService()
};
ServiceBase.Run(ServicesToRun);
#endif
}
OnStart()
protected override void OnStart(string[] args)
{
this.ConfigureServices();
this.timer.Start();
this.logger.Information("SalesforceToJira service started.");
}
Update 2
More code:
ConfigureServices()
protected void ConfigureServices()
{
this.configuration = ConfigurationHelper.LoadConfiguration(ConfigurationPath);
this.logger = ConfigurationHelper.ConfigureLogger(this.configuration.Logs.LogsPath);
this.timer = ConfigurationHelper.ConfigureTimer(this.configuration.ProcessInterval.TotalMilliseconds,
(sender, eventArgs) => this.ProcessCasesAsync(sender, eventArgs).GetAwaiter().GetResult());
this.salesforceClient = new SalesforceCliClient(this.configuration.Salesforce.CliPath);
this.jiraClient = Jira.CreateRestClient(
this.configuration.Jira.Url,
this.configuration.Jira.Username,
this.configuration.Jira.Password);
}
I'm using Newtonsoft.JSON for deserializing a JSON configuration file, Serilog for logging, System.Timers.Timer for periodic events, AtlassianSDK for the Jira API and some wrappers over Salesforce CLI for Salesforce.
Thanks to #Siderite Zackwehdex's comment, I was able to find the full stack trace of the underlying exception in EventViewer, under:
Windows Logs\Application
In my case, my service is named "HttpDispatcher", which appears in the "Source" column in the top pane.
I could see immediately it was due to a dependency issue where my .NET 4.7.2 project was not pulling across my .NET Standard references. (That ol' chestnut).
I faced the same issue. The reason was I forgot to set the Database connection properly in configurations.
I had this exact same error 1064 starting my service. For me the user I had the service registered as was not a valid user in the database. Once added, it worked great.
I also had the same error in my Windows Service.
The reason was it can't read a configuration parameter, so it crash.
Adding some validation (bugfixing), the Windows Services can start it correctly.
In my case the error was due to issues with Event log name
It got fixed after I went to RegEdit and deleted old service name from HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
I have also faced this issue. In my case it is due to connection fail with the data base. I think it is due to code throw the exception.
My error :
Windows could not start the service1 service on local computer.
Error 1064: An exception occured in the service when handling the control request
I corrected my issue by updating the third party DLL.
I faced the same issue, here is how I resolved it after troubleshooting.
If you are running service on the Server with multiple users, make
sure to run the service as admin user. Click on the service
properties and then on Log on tab click on this account and provide
the admin user name and password.
And If your service is accessing some shared drive, then make sure
you have a general user on all servers for accessing the shared
drives and add the user as local admin as well.
For me it happened when I tried to restart a process. Turned out the process was hanging in 'Stopping' so I had to kill it manually via command line and the PID.

Performance and diagnostics with "Cannot start service... A Windows Service must first be intalled (using installutil.exe)..."

Presently, I am attempting to profile a Windows service that I am working on using the new "Performance and Diagnostics" feature in Visual Studio 2013 (see http://blogs.msdn.com/b/visualstudioalm/archive/2013/07/12/performance-and-diagnostics-hub-in-visual-studio-2013.aspx). When I attempt to profile the service, I get this error message:
Cannot start service from the command line or a debugger. A Windows Service must first be intalled (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative Tool or the NET START command.
Normally when debugging the service, it works fine because I have the following code in Program.cs:
private static MySvc _serviceInstance;
private static readonly List<ServiceBase> _servicesToRun =
new List<ServiceBase>();
static void Main(string[] args)
{
_servicesToRun.Add(_serviceInstance);
if (Environment.UserInteractive)
{
_servicesToRun.ToArray().LoadServices();
}
else
{
ServiceBase.Run(_servicesToRun.ToArray());
}
}
static Program()
{
_serviceInstance = new MySvc();
}
Also, if I attempt to attach to a running app, in the dialog that appears it doesn't display any executing processes, and when I put the name of the service in there, it does not find it. Does anyone have any suggestions? TIA.
UPDATE: This is what I get when I attempt to attach to a process. Why doesn't the "Performance and Diagnostics" see any processes running on my computer? Why would it only connect to Windows Store apps instead of all exes? Please see this image:
The way I resolved the problem was the copy all the source code and make minor modifications to get everything to run in a Console application, then chose Debug->Performance and Diagnostics and ran the Console application using "Change Target" -> "Launch and executable file (.exe)"

Unable to start service written in .NET 2.0 on Windows XP Embedded

I've created a small executable that can be launched either as a normal application by calling MyApp.exe or as a service by calling MyApp.exe -s. Because I'm trying to keep as simple as possible, I "install" this app by manually running
sc create MyAppService binPath= "C:\MyApp\MyApp.exe -s"
Then I start the service with net start MyAppService like normal.
On two Windows XP machines and two Windows 2000 machines, this works fine. However, on two different Windows XP Embedded machines, when I try to start the service I get the message:
System error 1083 has occurred.
The executable program that this service is configured to run in does not implement the service.
On one machine, I was able to fix this by uninstalling and reinstalling .NET 2.0, but on the second machine this did not work.
I'm not sure how to go about debugging this, and searching google only seems to turn up specific services that fail with this message such as BITS and an Exchange service.
Below are the classes MyApp, which is the startup class, and MyAppService, which is the class that extends ServiceBase. Thanks in advance for any direction on this.
MyApp.cs
static class MyApp
{
[STAThread] static void Main( string[] args )
{
....
switch ( arg1 )
{
case "-s":
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyAppService() };
ServiceBase.Run( ServicesToRun );
break;
....
}
}
}
MyAppService.cs:
class MyAppService : ServiceBase
{
static MyAppService()
{
// ...
}
protected override void OnStart( string[] args )
{
// ...
}
}
On the desktop, this can happen if the service isn't registered correctly in the Windows Registry under the account that the svchost instance is supposed to run under. I don't have experience in XPe, but try looking in HKLM\Software\Microsoft\Windows NT\CurrentVersion\Svchost and make sure that MyAppService is correctly listed for the account.
Try to check in the Event log if there is useful info including Security log.
It seems did not recognize the MyAppService as a service or MyApp.exe does not expose any services to the XPe. Focus on this thing to get the root cause.
For fast testing, you can get XPe run in your development PC by using VMWare. VMWare has the way to copy the current running XPe into image and copy to your PC but not sure if it can work properly.
It appears that I have the same problem. The ServiceController.Start() does not start service successfully. The application is in C# .NET2 and running in Window XPe. The work around is below:
TimeSpan timeout = TimeSpan.FromMilliseconds(20000);
while (true)
{
ServiceController service = new ServiceController("myservice");
service.MachineName = ".";
try
{
service.Start()
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
service.Stop();
continue;
}
}
after looping 2 or 3 times, the service usually get started successfully.
But 30-40 seconds has passed. This is not acceptable.
Dos anybody have experienced on this issue? Thanks!

Installing a self-developed Windows Service

I'm trying to deploy a service that I wrote. Here's the InstallLog file:
Installing assembly 'c:\Users\brwatson\Development\Projects\TweetLinks\TweetLinkQueue\bin\Debug\TweetLinkQueue.exe'.
Affected parameters are:
logtoconsole =
assemblypath = c:\Users\brwatson\Development\Projects\TweetLinks\TweetLinkQueue\bin\Debug\TweetLinkQueue.exe
logfile = c:\Users\brwatson\Development\Projects\TweetLinks\TweetLinkQueue\bin\Debug\TweetLinkQueue.InstallLog
Installing service TweetLinkService...
Creating EventLog source TweetLinkService in log Application...
Rolling back assembly 'c:\Users\brwatson\Development\Projects\TweetLinks\TweetLinkQueue\bin\Debug\TweetLinkQueue.exe'.
Affected parameters are:
logtoconsole =
assemblypath = c:\Users\brwatson\Development\Projects\TweetLinks\TweetLinkQueue\bin\Debug\TweetLinkQueue.exe
logfile = c:\Users\brwatson\Development\Projects\TweetLinks\TweetLinkQueue\bin\Debug\TweetLinkQueue.InstallLog
Restoring event log to previous state for source TweetLinkService.
An exception occurred during the Rollback phase of the System.Diagnostics.EventLogInstaller installer.
System.Security.SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.
An exception occurred during the Rollback phase of the installation. This exception will be ignored and the rollback will continue. However, the machine might not fully revert to its initial state after the rollback is complete.
As you can see, it's not working. I am not sure how to proceed, and have hit the wall with Bing and Google. I have set the Account to LocalSystem for the serviceProcessInstaller1. The code compiles fine, but now I would like to run the thing...any ideas? I am an administrator on my box, and I am running the command:
InstallUtil TweetLinkQueue.exe
from the VS2008 admin console.
UPDATED WITH /ShowCallStack option
Call Stack
An exception occurred during the Install phase.
System.Security.SecurityException: The source was not found, but some or all eve
nt logs could not be searched. Inaccessible logs: Security.
at System.Diagnostics.EventLog.FindSourceRegistration(String source, String m
achineName, Boolean readOnly)
at System.Diagnostics.EventLog.SourceExists(String source, String machineName
)
at System.Diagnostics.EventLogInstaller.Install(IDictionary stateSaver)
at System.Configuration.Install.Installer.Install(IDictionary stateSaver)
at System.ServiceProcess.ServiceInstaller.Install(IDictionary stateSaver)
at System.Configuration.Install.Installer.Install(IDictionary stateSaver)
at System.Configuration.Install.Installer.Install(IDictionary stateSaver)
at System.Configuration.Install.AssemblyInstaller.Install(IDictionary savedSt
ate)
at System.Configuration.Install.Installer.Install(IDictionary stateSaver)
at System.Configuration.Install.TransactedInstaller.Install(IDictionary saved
State)
and here is the constructor:
public TweetLinkService()
{
InitializeComponent();
if (!EventLog.SourceExists("TweetLinkQueue"))
{
EventLog.CreateEventSource("TweetLinkQueue", "Log");
TweetLinksLog.Source = "TweetLinkQueue";
TweetLinksLog.Log = "Log";
TweetLinksLog.WriteEntry("Log Created!");
}
}
UPDATED with ENtry Point:
namespace TweetLinkQueue
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new TweetLinkService()
};
ServiceBase.Run(ServicesToRun);
}
}
}
I was just having this issue and it was because I wasn't running my visual studio command prompt as an administrator.
I'm not sure what your specific problem is. It looks to me like the problem occurs while creating the EventLog source. Double-check that you've done that part correctly. You can reference the step-by-step here. EDIT: SPECIFICALLY LOOK AT STEP 9. The problem may be occuring because you're messing with the Application log instead of one specific to your application.
There's nothing wrong with using InstallUtil, but if you need to install your service on a foreign machine, InstallUtil is not guaranteed to be there. You can follow this step-by-step to make your Windows service executable install/uninstall itself without the need of InstallUtil. See here for those instructions.
To solve this issue right click on your Visual Studio 2008 Command Prompt and click run as administrator then you run your command like installutil C:\mcWebService\bin\Debug\mcWebService.exe
then it will show you successful message.
Hope this will solve your solution.
The LocalSystem account doesn't normally have permission to read the Security event log (or to create event sources for that matter).
The easiest and safest solution is to create an event source installation program that you can run under your own administration-level credentials on any machine for which you'll want to run this. It might be even worth trying this as a simple test, just to see if your account has the permission to do this.
class Program {
static void Main(string[] args) {
EventLog.CreateEventSource("TestSource", "Application");
}
}
If you execute that, does it succeed? You can check it by looking at the Application log's properties and browsing the Event sources on its Filter tab.
Alternately, since services have to be installed anyway, you could add an EventLogInstaller (which is misnamed - it's really an 'EventSourceInstaller' that will create EventLogs as needed) to the assembly instead of using EventLog.CreateEventSource in the service's constructor.
My issue was a window was popping to enter credentials and I was entering my username without the domain. Once I entered domain\username all was fine.
I got the same unexplainable errors when installing windows services.
In our case the user was the problem.
Installing the server with the administrator-user worked, but not for a local admin. This, however, is not a preferred solution, so we used this information to create a different user that could install the service.

Categories