public void GetNotificationsMultipleWatchers(int number, bool recursive)
        {
            using var helper = new HelperTest();

            using var watcher1 = new Watcher();
            watcher1.Add(new Request(helper.Folder, recursive));
            using var watcher2 = new Watcher();
            watcher2.Add(new Request(helper.Folder, recursive));

            var added1 = 0;
            var added2 = 0;

            watcher1.OnAddedAsync += (ft, t) =>
            {
                ++added1;
                return(Task.CompletedTask);
            };
            watcher2.OnAddedAsync += (ft, t) =>
            {
                ++added2;
                return(Task.CompletedTask);
            };

            // start
            watcher1.Start();
            watcher2.Start();

            for (var i = 0; i < number; ++i)
            {
                helper.AddFile();
            }

            // wait a bit
            _ = SpinWait.SpinUntil(() =>
            {
                return(number == added1 && number == added2);
            }, number * 1000);

            watcher1.Stop();
            watcher2.Stop();

            // stop
            Assert.AreEqual(number, added1);
            Assert.AreEqual(number, added2);
        }
        public async Task DeleteWatchedFolder(bool recursive)
        {
            using var helper = new HelperTest();

            // create a folder will be actually watch
            var folder = helper.AddFolder();
            await Task.Delay(100).ConfigureAwait(false);

            // start watching it.
            using var watcher = new Watcher();
            watcher.Add(new Request(folder, recursive));
            watcher.Start();

            // try and delete it
            Assert.DoesNotThrow(() => Directory.Delete(folder, true));

            watcher.Stop();
        }
Example #3
0
        public async Task TestSimpleAddFilesNotification(int numberToAdd, bool recursive)
        {
            using var helper = new HelperTest();

            // the number of files we will be adding
            var numberAdded = 0;

            // first we need to create the watcher
            using (var watcher = new Watcher())
            {
                watcher.Add(new Request(helper.Folder, recursive));
                watcher.OnAddedAsync += (fse, token) =>
                {
                    TestContext.Out.WriteLine($"Adding {(fse.IsFile?"File":"Folder")}");
                    if (fse.IsFile)
                    {
                        Interlocked.Increment(ref numberAdded);
                    }
                    return(Task.CompletedTask);
                };
                watcher.Start();

                //we then need to wait a bit for all the workers to have started.
                TestContext.Out.WriteLine("Waiting for watchers!");

                //we then need to wait a bit for all the workers to have started.
                var timeout = (numberToAdd <= 2 ? 3 : numberToAdd) * 1000;
                Assert.IsTrue(SpinWait.SpinUntil(() => watcher.Ready(), timeout));

                TestContext.Out.WriteLine("All watchers ready!");

                for (var i = 0; i < numberToAdd; ++i)
                {
                    // create an empty file
                    helper.AddFile();
                    await Task.Yield();
                }

                // give a bit of time
                SpinWait.SpinUntil(() => numberAdded >= numberToAdd, timeout);
            }
            Assert.AreEqual(numberToAdd, numberAdded);
        }
        public void RemoveAddedDelegateBeforeStop(int number, bool recursive)
        {
            var added = 0;

            Task Fn(IFileSystemEvent ft, CancellationToken token)
            {
                Interlocked.Increment(ref added);
                return(Task.CompletedTask);
            }

            using var helper  = new HelperTest();
            using var watcher = new Watcher();
            watcher.Add(new Request(helper.Folder, recursive, new Rates(50)));
            watcher.Start();

            SpinWait.SpinUntil(() => watcher.Ready());

            watcher.OnAddedAsync += Fn;

            for (var i = 0; i < number; ++i)
            {
                helper.AddFile();
            }

            // wait a bit
            Assert.IsTrue(SpinWait.SpinUntil(() => number == added, number * 1000));

            // check that they all added.
            Assert.AreEqual(number, added);

            // stop watching
            watcher.OnAddedAsync -= Fn;

            // add some more
            for (var i = 0; i < number; ++i)
            {
                helper.AddFile();
            }

            Assert.AreEqual(number, added);

            watcher.Stop();
        }
        public Task GetNotifications(int number, bool recursive)
        {
            using var helper = new HelperTest();

            using var watcher = new Watcher();
            watcher.Add(new Request(helper.Folder, recursive, new Rates(100)));

            var added = 0;

            watcher.OnAddedAsync += (ft, t) =>
            {
                Interlocked.Increment(ref added);
                return(Task.CompletedTask);
            };

            // start
            watcher.Start();

            //we then need to wait a bit for all the workers to have started.
            TestContext.Out.WriteLine("Waiting for watchers!");

            //we then need to wait a bit for all the workers to have started.
            var timeout = number * 1000;

            Assert.IsTrue(SpinWait.SpinUntil(() => watcher.Ready(), timeout));

            TestContext.Out.WriteLine("All watchers ready!");

            for (var i = 0; i < number; ++i)
            {
                helper.AddFile();
            }

            // wait a bit
            SpinWait.SpinUntil(() => number == added, timeout);

            watcher.Stop();

            // stop
            Assert.AreEqual(number, added);
            return(Task.CompletedTask);
        }
        public async Task DeleteWatchedFolder(bool recursive)
        {
            using var helper = new HelperTest();

            // create a folder will be actually watch
            var folder = helper.AddFolder();
            await Task.Delay(100).ConfigureAwait(false);

            // start watching it.
            using var watcher = new Watcher();
            watcher.Add(new Request(folder, recursive));
            watcher.Start();

            //we then need to wait a bit for all the workers to have started.
            SpinWait.SpinUntil(() => watcher.Ready());

            // try and delete it
            Assert.DoesNotThrow(() => Directory.Delete(folder, true));

            watcher.Stop();
        }
