Ejemplo n.º 1
0
		public static FileChecker TryCreate(ReadedFileInfo fileInfo, WatchMode watch, TimeSpan? delay, CheckMode check)
		{
			switch (watch)
			{
				case WatchMode.None:
					return null;

				case WatchMode.Time:
					if (delay == null)
						throw new ArgumentNullException("delay");
					return new PeriodicFileChecker(fileInfo, delay.Value, check);

				case WatchMode.Auto:
					try
					{
						return new WatchedFileChecker(fileInfo, delay, check);
					}
					catch (Exception)
					{
						if (delay == null)
							throw;
					}
					return new PeriodicFileChecker(fileInfo, delay.Value, check);

				case WatchMode.System:
					return new WatchedFileChecker(fileInfo, delay, check);

				default:
					throw new ArgumentOutOfRangeException("unexpected mode");
			}
		}
Ejemplo n.º 2
0
        public void DeleteDirectory()
        {
            var tempPath    = Path.Combine(Path.GetTempPath(), "NConfiguration.Tests");
            var dirName     = Guid.NewGuid().ToString();
            var watchedFile = Path.Combine(tempPath, dirName, "test.xml");

            Directory.CreateDirectory(Path.Combine(tempPath, dirName));

            File.WriteAllText(watchedFile, _xmlCfg);

            var fileInfo    = ReadedFileInfo.Create(watchedFile, _ => _.CopyTo(Stream.Null));
            var fileChecker = FileChecker.TryCreate(fileInfo, WatchMode.System, TimeSpan.FromMilliseconds(100), CheckMode.All);

            Thread.Sleep(50);

            var wait = new ManualResetEvent(false);

            fileChecker.Changed += (a, e) =>
            {
                wait.Set();
            };

            Directory.Delete(Path.Combine(tempPath, dirName), true);
            Directory.CreateDirectory(Path.Combine(tempPath, dirName));             //no lock directory

            Assert.IsTrue(wait.WaitOne(10000), "no event");
        }
Ejemplo n.º 3
0
        public static FileChecker TryCreate(ReadedFileInfo fileInfo, WatchMode watch, TimeSpan?delay, CheckMode check)
        {
            switch (watch)
            {
            case WatchMode.None:
                return(null);

            case WatchMode.Time:
                if (delay == null)
                {
                    throw new ArgumentNullException("delay");
                }
                return(new PeriodicFileChecker(fileInfo, delay.Value, check));

            case WatchMode.Auto:
                try
                {
                    return(new WatchedFileChecker(fileInfo, delay, check));
                }
                catch (Exception)
                {
                    if (delay == null)
                    {
                        throw;
                    }
                }
                return(new PeriodicFileChecker(fileInfo, delay.Value, check));

            case WatchMode.System:
                return(new WatchedFileChecker(fileInfo, delay, check));

            default:
                throw new ArgumentOutOfRangeException("unexpected mode");
            }
        }
Ejemplo n.º 4
0
        public void ChangeByte(CheckMode checkMode, bool expectedEvent)
        {
            string file = Path.GetTempFileName();

            File.WriteAllBytes(file, new byte[] { 1, 2, 3 });

            var fileInfo = ReadedFileInfo.Create(file, _ => _.CopyTo(Stream.Null));
            var m        = createChecker(fileInfo, checkMode);
            var wait     = new ManualResetEvent(false);

            m.Changed += (a, e) =>
            {
                wait.Set();
            };

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(400);
                using (var fs = new FileStream(file, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                {
                    fs.Position = 2;
                    fs.WriteByte(1);
                    fs.Close();
                }
            }, TaskCreationOptions.LongRunning);

            Assert.AreEqual(expectedEvent, wait.WaitOne(700), "700 ms elapsed");
        }
Ejemplo n.º 5
0
		public static FileChecker TryCreate(IConfigNodeProvider nodeProvider, ReadedFileInfo fileInfo)
		{
			var node = nodeProvider.ByName(ConfigSectionName).FirstOrDefault();
			if (node == null)
				return null;

			var cfg = DefaultDeserializer.Instance.Deserialize<WatchFileConfig>(node);
			return TryCreate(fileInfo, cfg.Mode, cfg.Delay, cfg.Check.GetValueOrDefault(CheckMode.All));
		}
