Saturday, 6 February 2010

SOLVED: Error 1053 / EventType clr20r3 when trying to start a Windows Service

If you have seen errors when trying to deploy your Windows Service that have error 1053 and cryptic codes starting with EventType clr20r3 in your Event Log then this is your solution!

Scenario

I have recently been writing my first Windows Service which I tested and successfully used on my local development rig. Then when it came to deploying it I got cryptic error codes appearing which had me totally stumped.

When I tried to start the service it would time out after 30 seconds and give me the following error message:

The Sample Web Service service failed to start due to the following error:
The service did not respond to the start or control request in a timely fashion.

Error 1053

I tried to test the service on Windows Server 2003 and Windows Server 2008 servers but it wouldn't work on either.

Because the Windows Service was installed on the remote server it was out of reach of my debugger so I started blindly editing parts of the code, compiling, uploading, reinstalling the service and then attempting to start it. Needless to say this was a time consuming and frustrating process.

During each test I would get the same error message popup but a slightly varying error message in the Application Event Log. The three unique errors that I noted down looked like this:

EventType clr20r3, P1 windowsservice.exe, P2 1.0.0.0, P3 4b69efe0, P4 mscorlib, P5 2.0.0.0, P6 4a7cd8f7, P7 35f9, P8 40b, P9 system.argumentexception, P10 NIL.

 

EventType clr20r3, P1 windowsservice.exe, P2 1.0.0.0, P3 4b69e583, P4 windowsservice, P5 1.0.0.0, P6 4b69e583, P7 17, P8 1a, P9 system.nullreferenceexception, P10 NIL.

 

EventType clr20r3, P1 windowsservice.exe, P2 1.0.0.0, P3 4b68be72, P4 system, P5 2.0.0.0, P6 4889de7a, P7 36dc, P8 7f, P9 system.argumentexception, P10 NIL.

Solution

After dropping all of the error messages I could into Google and discovering that a lot of other developers were having the same problems I thought it would be an easy fix. Unfortunately for most users their cries for help went unanswered or unresolved.

I did find several threads with people saying that I should put the service in a try catch block and then log the error to the Event Log but the problem was that nobody posted any code to go along with the suggestion. At the time I was stressed and wanted a copy paste answer!

So in the end I caved, wrote the code, went through the test cycle one more time and then checked my event log.

I should have done that the first time.

In my event log was the actual exception that was being raised plus the full stack trace pointing right at the line of code that was causing the problem.

It turned out that my problem was a FileSystemWatcher I had dropped on the design canvas. I had set a default path which was incorrect when placed on the server. At run time I manually set the path in my main code which I had checked and double checked but when the FileSystemWatcher was initialised at design time it was using the settings in the hidden .designer.cs file first - and crashing the service!

The only silver lining I can see in this experience is that I am not going to forget it any time soon. If this -ever- happens to me again I am sure that I wont have any trouble instantly recalling the exact steps to solve this.

Your specific error will probably not be the same one as mine, however by using the code in the next section you will be able to track down your offending error with ease.

Implementation

If you created a bog standard Windows Service project you should have a file called Program.cs. This file contains your Main() which is the entry point for the application. You should have some code that looks like this:

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] 
{ 
    new SampleWindowsService() 
};
ServiceBase.Run(ServicesToRun);

To trap the error you will need to wrap the whole block inside a try catch:

try
{
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] 
{ 
    new SampleWindowsService() 
};
    ServiceBase.Run(ServicesToRun);
}
catch (Exception ex)
{
}

In the catch() block we will need to write out the details of the Exception into the Application Event Log. Here is the minimum code you need to log an error to the Windows Event Log.

string SourceName = "WindowsService.ExceptionLog";
if (!EventLog.SourceExists(SourceName))
{
    EventLog.CreateEventSource(SourceName, "Application");
}

EventLog eventLog = new EventLog();
eventLog.Source = SourceName;
string message = string.Format("Exception: {0} \n\nStack: {1}", ex.Message, ex.StackTrace);
eventLog.WriteEntry(message, EventLogEntryType.Error);

I am not going to go through this code as it is reasonably self explanatory and not the focus of this article. When you drop that code in to the catch block you will also need to add in a reference to the System.Diagnostics namespace so that you can use EventLog.

Putting all of this together our Program.cs should now look something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Diagnostics;