Example #7
0
        public async Task StartWatcherBeforeAddingAnything(bool recursive)
        {
            using var helper  = new HelperTest();
            using var watcher = new Watcher();

            // start the watcher
            watcher.Start();

            // the number of files we actually added
            var       numberAdded = 0;
            const int numberToAdd = 10;
            var       timeout     = (numberToAdd <= 2 ? 3 : numberToAdd) * 1000;

            Assert.IsTrue(SpinWait.SpinUntil(() => watcher.Ready(), timeout));

            // and then add the folder we are after
            watcher.Add(new Request(helper.Folder, recursive));

            // then wait
            Assert.IsTrue(SpinWait.SpinUntil(() => watcher.Ready(), timeout));

            watcher.OnAddedAsync += (fse, token) =>
            {
                Interlocked.Increment(ref numberAdded);
                return(Task.CompletedTask);
            };

            TestContext.Out.WriteLine("All watchers ready!");

            for (var i = 0; i < numberToAdd; ++i)
            {
                // create an empty file
                helper.AddFile();
                await Task.Yield();
            }

            // give a bit of time
            SpinWait.SpinUntil(() => numberAdded >= numberToAdd, timeout);
        }
Example #8
0
        private static void Main()
        {
            try
            {
                Console.WriteLine("Press Ctrl+C to stop the monitors.");

                // start the monitor.
                var watch = new Watcher();
                var drvs  = System.IO.DriveInfo.GetDrives();
                foreach (var drv in drvs)
                {
                    if (drv.DriveType == System.IO.DriveType.Fixed)
                    {
                        watch.Add(new Request(drv.Name, true));
                    }
                }

                // prepare the console watcher so we can output pretty messages.
                var _ = new ConsoleWatch(watch);

                // start watching
                watch.Start();

                // listen for the Ctrl+C
                WaitForCtrlC();

                // stop everything.
                watch.Stop();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                    Console.WriteLine(ex.Message);
                }
            }
        }
        private static void Main()
        {
            try
            {
                Console.WriteLine(Environment.Is64BitProcess ? "x64 version" : "x86 version");
                Console.WriteLine("Press Ctrl+C to stop the monitors.");

                // start the monitor.
                using (var watch = new Watcher())
                {
                    var drvs = System.IO.DriveInfo.GetDrives();
                    foreach (var drv in drvs)
                    {
                        if (drv.DriveType == System.IO.DriveType.Fixed)
                        {
                            watch.Add(new Request(drv.Name, true));
                        }
                    }

                    // prepare the console watcher so we can output pretty messages.
                    var _ = new ConsoleWatch(watch);

                    // start watching
                    watch.Start();

                    // listen for the Ctrl+C
                    WaitForCtrlC();

                    // stop everything.
                    watch.Stop();
                }
            }
            catch (Exception ex)
            {
                WriteException(ex);
            }
        }