Ejemplo n.º 6
0
		public PeriodicFileChecker(ReadedFileInfo fileInfo, TimeSpan delay, CheckMode checkMode)
			: base(fileInfo)
		{
			if (delay <= TimeSpan.FromMilliseconds(1))
				throw new ArgumentOutOfRangeException("delay should be greater of 1 ms");

			_delay = delay;
			_checkMode = checkMode;
			_cts = new CancellationTokenSource();
			Task.Run(() => checkLoop()).ThrowUnhandledException("Error while file checking.");
		}
Ejemplo n.º 7
0
        public IChangeable createChecker(ReadedFileInfo fileInfo, CheckMode checkMode)
        {
            if (_fromConfig)
            {
                string modeText;
                if (_monitorType == "Periodic")
                {
                    modeText = "Time";
                }
                else if (_monitorType == "Watched")
                {
                    modeText = "System";
                }
                else
                {
                    throw new NotImplementedException();
                }

                string checkText = "None";
                if (checkMode.HasFlag(CheckMode.Hash))
                {
                    checkText = "Hash";
                }
                if (checkMode.HasFlag(CheckMode.Attr))
                {
                    if (checkText == "None")
                    {
                        checkText = "Attr";
                    }
                    else
                    {
                        checkText += ",Attr";
                    }
                }

                var settings = string.Format(_xmlFormat, modeText, checkText).ToXmlSettings();

                return(FileChecker.TryCreate(settings, fileInfo));
            }
            else
            {
                if (_monitorType == "Periodic")
                {
                    return(new PeriodicFileChecker(fileInfo, TimeSpan.FromMilliseconds(100), checkMode));
                }

                if (_monitorType == "Watched")
                {
                    return(new WatchedFileChecker(fileInfo, TimeSpan.FromMilliseconds(100), checkMode));
                }
            }

            throw new NotImplementedException();
        }
Ejemplo n.º 8
0
 /// <summary>
 /// settings loaded from a file
 /// </summary>
 /// <param name="fileName">file name</param>
 public XmlFileSettings(string fileName)
 {
     try
     {
         _fileInfo = ReadedFileInfo.Create(fileName,
             stream => { _root = XDocument.Load(stream).Root; });
     }
     catch(SystemException ex)
     {
         throw new ApplicationException(string.Format("Unable to load file `{0}'", fileName), ex);
     }
 }
Ejemplo n.º 9
0
		public WatchedFileChecker(ReadedFileInfo fileInfo, TimeSpan? delay, CheckMode checkMode)
			: base(fileInfo)
		{
			_delay = delay.GetValueOrDefault(TimeSpan.FromSeconds(5 * 60));

			if (_delay <= TimeSpan.FromMilliseconds(1))
				throw new ArgumentOutOfRangeException("delay should be greater of 1 ms");

			_fileInfo = fileInfo;
			_checkMode = checkMode;
			_watcher = createWatch();
			Task.Run(() => checkLoop()).ThrowUnhandledException("Error while file checking.");
		}
Ejemplo n.º 10
0
        public static FileChecker TryCreate(IConfigNodeProvider nodeProvider, ReadedFileInfo fileInfo)
        {
            var node = nodeProvider.ByName(ConfigSectionName).FirstOrDefault();

            if (node == null)
            {
                return(null);
            }

            var cfg = DefaultDeserializer.Instance.Deserialize <WatchFileConfig>(node);

            return(TryCreate(fileInfo, cfg.Mode, cfg.Delay, cfg.Check.GetValueOrDefault(CheckMode.All)));
        }
Ejemplo n.º 11
0
        private static IChangeable checkerCreatorByName(string name, ReadedFileInfo fi, TimeSpan delay, CheckMode mode)
        {
            switch (name)
            {
            case "PeriodicFileChecker":
                return(new PeriodicFileChecker(fi, delay, mode));

            case "WatchedFileChecker":
                return(new WatchedFileChecker(fi, delay, mode));

            default:
                throw new NotSupportedException();
            }
        }
Ejemplo n.º 12
0
        public void None(int?ms)
        {
            TimeSpan?ts = null;

            if (ms != null)
            {
                ts = TimeSpan.FromMilliseconds(ms.Value);
            }

            string file     = Path.GetTempFileName();
            var    fileInfo = ReadedFileInfo.Create(file, _ => _.CopyTo(Stream.Null));

            Assert.IsNull(FileChecker.TryCreate(fileInfo, WatchMode.None, ts, CheckMode.All));
        }
