public void RenameFileTest()
        {
            string fileName = Path.Combine(_testDirectory, "Test.txt");
            File.WriteAllText(fileName, "Test");

            var settings = new FileWatchSetting();
            settings.Directory = _testDirectory;
            settings.DelayInMS = 100;

            FileWatcherEventArgs args = null;
            int events = 0;
            using (var watch = new FileWatch(settings))
            {
                watch.StartWatching();
                watch.Changed += (o, a) =>
                {
                    args = a;
                    events++;
                };
                string newFileName = Path.Combine(_testDirectory, "TestNew.txt");
                File.Move(fileName, newFileName);
                Thread.Sleep(50);
                Assert.AreEqual(0, events);
                Thread.Sleep(80);
                Assert.AreEqual(1, events);
                Assert.AreEqual(1, args.NewFiles.Length);
                Assert.AreEqual(newFileName, args.NewFiles[0]);
                Assert.AreEqual(0, args.ChangedFiles.Length);
                Assert.AreEqual(1, args.DeletedFiles.Length);
                Assert.AreEqual(fileName, args.DeletedFiles[0]);

                Thread.Sleep(200);
                Assert.AreEqual(1, events);
            };
        }
        public void NewAndChangeDeleteFileTest()
        {
            var settings = new FileWatchSetting();
            settings.Directory = _testDirectory;
            settings.DelayInMS = 100;

            FileWatcherEventArgs args = null;
            int events = 0;
            using (var watch = new FileWatch(settings))
            {
                watch.StartWatching();
                watch.Changed += (o, a) =>
                {
                    args = a;
                    events++;
                };
                string fileName = Path.Combine(_testDirectory, "Test.txt");
                File.WriteAllText(fileName, "Test");
                Thread.Sleep(20);
                File.AppendAllText(fileName, "Test");
                Thread.Sleep(20);
                File.Delete(fileName);
                Thread.Sleep(20);
                Assert.AreEqual(0, events);
                Thread.Sleep(100);
                Assert.AreEqual(0, events);
            };
        }
        public void MultipleChangesWhileDelayTimeTest()
        {
            string fileName1 = Path.Combine(_testDirectory, "Test1.txt");
            File.WriteAllText(fileName1, "Test");
            string fileName2 = Path.Combine(_testDirectory, "Test2.txt");
            File.WriteAllText(fileName2, "Test");

            var settings = new FileWatchSetting();
            settings.Directory = _testDirectory;
            settings.DelayInMS = 100;

            FileWatcherEventArgs args = null;
            int events = 0;
            using (var watch = new FileWatch(settings))
            {
                watch.StartWatching();
                watch.Changed += (o, a) =>
                {
                    args = a;
                    events++;
                };
                string fileName3 = Path.Combine(_testDirectory, "Test3.txt");
                File.WriteAllText(fileName3, "Test");
                string fileName4 = Path.Combine(_testDirectory, "Test4.txt");
                File.WriteAllText(fileName4, "Test");
                Thread.Sleep(50);
                Assert.AreEqual(0, events);
                Thread.Sleep(80);
                Assert.AreEqual(1, events);
                Assert.AreEqual(2, args.NewFiles.Length);
                Assert.AreEqual(fileName3, args.NewFiles[0]);
                Assert.AreEqual(fileName4, args.NewFiles[1]);
                Assert.AreEqual(0, args.ChangedFiles.Length);
                Assert.AreEqual(0, args.DeletedFiles.Length);
                Thread.Sleep(200);
                Assert.AreEqual(1, events);
                File.Delete(fileName1);
                File.Delete(fileName2);
                File.AppendAllText(fileName3, "Test");
                File.AppendAllText(fileName4, "Test");
                string fileName5 = Path.Combine(_testDirectory, "Test5.txt");
                File.WriteAllText(fileName5, "Test");
                string fileName6 = Path.Combine(_testDirectory, "Test6.txt");
                File.WriteAllText(fileName6, "Test");
                Thread.Sleep(50);
                Assert.AreEqual(1, events);
                Thread.Sleep(80);
                Assert.AreEqual(2, events);
                Assert.AreEqual(fileName5, args.NewFiles[0]);
                Assert.AreEqual(fileName6, args.NewFiles[1]);
                Assert.AreEqual(fileName3, args.ChangedFiles[0]);
                Assert.AreEqual(fileName4, args.ChangedFiles[1]);
                Assert.AreEqual(fileName1, args.DeletedFiles[0]);
                Assert.AreEqual(fileName2, args.DeletedFiles[1]);

                Thread.Sleep(200);
                Assert.AreEqual(2, events);
            };
        }
