I'm trying to write to the application event log. The following code executes without error under Windows 8 (when run with admin privileges), but I don't see any events showing up when looking at the Application log in the Windows Event Viewer. Can anyone help me figure out what I'm doing wrong. Do I need to add something to app.config?
using System.Diagnostics;
namespace tracetest2
{
class Program
{
static void Main(string[] args)
{
if (!EventLog.SourceExists("TestSource"))
{
EventLog.CreateEventSource("TestSource", "Application");
}
EventLog appLog = new EventLog("Application", ".", "TestSource");
appLog.EnableRaisingEvents = true;
appLog.EndInit();
Debug.WriteLine(appLog.Entries.Count);
appLog.WriteEntry("An entry to the Application event log.");
Debug.WriteLine(appLog.Entries.Count);
}
}
}
According to the Microsoft website, we have the following information:
Note:
If a source has already been mapped to a log and you remap it to a new log, you must restart the computer for the changes to take effect.
The machine must be restarted every time you create a new custom event key. (Or just restart the EventViewer service) :)
Related
I'm trying to run some console app as windows service, I followed this question, and I made a few changes to make it fit to my app.
My main code looks like that:
public static class Program
{
public class Service : ServiceBase
{
public Service(string serviceName)
{
this.ServiceName = serviceName;
}
protected override void OnStart(string[] args)
{
Program.Start(args);
}
protected override void OnStop()
{
Program.Stop(this.ServiceName);
}
}
#endregion
static void Main(string[] args)
{
if (!Environment.UserInteractive)
// running as service
using (var service = new Service("TestService"))
ServiceBase.Run(service);
else
{
// running as console app
Start(args);
}
}
private static void Start(string[] args)
{
while(true)
{
//DO SOMTHING
}
}
private static void Stop(string serviceName)
{
//Writing to log that 'serviceName' stopped
}
}
I tried to run the following console app as a service, by using the following steps:
1) Use the command: sc create ServiceTestName123 binPath= "PATH TO THE EXE FILE IN THE PROJECT DEBUG FOLDER".
2) Use the command: sc start ServiceTestName123 "parameter1".
And I got an error:
"StartService FAILED 1053:
The service did not respond to the start or control request in a timely fashion"
I read about the error in the internet and found out that I can try to solve this problem by running the start function with another thread, so I updated the OnStart function to the following function:
protected override void OnStart(string[] args)
{
Thread t = new Thread(() => Program.Start(args));
t.Start();
}
After trying to re-create the service (delete the old one and create the service again with the new OnStart function) and re-run it I got the same error.
By the way, when I ran this code as console app it worked properly.
Could someone please explaing me what am I doing wrong?
Thanks a lot.
I tried your exact steps and it worked for me. I will highlight a few key points that I came across
OnStart should definitely return in a timely fashion. i.e. the work should happen in a separate process/thread. I used your code for thread and it worked fine for me.
Make sure the executable is on a local drive which can be accessed from your "Local System" account without any permission issues.
Make sure when you create the service, you provide the absolute path and not relative path.
Make sure the sc create ... command responds back with [SC] CreateService SUCCESS
Check the service was created in the service control panel
Make sure you can start it from the service control panel before attempting it from command line
Also, open task manager or process explorer to make sure the service executable is running or not (irrespective of what status is returned by service control panel or scm start)
For debugging, I logged the information into a local temp file - again watch out for permissions issues with Local System account.
If for whatever reasons you have to delete the service, make sure that it indeed disappeared from the service control panel
To debug what's going on, you can attach the debugger at the very beggining of your program start up.
This way, you can check what your program is doing.
You can also check in the Windows ever viewer, the error that windows is throwing.
Put this line at the start trace of your program:
System.Diagnostics.Debugger.Launch()
First time posting long time reader.
I built a working filewatcher inside of a windows forms application functioning 100% properly before moving it to a windows Service and am now recieving two seperate issues. This file watcher reads a flatfile for line updates(lastwrite), deletes/recreates file(streamwriter), and finally parses through a strongly typed data set and then uploads to an SQL server.
(This is my first Windows Service)
Questions:
1. Does the double event trigger in filewatcher effect the service differently then a forms application?
2. Does anyone have an answer about why the thread will break if the class I am calling has no issue?
3. Are there any known issues with Windows Authentication through a windows service?
4. Does anyone have any strong debug methods for windows services?
Here is my code from the windows Service, thanks in advance and my apologies if there is a silly mistake in the code, again first time making a windows service.
FileMonitor m_FileMonitor;
public WindowsService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
Thread myThread = new Thread(DoTheWork);
myThread.Start();
}
catch
{
}
}
void DoTheWork()
{
m_FileMonitor = new FileMonitor(Properties.Settings.Default.PathToFileToWatch, Properties.Settings.Default.PathToErrorLog);
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
For debugging, make sure your project type is Windows Application, and then use this:
[DllImport("kernel32")]
static extern bool AllocConsole();
private static void Main(string[] args)
{
var service = new MyService();
var controller = ServiceController.GetServices().FirstOrDefault(c => c.ServiceName == service.ServiceName);
if (null != controller && controller.Status == ServiceControllerStatus.StartPending)
{
ServiceBase.Run(service);
}
else
{
if (AllocConsole())
{
service.OnStart(args);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
service.OnStop();
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}
If the code is running because the Windows Service was started, it will run as a Windows Service. Otherwise it will allocate a console, run the service, then wait for a key press before exiting the service. You could build on this for testing pause and continue.
For debugging:
You have to use the ServiceBase.Run method in Main() to execute as a windows service, but you can make a switch in the main method to run the same application as a normal console application (e.g. --standalone). I'm using this on all my services to make them easy to debug.
Regarding the other problems:
I'm not completely sure which problems you encounter and what you mean by "class break" and "double event trigger".
Windows services run under a special service account, which might or might not have permissions to watch the directory you are interested in. You can change the service account or give it permission for the directory if you need to.
Links:
Here is a link to a codeproject article who seems to have implemented a file watcher windows service. Maybe it helps:
http://www.codeproject.com/Articles/18521/How-to-implement-a-simple-filewatcher-Windows-serv
I'm developing a service using .NET on Windows platforms.
It had worked until yesterday... but today it doesn't want to start!!! It seems strange, and I feel I'm missing something...
I've also tried to revert sources to the last working version, but nothing else happens: net start outputs:
The service is not responding to the control function.
What could cause this malfunction?
Probably most of you wants to know more about it. So, let me show you some code:
The service code:
#if DEBUG
class iGeckoService : DebuggableService
#else
class iGeckoService : ServiceBase
#endif
{
static void Main()
{
#if DEBUG
if (Debugger.IsAttached == true) {
DebuggableService[] services = Services;
// Create console
AllocConsole();
// Emulate ServiceBase.Run
foreach (DebuggableService service in services)
service.Start(null);
// Wait for new line
Console.WriteLine("Press ENTER to exit..."); Console.ReadLine();
// Emulate ServiceBase.Run
foreach (DebuggableService service in services)
service.Stop();
} else
ServiceBase.Run(Services);
#else
ServiceBase.Run(Services);
#endif
}
#if DEBUG
static DebuggableService[] Services
{
get {
return (new DebuggableService[] { new iGeckoService() });
}
}
[DllImport("kernel32")]
static extern bool AllocConsole();
#else
static DebuggableService[] Services
{
get {
return (new ServiceBase[] { new iGeckoService() });
}
}
#endif
#endregion
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
public iGeckoService()
{
// Base properties
ServiceName = DefaultServiceName;
// Service feature - Power events
}
#endregion
protected override void OnStart(string[] args)
{
try {
...
} catch (Exception e) {
sLog.Error("Unable to initialize the service. Request to stop.", e);
}
}
/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
...
}
}
[RunInstaller(true)]
public class iGeckoDaemonInstaller : Installer
{
/// <summary>
/// Default constructor.
/// </summary>
public iGeckoDaemonInstaller()
{
ServiceProcessInstaller spi = new ServiceProcessInstaller();
spi.Account = ServiceAccount.LocalSystem;
ServiceInstaller si = new ServiceInstaller();
si.ServiceName = iGeckoService.DefaultServiceName;
si.StartType = ServiceStartMode.Automatic;
Installers.AddRange(new Installer[] {spi, si});
}
}
class DebuggableService : ServiceBase
{
public void Start(string[] args) { OnStart(args); }
}
The start script is:
installutil ..\bin\Debug\iGeckoService.exe
net start "Gecko Videowall"
while the stop script is:
net stop "Gecko Videowall"
installutil /u ..\bin\Debug\iGeckoService.exe
However, I think it is a system setting, since the application has worked well until the last day. (Sigh).
Update
When the service was working, I used log4net for logging service activity (I'm unable to attach the debugger to the running service...), and it has always logged.
From now, the log4net log it is never created (even if I enable internal debug option), even if I log at the Main routine!
Another update
It seems that the application is never executed. I've reduced every routine (Main, OnStart, OnStop), and I run an empty service. OnStart routine creates a file on a directory (fully writeable by everyone), but when the service is started, no file is created.
Yet another update
Stimulated by the Rob's comment, I've seen this message on the event viewer:
> Faulting application name: iGeckoService.exe, version: 1.0.0.0, time stamp: 0x4c60de6a
> Faulting module name: ntdll.dll, version: 6.1.7600.16385, time stamp: 0x4a5be02b
> Exception code: 0x80000003
> Fault offset: 0x000000000004f190
> Faulting process id: 0x1258
> Faulting application start time: 0x01cb384a726c7167
> Faulting application path: C:\Users\Luca\Documents\Projects\iGeckoSvn\iGeckoService\bin\Debug\iGeckoService.exe
> Faulting module path: C:\Windows\SYSTEM32\ntdll.dll
> Report Id: b096a237-a43d-11df-afc4-001e8c414537
This is, definitively, the reason on the service shutdown... not question becomes: "How to debug it?" (Thank you Rob, I've never thought about the event viewer until now!)
Debugging it running as console application it doesn't show any error, indeed it seems related to the service environment. The only thing that comes to my mind could be some DLL loading failure, since now the service is empty... any idea?
(Thank you all for following me... I'd like to offer you pizza & beer)
Solved!
The service was unable to start since a crash before the Main routine, caused by the installation and the setup of the MS Application Verifier (x64). After having uninstalled that application, everything worked as usual!
Thank you all!
In general every service must do following two simple things
if the service manager send him a control code like SERVICE_CONTROL_START, SERVICE_CONTROL_STOP and so on if should return in a short interval. Using SetServiceStatus function service can prolong this interval for example with calling SetServiceStatus with incremented dwCheckPoint value. (In .NET use can use ServiceBase.RequestAdditionalTime instead)
every service must answer to SERVICE_CONTROL_INTERROGATE control code just with return. This control code are used from the service manager to detect whether the service still living.
If your program don't follow one of the rules you receive the error "The service is not responding to the control function."
If you write a program in .NET you don't need to do directly the two things which I described before. The ServiceBase class do there for you. Nevertheless you can easy break this rules if create a thread running with priority higher as normal or if you do some too long work inside an OnXXX handle (OnStop, OnStart, OnPowerEvent etc) without calling of ServiceBase.RequestAdditionalTime. Some other tricks with additional threads can also make problems.
Usually this happens if you're trying to do too much work in the OnStart call. For example, if you start an endless loop in the same thread, you'll get this error message.
Generally the service should create a new thread in the OnStart call, and then cleanly terminate it in the OnStop call.
Of course that doesn't help if you're using code which was previously working. Have you tried rebooting it since the failure? I seem to remember that if you've already got a service which is borked, it can sometimes be tricky to get back to a working state without rebooting it. You may want to look in your process list and see whether you've got a copy still running, and kill it if so.
For me it just meant that an exception was being thrown. (Platform conflict in Configuration Manager, resulting in "bad image format".) Try running the .exe from the command line and see if you get an error.
I see that there is a code block
// Wait for new line
Console.WriteLine("Press ENTER to exit..."); Console.ReadLine();
as stated by #Jon since this is a service. when service starts it waits for a stipulated time within which it should respond.
there is a statement "Console.ReadLine()" you service will wait until key is pressed. since this is a service will keep waiting at this point
For me it was an error in the file that is configured to the windows service. I found a syntax error due to which I was getting this error code.
Fixed the syntax error and I was able to restart the service again.
Is it possible to get shutdown reason in Windows Server 2008 immediately after user choose the reason in dialog window? For the shutdown event I'm using SystemEvents.SessionEnding.
I want to write windows service, which will send e-mail about this event.
Or is there any other way in windows server to send e-mails about shutdown/restart event with getting the reason entered by user? Also, I want to notify about power source change (electic line/battery), but this I have already solved by Kernel32.dll > GetSystemPowerStatus.
You can get the shutdown reason inspecting the EventLog.
I assembled a quick demo on Windows Forms that you can adapt to your Windows service.
I've added a EventLog component to the Form and configured it properly. The snippet below shows the code generated in InitializeComponent() for the settings I've maid through the designer.
this.eventLog1.EnableRaisingEvents = true;
this.eventLog1.Log = "System";
this.eventLog1.Source = "USER32";
this.eventLog1.SynchronizingObject = this;
this.eventLog1.EntryWritten += new System.Diagnostics.EntryWrittenEventHandler(this.eventLog1_EntryWritten);
On the event handler, you'll have something along the following lines:
private void eventLog1_EntryWritten(object sender, System.Diagnostics.EntryWrittenEventArgs e)
{
EventLogEntry entry = e.Entry;
if (e.Entry.EventID == 1074)
{
File.AppendAllText(#"c:\message.txt", entry.Message);
}
}
Take a look at your event log to see the appropriate EventIds to filter out.
The compiler will warn you about EventID being deprecated and telling you that you should use InstanceId, but in the quick tests I've done here, it didn't write to my log file and I think we already have enough information to put you on track.
sure it's possible.
in case you want to get that comboBox value in real-time, you will need to run a Thread monitor on that process to raise an event when that value change.
when i am using below code with windows application it always fires WOrkBookOpen event.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Microsoft.Office.Interop.Excel.Application app;
private void button1_Click(object sender, EventArgs e)
{
app = new Microsoft.Office.Interop.Excel.Application();
app.WorkbookOpen += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookOpenEventHandler(app_WorkbookOpen);
app.WorkbookActivate += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookActivateEventHandler(app_WorkbookActivate);
}
void app_WorkbookActivate(Microsoft.Office.Interop.Excel.Workbook Wb)
{
MessageBox.Show(Wb.FullName);
}
void app_WorkbookOpen(Microsoft.Office.Interop.Excel.Workbook Wb)
{
MessageBox.Show(Wb.FullName);
}
private void button2_Click(object sender, EventArgs e)
{
app.Quit();
Marshal.FinalReleaseComObject(app);
}
}
But when I want to fire same event using windows service its not firing. Below is the code used for service. I am creating Excel interop object in OnStart() of service and attaching same event. But after installation of service this event doesnt fire. whereas in same windows application it fires up. Here for testing purpose i am creating FIle on my disk to check if event is firing or not.
public partial class Service1 : ServiceBase
{
Microsoft.Office.Interop.Excel.Application excel;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
File.Create("C:\\SampleService\\Start - " + DateTime.Now.Ticks.ToString());
excel = new Microsoft.Office.Interop.Excel.Application();
excel.WorkbookOpen += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookOpenEventHandler(excel_WorkbookOpen);
excel.WorkbookActivate += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookActivateEventHandler(excel_WorkbookActivate);
File.Create("C:\\SampleService\\Start - " + DateTime.Now.Ticks.ToString());
}
catch (Exception e)
{
using (StreamWriter stream = new StreamWriter(#"C:\SampleService\Err.txt", true))
{
stream.Write(e.Message);
}
}
}
void excel_WorkbookActivate(Microsoft.Office.Interop.Excel.Workbook Wb)
{
File.Create("C:\\SampleService\\EXCEL - " + DateTime.Now.Ticks.ToString());
}
public void excel_WorkbookOpen(Microsoft.Office.Interop.Excel.Workbook Wb)
{
File.Create("C:\\SampleService\\EXCEL - " + DateTime.Now.Ticks.ToString());
}
protected override void OnStop()
{
if (excel != null)
{
excel.Quit();
Marshal.FinalReleaseComObject(excel);
}
}
}
I have also using serviceInstaller and i am installling service on machine. I am giving proper rights to service to create object of Excel.Application com component.
Is anyone came across such issue? Or do you find I am missing anything?
Thanks
Paresh
What account is your service running under? If it is SYSTEM make sure the option Allow service to interact with desktop is checked. Alternatively, try running your service under a normal user account.
First, it appears that you are trying to log excel files opening using a service and excel.application object. This is not a very good solution, and you will find it gives inconsistent results at best.
The Excel.Application object will be created within your application under the service account. This service may or may not be able to interact with the desktop, depending on your service settings. The user, however, will always be able to open the excel application within their user account.
Second, if you are running the excel object service from the system account, you are opening yourself up for a huge security problem. Office documents are a huge source for all kinds of malware, and you will be giving anything opened under it a level of access to your system not even the administrator has. You should not be opening documents under a privileged account without considering the security ramifications.
Third, many of the events in excel are specific to the gui, and if their is not a visible window, they may not fire. I learned this the hard way many years ago under 2000, and since then I have really limited my dependence on them.
If I may make some recommendations,
If your intent is to monitor who opens a file, consider using the file system security / logging built into windows. It can be set to audit a file and write to the security event log when the file is accessed. This information can easily be retrieved over the network with WMI.
Do not run anything under a privileged account unless you are certain of what it will do. Your excel files may be fine right now, but one user bringing in a macro virus could be disastrous.
If you must write your own "logging", consider using a global hook to monitor (monitor only, not change or modify) file opens by excel. A quickie hook application that only logs when an excel file is opened will not effect system performance, and will be much safer and more stable than what you are suggesting. If you are unfamiliar with hooks, desaware used to make some great components for hooking and subclassing and you should check them out. Unless you are very familiar with that the program is doing, though, only monitor the messages, don't attempt to "handle" them for excel.
An Excel addin is just a file that adds custom functions or functionality to excel, it is most commonly VBA in an xll or xla file. If you need security, do not depend on an addin to monitor file access because they can easily be disabled.
The most effective way to monitor who opens a file will be using file auditing that is built into NTFS.