Ejemplo n.º 13
0
        public void FileChange(WatchMode mode, int?ms)
        {
            TimeSpan?ts = null;

            if (ms != null)
            {
                ts = TimeSpan.FromMilliseconds(ms.Value);
            }

            string file = Path.GetTempFileName();

            File.WriteAllBytes(file, new byte[] { 1, 2, 3 });

            var fileInfo = ReadedFileInfo.Create(file, _ => _.CopyTo(Stream.Null));

            var m = FileChecker.TryCreate(fileInfo, mode, ts, CheckMode.All);

            var wait = new ManualResetEvent(false);

            m.Changed += (a, e) =>
            {
                wait.Set();
            };

            var t = Task.Factory.StartNew(() =>
            {
                Thread.Sleep(1000);
                using (var fs = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    fs.Position = 2;
                    fs.WriteByte(1);
                    fs.Close();
                };
            }, TaskCreationOptions.LongRunning);

            Task.WaitAll(t);

            Assert.IsTrue(wait.WaitOne(10000), "10 sec elapsed");

            wait.Reset();

            m.Changed += (a, e) =>
            {
                wait.Set();
            };

            Assert.IsTrue(wait.WaitOne(10000), "10 sec elapsed");
        }
Ejemplo n.º 14
0
 public IniFileSettings(string fileName)
 {
     try
     {
         var context = new ParseContext();
         _fileInfo = ReadedFileInfo.Create(fileName, stream =>
         {
             using (var sr = new StreamReader(stream, Encoding.UTF8))
                 context.ParseSource(sr.ReadToEnd());
         });
         _sections = new List<Section>(context.Sections);
     }
     catch(SystemException ex)
     {
         throw new ApplicationException(string.Format("Unable to load file `{0}'", fileName), ex);
     }
 }
Ejemplo n.º 15
0
        public PeriodicFileChecker(ReadedFileInfo fileInfo, TimeSpan delay, CheckMode checkMode)
            : base(fileInfo)
        {
            if (delay <= TimeSpan.FromMilliseconds(1))
            {
                throw new ArgumentOutOfRangeException("delay should be greater of 1 ms");
            }

            _delay     = delay;
            _checkMode = checkMode;
            _cts       = new CancellationTokenSource();

#if NET40
            Task.Factory.StartNew(checkLoop, TaskCreationOptions.LongRunning).ThrowUnhandledException(MsgErrorWhileFileChecking);
#else
            Task.Run(() => checkLoop()).ThrowUnhandledException(MsgErrorWhileFileChecking);
#endif
        }
Ejemplo n.º 16
0
        public WatchedFileChecker(ReadedFileInfo fileInfo, TimeSpan?delay, CheckMode checkMode)
            : base(fileInfo)
        {
            _delay = delay.GetValueOrDefault(TimeSpan.FromSeconds(5 * 60));

            if (_delay <= TimeSpan.FromMilliseconds(1))
            {
                throw new ArgumentOutOfRangeException("delay should be greater of 1 ms");
            }

            _fileInfo  = fileInfo;
            _checkMode = checkMode;
            _watcher   = createWatch();
#if NET40
            Task.Factory.StartNew(checkLoop, TaskCreationOptions.LongRunning).ThrowUnhandledException(MsgErrorWhileFileChecking);
#else
            Task.Run(() => checkLoop()).ThrowUnhandledException(MsgErrorWhileFileChecking);
#endif
        }
Ejemplo n.º 17
0
        public JsonFileSettings(string fileName)
        {
            try
            {
                JValue val = null;
                _fileInfo = ReadedFileInfo.Create(fileName, stream =>
                {
                    using (var sr = new StreamReader(stream, Encoding.UTF8))
                        val = JValue.Parse(sr.ReadToEnd());
                });

                if (val.Type != TokenType.Object)
                    throw new FormatException("required json object in content");

                _obj = (JObject)val;
            }
            catch(SystemException ex)
            {
                throw new ApplicationException(string.Format("Unable to load file `{0}'", fileName), ex);
            }
        }
Ejemplo n.º 18
0
        public void DeletedFile()
        {
            string file = Path.GetTempFileName();

            File.WriteAllBytes(file, new byte[] { 1, 2, 3 });

            var fileInfo = ReadedFileInfo.Create(file, _ => _.CopyTo(Stream.Null));

            File.Delete(file);

            var m = FileChecker.TryCreate(fileInfo, WatchMode.System, null, CheckMode.All);

            var wait = new ManualResetEvent(false);

            m.Changed += (a, e) =>
            {
                wait.Set();
            };

            Assert.IsTrue(wait.WaitOne(10000), "10 sec elapsed");
        }
