Facing Error 1053 in case of windows service - c#

I made a windows service. My code is similar to:
onstart()
{
while(true)
{
//code
}
}
I am trying to update my database every minute.
The service builds properly and installed properly, but when I start the service it gives error 1053.
I have tried alot to solve it but not get any solution.

protected override void OnStart(string[] args)
{
//put debugger.launch the first statement of OnStart...and make sure you running in debug mode
Debugger.Launch();
try
{
//your code
.
.
.
}
catch(Exception ex)
{
//see what exception is coming
}
}

Did you define onStop?
The ServiceBase class calls the OnStop
method directly from the Service
command handler that is defined in the
ScDispatcherLoop of the Advapi32.dll
file. After 30 seconds, if the
ScDispatcherLoop thread is not ready
to receive a new service command from
the service control manager, Windows
Service Controller marks the service
as "time out." Therefore, you receive
this error message.
-Microsoft

Go to the console of the server (in the server room if you will) and start the Window Service. Remote in won't work.

Related

Foreach is stopped when exception is caught in try catch block located within the loop in ASP.NET Webapi

In my API I'm calling external SOAP API method several times. In order to achieve this I use foreach loop and inside it I put try catch block to handle exception and continue the loop. Everything works fine on my machine but when I deploy the API to another server running IIS it seems to stop calling the external API's method when exception is thrown as if the try catch was suddenly moved outside of the loop. Is it possible that it might have something to do with IIS configuration?
I've already tried putting this method inside another one and then putting that method inside try catch block but it didn't help.
public class Loader
{
private static SoapClient client;
private static string AddItems(Order order)
{
foreach(item in order.items)
{
try
{
client.SoapMethod(item);
}
catch(Exception e)
{
// Log error and go to next iteration
Log.LogError(e.Message);
}
}
}
}
Log class uses Log4Net to put error message in a text file:
public class Log
{
private static readonly ILog log = LogManager.GetLogger("API");
public static void LogError(string message)
{
log.Error(message);
}
}
In case the external SOAP API's method throws exception it should be skipped and it's supposed to go to the next iteration of the foreach loop to call this method with another data.
EDIT: I deployed my API to another server and it works there without breaking the loop so it seems that there's something wrong with that particular machine.
Thanks to the comment of #Silvermind I found out what the problem was. Logs were also sent to Windows EventLog which threw IOException every time any application tried to save logs in Application source (from which a custom view was created). I googled it and it appears to be a known issue in all Windows systems from Windows 7 SP1 and Windows Server 2008 SP2 as described on this site. The same error can be seen while filtering the Application view in Event Viewer.

How to crash to get "Subsequent failures" of Windows Service Recovery to be considered

