I'm developing a new windows service and I follow the steps provided in this instruction.
In the service class, I do pretty much the same things as the article
static EventLog _eventLog;
public CMSMetadata()
{
InitializeComponent();
_eventLog = new EventLog();
if (!EventLog.SourceExists("CMSMetadata_Processing"))
{
EventLog.CreateEventSource(new EventSourceCreationData("CMSMetadata_Processing", "CMSMetadata"));
}
_eventLog.Source = "CMSMetadata_Processing";
_eventLog.Log = "CMSMetadata";
}
protected override void OnStart(string[] args)
{
_eventLog.WriteEntry("In OnStart.", EventLogEntryType.Information);
}
After I installed and try to start the service, it shows me the following error
Error 1053: the service did not respond to the start or control
request in a timely fashion
And I also notice CreateEventSource() does not create the event log entry when I look for it in the event viewer.
I found this SO post is discussing the 1053 error I'm facing but none of the solutions works for me.
I have confirmed/tried
The service is built by release mode.
Install by both InstallUtil and ManagedInstallerClass.InstallHelper()
The framework version matches what I have installed, actually, I
tried 4.5.2 and 4.7.2 in case somehow it really has something to do with
the framework.
The service is running as local system.
The config is alright.
If I remove every code related to event log the service can be launched successfully.
Then I think fine if the service somehow can't create event log entry properly maybe I can create the entry in advance as a workaround.
However, in this way, I won't even able to install the service.
The install log (CMSMetadata.InstallLog) as below indicates somehow the installation will create the event source no matter I'm using CreateEventSource() or not.
Installing assembly 'C:\temp\GisSoftware\CMSMetadata\CMSMetadata.exe'.
Affected parameters are:
logtoconsole =
logfile = C:\temp\GisSoftware\CMSMetadata\CMSMetadata.InstallLog
assemblypath = C:\temp\GisSoftware\CMSMetadata\CMSMetadata.exe
Installing service CMSMetadata...
Service CMSMetadata has been successfully installed.
Creating EventLog source CMSMetadata in log Application...
Rolling back assembly 'C:\temp\GisSoftware\CMSMetadata\CMSMetadata.exe'.
Affected parameters are:
logtoconsole =
logfile = C:\temp\GisSoftware\CMSMetadata\CMSMetadata.InstallLog
assemblypath = C:\temp\GisSoftware\CMSMetadata\CMSMetadata.exe
Restoring event log to previous state for source CMSMetadata.
Service CMSMetadata is being removed from the system...
Service CMSMetadata was successfully removed from the system.
To conclude my question, What did I miss to use the event log in windows service?
It seems the service does create an event log by default. I should probably set AutoLog property of Service to false before generate the Installer.
Find the EventLogInstaller insides the ServiceInstaller and modify the log and source fixed my problem(also remember to remove the eventlog entry creation in service ctor).
public ProjectInstaller()
{
InitializeComponent();
EventLogInstaller installer = this.Installers.OfType<ServiceInstaller>().First()
.Installers.OfType<EventLogInstaller>().First();
installer.Source = _source;
installer.Log = _logName;
}
Moreover, it seems better to create eventlog during the installation instead of service ctor since it appears the permission of LocalSystem to access registry is limited.
ref: Easiest language for creating a Windows service
I have created a windows service to send mail when service is started. The service works fine like it sends mail when i debug the service and run it via code. But the service is not working after i install it. It is not sending any mail after i install the service.
Can anyone please suggest me the solution?
There is an excellent chance that the service lacks permission to perform one or more actions when run as a service account.
Check the Windows Event Log for any related error messages. As a test, you can configure your service to run as the same user you log on with (just to make sure the issue is permission based... do NOT leave that configuration active as it is a major security hole).
Debugging service is a bit difficult.
use try..catch block with writing messages to file in every method; for example
try
{
..
}
catch(Exception ex)
{
SaveMessage(ex.ToString());
}
Save message method would be:
static void SaveMessage(string s)
{
StreamWriter sw = new StreamWriter(#"C:\service_exceptions_file.txt", true);
sw.WriteLine(s);
sw.Close();
}
Then you will see where is the problem.
Also you can add some messages in your code via abovementioned method to see what parts of code are working without problems
In your Main() method, just add the following lines before ServiceBase.Run(ServicesToRun); :
#if DEBUG
while(!Debugger.IsAttached)
{
Thread.Sleep(1000);
}
#endif
Then install your service and launch it.
While it's launching, attach your debugger to your service's process (Debug Menu => Attach to process) and you should be able to debug it.
Don't forget to set your breakpoints before launching your service.
i did set start my windows service or NT service like everybody says a then
came up this message:
The service myService on local computer started an then stopped.Some services stop automatically if they are not in use by another services or programs
i've started other services and it never hapened...
before i change the value of a parameter that have to find it's value on a web service method
that look on a sql database...
and other change is that got formatted the hard disk...maybe i have to enable somethig
please i need help
It happens most likely because
you have an exception at startup... try to debug your things either by
using a log or by trying to reproduce your behavior in a windows app....
You can even debug your windows service using the following method...
Write the following code in your Service file...
public void OnDebug()
{
OnStart(null);
}
In the program file,
YourService myService = new YourService();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
This can happen when the logic performed using a windows service exceeds the default timeout.
We cannot overcome the default timeout of a windows service. Usually windows services are used to instantiate a method. So start a child thread within the OnStart event of the windows service and call your method within it.
If this is not solving your issue, put the code in try catch and log the exceptions. This error can happen if there is any exception within OnStart event too.
I read the MSDN article on the topic. To quote:
Because a service must be run from
within the context of the Services
Control Manager rather than from
within Visual Studio, debugging a
service is not as straightforward as
debugging other Visual Studio
application types. To debug a service,
you must start the service and then
attach a debugger to the process in
which it is running. You can then
debug your application using all of
the standard debugging functionality
of Visual Studio.
Now my problem is that my service fails to start in the first place. First it crashes, and says:
An unhandled exception
(System.Runtime.InteropServices.COMException)
occurred in MyServiceName.exe[3596])
and suggests me to debug it (the debugger instance instantly crashes when I choose one). Then it says
Could not start the MyServiceName
service on Local Computer. Error
1053: The service did not respond to
the start or control request in a
timely fashion
So, how can I investigate/debug the reason that my service won't start? The thing is I created a console application that does EXACTLY what the service does and it works fine. (I mean I just copied the OnStart() method's and the main loop's contents to main).
Any help would be appreciated.
The Service is written in C# with heavy use of interop. I am using VS2008
You could use a parameter to let your application decide whether to start as service or regular app (i.e. in this case show a Form or start the service):
static void Main(string[] args)
{
if ((1 == args.Length) && ("-runAsApp" == args[0]))
{
Application.Run(new application_form());
}
else
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
}
Now if you pass the parameter "-runAsApp" you can debug the application normally - the SCM won't pass this parameter, so you can also use it as service w/o any code change (provided you derive from ServiceBase)
Edit:
The other difference with windows services is identity (this might be especially important with InterOp) - you want to make sure you are testing under the same identity in "app" mode as well as service mode.
To do so you can use impersonation (I can post a C# wrapper if it helps, but this can be easily googled) in app mode to use the same identity your windows service will be running under i.e. usually LocalService or NetworkService.
If another identity is required you can add settings to the app.config that allow you to decide whether to use credentials, and if so which user to impersonate - these settings would be active when running as app, but turned off for the windows service (since the service is already running under the desired identity):
<appSettings>
<add key="useCredentials" value="false"/>
<add key="user" value="Foo"/>
<add key="password" value="Bar"/>
</appSettings>
I usually just manually set a breakpoint, then point it to the currently open project in c#. The code to set a breakpoint is:
System.Diagnostics.Debugger.Break();
That should get you started, then you can just step through your code and see what's really happening.
I stole this from C. Lawrence Wenham, so I can't really take credit, but you can programmatically attach a debugger to a service, WITHOUT breaking execution at that point, with the following code:
System.Diagnostics.Debugger.Launch();
Put this in your service's OnStart() method, as the first line, and it will prompt you to choose an instance of VS to attach its debugger. From there, the system will stop at breakpoints you set, and on exceptions thrown out. I would put an #if DEBUG clause around the code so a Release build won't include it; or you can just strip it out after you find the problem.
You can use WinDbg/NTSD (another debugger from the "Debugging tools for windows" package) to start a debugger together with your service.
To do this open "gflags" (also available in the above mentioned package) to the "Image file" tab and set the path to debugger executable for your image file (service);
If your service is marked as interactive (only possible if it runs under the SYSTEM account) you can directly start WinDbg, just set the debugger to something like "PATH_TO_WINDBG\windbg.exe -g -G" (the -g / -G are needed so that the debugger doesn't break execution on application start or end - the default behaviour). Now when starting your service the windbg window should pop-up and will catch any unhandled exception.
If your service is not interactive you can start the NTSD debugger (a command line debugger) in remote mode and connect to it from WinDbg (that can even be running in another PC). To do this set the debugger in gflags to something like "PATH_TO_NTSD\ntsd -remote tcp:port=6666,server=localhost". Then connect to the remote debugger by starting windbg with something like "windbg -remote tcp:port=6666,server=localhost" and you should have complete control over the other debugging session.
As for finding the source of the exception itself a windbg tutorial is over the topic here but as a start try to execute the "!analyze -v" command after the exception was caught - with some luck this is all information you'll need..
Note: maybe this is overkill for your case but with this approach you can even debug services during system start-up (I had once a timing problem with a service had an issue only when starting the first time with the system)
One thing I do (which may be kind of a hack) is put a Thread.Sleep(10000) right at the beginning of my OnStart() method. This gives me a 10-second window to attach my debugger to the service before it does anything else.
Of course I remove the Thread.Sleep() statement when I'm done debugging.
One other thing you may do is the following:
public override void OnStart()
{
try
{
// all your OnStart() logic here
}
catch(Exception ex)
{
// Log ex.Message
if (!EventLog.SourceExists("MyApplication"))
EventLog.CreateEventSource("MyApplication", "Application");
EventLog.WriteEntry("MyApplication", "Failed to start: " + ex.Message);
throw;
}
}
When you log ex.Message, you may get a more detailed error message. Furthermore, you could just log ex.ToString() to get the whole stack trace, and if your .pdb files are in the same directory as your executable, it will even tell you what line the Exception occurred on.
Add lots of verbose logging in your OnStart. It's painful and old school, but it works.
Seems like the problem is with the user context. Let me confirm whether my assumptions are right.
When you say that the code works perfectly from console application, I assume you are executing the Console application under the same user which you had logged in.
When you say that the same code crashes while called from the windows service, I assume the service is running in "Local System" account in your development machine.
If both my assumptions are right, please try out the following steps.
In the services listing right-click your service, select properties and then "Log On" tab.
Select the option "This account" and provide the existing username and password.
Now try starting the service. It should now start without any errors.
Following could be the root cause of your error
If you are using SQL Server make sure you are not using SSPI authentication.
If you are trying to read any shared folder\resource which you don't have permission when using "local system" account.
If any of the required dependencies required by the application is in a different folder which the "Local System" user doesn't have permission to access.
If you are using VBA automation which wont work in "Local System" account.
Try disabling your firewall or antivirus.
You could add some logging around the interop calls to find out which one fails.
Also services by default aren't associated with a desktop; if you open the services.msc control panel applet, get the properties of your service, go to the "Log On" tab, you could check "Allow service to interact with desktop". This could fix the problem for you in some cases.
I would assume the reason could be causing because of heavy use of interops. So you need to tackle this problem differently. I would suggest create a windows or console app with same logic of you service and make sure that it works first without any issues, and then you may want to go with creation of the Win service.
Debugging services is a pain, particularly since startup seems to be when many of the problems manifest (at least for us).
What we typically do is extract as much of the logic as possible to a single class that has start and stop methods. Those class methods are all that the service calls directly. We then create a WinForm application that has two buttons: one to invoke start, another to invoke stop. We can then run this WinForm applicaiton directly from the debugger and see what is happening.
Not the most elegant solution, but it works for us.
Check out this question, which discusses how to catch unhandled exceptions in a window service.
In order to attach a debugger to the Windows Service, it needs to be started first. The reason why the service failed to start can be checked in Windows Event Log.
After that the process of attaching a debugger is pretty straight forward from Visual Studio Debug->Attach To Process.
What I've done is implemented by OnStart() to look something like this:
_myBusinessObject = new MyBusinessObject();
After the Business Object has been constructed, timers and IPC handlers do all the real (Service) work.
Doing it like this allows you to create a Forms/WPF application that call the same code above in the Form_Loaded handler. This way, debugging the Forms application is the exact same as debugging the Service.
The only issue is that if you are using app.config values, there will be a second app.config file that needs to be kept up-to-date.
Use following Code in Service OnStart Method:
System.Diagnostics.Debugger.Launch();
Choose Visual Studio option from Pop Up message
read the 2 articles mentioned here:
http://geekswithblogs.net/BlackRabbitCoder/archive/2011/03/01/c-toolbox-debug-able-self-installable-windows-service-template-redux.aspx
Step 1 - Add #if region to your Program.cs
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new StockInfoService()
};
ServiceBase.Run(ServicesToRun);
#if (!DEBUG)
ServiceBase[] ServicesToRun = new ServiceBase[] { new SqlBackupService() };
ServiceBase.Run(ServicesToRun);
#else
StockInfoService service = new StockInfoService();
service.OnStart();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif
}
Step 2 - In Service.cs change your OnStart(string[] args) method without parameter one. (I commended mine.)
public void OnStart()
//protected override void OnStart(string[] args)
{
**Do your thing.
}
Step 3 - Simply hit Start (F5) and debug your code.
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.