Exemple #4
0
        private readonly FileWatch m_watcher;                 // Watch the source file

        public Grapher()
        {
            DoubleBuffered = true;
            InitializeComponent();
            m_recent_files = new RecentFiles(m_menu_file_recent_files, LoadFile);
            m_recent_files.Import(Settings.RecentFiles);
            m_plot    = new List <Plot>();
            m_data    = new List <Series>();
            m_watcher = new FileWatch();

            m_menu_file_open.Click             += delegate { LoadFile(); };
            m_menu_exit.Click                  += delegate { Close(); };
            m_menu_add_plot.Click              += delegate { AddPlot(); };
            m_menu_data_add_series.Click       += delegate { AddSeries(); };
            m_menu_data_show_series_list.Click += delegate { ShowSeriesList(); };

            // Persist the window position
            StartPosition    = FormStartPosition.Manual;
            Bounds           = Settings.WindowPosition;
            LocationChanged += delegate { if (WindowState != FormWindowState.Minimized)
                                          {
                                              Settings.WindowPosition = Bounds; Settings.Save();
                                          }
            };
            ResizeEnd += delegate { Settings.WindowPosition = Bounds; Settings.Save(); };

            // Check for changed files
            GotFocus += delegate { m_watcher.CheckForChangedFiles(); };

            m_grid.AutoGenerateColumns     = false;
            m_grid.ClipboardCopyMode       = DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
            m_grid.KeyDown                += DataGridView_Extensions.Delete;
            m_grid.KeyDown                += DataGridView_Extensions.PasteGrow;
            m_grid.KeyDown                += DataGridView_Extensions.CutCopyPasteReplace;
            m_grid.RowPrePaint            += RowPrePaint;
            m_grid.ColumnAdded            += OnColumnAdded;
            m_grid.MouseClick             += OnClick;
            m_grid.ColumnHeaderMouseClick += OnColumnHeaderClicked;

            Load += delegate
            {
                m_grid.ColumnCount           = 2;
                m_grid.RowCount              = 10;
                m_grid.Columns[0].Width      = 40;
                m_grid.Columns[0].HeaderText = "Index";
                m_grid.ClearSelection();

                // Add a default plot
                Plot p = new Plot();
                p.Graph.SetLabels("Plot 0", "", "");
                m_plot.Add(p);
                UpdateGraphMenu();
            };
        }
Exemple #5
0
        public void StartFileWatcher()
        {
#if DDR_RUNTIME_DLL_LINKING_
            StopFileWatcher();
            m_fileWatch = new FileWatch();
            m_fileWatch.m_sourceFile = m_sourceFile;
            m_fileWatch.m_targetFile = m_targetFile;
            m_fileWatch.m_callback   = OnChanged;

            // Begin watching.
            m_fileWatch.Start();
#endif
        }
Exemple #6
0
        private void App_Startup(object sender, StartupEventArgs e)
        {
#if !DEBUG
            if (Process.GetProcessesByName("MultiRPC").Length > 1)
            {
                if (File.Exists(FileLocations.OpenFileLocalLocation))
                {
                    try
                    {
                        File.Delete(FileLocations.OpenFileLocalLocation);
                    }
                    catch
                    {
                        App.Logging.Application(App.Text.CouldntDelete + " " + FileLocations.OpenFileLocalLocation);
                    }
                }
                if (e.Args.Length > 0)
                {
                    File.WriteAllLines(FileLocations.OpenFileLocalLocation, new List <string> {
                        "LOADCUSTOM", e.Args[1]
                    });
                }
                else
                {
                    File.Create(FileLocations.OpenFileLocalLocation);
                }
                Current.Shutdown();
            }
            else if (e.Args.Length > 1 && e.Args[0] == "-custom")
            {
                StartedWithJumpListLogic = true;
                _ = CustomPage.JumpListLogic(e.Args[1], true);
            }
#endif

            FileWatch.Create();
            SettingsPage.UIText = new List <UIText>();
            GetLangFiles().ConfigureAwait(false).GetAwaiter().GetResult();
            UITextUpdate().ConfigureAwait(false).GetAwaiter().GetResult();
            Config = Config.Load().Result;
            UITextUpdate().ConfigureAwait(false).GetAwaiter().GetResult();
            Logging = new Logging();
            File.AppendAllText(FileLocations.ErrorFileLocalLocation,
                               $"\r\n------------------------------------------------------------------------------------------------\r\n{Text.ErrorsFrom} {DateTime.Now.ToLongDateString()} {DateTime.Now.ToLongTimeString()}");
            DispatcherUnhandledException += App_DispatcherUnhandledException;
        }