Example #10
0
    public bool MonitorFolders(List <string> folders)
    {
        Log.Logger.Information("Monitoring folders ...");

        void ChangeHandler(object s, FileSystemEventArgs e)
        {
            OnChanged(e, this);
        }

        void RenameHandler(object s, RenamedEventArgs e)
        {
            OnRenamed(e, this);
        }

        void ErrorHandler(object s, ErrorEventArgs e)
        {
            OnError(e);
        }

        // Create file system watcher for each folder
        foreach (string folder in folders)
        {
            // Create a file system watcher for the folder
            Log.Logger.Information("Monitoring : {Folder}", folder);
            FileSystemWatcher watch = new();
            Watcher.Add(watch);
            watch.Path                  = folder;
            watch.NotifyFilter          = NotifyFilters.Size | NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watch.Filter                = "*.*";
            watch.IncludeSubdirectories = true;
            watch.Changed              += ChangeHandler;
            watch.Created              += ChangeHandler;
            watch.Deleted              += ChangeHandler;
            watch.Renamed              += RenameHandler;
            watch.Error                += ErrorHandler;
        }

        // Enable event watching
        Watcher.ForEach(item => item.EnableRaisingEvents = true);

        // Wait for exit to be signalled
        while (!Program.IsCancelled(1000))
        {
            // Lock and process the list of folders
            List <string> watchlist = new();
            lock (WatchLock)
            {
                if (WatchFolders.Any())
                {
                    // Remove root folders from the watchlist
                    //TODO : Maybe we need a way to not process sub-directories?
                    //foreach (string folder in folders)
                    //    WatchFolders.Remove(folder);

                    // Find folders that have settled down, i.e. not modified in last wait time
                    DateTime settleTime = DateTime.UtcNow.AddSeconds(-Program.Config.MonitorOptions.MonitorWaitTime);
                    foreach ((string key, DateTime value) in WatchFolders)
                    {
                        // If not recently modified and all files in the folder are readable
                        if (value < settleTime)
                        {
                            if (!FileEx.AreFilesInDirectoryReadable(key))
                            {
                                Log.Logger.Information("Folder not readable : {Folder}", key);
                            }
                            else
                            {
                                watchlist.Add(key);
                            }
                        }
                    }

                    // Remove watched folders from the watchlist
                    watchlist.ForEach(item => WatchFolders.Remove(item));
                }
            }

            // Any work to do
            if (!watchlist.Any())
            {
                continue;
            }

            // Process changes in the watched folders
            foreach (string folder in watchlist)
            {
                Log.Logger.Information("Monitored changes in : {Folder}", folder);
            }

            Process process = new();
            process.ProcessFolders(watchlist);
            Process.DeleteEmptyFolders(watchlist);
        }

        // Disable event watching
        Watcher.ForEach(item => item.EnableRaisingEvents = false);
        Watcher.Clear();

        return(true);
    }
 public void StopWithoutStart()
 {
     using var watcher = new Watcher();
     watcher.Add(new Request("%temp%", false));
     Assert.DoesNotThrow(() => watcher.Stop());
 }