We have a Windows service written in C# that starts basically a Web API on a certain port. The service is configured to be restarted on the first failure and the second failure. The "Subsequent failures" is set to "Take No Action".
In case this port might be taken the service crashes with an unhandled exception and in our unhandled exception callback we write dump files to a certain application directory. For whatever reason Windows keeps restarting the service over and over even though it crashed already multiple times. The structure of our service is like this:
public class WinService : ServiceBase
{
private WebApiHostWrapper _apiHost;
private Thread _workerThread;
public WinService()
{
InitializeComponent();
ServiceName = "MyService";
// register handler for writing dumpfiles
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptions.DomainUnhandledException;
}
protected override void OnStart(string[] args)
{
_workerThread = new Thread(InternalStart) { Name = "StartupThread" };
_workerThread.Start(args);
}
private void InternalStart(object args)
{
if (null == _service)
{
Thread.MemoryBarrier();
_apiHost= new WebApiHostWrapper();
_apiHost.Start((string[])args); // exception here
}
}
protected override void OnStop()
{
if (null != _workerThread)
{
_apiHost.Dispose();
_apiHost= null;
if (!_workerThread.Join(5000))
{
_workerThread.Abort();
}
Thread.MemoryBarrier();
_workerThread = null;
}
}
In the Windows event log I see 4 entries.
Service started successfully. (source: MyService)
Applicatio .... stacktrace etc. (source: .NET Runtime)
Faulting application name... dll and exe name (source: Application Error)
Fault bucket, type 0.... (source: Windows Error Reporting)
In a scenario where the port is already in use, this causes the service to crash over and over, flooding the system with dump files. Windows will always restart the service independent from the settings. Is there a special way how to crash in order to get the the "Subsequent Failures" to be considered and NOT to restart the service?
I found the problem that caused only the "First failure" to be executed. We had the "Reset fail count after" set to 0 days. After setting this value to 1 the service crashed 2 times and then was not restarted anymore.
Sources:
https://social.technet.microsoft.com/Forums/windows/en-US/3db76753-4607-4a20-97a0-790c73e379cc/the-actions-after-system-service-failure?forum=winserver8gen
Clarification on Windows Service Recovery Actions Settings
http://www.happysysadm.com/2011/12/understanding-windows-services-recovery.html

Windows service doesn't hit OnStart unless using Administrator account

The service installs correctly but when attempting to start it via net start or from the services window it doesn't start at all, not even getting to the OnStart handler.
If I use an administrator account, the service starts and works correctly. This seems to suggest something in the service requires admin privileges but this is purely an on-demand style service with nothing executing until requested. With this type of service I'd assume that is should at least start and then fail later when a request is made to it that requires admin privileges?
It's impossible to debug as I can't even get it to start and nothing is appearing on the event logs apart from an Information log stating that the service stopped. There's too much code in the service to add it all here but the entry point is a fairly standard Unity style service:
partial class MyServiceHost : UnityServiceBase
{
private Bootstrapper _bootstrapper;
public MyServiceHost()
{
InitializeComponent();
}
protected override void OnStart( string[] args )
{
TextWriter tw = new StreamWriter( "ServiceTestLog.txt" );
tw.Write( "Date: " + DateTime.Now + "\n" );
try
{
base.OnStart( args );
_bootstrapper = new Bootstrapper( UnityContainer );
_bootstrapper.Run();
}
catch ( Exception ex )
{
tw.Write( ex.ToString() );
}
tw.Close();
}
protected override void OnStop()
{
_bootstrapper.Teardown();
base.OnStop();
}
}
For business reasons I can't just make the user account it uses an administrator so I'd appreciate any suggestions on how to fix this issue.
Writing to "ServiceTestLog.txt" may require local admin rights.
Make sure your user account has the "Log on as a Service" privilege. This won't work without that, and it's not on by default for users, though it would be for administrator. Instructions here.
Run the Visual Studio Debugger and attach to the service and you can step through it and see what's going on.
You can add this before initializecomponent() and add WAITFORDEBUGGER in the Service Control Panel "Start parameters" textbox for your service.
C#:
foreach (string arg in args) {
if (arg == "WAITFORDEBUGGER") {
while (!Debugger.IsAttached) {
Threading.Thread.Sleep(1000);
}
}
}
VB.Net:
For Each arg As String In args
If arg = "WAITFORDEBUGGER" Then
While Not Debugger.IsAttached
Threading.Thread.Sleep(1000)
End While
End If
Next
The service will then wait for you to fire up Visual Studio and attach the debugger, at which point you can trace through the entire initialization and run sequence and see what's broken.
If it never hits the WAITFORDEBUGGER code, it's probably having trouble loading a dependency, in which case Sysinternals Process Monitor (https://technet.microsoft.com/en-us/sysinternals/bb896645) can tell you what it's getting hosed on.

Windows service on Local Computer started and then stopped error

Usually, I get this error:
(The "service name" service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other service or programs) when there's something wrong with my code, like non-existing drive paths, etc. The windows service will not start.
I have a windows service that backs up folder/files, to a location if it reached the size limit. Details are all provide by an XML Configuration that the windows service reads on start. I have a separate windows forms that has a button that does exactly what my windows service's onstart is doing. I use my windows forms for debugging the code before I put it in my windows service.
When I start my windows forms. It does what it suppose to do. When I put my code in the windows service OnStart() method the error showed up.
Here's my code:
protected override void OnStart(string[] args)
{
private static string backupConfig = #"D:\LogBackupConfig\backupconfig.xml";
private static string serviceStat = #"D:\LogBackupConfig\Status.txt";
private static string fileFolderStat = #"D:\LogBackupConfig\FileFolderStat.txt";
protected override void OnStart(string[] args)
{
if (File.Exists(backupConfig))
{
FileSystemWatcher watcher = new FileSystemWatcher();
XmlTextReader reader = new XmlTextReader(backupConfig);
XmlNodeType type;
List<string> listFile = new List<string>();
string fileWatch = "";
//this loop is for reading XML elements and assigning to variables
while (reader.Read())
{
type = reader.NodeType;
if (type == XmlNodeType.Element)
{
if (reader.Name == "File")
{
reader.Read();
fileWatch = reader.Value;
}
else if (reader.Name == "Folder")
{
reader.Read();
fileWatch = reader.Value;
}
}
}
reader.Close();
watcher.Path = fileWatch;
watcher.Filter = "*.*";
//this loop reads whether the service will watch a file/folder
XmlTextReader reader1 = new XmlTextReader(backupConfig);
while (reader1.Read())
{
type = reader1.NodeType;
if (type == XmlNodeType.Element)
{
if (reader1.Name == "File")
{
watcher.IncludeSubdirectories = false;
watcher.Changed += new FileSystemEventHandler(OnChangedFile);
}
else if (reader1.Name == "Folder")
{
watcher.IncludeSubdirectories = true;
watcher.Changed += new FileSystemEventHandler(OnChangedFolder);
}
}
}
reader1.Close();
watcher.EnableRaisingEvents = true;
}
else
{
StreamWriter sw = new StreamWriter(serviceStat, true);
sw.WriteLine("File not found. Please start the Log Backup UI first.");
sw.Close();
}
}
I don't know what keeps the windows service not starting, the windows form simulator worked fine. What seems to be the problem?
UPDATE:
After many trials I've noticed that using only a folder directory (w/out file), the windows service doesn't work. When I replaced the fileWatch variable with a specific file (including its directory), the windows service started. When I changed it back to a folder location, it didn't work. What I think is that folder locations doesn't work in a filewatcher.
When I tried creating a new windows service that watches a folder location, it worked.. However, when I tried the same location in my original windows service, it didn't work! I was mindf$#*ed! It seems that I have to create a new windows service and build the installer everytime I place a new code/function.. This way I can keep track where I get an error.
If the service starts and stops like that, it means your code is throwing an unhandled exception. This is pretty difficult to debug, but there are a few options.
Consult the Windows Event Viewer. Normally you can get to this by going to the computer/server manager, then clicking Event Viewer -> Windows Logs -> Application. You can see what threw the exception here, which may help, but you don't get the stack trace.
Extract your program logic into a library class project. Now create two different versions of the program: a console app (for debugging), and the windows service. (This is a bit of initial effort, but saves a lot of angst in the long run.)
Add more try/catch blocks and logging to the app to get a better picture of what's going on.
Not sure this will be helpful, but for debugging a service you could always use the following in the OnStart method:
protected override void OnStart(string[] args)
{
System.Diagnostics.Debugger.Launch();
...
}
than you could attach your visual studio to the process and have better debug abilities.
hope this was helpful,
good luck
I have found it very handy to convert your existing windows service to a console by simply changing your program with the following. With this change you can run the program by debugging in visual studio or running the executable normally. But it will also work as a windows service. I also made a blog post about it
program.cs
class Program
{
static void Main()
{
var program = new YOUR_PROGRAM();
if (Environment.UserInteractive)
{
program.Start();
}
else
{
ServiceBase.Run(new ServiceBase[]
{
program
});
}
}
}
YOUR_PROGRAM.cs
[RunInstallerAttribute(true)]
public class YOUR_PROGRAM : ServiceBase
{
public YOUR_PROGRAM()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Start();
}
protected override void OnStop()
{
//Stop Logic Here
}
public void Start()
{
//Start Logic here
}
}
Please check that you have registered all HTTP endpoints in the local mahcine's Access Control List (ACL)
http://just2thepoint.blogspot.fr/2013/10/windows-service-on-local-computer.html
EventLog.Log should be set as "Application"
Meanwhile, another reason : accidentally deleted the .config file caused the same error message appears:
"Service on local computer started and then stopped. some services stop automatically..."
Use Timer and tick event to copy your files.
On start the service, start the time and specify the interval in the time.
So the service is keep running and copy the files ontick.
Hope it help.
You may want to unit test the initialization - but because it's in the OnStart method this is near to impossible. I would suggest moving the initialization code out into a separate class so that it can be tested or at least re-used in a form tester.
Secondly to add some logging (using Log4Net or similar) and add some verbose logging so that you can see details about runtime errors. Examples of runtime errors would be AccessViolation etc. especially if your service is running without enough privileges to access the config files.
The account which is running the service might not have mapped the D:-drive (they are user-specific). Try sharing the directory, and use full UNC-path in your backupConfig.
Your watcher of type FileSystemWatcher is a local variable, and is out of scope when the OnStart method is done. You probably need it as an instance or class variable.
I came across the same issue. My service is uploading/receiving XMLS and write the errors to the Event Log.
When I went to the Event Log, I tried to filter it. It prompt me that the Event Log was corrupted.
I cleared the Event Log and all OK.
In our case, nothing was added in the Windows Event Logs except logs that the problematic service has been started and then stopped.
It turns out that the service's CONFIG file was invalid. Correcting the invalid CONFIG file fixed the issue.

C# Windows Service

Scenario
I've created a windows service, but whenever I start it, it stops immediately. The service was concieved from a console application that used to subscribe to an event and watch processes on a server. If anything happened to process (i.e. It was killed), then the event would trigger the process to be restarted. The reason I'm telling you this is because the original code used to look like this:
Original Console App Code:
static void Main(string[] args)
{
StartProcess sp = new StartProcess();
//Note the readline that means the application sits here waiting for an event!
Console.ReadLine();
}
Now that this code has been turned into a Windows Service, it is essentially EXACTLY THE SAME. However, the service does not sit there waiting, even with the readline, it just ends.....
New Windows Service Code:
protected override void OnStart(string[] args)
{
ProcessMonitor pm = new ProcessMonitor();
Console.ReadLine();
}
Thoughts
Since the functionality is entirely encapsulated within this single class (It quite literally starts, sets up some events and waits) - How can I get the service to actually sit there and just wait? It seems to be ignoring the readline. However this works perfectly as a console application, it is just far more convenient to have it as a service.
Typically you would want something like this. As Joe mentioned in the comments you want Start to initialize and release control to another thread to make sure that you return within 30 seconds.
private readonly ProcessMonitor processMonitor = new ProcessMonitor();
protected override void OnStart(string[] args)
{
processMonitor.Start();
}
protected override void OnStop()
{
processMonitor.Stop();
}
In a Service there is no concept of a readline - there's no keyboard. I wouldn't be surprised if this is throwing an exception at that call. Have you checked your Application Log?
Well... A service doesn't have a console input/output. So the ReadLine won't stop it from executing.
What does ProcessMonitor do?
Typically, for services your code lives in a thread that monitors whether the service has been stopped or paused.
OnStart() must complete and end successfully for the service to be considered "Started"
Move your Console.ReadLine(); into your ProcessMonitor() constructor, and create your ProcessMonitor inside the constructor for the service. Your OnStart method can be empty. Despite what people are saying the Console methods will NOT crash your service, however it is probably not best practice. I guess the proper way to keep a service running (after your timers are started) is to use a while loop with a Thread.Sleep(60000) inside it.
When I am writing a service I put all the functionality in a Class Library project, then I create a Console Application project to test the service functionality, and then a Windows Service project. Both the Console Application and Windows Service project call one method in the Class Library to start the service functionality. If you use this technique you can call Console.WriteLine in the Class Library which can be viewed when running the Console Application. PS Topshelf is overrated, writing a windows service is not that difficult.
public partial class ProcessMonitor_Service : ServiceBase
{
public ProcessMonitor_Service()
{
InitializeComponent();
ProcessMonitor pm = new ProcessMonitor();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}
public class ProcessMonitor
{
public ProcessMonitor()
{
// start timers
Console.ReadLine();
}
}

Categories

Resources