Exemple #7
0
        public LogUI(string title, string persist_name)
        {
            InitializeComponent();
            m_watch = new FileWatch {
                PollPeriod = TimeSpan.FromMilliseconds(FilePollPeriodMS)
            };

            Title = title;

            // Support for dock container controls
            DockControl = new DockControl(this, persist_name)
            {
                TabText             = Title,
                DefaultDockLocation = new DockContainer.DockLocation(auto_hide: EDockSite.Right),
                TabColoursActive    = new DockContainer.OptionData().TabStrip.ActiveTab,
            };

            // When docked in an auto-hide panel, pop out on new messages
            PopOutOnNewMessages = true;

            // Line wrap default
            SetLineWrap(false);

            // A buffer of the log entries.
            // This is populated by calls to AddMessage or from the log file.
            LogEntries = new BindingListEx <LogEntry>();

            // Define a line in the log
            LogEntryPattern = null;
            //new Regex(@"^(?<File>.*?)\|(?<Level>.*?)\|(?<Timestamp>.*?)\|(?<Message>.*)\n"
            //	,RegexOptions.Singleline|RegexOptions.Multiline|RegexOptions.CultureInvariant|RegexOptions.Compiled);
            //new Regex(@"^\u001b(?<lvl>\d),(?<time>.*?),(?<name>.*?),""(?<msg>.*?)"",""(?<except>.*?)"",(?<count>\d+)\s*\n"
            //	,RegexOptions.Singleline|RegexOptions.Multiline|RegexOptions.CultureInvariant|RegexOptions.Compiled);

            // Highlighting patterns
            Highlighting = new BindingListEx <HLPattern>();

            // Column fill weights
            FillWeights = new Dictionary <string, float>
            {
                { ColumnNames.Tag, 0.3f },
                { ColumnNames.Level, 0.3f },
                { ColumnNames.Timestamp, 0.6f },
                { ColumnNames.Message, 5.0f },
                { ColumnNames.File, 2.0f },
                { ColumnNames.Line, 0.02f },
                { ColumnNames.Occurrences, 0.02f },
            };

            // The log entry delimiter
            LineDelimiter = Log_.EntryDelimiter;

            // Limit the number of log entries to display
            MaxLines     = 500;
            MaxFileBytes = 2 * 1024 * 1024;

            // Hook up UI
            SetupUI();

            // Create straight away
            CreateHandle();
        }
