I want my Windows Service to log (log4net) error if the service terminates unexpectedly, i.e crashes due to any reason. I terminated the service from Windows Task Manager, checked Event Viewer i.e.
Windows logs -> System
and found error was 7034.
Update:
Here is what I tried, I used EventLog class for writing entry in Application log, which was successful. Although I want an entry to be written in case windows service crashes or terminates unexpectedly.
static int Main(string[] args)
{
try
{
// Do something here
}
catch (Exception ex)
{
if (!EventLog.SourceExists("ApplicationName"))
EventLog.CreateEventSource("ApplicationName", "WindowsService");
EventLog.WriteEntry("ApplicationName", ex.Message);
}
return -1;
}
But it didn't log anything upon crash, where should I write entry in EventLog so that it can log upon crash?
Related
I would like to disable service programmatically through registry. To do that, I modify the following registry key : Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\SensorDataService\Start, where I set its value 0x4 which corresponds to disabled state. Now, when I check service in Windows Service Manager - it's reported as disabled and I can't start it.
However, if I try to have it started programmatically like this:
var serviceController = new ServiceController("SensorDataService");
try
{
serviceController.Start();
} catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Then service is started...
When I disable service through windows service UI or SC command line, then I got exception stating that can't start disabled service, exactly what I expect.
Does anyone know if setting above-mentioned value in registry is just not enough to disable the service?
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");
}
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
I have a very simple console exe application. This application will be executed by Windows Server R2 Task Scheduler after every 15 minutes. This was working fine for a long period of time but since last 2 days the application is not exiting some times. The problem is that Task Scheduler will never run the application again unless the previous started application exit. Here is my application code,
static void Main(string[] args)
{
MyService.Process();
}
internal static void Process()
{
try
{
Logger.Log("Starting Service");
// Synchronous Work
Logger.Log("Ending Service");
}
catch (Exception ex)
{
Logger.Log("Unknown error occured: " + ex.Message);
}
}
When I check the log file I am seeing these lines at the end of file,
Starting Service
--------------------------
Ending Service
The Task Scheduler in Windows Server 2008 R2 showing me memory = 480), CPU = 0 and Threads = 1. What can be the possible cause that forbid the exe to exit. Also, note that it only happens some times. My application creates, moves, delete some files/directories using File and Directory class and send some data to server using WebClient.UploadValues
I'm writing a series of Windows services. I want them to fail if errors are thrown during startup (in OnStart() method). I had assumed that merely throwing an error in OnStart() would do this, but I'm finding that instead it "Starts" and presents me with a message stating "The service has started, but is inactive. Is this correct?" (Paraphrase). How do I handle the error so it actually fails to start the service?
If the main thing you want is for the Services window to report that there was an error, from what I've tried (.NET3.5 on Windows 7), the only way to do this is by setting the ExitCode. I recommend setting it to 13816, since this results in the message, "An unknown error has occurred." See the windows error codes.
The sample below accomplishes three things.
Setting ExitCode results in a useful message for the end-user. It doesn't affect the Windows Application log but does include a message in the System log.
Calling Stop results in a "Service successfully stopped" message in the Application log.
throwing the exception results in a useful log entry in the Application log.
protected override void OnStart(string[] args) {
try {
// Start your service
}catch (Exception ex) {
// Log exception
this.ExitCode = 13816;
this.Stop();
throw;
}
}
if you are running .NET 2.0 or higher, you can use ServiceBase.Stop to stop the service from OnStart. Otherwise call Stop from a new thread.
ref [devnewsgroups] (http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic50404.aspx)
(news group gone)
Move all of your startup logic to a separate method, and Throw exceptions (or call OnStop) from that seperate method.
OnStart has some oddities when starting up. I have found that if OnStart() has no more than one line in it, then I dont get the "The service started and then stopped.Some services stop automatically if they have no work to do" message, and thrown exceptions will terminate the process and log to the app event log.
Also with the seperate startup method, you can use a technique like this to debug it without attaching. http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx