/// <summary> /// 读取最新文件内容,只管读就是了,FileWatch会自动加载最新的文件 /// </summary> /// <param name="file"></param> /// <param name="encoding"> </param> /// <returns></returns> /// <exception cref="FileNotFoundException"></exception> /// <exception cref="NullReferenceException"></exception> public static string GetFileCurrentContent(string file, System.Text.Encoding encoding) { if (!File.Exists(file)) { throw new FileNotFoundException(file); } var content = FileWatchStorageProvider.Provider.Get(file); if (content == null) { Action readFile = () => { content = IOUtility.ReadAsBypeArray(file); FileWatchStorageProvider.Provider.AddOrUpdate(file, content); }; readFile(); var fw = new FileWatcher(file) { OnChanged = (o, e) => readFile() }; } if (content == null) throw new NullReferenceException("content"); return encoding.GetString(content); }
public void TestFileWatcher() { var fileName = Path.GetFullPath("test.txt"); var watcher = new FileWatcher(fileName, "watcher"); watcher.Changed += watcher_Changed; changeEventFired = false; Assert.AreEqual(fileName, watcher.FileName); Assert.AreEqual("watcher", watcher.Channel); try { File.WriteAllText(fileName, "test"); Thread.Sleep(250); Assert.IsTrue(changeEventFired); } finally { File.Delete(fileName); } }
public Repository(string path) { Path = path; Internal = new LibGit2Sharp.Repository(path).AddTo(MultipleDisposable); MultipleDisposable.Add(() => Commits.ForEach(x => x.Dispose())); // ジョブキュー _jobQueue.AddTo(MultipleDisposable); WorkingJob = _jobQueue.WorkingJob .ToReadOnlyReactiveProperty(eventScheduler: Scheduler.Immediate) .AddTo(MultipleDisposable); // ファイルステータス FileStatus = new FileStatus(this) .AddTo(MultipleDisposable); Observable.FromEventPattern<ExceptionEventArgs>(_jobQueue, nameof(JobQueue.JobExecutingException)) .Select(x => x.EventArgs) .Subscribe(e => JobExecutingException?.Invoke(this, e)) .AddTo(MultipleDisposable); Branches = _branchesPool .ToReadOnlyReactiveCollection(x => new Branch(x.CanonicalName, Internal), Scheduler.Immediate) .AddTo(MultipleDisposable); UpdateAll(); { var watcher = new FileWatcher(System.IO.Path.Combine(Path, @".git\refs"), true) .AddTo(MultipleDisposable); new EventListener<FileSystemEventHandler>( h => watcher.FileUpdated += h, h => watcher.FileUpdated -= h, (s, e) => _jobQueue.AddJob("UpdateAll", UpdateAll)) .AddTo(MultipleDisposable); watcher.Start(); } { var watcher = new FileWatcher(System.IO.Path.Combine(Path, @".git\HEAD"), false) .AddTo(MultipleDisposable); new EventListener<FileSystemEventHandler>( h => watcher.FileUpdated += h, h => watcher.FileUpdated -= h, (s, e) => UpdateBranchProps(Branches.ToArray())) .AddTo(MultipleDisposable); watcher.Start(); } MultipleDisposable.Add(() => _commitLabelDict.Values .SelectMany(x => x) .ForEach(x => x.Dispose()) ); }
public void Start(bool enableAutoReload) { IsRunning = true; _watcher = new FileWatcher(LocalDirectory, enableAutoReload); _watcher.Handler = FileWatchUpdate; }
public void FileAdditionsForUnwatchedExtensionsAreNotDetected() { var watcher = new FileWatcher(); watcher.WatchDirectory(@"c:\", ".cs"); var changed = watcher.ReportChange(@"c:\foo.cshtml", WatcherChangeTypes.Created); Assert.False(changed); }
public FileWatcherEventArgs(string fileName, string path, string oldPath, string oldName, FileWatcher.FileWatcherChangeType changeType) { mFileName = fileName; mPath = path; mOldName = oldName; mOldPath = oldPath; mChangeType = changeType; }
public Mysql() { mysqlDriver = new ProcessDriver(Global.MysqlFile, "mysqld.exe", "--defaults-file=\"" + Global.Mysql + "/my.ini\" --console"); mysqlDriver.OutputTrigger += (ot, dt) => Console.WriteLine(@"{0} {1}", ot, dt); fileWatcher = new FileWatcher(Global.SettingsRoot, "mysql_*.cc"); fileWatcher.FileChanged += path => { Global.Compiler.Compile(path); Restart();}; }
public Apache() { apacheDriver = new ProcessDriver(Global.ApacheFile, "httpd.exe", "-f \"" + Global.Apache + "/conf/httpd.conf\""); apacheDriver.OutputTrigger += (ot, dt) => Console.WriteLine(@"{0} {1}", ot, dt); fileWatcher = new FileWatcher(Global.SettingsRoot, "apache_*.cc"); fileWatcher.FileChanged += path => { Global.Compiler.Compile(path); Restart();}; }
public void Start() { _logger.DebugFormat("Starting to listen on {0}", _endpointToListenTo); _listener = new SimpleFileWatcher(_endpointToListenTo); _listener.Start(); _listener.BeginAcceptFile(BeginAcceptFileCallback, null); _logger.DebugFormat("Now listen on {0}", _endpointToListenTo); }
public void FileAdditionsAreDetected() { var watcher = new FileWatcher(); watcher.WatchDirectory(@"c:\", ".cs"); var changed = watcher.ReportChange(@"c:\foo.cs", WatcherChangeTypes.Created); Assert.True(changed); }
public void FileAdditionsAreDetected() { var watcher = new FileWatcher(); watcher.WatchDirectory(PathHelpers.GetRootedPath(), ".cs"); var changed = watcher.ReportChange(PathHelpers.GetRootedPath("foo.cs"), WatcherChangeTypes.Created); Assert.True(changed); }
public void FileAdditionsForUnwatchedExtensionsAreNotDetected() { var watcher = new FileWatcher(); watcher.WatchDirectory(PathHelpers.GetRootedPath(), ".cs"); var changed = watcher.ReportChange(PathHelpers.GetRootedPath("foo.cshtml"), WatcherChangeTypes.Created); Assert.False(changed); }
static void Main(string[] args) { // FileSystemWatcher FileWatcher fileWorker = new FileWatcher(@".\csv\"); fileWorker.Run(); Console.ReadKey(); }
public void DeletedDirectoryReportsChange() { var watcher = new FileWatcher(); watcher.WatchDirectory(PathHelpers.GetRootedPath(), ".cs"); watcher.WatchDirectory(PathHelpers.GetRootedPath("foo"), ".cs"); var changed = watcher.ReportChange(PathHelpers.GetRootedPath("foo"), WatcherChangeTypes.Deleted); Assert.True(changed); }
public void Stop() { IsRunning = false; if (_watcher != null) { _watcher.Dispose(); _watcher = null; } }
public void DeletedDirectoryReportsChange() { var watcher = new FileWatcher(); watcher.WatchDirectory(@"c:\", ".cs"); watcher.WatchDirectory(@"c:\foo", ".cs"); var changed = watcher.ReportChange(@"c:\foo", WatcherChangeTypes.Deleted); Assert.True(changed); }
public void FileDeletionsAreDetected() { var watcher = new FileWatcher(); watcher.WatchFile(@"c:\foo.cs"); watcher.WatchFile(@"c:\bar.cs"); var changed = watcher.ReportChange(@"c:\foo.cs", WatcherChangeTypes.Deleted); Assert.True(changed); }
public void FileChangesAreDetected() { var watcher = new FileWatcher(); watcher.WatchFile(PathHelpers.GetRootedPath("foo.cs")); watcher.WatchFile(PathHelpers.GetRootedPath("bar.cs")); var changed = watcher.ReportChange(PathHelpers.GetRootedPath("foo.cs"), WatcherChangeTypes.Changed); Assert.True(changed); }
public ProcessedDocumentCacheElement(string path, Preprocessor preprocessor, ProcessedDocumentCache cache) { this.path = path; this.preprocessor = preprocessor; this.cache = cache; Reload(); watcher = new FileWatcher(path); watcher.Changed += (sender, args) => Reload(); }
/// <summary> /// Kdyz se objevi novy soubor /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void newFile_Created(object sender, FileSystemEventArgs e) { Console.WriteLine("Novy soubor: {0}", e.Name); fw = new FileWatcher(e.Name); if (fw != null) { fw.Stop(); fw.Changed -= fw_Changed; } fw.Changed += fw_Changed; }
public AssemblyTest(AssemblyTestConfiguration config, UI.AssemblyTestControl control) { _config = config; Control = control; var path = _config.AssemblyPath; control.Title.Content = Path.GetFileName(path); _watcher = new FileWatcher(path); _watcher.Changed += refresh; }
/// <summary> /// Starts the peer service. /// </summary> /// <param name='port'> /// Listening port of the peer. /// </param> private static void StartPeer(int port) { string peerListName = Config.PeerListFilePath; // Initialize anti entropy protocol var vs = new VersionControl(); protocol = new AntiEntropyProtocol(port, peerListName, vs); // Initialize file watcher FileWatcher watcher = new FileWatcher(); watcher.Created += vs.Created; watcher.Changed += vs.Changed; watcher.Deleted += vs.Deleted; watcher.Renamed += vs.Renamed; watcher.Idle += vs.Flush; }
public void NestedFolderCreationAndFileCreationOnFolderUp() { var watcher = new FileWatcher(); watcher.WatchDirectory(@"c:\", ".cs"); // Create a folder watcher.ReportChange(@"c:\foo", WatcherChangeTypes.Created); // Create a nested folder watcher.ReportChange(@"c:\foo\bar", WatcherChangeTypes.Created); // Add a file var changed = watcher.ReportChange(@"c:\foo\foo.cs", WatcherChangeTypes.Created); Assert.True(changed); }
public void TestWatchedFileChanged() { var fileName = Path.GetFullPath("test.txt"); var e = new FileSystemEventArgs(WatcherChangeTypes.All, "", fileName); var watcher = new FileWatcher(fileName, "channel"); service.FileWatchers.Add(watcher); File.WriteAllText(fileName, "test contents"); service.FileChanged(watcher, e); Mock<IChatService>() .Verify(call => call.Reply(It.IsAny<Message>(), "test contents")); Assert.IsFalse(File.Exists(fileName)); }
public DomainAdapter(string appPath, string appName,DomainArgs args) { Status = DomainStatus.Stop; mArgs = args; if (appPath.LastIndexOf(System.IO.Path.DirectorySeparatorChar) != appPath.Length - 1) { appPath += System.IO.Path.DirectorySeparatorChar; } AppPath = appPath; CachePath = Path.Combine(AppPath, "_tempdll" + Path.DirectorySeparatorChar); AppName = appName; if (args !=null && args.UpdateWatch) { mWatcher = new FileWatcher(appPath, args.WatchFilter); mWatcher.Change += OnChange; } }
public void TestFileWatcherTailsFile() { string filename = Path.GetTempFileName(); var rows = new List<string>(); using (TextWriter writer = new StreamWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))) { writer.WriteLine("moi"); var watcher = new FileWatcher(); watcher.RowsAdded += (s, r) => rows.AddRange(r.Rows); Assert.IsTrue(watcher.Watch(filename)); writer.WriteLine("Terve" + Environment.NewLine + "hello"); writer.Write("äöä morjens äöä"); } Thread.Sleep(100); CollectionAssert.AreEqual(new[] { "moi", "Terve", "hello", "äöä morjens äöä" }, rows); }
private void ReCreateWatcher() { // ensure old watcher is disposed if (_watchDataFileForChanges != null) { _watchDataFileForChanges.Dispose(); } // setting FileSystemWatcher to watch messagesFilePath dir for given file var messagesFileName = Path.GetFileName(string.Format("messages.{0}.csv", LangID)); if (messagesFileName != null) { _watchDataFileForChanges = new FileWatcher(Path.Combine(InternationalizationFilesDirectory, messagesFileName)); _watchDataFileForChanges.Changed += (sender, args) => Reload(); } }
public LogReader() { string file = Config.get_game_path() + "\\Chat.log"; try { //Open the file FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); reader = new StreamReader(fs, System.Text.Encoding.Default); // set position to end reader.ReadToEnd(); // start the filewatcher watcher = new FileWatcher(file_changed); } catch (Exception e) { System.Windows.Forms.MessageBox.Show("The log file " + file + " can not be found! Please set your AION path", "Log file error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } }
public async Task CleanupOnStartup() { Environment.SetEnvironmentVariable("MAX_DISK_BYTES", "4500000"); CancellationTokenSource cts = new CancellationTokenSource(); await Task.WhenAll(Enumerable.Range(0, 10).Select(i => TestUtilities.MakeBigFile(Path.Combine(incomingDir, $"test{i}.txt"), 1000))); FileWatcher watcher = new FileWatcher(); Task watchTask = watcher.WatchFolder(cts.Token); await Task.Delay(50); cts.Cancel(); await watchTask; string[] files = Directory.GetFiles(storageDir); Assert.AreEqual(4, files.Length, "Expected 4 files in storage directory"); }
public static IServiceProvider UseScriptWatching(this IServiceProvider serviceProvider, params string[] scriptPaths) { if (serviceProvider == null) { throw new ArgumentNullException(nameof(serviceProvider)); } if (scriptPaths == null || scriptPaths.Length == 0) { throw new ArgumentNullException(nameof(scriptPaths)); } var bundleManager = serviceProvider.GetService <IScriptBundleManager>(); var contentHashCache = serviceProvider.GetService <IContentHashCache>(); if (bundleManager == null && contentHashCache == null) { throw new InvalidOperationException("Script watching has no use when " + "there is no script bundle manager or content hash cache!"); } foreach (var path in scriptPaths) { var fileWatcherFactory = serviceProvider.GetRequiredService <IFileWatcherFactory>(); if (fileWatcherFactory.Watchers.Any(x => x.Path == path && x.Filter == "*.js") == true) { continue; } var scriptWatcher = new FileWatcher(path, "*.js"); scriptWatcher.Changed += (name) => { bundleManager?.ScriptsChanged(); contentHashCache?.ScriptsChanged(); }; fileWatcherFactory.KeepAlive(scriptWatcher); } return(serviceProvider); }
private void RegisterConfigMonitor() { var path = Path.Combine(Directory.GetCurrentDirectory(), Strings.ConfigFileName); var fileWatcher = new FileWatcher(path); fileWatcher.Changed += (sender, e) => { try { _whConfig.Instance = WhConfig.Load(e.FullPath); } catch (Exception ex) { _logger.Error("Error while reloading config:"); _logger.Error(ex); } }; fileWatcher.Start(); }
/// <summary> /// 读取最新文件内容,只管读就是了,FileWatch会自动加载最新的文件 /// </summary> /// <param name="file"> </param> /// <param name="encoding"> </param> /// <param name="afterHander"> </param> /// <param name="preHander"> </param> /// <returns> </returns> /// <exception cref="FileNotFoundException"></exception> /// <exception cref="NullReferenceException"></exception> public static string GetFileCurrentContent(string file, System.Text.Encoding encoding, Func<string, string> preHander, Func<string, string> afterHander) { if (!File.Exists(file)) { throw new FileNotFoundException(file); } var content = FileWatchStorageProvider.Provider.Get(file); if (content == null) { Action readFile = () => { var strFileContent = IOUtility.ReadAsString(file); if (preHander != null) strFileContent = preHander(strFileContent); content = encoding.GetBytes(strFileContent); FileWatchStorageProvider.Provider.AddOrUpdate(file, content); }; readFile(); var fw = new FileWatcher(file) { OnChanged = (o, e) => readFile() }; } if (content == null) throw new NullReferenceException("content"); var strcontent = encoding.GetString(content); if (afterHander != null) { return afterHander(strcontent); } return strcontent; }
public static IServiceCollection SettingsTigerWebApi(this IServiceCollection services) { #region 验证文件夹 string packagePath = Path.Combine(Environment.CurrentDirectory, CommonConstant.PACKAGE_NAME); if (!Directory.Exists(packagePath)) { Directory.CreateDirectory(packagePath); } #endregion #region 设置PackageItem PackageItem[] packageItems = AssemblyHelper.GetPackageItems(packagePath); foreach (PackageItem packageItem in packageItems) { // 设置PackageItem(重复出现则会覆盖) Global.PackageItem[packageItem.AssemblyName] = packageItem; foreach (Type typeItem in packageItem.Assembly.GetExportedTypes()) { Common.AddService(typeItem); } } #endregion #region 设置APP,后期使用DB|Cache替换 Global.App.Add("10000", "qwerasdfzxcv"); #endregion #region 自动引用依赖文件 AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(TigerResolveEventHandler); #endregion #region 监听文件 FileWatcher fileWatcher = new FileWatcher(Path.Combine(Environment.CurrentDirectory, "Packages")); fileWatcher.Changed += FileWatcherChanged; fileWatcher.Run(); #endregion return(services); }
private PipelineController(IView view) { Instance = this; PipelineSettings.Default.Load(); SelectedItems = new List <IProjectItem>(); _actionStack = new ActionStack(this); View = view; View.Attach(this); ProjectOpen = false; _watcher = new FileWatcher(this, view); _templateItems = new List <ContentItemTemplate>(); LoadTemplates(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Templates")); UpdateMenu(); view.UpdateRecentList(PipelineSettings.Default.ProjectHistory); }
public async Task ShouldDetect_FileUpdate() { var updateOccured = false; using var watcher = new FileWatcher(TestFilePath); watcher.Updates .Where(x => x == LogStateChangeType.Updated) .Subscribe( _ => updateOccured = true); await watcher.StartAsync(); await File.AppendAllTextAsync(TestFilePath, "newText"); while (!updateOccured) { } Assert.True(updateOccured); }
public FileStatus(Repository repos) { Debug.Assert(repos != null); _repos = repos; MultipleDisposable.Add(() => WipFiles.Value.ForEach(c => c.Dispose())); UpdateWipFiles(null); var watcher = new FileWatcher(repos.Path, true) .AddTo(MultipleDisposable); new EventListener<FileSystemEventHandler>( h => watcher.FileUpdated += h, h => watcher.FileUpdated -= h, (s, e) => UpdateWipFiles(e)) .AddTo(MultipleDisposable); watcher.Start(); }
public async Task Stops_IsCalled_StopsRaisingEvents() { ResetTestFileData(); try { var fileWatcher = new FileWatcher(ValidWatchablePath); fileWatcher.Stop(); using (var monitoredFileWatcher = fileWatcher.Monitor()) { File.WriteAllText(TestTxtPath, File.ReadAllText(TestTxtPath) + "s"); await Task.Delay(1000); monitoredFileWatcher.Should().NotRaise(nameof(fileWatcher.ResourceModified)); } } finally { ResetTestFileData(); } }
private void btnFile_Click(object sender, RoutedEventArgs e) { var folderDialog = new FolderSelectDialog(); folderDialog.InitialDirectory = _fileWatcher?.InputFolder ?? Environment.CurrentDirectory; // Show open file dialog box var result = folderDialog.ShowDialog(); // Process open file dialog box results if (result) { // Open document var folderName = folderDialog.FolderName; lbFolder.Text = folderName; btnStart.Content = "Start"; _isFileWatcherRunning = false; //Dispose all outstanding tasks (if any) _fileWatcher?.Dispose(); _fileWatcher = new FileWatcher(folderName); //Dispose all subscription if it exists. _subscription?.Dispose(); //Register action happens when new message signaled. _subscription = _fileWatcher.InputValue.ObserveOnDispatcher().Subscribe((msg) => { _session?.Messages.Add(new Message() { Content = msg, Timestamp = DateTime.Now }); }); //Create new session for output to UI _session = new Session(folderName); DataContext = _session; } }
public async Task MoveExistingFile() { CancellationTokenSource cts = new CancellationTokenSource(); File.WriteAllText(Path.Combine(incomingDir, "test.txt"), "This is a test file!"); FileWatcher watcher = new FileWatcher(); Task watchTask = watcher.WatchFolder(cts.Token); await Task.Delay(50); cts.Cancel(); await watchTask; string[] files = Directory.GetFiles(storageDir); Assert.AreEqual(1, files.Length, "Expected only one file in storage directory"); string file = files[0]; Assert.True(file.Contains("test.txt"), "Expected file to contain original name"); Assert.AreEqual(File.ReadAllText(file), "This is a test file!", "Expected file contents to remain the same"); }
static async Task Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Use is like this:\n dataAtr [folderWithRazorFiles] [out.d.ts file]"); } var inDir = args[0]; var outFile = args[1]; var file = new FileWatcher(inDir, "*.cshtml", outFile); await file.UpdateFiles(); //System.Console.WriteLine(file.FileModels.Select(i => i.ToString()).Aggregate((i, j) => i + "\n" + j)); //var outTs = new TypescriptFileBuilder(new DataAtr.Models.ProjectModel() { FileModels = file.FileModels }).GetTypescript(); //var TsProj = new DataAtr.Models.Typescript.TypeDeffinition(new DataAtr.Models.ProjectModel { FileModels = file.FileModels }).TypescriptPoject(); //File.WriteAllText(outFile, TsProj); //Console.WriteLine("Started"); while (Console.ReadKey().KeyChar != '\0') { ; } }
public async Task Start_SingleFile_CreateCaptured() { // arrange var fileName = "file.test"; var filePath = $"{TestFolder}/{fileName}"; using var watcher = new FileWatcher($"{TestFolder}"); var firstEventTask = SubscribeFirstAsync <IFileEvent, FileCreated>(watcher.FileObservable()); // act watcher.Start(); await using var file = File.Create(filePath); // assert var ev = await firstEventTask; ev.Should().BeOfType <FileCreated>(); ev.As <FileCreated>().FileName.Should().Be(fileName); IsPathEqual(ev.As <FileCreated>().Path, filePath).Should().BeTrue(); }
public async Task Start_Directory_CreateCaptured() { // arrange var dirName = "dir"; var dirPath = $"{TestFolder}/{dirName}"; using var watcher = new FileWatcher($"{TestFolder}"); var firstEventTask = SubscribeFirstAsync <IFileEvent, FileCreated>(watcher.FileObservable()); // act watcher.Start(); Directory.CreateDirectory(dirPath); // assert var ev = await firstEventTask; ev.Should().BeOfType <FileCreated>(); ev.As <FileCreated>().FileName.Should().Be(dirName); IsPathEqual(ev.As <FileCreated>().Path, dirPath).Should().BeTrue(); }
public async Task ShouldDetect_FileDelete() { var deleteOccured = false; using var watcher = new FileWatcher(TestFilePath); watcher.Updates .Where(x => x == LogStateChangeType.NotAvailable) .Subscribe( _ => deleteOccured = true); await watcher.StartAsync(); File.Delete(TestFilePath); while (!deleteOccured) { } Assert.True(deleteOccured); }
public ShaderFileDebugger(string vertexFile, string fragmentFile, byte[] vertexShader = null, byte [] fragmentShader = null) { if (File.Exists(vertexFile) && File.Exists(fragmentFile)) { shaderWatcherVertex = new FileWatcher(vertexFile); shaderWatcherFragment = new FileWatcher(fragmentFile); CheckForShaderChange(); while(null != LastException) { form.Hide(); FormShaderExceptionFacade.ShowModal(LastException); CheckForShaderChange(); } } else { var sVertex = Encoding.UTF8.GetString(vertexShader); var sFragment = Encoding.UTF8.GetString(fragmentShader); shader = ShaderLoader.FromStrings(sVertex, sFragment); } }
private static FileHandler InstantiateDefaultFileHandler() { AppSettingsReader appSettingsReader = new AppSettingsReader(); string ourMail = (string)appSettingsReader.GetValue("OurMailAddress", typeof(string)); string targetMail = (string)appSettingsReader.GetValue("TargetMailAddress", typeof(string)); ISmtpHandler smtpHandler = GetSmtpHandler(appSettingsReader); ISendingFileFactory fileFactory = new SendingFileFactory(); FileSender sender = new FileSender(ourMail, targetMail, smtpHandler, fileFactory); IFileManipulator manipulator = new FileManipulator(); string mailToSendFolderPath = (string)appSettingsReader.GetValue("MailToSendFP", typeof(string)); string invalidMailFolderPath = (string)appSettingsReader.GetValue("InvalidMailFP", typeof(string)); // NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; NotifyFilters notifyFilter = (NotifyFilters)appSettingsReader.GetValue("NotifyFilter", typeof(int)); string filter = (string)appSettingsReader.GetValue("Filter", typeof(string)); IFileWatcher watcher = new FileWatcher(mailToSendFolderPath, filter, notifyFilter, manipulator); ILog logger = LogManager.GetLogger(typeof(FileHandler)); FileHandler result = new FileHandler(mailToSendFolderPath, invalidMailFolderPath, watcher, manipulator, sender, logger); return(result); SmtpHandler GetSmtpHandler(AppSettingsReader settingsReader) { string host = (string)settingsReader.GetValue("Host", typeof(string)); int port = (int)settingsReader.GetValue("Port", typeof(int)); SmtpDeliveryMethod method = (SmtpDeliveryMethod)settingsReader.GetValue("SMTPDeliveryMethod", typeof(int)); string ourMailPassword = (string)settingsReader.GetValue("OurMailPassword", typeof(string)); bool enableSsl = (bool)settingsReader.GetValue("EnableSSL", typeof(bool)); return(new SmtpHandler(host, port, method, new NetworkCredential(ourMail, ourMailPassword), enableSsl)); } }
/// <summary> /// Exports file with given filename, replaces already existing file with same filename /// FILE WATCHER will check if file was created or modified /// </summary> /// <param name="fileName"> /// Filename and path for export. Use this form: C:\test\testExport /// </param> /// <returns> /// true: if file was exported successful /// false: if an error occurred /// </returns> public bool Run(string fileName) { try { string pathForWatcher = Path.GetDirectoryName(fileName); var watcher = new FileWatcher(pathForWatcher, "*.xls"); watcher.StartFileWatcher(); if (new OpenExport().ViaIcon() == false) { // failed to open export dialog Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Failed to open export file browser dialog"); return(false); } if (Execution.SaveAsFileBrowser.SaveAs(fileName) == false) { // failed to save file Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Failed to export file"); return(false); } // HACK: 2013-06-07: replaces uncommented line below if (!watcher.WaitUntilEventFired(DefaultValues.GeneralTimeout)) { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "FileSystemWatcher did not recognize a file operation, saving failed"); watcher.StopFileWatcher(); return(false); } // saving successful Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Exported file successfully"); return(true); } catch (Exception exception) { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), exception.Message); return(false); } }
private static void Init() { try { _hbService = new ServiceHost <HeartBeatService>(); _hbService.Open(); IList <WatchElement> elements = WatchSection.GetActiveWatches(); EnqueueMissedFiles(elements); _fwatcher = new FileWatcher(elements); _fwatcher.Error += new EventHandler <ErrorArgs>(Error); _fwatcher.NeedAction += new EventHandler <NeedActionArgs>(NeedAction); _fwatcher.Delete += new EventHandler <NeedDeleteArgs>(Delete); _fwatcher.Start(); _processor = new NotifyProcessor(Settings.Default.QueueProcessorInterval); _processor.NeedDelete += new EventHandler <NeedDeleteArgs>(Delete); _processor.Start(); } catch (Exception ex) { Trace.WriteLine(ex.ToString(), Constants.TRACE_ERROR); } }
/// <summary> /// 初始化使用 <paramref name="fileName"/> 作为配置文件的 <see cref="FileConfigurationRepo"/> 的新实例。 /// </summary> /// <param name="fileName">配置文件的文件路径。</param> public FileConfigurationRepo(string fileName) { if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); } var fullPath = Path.GetFullPath(fileName); _file = new FileInfo(fullPath); _saveLoop = new PartialAwaitableRetry(SaveCoreAsync); // 监视文件改变。 _watcher = new FileWatcher(_file); _watcher.Changed += OnFileChanged; #pragma warning disable 4014 _watcher.WatchAsync(); #pragma warning restore 4014 // 反序列化。 DeserializeTask = Task.Run(async() => await DeserializeFile(_file).ConfigureAwait(false)); }
public UploaderViewModel() { string ImageFolder = (string)ConfigurationManager.AppSettings["ImageFolder"]; imgManager = new ImageManager(); Version ver = Assembly.GetEntryAssembly().GetName().Version; VersionNumber = PhotoUploader.Properties.Resources.main_footer_version + ver.ToString(); SelectedIcon = "/Images/Logo.ico"; FileWatcher filewatcher = (FileWatcher)App.Current.Properties["FileWatcher"]; //filewatcher.NotificationChanged = new FileWatcher.delNotificationChanged(SetImageCountMessage); //filewatcher.ProgressBarChanged = new FileWatcher.delProgressBarChanged(SetProgressBar); filewatcher.SendMessageCreated = new FileWatcher.delSendMessageCreated(GetNotificationMessage); filewatcher.GetCountofRemainedFiles = new FileWatcher.delRemainedFileChanged(GetRemainedFiles); try { using (pwdManager = new PWDManager()) { pwdManager.CameraConnectionStatusChanged = new PWDManager.DigitalDeviceAttached(RefreshConnectionStatus); pwdManager.DeviceErrorMessageThrow = new PWDManager.DeviceErrorMessageThrowed(GetNotificationMessage); pwdManager.PlugAndPlayChanged = new PWDManager.delPlugAndPlayMessage(SetNotificationMessage); pwdManager.CheckPnPPoint(); } } catch (Exception ex) { Logger.Basic.Debug("Error : " + ex.ToString(), ex); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(timeout = TEST_TIMEOUT) public void notifyAboutStoreFileDeletion() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void NotifyAboutStoreFileDeletion() { assumeFalse(SystemUtils.IS_OS_WINDOWS); string fileName = TestDirectory.databaseLayout().metadataStore().Name; FileWatcher fileWatcher = GetFileWatcher(_database); CheckPointer checkpointer = GetCheckpointer(_database); DeletionLatchEventListener deletionListener = new DeletionLatchEventListener(fileName); fileWatcher.AddFileWatchEventListener(deletionListener); do { CreateNode(_database); ForceCheckpoint(checkpointer); } while (!deletionListener.AwaitModificationNotification()); DeleteFile(TestDirectory.storeDir(), fileName); deletionListener.AwaitDeletionNotification(); _logProvider.rawMessageMatcher().assertContains("'" + fileName + "' which belongs to the store was deleted while database was running."); }
public void _watcher_DeletedTest() { string dirName = "TestDirectory4"; Directory d = fact_createTestDirectory(dirName); string fname = System.IO.Path.Combine(d.Path, "Test1.txt"); File df = new File(fname); df.Create(); FileWatcher fw = new FileWatcher(fname); // add deleted event and test if fires when file is deleted. _TestTrigger = new AutoResetEvent(false); bHandlerRaised = false; tmpFileName = ""; fw.FileDeleted += fw_FileDeleted; df.Delete(); _TestTrigger.WaitOne(2000); Assert.IsTrue(bHandlerRaised, "File Deleted Event not raised"); Assert.AreEqual(fname, tmpFileName, "Wrong File Delete Event raised"); // now prove event is not raised if file is deleted df.Create(); fw.FileDeleted -= fw_FileDeleted; // remove event _TestTrigger = null; _TestTrigger = new AutoResetEvent(false); bHandlerRaised = false; GC.WaitForPendingFinalizers(); df.Delete(); _TestTrigger.WaitOne(2000); // should time out Assert.IsFalse(bHandlerRaised, "File Deleted Event should not raised"); _TestTrigger = null; fw = null; }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(timeout = TEST_TIMEOUT) public void doNotNotifyAboutLuceneIndexFilesDeletion() throws InterruptedException, java.io.IOException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void DoNotNotifyAboutLuceneIndexFilesDeletion() { DependencyResolver dependencyResolver = (( GraphDatabaseAPI )_database).DependencyResolver; FileWatcher fileWatcher = GetFileWatcher(_database); CheckPointer checkPointer = dependencyResolver.ResolveDependency(typeof(CheckPointer)); string propertyStoreName = TestDirectory.databaseLayout().propertyStore().Name; AccumulativeDeletionEventListener accumulativeListener = new AccumulativeDeletionEventListener(); ModificationEventListener modificationListener = new ModificationEventListener(propertyStoreName); fileWatcher.AddFileWatchEventListener(modificationListener); fileWatcher.AddFileWatchEventListener(accumulativeListener); string labelName = "labelName"; string propertyName = "propertyName"; Label testLabel = Label.label(labelName); CreateIndexes(_database, propertyName, testLabel); do { CreateNode(_database, propertyName, testLabel); ForceCheckpoint(checkPointer); } while (!modificationListener.AwaitModificationNotification()); fileWatcher.RemoveFileWatchEventListener(modificationListener); ModificationEventListener afterRemovalListener = new ModificationEventListener(propertyStoreName); fileWatcher.AddFileWatchEventListener(afterRemovalListener); DropAllIndexes(_database); do { CreateNode(_database, propertyName, testLabel); ForceCheckpoint(checkPointer); } while (!afterRemovalListener.AwaitModificationNotification()); accumulativeListener.AssertDoesNotHaveAnyDeletions(); }
private async Task CheckGameOld() { ResultGameVerification result = CheckSkyrim(); ModVersion.Load(); FileWatcher.Init(); if (!result.IsSKSEFound && MessageBox.Show(Res.SKSENotFound, Res.Warning, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { blockMainBtn = true; await InstallSKSE(); blockMainBtn = false; } try { if (!result.IsRuFixConsoleFound && ModVersion.HasRuFixConsole == null && MessageBox.Show(Res.SSERFix, Res.Warning, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { blockMainBtn = true; await InstallRuFixConsole(); ModVersion.Save(); blockMainBtn = false; } else { ModVersion.HasRuFixConsole = result.IsRuFixConsoleFound; ModVersion.Save(); } } catch (Exception er) { blockMainBtn = false; Logger.FatalError("CheckGame_SSERFix", er); } }
private void LoadGeofencesOnChange() { _logger.Trace($"WebhookManager::LoadGeofencesOnChange"); var geofencesFolder = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), Strings.GeofenceFolder)); var fileWatcher = new FileWatcher(geofencesFolder); fileWatcher.Changed += (sender, e) => { try { _logger.Debug("Reloading Geofences"); LoadGeofences(); LoadAlarms(); // Reload alarms after geofences too } catch (Exception ex) { _logger.Error("Error while reloading geofences:"); _logger.Error(ex); } }; fileWatcher.Start(); }
public void Dispose() { ThreadHelper.ThrowIfNotOnUIThread(); FileWatcher.Unwatch(); // Ignore failures in UnadviseSolutionEvents if (this.cookie1 != VSConstants.VSCOOKIE_NIL) { _ = this.solution.UnadviseSolutionEvents(this.cookie1); this.cookie1 = VSConstants.VSCOOKIE_NIL; } if (this.cookie2 != VSConstants.VSCOOKIE_NIL) { _ = ((IVsSolutionBuildManager2)this.buildManager).UnadviseUpdateSolutionEvents(this.cookie2); this.cookie2 = VSConstants.VSCOOKIE_NIL; } if (this.cookie3 != VSConstants.VSCOOKIE_NIL) { _ = this.buildManager.UnadviseUpdateSolutionEvents3(this.cookie3); this.cookie3 = VSConstants.VSCOOKIE_NIL; } }
private void MiOpenFile_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog fileBrowserDialog = new Microsoft.Win32.OpenFileDialog(); fileBrowserDialog.RestoreDirectory = true; fileBrowserDialog.Multiselect = false; if (fileBrowserDialog.ShowDialog() == true) { fw?.Dispose(); fw = new FileWatcher(fileBrowserDialog.FileName); Lb_EcondingChanged(this, fw.Encoding); fw.EcondingChanged += Lb_EcondingChanged; sl = new ScrollLogic(fw, textBox.Dispatcher); STextBox.ScrollLogic = sl; sl.FollowTail = followTail; eofMarker.Fill = new SolidColorBrush(Color.FromRgb(127, 127, 127)); sl.IsAtEndOfFileChanged += (_, isAtEnd) => { eofMarker.Fill = new SolidColorBrush(isAtEnd ? Color.FromRgb(0, 0, 255) : Color.FromRgb(127, 127, 127)); }; sl.Init(0, Origin.Begin, STextBox.LinesOnScreen); } }
public void CreatedWorks() { this.CheckFile("created.tdd"); AutoResetEvent resetEvent = new AutoResetEvent(false); string method = string.Empty; // Github tests for some reason do not raise created compared to local os. FileWatcher from = this.Setup("Created"); from.OnAction += delegate(object sender, Routable e) { method = e.Headers["Method"]; resetEvent.Set(); }; from.Setup(); from.Start(); System.IO.File.WriteAllText($"{this.location}/Created.tdd", "test data"); this.fileSystemWatcher.Raise(x => x.Created += null, new FileSystemEventArgs(WatcherChangeTypes.Created, this.location, "Created.tdd")); bool wasAssigned = resetEvent.WaitOne(TimeSpan.FromSeconds(5)); from.Stop(); Assert.IsTrue(!string.IsNullOrWhiteSpace(method)); }
private FileWatcher constructFileWatcher(string path, bool?startWatching) { FileWatcher fileWatcher; if (path == null && startWatching == null) { fileWatcher = new FileWatcher(); } else if (path == null) { fileWatcher = new FileWatcher(startWatching: (bool)startWatching); } else if (startWatching == null) { fileWatcher = new FileWatcher(path: path); } else { fileWatcher = new FileWatcher(path: path, startWatching: (bool)startWatching); } return(fileWatcher); }
private void FileUploadButton_Click(object sender, EventArgs e) { if (logFileUploadDialog.ShowDialog() == DialogResult.OK) { SetUploadFileName(logFileUploadDialog.SafeFileName); CharacterName = GetCharacterName(logFileUploadDialog.SafeFileName); _overlay.PlayerName = CharacterName; FileWatcher fileWatcher = new FileWatcher(logFileUploadDialog.FileName, logFileUploadDialog.SafeFileName); Thread fileWatcherThread = new Thread(() => fileWatcher.Start()); fileWatcherThread.Start(); BattleWatcher battleWatcher = new BattleWatcher(fileWatcher, CharacterName); Thread battleWatcherThread = new Thread(() => battleWatcher.Start()); battleWatcherThread.Start(); PetWatcher petWatcher = new PetWatcher(fileWatcher, battleWatcher, CharacterName); Thread petWatcherThread = new Thread(() => petWatcher.Start()); petWatcherThread.Start(); _overlay.AddBattleWatcher(battleWatcher); } }
public void _watcher_ChangedTest() { string dirName = "TestDirectory3"; Directory d = fact_createTestDirectory(dirName); string fname = System.IO.Path.Combine(d.Path, "Test2.txt"); File df = new File(fname); df.Create(); FileWatcher fw = new FileWatcher(fname); // add created event and test if fires when file is created. _TestTrigger = new AutoResetEvent(false); bHandlerRaised = false; tmpFileName = ""; fw.FileChanged += fw_FileChanged; df.WriteTextLine("Changing text file", true, System.Text.Encoding.UTF8); _TestTrigger.WaitOne(2000); Assert.IsTrue(bHandlerRaised, "File Changed Event not raised"); Assert.AreEqual(fname, tmpFileName, "Wrong File Changed Event raised"); //now check that event not passed on df.Delete(); fw.FileChanged -= fw_FileChanged; bHandlerRaised = false; tmpFileName = ""; df.WriteTextLine("Changing text file again", true, System.Text.Encoding.UTF8); _TestTrigger.WaitOne(2000); // should time out Assert.IsFalse(bHandlerRaised, "File Created Event should not raised"); fw = null; }