Exemple #8
0
        private void App_Startup(object sender, StartupEventArgs e)
        {
            #if !DEBUG
            var args = e.Args?.ToList() ?? System.Extra.Uri.GetQueryStringParameters() ?? new List <string>();
            if (Process.GetProcessesByName("MultiRPC").Length > 1)
            {
                if (File.Exists(FileLocations.OpenFileLocalLocation))
                {
                    try
                    {
                        File.Delete(FileLocations.OpenFileLocalLocation);
                    }
                    catch
                    {
                        Logging.Application(Text.CouldntDelete + " " + FileLocations.OpenFileLocalLocation);
                    }
                }

                if (args.Contains("-custom") && args.IndexOf("-custom") + 1 >= args.Count)
                {
                    File.WriteAllLines(FileLocations.OpenFileLocalLocation,
                                       new List <string> {
                        "LOADCUSTOM", args.ElementAt(args.IndexOf("-custom") + 1)
                    });
                }
                else
                {
                    File.Create(FileLocations.OpenFileLocalLocation);
                }

                if (!args.Contains("--fromupdate"))
                {
                    Current.Shutdown();
                }
            }
            else if (args.Contains("-custom") && args.IndexOf("-custom") + 1 >= args.Count)
            {
                StartedWithJumpListLogic = true;
                _ = CustomPage.StartCustomProfileLogic(args.ElementAt(args.IndexOf("-custom") + 1), true);
            }
            #endif

            FileWatch.Create();
            SettingsPage.UIText = new List <UIText>();
            GetLangFiles();
            Config = Config.Load();
            if (Config.Debug)
            {
                try
                {
                    UITextUpdate();
                    Logging = new Logging();
                    File.AppendAllText(FileLocations.ErrorFileLocalLocation,
                                       $"\r\n------------------------------------------------------------------------------------------------\r\n{Text.ErrorsFrom} {DateTime.Now.ToLongDateString()} {DateTime.Now.ToLongTimeString()}");
                    DispatcherUnhandledException += App_DispatcherUnhandledException;
                    Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
                    AppDomain.CurrentDomain.UnhandledException       += CurrentDomain_UnhandledException;
                    TaskScheduler.UnobservedTaskException            += TaskScheduler_UnobservedTaskException;
                    Dispatcher.UnhandledException += Dispatcher_UnhandledException;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "Startup error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                UITextUpdate();
                Logging = new Logging();
                File.AppendAllText(FileLocations.ErrorFileLocalLocation,
                                   $"\r\n------------------------------------------------------------------------------------------------\r\n{Text.ErrorsFrom} {DateTime.Now.ToLongDateString()} {DateTime.Now.ToLongTimeString()}");
                DispatcherUnhandledException += App_DispatcherUnhandledException;
            }
        }
Exemple #9
0
        private static void OnMessageReceived(object sender, NetCoreEventArgs e)
        {
            try
            {
                // This is where you implement interaction.
                // Warning: Any error thrown in here will be caught by NetCore and handled by being displayed in the console.

                var message         = e.message;
                var simpleMessage   = message as NetCoreSimpleMessage;
                var advancedMessage = message as NetCoreAdvancedMessage;

                ConsoleEx.WriteLine(message.Type);
                switch (message.Type) //Handle received messages here
                {
                case RTCV.NetCore.Commands.Remote.AllSpecSent:
                {
                    //We still need to set the emulator's path
                    AllSpec.VanguardSpec.Update(VSPEC.EMUDIR, FileWatch.currentDir);
                    SyncObjectSingleton.FormExecute(() =>
                        {
                            FileWatch.UpdateDomains();
                        });
                }
                break;

                case RTCV.NetCore.Commands.Basic.SaveSavestate:
                    e.setReturnValue("");
                    break;

                case RTCV.NetCore.Commands.Basic.LoadSavestate:
                    e.setReturnValue(true);
                    break;

                case RTCV.NetCore.Commands.Remote.PreCorruptAction:
                    FileWatch.KillProcess();
                    FileWatch.currentSession.fileInterface?.CloseStream();
                    FileWatch.RestoreTarget();
                    break;

                case RTCV.NetCore.Commands.Remote.PostCorruptAction:
                    FileWatch.currentSession.fileInterface.CloseStream();
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        Executor.Execute();
                        Vault.SaveVaultDb();
                    });
                    break;

                case RTCV.NetCore.Commands.Remote.CloseGame:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        FileWatch.KillProcess();
                    });
                    break;

                case RTCV.NetCore.Commands.Remote.DomainGetDomains:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        e.setReturnValue(FileWatch.GetInterfaces());
                    });
                    break;

                case RTCV.NetCore.Commands.Remote.EventEmuMainFormClose:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        S.GET <StubForm>()?.Close();
                        Environment.Exit(-1);
                    });
                    break;

                case RTCV.NetCore.Commands.Remote.IsNormalAdvance:
                    e.setReturnValue(true);
                    break;

                case RTCV.NetCore.Commands.Remote.EventCloseEmulator:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        S.GET <StubForm>()?.Close();
                        Environment.Exit(-1);
                    });
                    break;
                }
            }
            catch (Exception ex)
            {
                if (VanguardCore.ShowErrorDialog(ex, true) == DialogResult.Abort)
                {
                    throw new RTCV.NetCore.AbortEverythingException();
                }
            }
        }