namespace SampleWindowsService
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            try
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new SampleWindowsService() 
                };
                ServiceBase.Run(ServicesToRun);
            }
            catch (Exception ex)
            {
                string SourceName = "WindowsService.ExceptionLog";
                if (!EventLog.SourceExists(SourceName))
                {
                    EventLog.CreateEventSource(SourceName, "Application");
                }

                EventLog eventLog = new EventLog();
                eventLog.Source = SourceName;
                string message = string.Format("Exception: {0} \n\nStack: {1}", ex.Message, ex.StackTrace);
                eventLog.WriteEntry(message, EventLogEntryType.Error);
            }
        }
    }
}

Install your Windows Service on the server and attempt to start it up. You will still get your error 1053 message. Now you can go to Event Viewer (Look for it under Administrative Tools in the Start menu or type eventvwr into Run). Click through to the Application log and you will see an error logged under "WindowsService.ExceptionLog". Open it up and read the details to find a full stack trace of whatever exception it was that has been stopping you all this time!

You should now be able to solve the problem pretty quickly…

Final note

When I was working on this solution I was building my Windows Service in Release mode. This was one of the things that I tried early on thinking it might not work in Debug mode on the server. Each time I tested out my service I would delete all files from the ftp folder and then upload the whole Release folder. This meant that the .pdb files were uploaded next to the Windows Service executable.

I haven't tested it both ways but as far as I know the pdb file has to be there for the application to emit the line numbers in the stack trace. It can't hurt to include them while your doing this debugging.

Hopefully once you get over this hurdle you will start seeing Windows Services as a fun application

kick it Shout it vote it on WebDevVote.com

13 comments:

Anonymous said...

In case it's of use to anyone, I was encountering this error when using encrypted sections of the config file for my Windows service. We do this for Web sites all the time, and make sure to grant the IIS worker process access to the RSA key that's used to decrypt the config file. However, when your Windows service is running as LocalService, it can't access that key and decrypt the config file. If you elevate it to run as NetworkService, then it's OK.

tahir said...

Hey thanks man... it really helped me find n locate the exact error.. gr8 ..tc

Nizam said...

see i was having the same problem about this error..i download the HTC home for windows from a website..then i try to run it but after several seconds, and error message pops out telling something like this..can you solve it please..mail me at nzdesign@live.com

problem:

Problem signature:
Problem Event Name: CLR20r3
Problem Signature 01: htchome.exe
Problem Signature 02: 2.0.122.0
Problem Signature 03: 4c7a83a9
Problem Signature 04: System
Problem Signature 05: 4.0.0.0
Problem Signature 06: 4ba1dff4
Problem Signature 07: 1b9d
Problem Signature 08: 1f3
Problem Signature 09: System.Net.WebException
OS Version: 6.1.7600.2.0.0.256.1
Locale ID: 17417
Additional Information 1: 0a9e
Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
Additional Information 3: 0a9e
Additional Information 4: 0a9e372d3b4ad19135b953a78882e789

Read our privacy statement online:
http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409

If the online privacy statement is not available, please read our privacy statement offline:
C:\Windows\system32\en-US\erofflps.txt

thank you in advance

Anonymous said...

Holy crap ... you just saved my sanity. Was doing exactly the same with a File System Watcher ... I was looking through dependency walkers, installing service packs, trawling discussions boards ... awesome. I have -5 minutes to get this up and running.

Anonymous said...

Thanks a lot, you have saved my day :)

Cory Mathews said...

I ran into this problem as well, except my app is far to large to solve with your method above (which works as well). I ended up having to use the IL Disassembler and parts of the error message to discover why it was crashing after all.

http://corymathews.com/eventtype-clr20r3-p1-w3wp-exe-system-nullreferenceexception/

Vikash Anil said...

Silly Me.

Great. Resolved my Issue. Wasted 8 hours.

Thanks.

Anonymous said...

i got fixed my issue.but just i have to do is stat my event log service

Mike Harmon said...

I was having issues with a scheduled C# process running on a VM. With my username it worked ok but with the generic name it wouldn't work. So I looked and found that the generic didn't have permission to read a config file.

Anonymous said...

Getting the same error as you are. Added your try...catch block. Doesn't write to the event log. Could that code not be running at all?

Anonymous said...

The popup said that you should run a chkdsk so I am going to do that before taking this advise

rtpHarry said...

Hey, not sure what popup you are referring to but don't see how chkdsk would solve the problem I'm describing. It sounds more like you have clicked a spammy advert to install a pc tune up tool.

Doug said...

Thanks so much! I struggled with this for about 6 hours yesterday, and the try/catch enabled me to run the error down exactly. It seems that I had two event logs and the first 8 characters were the same, so it was a no-go. Funny Microsoft is still caught up in the old 8.3 naming convention, even after all these years. Thanks again


-->