Windows Service with FileSystemWatcher stops after the first event - c#

I'm building a simple Windows Service (basically combining this tutorial with this class).
Now I have a "FROM" directory and two "TO" (TO1, TO2) directories. When I place a file into FROM, it should be copied both to TO1 and TO2. I install the service and I start it in the Service Control Manager where I see it's running. On the first run, it copies the file to TO1 and TO2 and the service is still running after that.
Then, when I place another file to FROM (with a different name), nothing happens. And refreshing the services I find that the service stopped.
Why does the service stop? It seems it stops just in the moment when I place the second file.
Here I register the file system watcher:
// File System Watcher
var fileSystemWatcher = new FileSystemWatcher();
fileSystemWatcher.Created += FileSystemWatcher_MoveOnCreate;
fileSystemWatcher.Path = this.fromPath;
fileSystemWatcher.EnableRaisingEvents = true;
And here is the event handler:
private void FileSystemWatcher_MoveOnCreate(object sender, FileSystemEventArgs e)
{
string FROM = Path.Combine(fromPath, e.Name);
string TO1 = Path.Combine(toPathOne, e.Name);
string TO2 = Path.Combine(toPathTwo, e.Name);
File.Copy(FROM, TO1);
File.Copy(FROM, TO2)
}

If the Windows Service stops there was an unhandled exception in your code somewhere. Try to surround the key point of your code ( maybe the entire body of the function FileSystemWatcher_MoveOnCreate ) with try{}catch(){} and log what's happening. In general you should add log to your windows service is the only way you can understand if things are going on anyway.

Related

Writing Events to Specific EventViewer

I have read multiple articles and SO questions on the Windows Event Viewer. However, I am still unable to accomplish my goal. I have a Windows Service that I'll call "Social". I want to write information from this Windows Service to the Windows Event Viewer. At this time, I'm trying the following:
var message = "Test Log";
using (var sw = File.AppendText(AppDomain.CurrentDomain.BaseDirectory + "test.txt"))
{
sw.WriteLine(message);
}
var eventLog = new EventLog();
eventLog.Source = "Service";
eventLog.Log = "Social";
eventLog.BeginInit();
if (EventLog.SourceExists(eventLog.Source) == false)
{
EventLog.CreateEventSource(eventLog.Source, "Social");
}
eventLog.EndInit();
eventLog.WriteEntry(message, EventLogEntryType.Information);
I added the "test.txt" file just to ensure my code was being reached. That code runs fine. However, I never see my message written in the Event Viewer. In fact, I never see a new Event source get created. I was expecting to go to the Windows Event Viewer and see a new item located at "Event Viewer -> Applications and Services Logs -> Social Media Analyzer". However, I do not see that anywere.
Notably, the "Social" log exists in the event viewer. However, nothing gets written to it. The logs get written to the "Application" log instead. It's almost like the Windows Service is ignoring the fact that I want to write to a specific log.
What am I doing wrong?
eventLog.Log = "Application";
...
EventLog.CreateEventSource(eventLog.Source, "Application");
You're writing your events to the Application Log under "Windows Logs". The events should specify the Source (column) as being "Social Media Analyzer".
If you want to write to a custom log you need something like
EventLog.CreateEventSource("MyEventSource", "Social Media Analyzer");

Extract values from the Open with dialog

In my C# Winforms application I implemented a watcher that notify me when a new process starts in the local OS.
ManagementEventWatcher watcher = new ManagementEventWatcher(new ManagementScope("\\\\.\\root\\cimv2"), new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 0, 1), "TargetInstance ISA 'Win32_Process'"));
watcher.Scope.Options.EnablePrivileges = true;
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
I'm not directly interested in the process started but in an eventual file that caused the process to start.
Think about a double click on "d:\documents\doc.txt" that causes notepad.exe to be launched.
The watcher notifies me about the new notepad.exe process and then I can check if there is a file responsible for its starting.
This is the code that notifies me when the event arrives.
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject mbo = (ManagementBaseObject)e.NewEvent["TargetInstance"];
string executable = mbo.GetPropertyValue("ExecutablePath").ToString().ToLower();
string commandLine = mbo.GetPropertyValue("CommandLine").ToString().ToLower();
[...]
}
Inside the variable commandLine I find the full command line, in my example:
c:\windows\system32\notepad.exe d:\documents\doc.txt
The code works well for almost every program but I found a problem with files whose extensions are linked with no program.
When I double click on one of this file the Open With dialog (the process name is openwith.exe) pops up and I am regularly notified by the watcher but when I read the CommandLine property I found something like this:
c:\windows\system32\openwith.exe -embedding
instead of the expected:
c:\windows\system32\openwith.exe d:\documents\document.unlinkedExt
All the properties I can analize from the mbo oject don't help me. My assumption is that this kind of instance is not using an usual command line to execute the process.
The question is: how can I extract the full file path that caused the Open With dialog opening?
Checked on Windows 8.1 and 10 with .NET framework 2.0 and 4.0.