Exemple #10
0
        private static void OnMessageReceived(object sender, NetCoreEventArgs e)
        {
            try
            {
                // This is where you implement interaction.
                // Warning: Any error thrown in here will be caught by NetCore and handled by being displayed in the console.

                var message         = e.message;
                var simpleMessage   = message as NetCoreSimpleMessage;
                var advancedMessage = message as NetCoreAdvancedMessage;

                ConsoleEx.WriteLine(message.Type);
                switch (message.Type) //Handle received messages here
                {
                case REMOTE_ALLSPECSSENT:
                {
                    //We still need to set the emulator's path
                    AllSpec.VanguardSpec.Update(VSPEC.EMUDIR, FileWatch.currentDir);
                    SyncObjectSingleton.FormExecute(() =>
                        {
                            FileWatch.UpdateDomains();
                        });
                }
                break;

                case SAVESAVESTATE:
                    e.setReturnValue("");
                    break;

                case LOADSAVESTATE:
                    e.setReturnValue(true);
                    break;

                case REMOTE_PRECORRUPTACTION:
                    FileWatch.KillProcess();
                    FileWatch.currentFileInfo.targetInterface.CloseStream();
                    FileWatch.RestoreTarget();
                    break;

                case REMOTE_POSTCORRUPTACTION:
                    //var fileName = advancedMessage.objectValue as String;
                    FileWatch.currentFileInfo.targetInterface.CloseStream();
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        Executor.Execute();
                    });
                    break;

                case REMOTE_CLOSEGAME:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        FileWatch.KillProcess();
                    });
                    break;

                case REMOTE_DOMAIN_GETDOMAINS:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        e.setReturnValue(FileWatch.GetInterfaces());
                    });
                    break;

                case REMOTE_EVENT_EMU_MAINFORM_CLOSE:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        Environment.Exit(0);
                    });
                    break;

                case REMOTE_ISNORMALADVANCE:
                    e.setReturnValue(true);
                    break;

                case REMOTE_EVENT_CLOSEEMULATOR:
                    Environment.Exit(-1);
                    break;
                }
            }
            catch (Exception ex)
            {
                if (VanguardCore.ShowErrorDialog(ex, true) == DialogResult.Abort)
                {
                    throw new RTCV.NetCore.AbortEverythingException();
                }
            }
        }
        private static void OnMessageReceived(object sender, NetCoreEventArgs e)
        {
            try
            {
                // This is where you implement interaction.
                // Warning: Any error thrown in here will be caught by NetCore and handled by being displayed in the console.

                var message         = e.message;
                var simpleMessage   = message as NetCoreSimpleMessage;
                var advancedMessage = message as NetCoreAdvancedMessage;

                ConsoleEx.WriteLine(message.Type);
                switch (message.Type) //Handle received messages here
                {
                case RTCV.NetCore.Commands.Remote.AllSpecSent:
                {
                    //We still need to set the emulator's path
                    AllSpec.VanguardSpec.Update(VSPEC.EMUDIR, FileWatch.currentDir);
                    SyncObjectSingleton.FormExecute(() =>
                        {
                            FileWatch.UpdateDomains();
                        });
                }
                break;

                case RTCV.NetCore.Commands.Basic.SaveSavestate:

                    string key = (advancedMessage.objectValue as string);

                    //TODO: Sync states with keys

                    SyncObjectSingleton.FormExecute(() =>
                    {
                        S.GET <StubForm>().btnRamSaveState_Click(null, null);
                        string returnKey = VanguardCore.SaveSavestate_NET(key);
                        e.setReturnValue(returnKey);
                    });

                    break;

                case RTCV.NetCore.Commands.Basic.LoadSavestate:

                    var cmd      = advancedMessage.objectValue as object[];
                    var path     = cmd[0] as string;
                    var location = (StashKeySavestateLocation)cmd[1];

                    SyncObjectSingleton.FormExecute(() =>
                    {
                        //e.setReturnValue(VanguardCore.LoadSavestate_NET(path, location));
                        VanguardCore.LoadSavestate_NET(path, location);
                        S.GET <StubForm>().RepackState(false);
                    });

                    e.setReturnValue(true);

                    break;

                case RTCV.NetCore.Commands.Remote.PreCorruptAction:
                    FileWatch.KillProcess();
                    FileWatch.currentFileInfo.targetInterface.CloseStream();
                    FileWatch.RestoreTarget();
                    break;

                case RTCV.NetCore.Commands.Remote.PostCorruptAction:
                    //var fileName = advancedMessage.objectValue as String;
                    FileWatch.currentFileInfo.targetInterface?.CloseStream();
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        Executor.Execute();
                    });
                    break;

                case RTCV.NetCore.Commands.Remote.CloseGame:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        FileWatch.KillProcess();
                    });
                    break;

                case RTCV.NetCore.Commands.Remote.DomainGetDomains:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        e.setReturnValue(FileWatch.GetInterfaces());
                    });
                    break;

                case RTCV.NetCore.Commands.Remote.EventEmuMainFormClose:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        Environment.Exit(0);
                    });
                    break;

                case RTCV.NetCore.Commands.Remote.IsNormalAdvance:
                    e.setReturnValue(true);
                    break;

                case RTCV.NetCore.Commands.Remote.EventCloseEmulator:
                    Environment.Exit(-1);
                    break;
                }
            }
            catch (Exception ex)
            {
                if (VanguardCore.ShowErrorDialog(ex, true) == DialogResult.Abort)
                {
                    throw new RTCV.NetCore.AbortEverythingException();
                }
            }
        }
 public void Dispose()
 {
     FileWatch?.Dispose();
 }