Ejemplo n.º 19
0
        public void ExceptionInEventHandler(Func <ReadedFileInfo, IChangeable> checkerCreator, string[] workflow)
        {
            string file = Path.GetTempFileName();

            File.WriteAllBytes(file, new byte[] { 1, 2, 3 });
            var fileInfo = ReadedFileInfo.Create(file, _ => _.CopyTo(Stream.Null));

            IChangeable monitor = null;

            var       wait = new ManualResetEvent(false);
            Exception unhandledException           = null;
            UnhandledExceptionEventHandler handler = (sender, args) =>
            {
                unhandledException = (Exception)args.ExceptionObject;
                wait.Set();
            };

            AppDomain.CurrentDomain.UnhandledException += handler;
            try
            {
                foreach (var op in workflow)
                {
                    switch (op)
                    {
                    case "create":
                        monitor = checkerCreator(fileInfo);
                        break;

                    case "subscribe":
                        monitor.Changed += (a, e) =>
                        {
                            throw new Exception("test");
                        };
                        break;

                    case "delete":
                        SafeDelete(file);
                        break;

                    case "modify":
                        Task.Factory.StartNew(() =>
                        {
                            Thread.Sleep(150);
                            using (var fs = new FileStream(file, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                            {
                                fs.Position = 2;
                                fs.WriteByte(1);
                                fs.Close();
                            };
                        }, TaskCreationOptions.LongRunning);
                        break;

                    case "delay":
                        Thread.Sleep(75);
                        break;

                    default:
                        throw new NotSupportedException();
                    }
                }

                Assert.IsTrue(wait.WaitOne(10000), "10 sec elapsed");
            }
            finally
            {
                AppDomain.CurrentDomain.UnhandledException -= handler;
            }

            Console.WriteLine(unhandledException);

            Assert.That(unhandledException.Message, Is.EqualTo("Error while file checking."));
            Assert.That(unhandledException.InnerException, Is.Not.Null);
            Assert.That(unhandledException.InnerException.Message, Is.EqualTo("test"));
        }
Ejemplo n.º 20
0
        public void WrongTimeArguments_Null()
        {
            var fileInfo = ReadedFileInfo.Create(Path.GetTempFileName(), _ => _.CopyTo(Stream.Null));

            Assert.Throws <ArgumentNullException>(() => FileChecker.TryCreate(fileInfo, WatchMode.Time, null, CheckMode.All));
        }
Ejemplo n.º 21
0
		protected FileChecker(ReadedFileInfo fileInfo)
		{
			_fileInfo = fileInfo;
		}
Ejemplo n.º 22
0
        public void WrongTimeArguments_OutOfRange()
        {
            var fileInfo = ReadedFileInfo.Create(Path.GetTempFileName(), _ => _.CopyTo(Stream.Null));

            Assert.Throws <ArgumentOutOfRangeException>(() => FileChecker.TryCreate(fileInfo, WatchMode.Time, TimeSpan.FromMilliseconds(1), CheckMode.All));
        }
Ejemplo n.º 23
0
        public IChangeable createChecker(ReadedFileInfo fileInfo, CheckMode checkMode)
        {
            if (_fromConfig)
            {
                string modeText;
                if (_monitorType == "Periodic")
                    modeText = "Time";
                else if(_monitorType == "Watched")
                    modeText = "System";
                else
                    throw new NotImplementedException();

                string checkText = "None";
                if(checkMode.HasFlag(CheckMode.Hash))
                    checkText = "Hash";
                if(checkMode.HasFlag(CheckMode.Attr))
                {
                    if(checkText == "None")
                        checkText = "Attr";
                    else
                        checkText += ",Attr";
                }

                var settings = string.Format(_xmlFormat, modeText, checkText).ToXmlSettings();

                return FileChecker.TryCreate(settings, fileInfo);
            }
            else
            {
                if (_monitorType == "Periodic")
                    return new PeriodicFileChecker(fileInfo, TimeSpan.FromMilliseconds(100), checkMode);

                if (_monitorType == "Watched")
                    return new WatchedFileChecker(fileInfo, TimeSpan.FromMilliseconds(100), checkMode);
            }

            throw new NotImplementedException();
        }
Ejemplo n.º 24
0
 protected FileChecker(ReadedFileInfo fileInfo)
 {
     _fileInfo = fileInfo;
 }