FileSystemWatcher IncludeSubdirectories not working on network share

I'm attempting to watch a network share for folders where a file is added to the share to indicate the upload is complete. I wanted to use a FileSystemWatcher to monitor that share and its subdirectories for that trigger file, as shown below.
FileSystemWatcher fsw = new FileSystemWatcher(share, triggerFilePattern);
fsw.IncludeSubdirectories = true;
fsw.Created += new FileSystemEventHandler(OnCreated);
fsw.Renamed += new RenamedEventHandler(OnRenamed);
fsw.Error += new ErrorEventHandler(OnError);
If a file is created at the root of the share, the event triggers. If a file is created within a subdirectory of the share, the event does not trigger, and I don't get an error either.
If I create a new FileSystemWatcher for that subdirectory, then I do receive an event when a file is created there. But, similar to the top level FileSystemWatcher, I won't get events for files created in any further subdirectories.
If I change the network share to a local directory for testing, it does work as expected.
Any ideas? Could I have set up some wonky network share setting that blocks recursive FileSystemWatcher checks? I can work around this, but it would be nice to not have to complicate the code.
Edit: I saw that I didn't have Full Control under Properties->Security tab, so I thought that could be it. But I was able to get normal desired behavior on a different share with the same visible permissions, so I'm back to not knowing why this specific share isn't working.
Edit2: At a coworker's suggestion, I added a Changed handler too. Doesn't make sense to me how a file can be changed without getting Created first, but... I'm getting Changed events on the share in question when creating files in a subdirectory. (And I'm still getting nothing when renaming them.) This solves my immediate problem, but I'm going to leave the question open in case someone's able to answer why that's happening.
Try this
private static FileSystemWatcher fw;
static void Main(string[] args)
{
fw = new FileSystemWatcher(#"D:\Folder_Watch");
fw.IncludeSubdirectories = true;
fw.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
fw.Created += fw_Created;
fw.Changed += fw_Created;
fw.Renamed += fw_Created;
fw.Filter = "*.*";
fw.EnableRaisingEvents = true;
new System.Threading.AutoResetEvent(false).WaitOne();
}
static void fw_Created(object sender, FileSystemEventArgs e)
{
try
{
fw.EnableRaisingEvents = false;
//Your Code
}
finally
{
fw.EnableRaisingEvents = true;
}
}
I had same problem and I solved it by giving write permission to the shared network folder (it had only read permission so far). Shared folder is originally on Linux but I have it mounted on Windows Server 2008 R2 where I'm running program with FileSystemWatcher.

Windows Service installation - current directory

this question is related to my previous one . I've written a service in C# and I need to make it's name dynamic and load the name from configuration file. The problem is that current directory while the service installer is invoked is the net framework 4 directory instead of the one that my assembly sits in.
Using the line (which helps with the same problem, but while the service is already running)
System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
sets the directory to
C:\Windows\Microsoft.NET\Framework\v4.0.30319
which was also the initial value.
How to get the right path?
try this one:
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
You can also try
Assembly.GetExecutingAssembly( ).Location
That also works if you're not referencing winforms or wpf
We had the same problem in a project i was working on but we took a different approach. Instead of using App.config files that has to be in the same path as the executable, we changed both the installer class and the Main entry point of the service.
We did this because we didn't want the same project files in different locations. The idea was to use the same distribution files, but with different service names.
So what we did was inside our ProjectInstaller:
private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
{
string keyPath = #"SYSTEM\CurrentControlSet\Services\" + this.serviceInstaller1.ServiceName;
RegistryKey ckey = Registry.LocalMachine.OpenSubKey(keyPath, true);
// Pass the service name as a parameter to the service executable
if (ckey != null && ckey.GetValue("ImagePath")!= null)
ckey.SetValue("ImagePath", (string)ckey.GetValue("ImagePath") + " " + this.serviceInstaller1.ServiceName);
}
private void ProjectInstaller_BeforeInstall(object sender, InstallEventArgs e)
{
// Configura ServiceName e DisplayName
if (!String.IsNullOrEmpty(this.Context.Parameters["ServiceName"]))
{
this.serviceInstaller1.ServiceName = this.Context.Parameters["ServiceName"];
this.serviceInstaller1.DisplayName = this.Context.Parameters["ServiceName"];
}
}
private void ProjectInstaller_BeforeUninstall(object sender, InstallEventArgs e)
{
if (!String.IsNullOrEmpty(this.Context.Parameters["ServiceName"]))
this.serviceInstaller1.ServiceName = this.Context.Parameters["ServiceName"];
}
We used InstallUtil to instal our service like this:
[FramerokPath]\installutil /ServiceName=[name] [ExeServicePath]
Then, inside the Main entry point of your application, we checked the args attribute to get what was the installation name of the service that we setted inside the AfterInstall event.
This approach has some issues, like:
We had to create a default name for the service that was installed without the parameter. For instance, if no name was passed to our service, then we use the default one;
You can change the service name passed to our application to be different from the one that was installed.

What is the most reliable way to create a custom event log and event source during the installation of a .Net Service

I am having difficulty reliably creating / removing event sources during the installation of my .Net Windows Service.
Here is the code from my ProjectInstaller class:
// Create Process Installer
ServiceProcessInstaller spi = new ServiceProcessInstaller();
spi.Account = ServiceAccount.LocalSystem;
// Create Service
ServiceInstaller si = new ServiceInstaller();
si.ServiceName = Facade.GetServiceName();
si.Description = "Processes ...";
si.DisplayName = "Auto Checkout";
si.StartType = ServiceStartMode.Automatic;
// Remove Event Source if already there
if (EventLog.SourceExists("AutoCheckout"))
EventLog.DeleteEventSource("AutoCheckout");
// Create Event Source and Event Log
EventLogInstaller log = new EventLogInstaller();
log.Source = "AutoCheckout";
log.Log = "AutoCheckoutLog";
Installers.AddRange(new Installer[] { spi, si, log });
The facade methods referenced just return the strings for the name of the log, service, etc.
This code works most of the time, but recently after installing I started getting my log entries showing up in the Application Log instead of the custom log. And the following errors are in the log as well:
The description for Event ID ( 0 ) in Source ( AutoCheckout ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details.
For some reason it either isn't properly removing the source during the uninstall or it isn't creating it during the install.
Any help with best practices here is appreciated.
Thanks!
In addition, here is a sample of how I am writing exceptions to the log:
// Write to Log
EventLog.WriteEntry(Facade.GetEventLogSource(), errorDetails, EventLogEntryType.Error, 99);
Regarding stephbu's answer: The recommended path is an installer script and installutil, or a Windows Setup routine.
I am using a Setup Project, which performs the installation of the service and sets up the log. Whether I use the installutil.exe or the windows setup project I believe they both call the same ProjectInstaller class I show above.
I see how the state of my test machine could be causing the error if the log isn't truly removed until rebooting. I will experiment more to see if that solves the issue.
Edit:
I'm interested in a sure fire way to register the source and the log name during the installation of the service. So if the service had previously been installed, it would remove the source, or reuse the source during subsequent installations.
I haven't yet had an opportunity to learn WiX to try that route.
The ServiceInstaller class automatically creates an EventLogInstaller and puts it inside its own Installers collection.
Try this code:
ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
serviceProcessInstaller.Password = null;
serviceProcessInstaller.Username = null;
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
// serviceInstaller
ServiceInstaller serviceInstaller = new ServiceInstaller();
serviceInstaller.ServiceName = "MyService";
serviceInstaller.DisplayName = "My Service";
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.Description = "My Service Description";
// kill the default event log installer
serviceInstaller.Installers.Clear();
// Create Event Source and Event Log
EventLogInstaller logInstaller = new EventLogInstaller();
logInstaller.Source = "MyService"; // use same as ServiceName
logInstaller.Log = "MyLog";
// Add all installers
this.Installers.AddRange(new Installer[] {
serviceProcessInstaller, serviceInstaller, logInstaller
});
Couple of things here
Creating Event Logs and Sources on the fly is pretty frowned upon. primarily because of the rights required to perform the action - you don't really want to bless your applications with that power.
Moreover if you delete an event log or source the entry is only truely deleted when the server reboots, so you can get into wierd states if you delete and recreate entries without bouncing the box. There are also a bunch of unwritten rules about naming conflicts due to the way the metadata is stored in the registry.
The recommended path is an installer script and installutil, or a Windows Setup routine.
The best recommendation would be to not use the Setup Project in Visual Studio. It has very severe limitations.
I had very good results with WiX
I have to agree with stephbu about the "weird states" that the event log gets into, I've run into that before. If I were to guess, some of your difficulties lie there.
However, the best way that I know of to do event logging in the application is actually with a TraceListener. You can configure them via the service's app.config:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlogtracelistener.aspx
There is a section near the middle of that page that describes how to use the EventLog property to specify the EventLog you wish to write to.
Hope that helps.
I also followed helb's suggestion, except that I basically used the standard designer generated classes (the default objects "ServiceProcessInstaller1" and "ServiceInstaller1"). I decided to post this since it is a slightly simpler version; and also because I am working in VB and people sometimes like to see the VB-way.
As tartheode said, you should not modify the designer-generated ProjectInstaller class in the ProjectInstaller.Designer.vb file, but you can modify the code in the ProjectInstaller.vb file. After creating a normal ProjectInstaller (using the standard 'Add Installer' mechanism), the only change I made was in the New() of the ProjectInstaller class. After the normal "InitializeComponent()" call, I inserted this code:
' remove the default event log installer
Me.ServiceInstaller1.Installers.Clear()
' Create an EventLogInstaller, and set the Event Source and Event Log
Dim logInstaller As New EventLogInstaller
logInstaller.Source = "MyServiceName"
logInstaller.Log = "MyCustomEventLogName"
' Add the event log installer
Me.ServiceInstaller1.Installers.Add(logInstaller)
This worked as expected, in that the installer did not create the Event Source in the Application log, but rather created in the new custom log file.
However, I had screwed around enough that I had a bit of a mess on one server. The problem with the custom logs is that if the event source name exists associated to the wrong log file (e.g. the 'Application' log instead of your new custom log), then the source name must first be deleted; then the machine rebooted; then the source can be created with association to the correct log. The Microsoft Help clearly states (in the EventLogInstaller class description):
The Install method throws an exception
if the Source property matches a
source name that is registered for a
different event log on the computer.
Therefore, I also have this function in my service, which is called when the service starts:
Private Function EventLogSourceNameExists() As Boolean
'ensures that the EventSource name exists, and that it is associated to the correct Log
Dim EventLog_SourceName As String = Utility.RetrieveAppSetting("EventLog_SourceName")
Dim EventLog_LogName As String = Utility.RetrieveAppSetting("EventLog_LogName")
Dim SourceExists As Boolean = EventLog.SourceExists(EventLog_SourceName)
If Not SourceExists Then
' Create the source, if it does not already exist.
' An event log source should not be created and immediately used.
' There is a latency time to enable the source, it should be created
' prior to executing the application that uses the source.
'So pass back a False to cause the service to terminate. User will have
'to re-start the application to make it work. This ought to happen only once on the
'machine on which the service is newly installed
EventLog.CreateEventSource(EventLog_SourceName, EventLog_LogName) 'create as a source for the SMRT event log
Else
'make sure the source is associated with the log file that we want
Dim el As New EventLog
el.Source = EventLog_SourceName
If el.Log <> EventLog_LogName Then
el.WriteEntry(String.Format("About to delete this source '{0}' from this log '{1}'. You may have to kill the service using Task Manageer. Then please reboot the computer; then restart the service two times more to ensure that this event source is created in the log {2}.", _
EventLog_SourceName, el.Log, EventLog_LogName))
EventLog.DeleteEventSource(EventLog_SourceName)
SourceExists = False 'force a close of service
End If
End If
Return SourceExists
End Function
If the function returns False, the service startup code simply stops the service. This function pretty much ensures that you will eventually get the correct Event Source name associated to the correct Event Log file. You may have to reboot the machine once; and you may have to try starting the service more than once.
I am having the same problems. In my case it seems that Windows installer is adding the event source which is of the same name as my service automatically and this seems to cause problems. Are you using the same name for the windows service and for the log source? Try changing it so that your event log source is called differently then the name of the service.
I just posted a solution to this over on MSDN forums which was to that I managed to get around this using a standard setup MSI project. What I did was to add code to the PreInstall and Committed events which meant I could keep everything else exactly as it was:
SortedList<string, string> eventSources = new SortedList<string, string>();
private void serviceProcessInstaller_BeforeInstall(object sender, InstallEventArgs e)
{
RemoveServiceEventLogs();
}
private void RemoveServiceEventLogs()
{
foreach (Installer installer in this.Installers)
if (installer is ServiceInstaller)
{
ServiceInstaller serviceInstaller = installer as ServiceInstaller;
if (EventLog.SourceExists(serviceInstaller.ServiceName))
{
eventSources.Add(serviceInstaller.ServiceName, EventLog.LogNameFromSourceName(serviceInstaller.ServiceName, Environment.MachineName));
EventLog.DeleteEventSource(serviceInstaller.ServiceName);
}
}
}
private void serviceProcessInstaller_Committed(object sender, InstallEventArgs e)
{
RemoveServiceEventLogs();
foreach (KeyValuePair<string, string> eventSource in eventSources)
{
if (EventLog.SourceExists(eventSource.Key))
EventLog.DeleteEventSource(eventSource.Key);
EventLog.CreateEventSource(eventSource.Key, eventSource.Value);
}
}
The code could be modified a bit further to only remove the event sources that didn't already exist or create them (though the logname would need to be stored somewhere against the installer) but since my application code actually creates the event sources as it runs then there's no point for me. If there are already events then there should already be an event source. To ensure that they are created, you can just automatically start the service.
I experienced some similar weird behaviour because I tried to register an event source with the same name as the service I was starting.
I notice that you also have the DisplayName set to the same name as your event Source.
On starting the service up, we found that Windows logged a "Service started successfully" entry in the Application log, with source as the DisplayName. This seemed to have the effect of registering Application Name with the application log.
In my event logger class I later tried to register Application Name as the source with a different event log, but when it came to adding new event log entries they always got added to the Application log.
I also got the "The description for Event ID ( 0 ) in Source" message several times.
As a work around I simply registered the message source with a slightly different name to the DisplayName, and it's worked ever since. It would be worth trying this if you haven't already.
The problem comes from installutil which by default registers an event source with your services name in the "Application" EventLog. I'm still looking for a way to stop it doing this crap. It would be really nice if one could influence the behaviour of installutil :(
Following helb's suggestion resolved the problem for me. Killing the default event log installer, at the point indicated in his example, prevented the installer from automatically registering my Windows Service under the Application Event log.
Far too much time was lost attempting to resolve this frustrating quirk. Thanks a million!
FWIW, I could not modify the code within my designer-generated ProjectInstaller class without causing VS to carp about the mods. I scrapped the designer-generated code and manually entered the class.
Adding an empty registry key to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\MY_CUSTOM_SOURCE_NAME_HERE seems to work fine.
An easy way to change the default behavior (that is, that the project installer creates an event log source with the name of your service in the application log) is to easily modify the constructor of the project installer as following:
[RunInstaller( true )]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
//Skip through all ServiceInstallers.
foreach( ServiceInstaller ThisInstaller in Installers.OfType<ServiceInstaller>() )
{
//Find the first default EventLogInstaller.
EventLogInstaller ThisLogInstaller = ThisInstaller.Installers.OfType<EventLogInstaller>().FirstOrDefault();
if( ThisLogInstaller == null )
continue;
//Modify the used log from "Application" to the same name as the source name. This creates a source in the "Applications and Services log" which separates your service logs from the default application log.
ThisLogInstaller.Log = ThisLogInstaller.Source;
}
}
}

Categories