public static void FileSystemWatcher_Renamed_Negative()
    {
        using (var dir = Utility.CreateTestDirectory())
        using (var watcher = new FileSystemWatcher())
        {
            // put everything in our own directory to avoid collisions
            watcher.Path = Path.GetFullPath(dir.Path);
            watcher.Filter = "*.*";
            AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Renamed);

            watcher.EnableRaisingEvents = true;

            // run all scenarios together to avoid unnecessary waits, 
            // assert information is verbose enough to trace to failure cause

            // create a file
            using (var testFile = new TemporaryTestFile(Path.Combine(dir.Path, "file")))
            using (var testDir = new TemporaryTestDirectory(Path.Combine(dir.Path, "dir")))
            {
                // change a file
                testFile.WriteByte(0xFF);
                testFile.Flush();

                // deleting a file & directory by leaving the using block
            }

            Utility.ExpectNoEvent(eventOccured, "created");
        }
    }
Example #2
0
File: test.cs Project: mono/gert
	static void Main (string [] args)
	{
		string base_dir = AppDomain.CurrentDomain.BaseDirectory;
		string watch_dir = Path.Combine (base_dir, "watch");

		FileSystemWatcher watcher = new FileSystemWatcher ();
		watcher.Path = watch_dir;
		watcher.NotifyFilter |= NotifyFilters.Size;
		watcher.Created += new FileSystemEventHandler (Created);
		watcher.Deleted += new FileSystemEventHandler (Deleted);
		watcher.Changed += new FileSystemEventHandler (Changed);
		watcher.Renamed += new RenamedEventHandler (Renamed);

		File.Create (Path.Combine (watch_dir, "tmp")).Close ();

		watcher.EnableRaisingEvents = true;
		Thread.Sleep (200);

		File.Move (Path.Combine (watch_dir, "tmp"), Path.Combine (watch_dir, "tmp2"));
		Thread.Sleep (200);

		Assert.AreEqual (1, _events.Count, "#A");

		RenamedEventArgs renamedArgs = _events [0] as RenamedEventArgs;
		Assert.IsNotNull (renamedArgs, "#B1");
		Assert.AreEqual (WatcherChangeTypes.Renamed, renamedArgs.ChangeType, "#B2");
		Assert.AreEqual (Path.Combine (watch_dir, "tmp2"), renamedArgs.FullPath, "#B3");
		Assert.AreEqual ("tmp2", renamedArgs.Name, "#B4");
		Assert.AreEqual (Path.Combine (watch_dir, "tmp"), renamedArgs.OldFullPath, "#B5");
		Assert.AreEqual ("tmp", renamedArgs.OldName, "#B6");
	}
        public void FileSystemWatcher_File_Delete_DeepDirectoryStructure()
        {
            // List of created directories
            List<TempDirectory> lst = new List<TempDirectory>();

            using (var testDirectory = new TempDirectory(GetTestFilePath()))
            using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
            using (var watcher = new FileSystemWatcher(dir.Path, "*"))
            {
                watcher.IncludeSubdirectories = true;
                watcher.NotifyFilter = NotifyFilters.FileName;

                // Create a deep directory structure
                lst.Add(new TempDirectory(Path.Combine(dir.Path, "dir")));
                for (int i = 1; i < 20; i++)
                {
                    string dirPath = Path.Combine(lst[i - 1].Path, String.Format("dir{0}", i));
                    lst.Add(new TempDirectory(dirPath));
                }

                // Put a file at the very bottom and expect it to raise an event
                string fileName = Path.Combine(lst[lst.Count - 1].Path, "file");
                Action action = () => File.Delete(fileName);
                Action cleanup = () => File.Create(fileName).Dispose();
                cleanup();

                ExpectEvent(watcher, WatcherChangeTypes.Deleted, action, cleanup, fileName);
            }
        }
        public void FileSystemWatcher_File_NotifyFilter_Attributes(NotifyFilters filter)
        {
            using (var testDirectory = new TempDirectory(GetTestFilePath()))
            using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
            using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
            {
                watcher.NotifyFilter = filter;
                var attributes = File.GetAttributes(file.Path);

                Action action = () => File.SetAttributes(file.Path, attributes | FileAttributes.ReadOnly);
                Action cleanup = () => File.SetAttributes(file.Path, attributes);

                WatcherChangeTypes expected = 0;
                if (filter == NotifyFilters.Attributes)
                    expected |= WatcherChangeTypes.Changed;
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && ((filter & LinuxFiltersForAttribute) > 0))
                    expected |= WatcherChangeTypes.Changed;
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & OSXFiltersForModify) > 0))
                    expected |= WatcherChangeTypes.Changed;
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & NotifyFilters.Security) > 0))
                    expected |= WatcherChangeTypes.Changed; // Attribute change on OSX is a ChangeOwner operation which passes the Security NotifyFilter.
                
                ExpectEvent(watcher, expected, action, cleanup, file.Path);
            }
        }
Example #5
0
 public static void FileSystemWatcher_ctor()
 {
     string path = String.Empty;
     string pattern = "*.*";
     using (FileSystemWatcher watcher = new FileSystemWatcher())
         ValidateDefaults(watcher, path, pattern);
 }
Example #6
0
 public static void FileSystemWatcher_ctor_path_pattern()
 {
     string path = @".";
     string pattern = "honey.jar";
     using (FileSystemWatcher watcher = new FileSystemWatcher(path, pattern))
         ValidateDefaults(watcher, path, pattern);
 }
    public static void FileSystemWatcher_Created_MoveDirectory()
    {
        // create two test directories
        using (TemporaryTestDirectory dir = Utility.CreateTestDirectory(),
            targetDir = new TemporaryTestDirectory(dir.Path + "_target"))
        using (var watcher = new FileSystemWatcher("."))
        {
            string testFileName = "testFile.txt";

            // watch the target dir
            watcher.Path = Path.GetFullPath(targetDir.Path);
            watcher.Filter = testFileName;
            AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);

            string sourceFile = Path.Combine(dir.Path, testFileName);
            string targetFile = Path.Combine(targetDir.Path, testFileName);

            // create a test file in source
            File.WriteAllText(sourceFile, "test content");

            watcher.EnableRaisingEvents = true;

            // move the test file from source to target directory
            File.Move(sourceFile, targetFile);

            Utility.ExpectEvent(eventOccured, "created");
        }
    }
 public void ConstructingWithPathShouldInitLog()
 {
     System.IO.FileInfo thisAssemblyPath = new System.IO.FileInfo(GetType().Assembly.Location);
       FileSystemWatcher tested = new FileSystemWatcher(thisAssemblyPath.Directory.FullName);
       ILogWriter logWriter = tested as ILogWriter;
       Assert.IsNotNull(logWriter.Log);
 }
Example #9
0
    public void Watch(string source, string target)
    {
        sourceFolder = source;
        targetFolder = target;

        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = source;
        watcher.IncludeSubdirectories = true;

        /* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;

        // Adds a filter
        watcher.Filter = "*.*";

        // Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnRenamed);

        // Begin watching.
        watcher.EnableRaisingEvents = true;
    }
Example #10
0
File: test.cs Project: mono/gert
	static void Main (string [] args)
	{
		string base_dir = AppDomain.CurrentDomain.BaseDirectory;
		string watch_dir = Path.Combine (base_dir, "watch");
		string bar_dir = Path.Combine (watch_dir, "bar");
		string foo_dir = Path.Combine (watch_dir, "foo");

		Directory.CreateDirectory (watch_dir);
		Directory.CreateDirectory (bar_dir);
		Directory.CreateDirectory (foo_dir);
		File.Create (Path.Combine (bar_dir, "hiWorld")).Close ();

		FileSystemWatcher watcher = new FileSystemWatcher ();
		watcher.Path = watch_dir;
		watcher.NotifyFilter |= NotifyFilters.Size;
		watcher.Renamed += new RenamedEventHandler (Renamed);
		watcher.IncludeSubdirectories = true;
		watcher.EnableRaisingEvents = true;

		Thread.Sleep (200);

		File.Move (Path.Combine (bar_dir, "hiWorld"), Path.Combine (bar_dir, "helloWorld"));

		Thread.Sleep (200);

		Assert.AreEqual (1, _events.Count, "#1");
		RenamedEventArgs renamedArgs = _events [0] as RenamedEventArgs;
		Assert.IsNotNull (renamedArgs, "#2");
		Assert.AreEqual (WatcherChangeTypes.Renamed, renamedArgs.ChangeType, "#3");
		AssertPaths (Path.Combine (bar_dir, "helloWorld"), renamedArgs.FullPath, "#4");
		AssertPaths (Path.Combine ("bar", "helloWorld"), renamedArgs.Name, "#5");
		AssertPaths (Path.Combine (bar_dir, "hiWorld"), renamedArgs.OldFullPath, "#6");
		AssertPaths (Path.Combine ("bar", "hiWorld"), renamedArgs.OldName, "#7");
	}
Example #11
0
    public static void Run()
    {
        // Create a new FileSystemWatcher and set its properties.
        watcher = new FileSystemWatcher();
       
        try
        {
            Console.WriteLine("Directory: ");
            String name;
            name = Console.ReadLine();
            watcher.Path = name;

            /* Watch for changes in LastAccess and LastWrite times, and
               the renaming of files or directories. */
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
               | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            // Watch all files
            watcher.Filter = "*.*";

            // Add event handlers.
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.Deleted += new FileSystemEventHandler(OnChanged);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);
            //set to watch subfolders
            watcher.IncludeSubdirectories = true;
            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Press \'q\' to quit the sample.");
            while (Console.Read() != 'q') ;
        }
        catch (SystemException) { Console.WriteLine("Wrong folder"); Console.ReadKey(); return; }
    }
 public void ConstructingWithPathAndFilter()
 {
     FileSystemWatcher tested = new FileSystemWatcher(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
       Assert.IsNotNull(tested);
       Assert.AreEqual(AppDomain.CurrentDomain.BaseDirectory, tested.Path);
       Assert.AreEqual("*.dll", tested.Filter);
 }
    public static void FileSystemWatcher_IncludeSubDirectories_Directory()
    {
        using (var dir = Utility.CreateTestDirectory())
        using (var watcher = new FileSystemWatcher(Path.GetFullPath(dir.Path)))
        {
            string dirPath = Path.GetFullPath(dir.Path);
            string subDirPath = Path.Combine(dirPath, "subdir");

            watcher.Path = dirPath;
            watcher.IncludeSubdirectories = true;
            AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);

            Directory.CreateDirectory(subDirPath);

            watcher.EnableRaisingEvents = true;

            Directory.CreateDirectory(Path.Combine(subDirPath, "1"));
            Utility.ExpectEvent(eventOccured, "created");

            watcher.IncludeSubdirectories = false;
            Directory.CreateDirectory(Path.Combine(subDirPath, "2"));
            Utility.ExpectNoEvent(eventOccured, "created");

            watcher.IncludeSubdirectories = true;
            Directory.CreateDirectory(Path.Combine(subDirPath, "3"));
            Utility.ExpectEvent(eventOccured, "created");
        }
    }
        public void FileSystemWatcher_Directory_Delete_DeepDirectoryStructure()
        {
            // List of created directories
            List<TempDirectory> lst = new List<TempDirectory>();

            using (var testDirectory = new TempDirectory(GetTestFilePath()))
            using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
            using (var watcher = new FileSystemWatcher(dir.Path, "*"))
            {
                watcher.IncludeSubdirectories = true;
                watcher.NotifyFilter = NotifyFilters.DirectoryName;

                // Priming directory
                lst.Add(new TempDirectory(Path.Combine(dir.Path, "dir")));

                // Create a deep directory structure and expect things to work
                for (int i = 1; i < 20; i++)
                {
                    // Test that the creation triggers an event correctly
                    string dirPath = Path.Combine(lst[i - 1].Path, String.Format("dir{0}", i));
                    Action action = () => Directory.Delete(dirPath);
                    Action cleanup = () => Directory.CreateDirectory(dirPath);
                    cleanup();

                    ExpectEvent(watcher, WatcherChangeTypes.Deleted, action, cleanup);

                    // Create the directory so subdirectories may be created from it.
                    lst.Add(new TempDirectory(dirPath));
                }
            }
        }
    bool flagFileChanged;   // for file watcher
    // Use this for initialization
    void Start () {
        parseConfigFile();

        absolutePath = Path.GetFullPath(absolutePath);
        // Prepare the audio files
        reloadSounds();
        clips = new List<AudioClip>();
        
        objprefab = (GameObject) Resources.Load("Lightbulbprefab");
        balls = new List<GameObject>();
        for (int j = 0; j<NUM_OF_BALLS; j++) balls.Add(Instantiate(objprefab));
        // File watcher
        locSoundFile = "location_sound.txt"; // the file initially watch
        watcher = new FileSystemWatcher();
        watcher.Path = ".";
        // Watch for change of LastWrite
        watcher.NotifyFilter = NotifyFilters.LastWrite;
        // watch all similar files
        watcher.Filter = "location_sound*.txt";
        // Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;
        flagFileChanged = false;

    }
Example #16
0
    public static void Run()
    {
        string[] args = System.Environment.GetCommandLineArgs();

        // If a directory is not specified, exit program.
        if (args.Length != 2)
        {
            // Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)");
            return;
        }

        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"C:\x";
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Filter = "geojson.json";

        /* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        // Only watch text files.

        // Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnDeleted);;
        watcher.Renamed += new RenamedEventHandler(OnRenamed);

        // Begin watching.
        watcher.EnableRaisingEvents = true;

        // Wait for the user to quit the program.
        Console.WriteLine("Press \'q\' to quit the sample.");
        while (Console.Read() != 'q') ;
    }
Example #17
0
 private static void ValidateDefaults(FileSystemWatcher watcher, string path, string filter)
 {
     Assert.Equal(false, watcher.EnableRaisingEvents);
     Assert.Equal(filter, watcher.Filter);
     Assert.Equal(false, watcher.IncludeSubdirectories);
     Assert.Equal(8192, watcher.InternalBufferSize);
     Assert.Equal(NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, watcher.NotifyFilter);
     Assert.Equal(path, watcher.Path);
 }
Example #18
0
 public void Dispose()
 {
     if (null != this.fsr) {
         this.fsr.Dispose();
         this.fsr = null;
     }
     if (null != this.changes) {
         this.changes.Dispose();
         this.changes = null;
     }
 }
 public void ZeroTimeout_TimesOut(bool enabledBeforeWait)
 {
     using (var testDirectory = new TempDirectory(GetTestFilePath()))
     using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName())))
     using (var fsw = new FileSystemWatcher(testDirectory.Path))
     {
         if (enabledBeforeWait) fsw.EnableRaisingEvents = true;
         AssertTimedOut(fsw.WaitForChanged(WatcherChangeTypes.All, 0));
         Assert.Equal(enabledBeforeWait, fsw.EnableRaisingEvents);
     }
 }
        public void FileSystemWatcher_Directory_Changed_WatchedFolder()
        {
            using (var testDirectory = new TempDirectory(GetTestFilePath()))
            using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
            using (var watcher = new FileSystemWatcher(dir.Path, "*"))
            {
                Action action = () => Directory.SetLastWriteTime(dir.Path, DateTime.Now + TimeSpan.FromSeconds(10));

                ExpectEvent(watcher, 0, action, expectedPath: dir.Path);
            }
        }
Example #21
0
 private void WireUp(FileSystemWatcher watcher)
 {
     //watch.NotifyFilter = /*NotifyFilters.LastAccess | */ NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
     // Only watch text files.
     //watch.Filter = "*.txt";
     watcher.IncludeSubdirectories = true;
     watcher.Changed += new FileSystemEventHandler(OnChanged);
     watcher.Created += new FileSystemEventHandler(OnChanged);
     watcher.Deleted += new FileSystemEventHandler(OnChanged);
     watcher.Renamed += new RenamedEventHandler(OnChanged);
     watcher.EnableRaisingEvents = true;
 }
        public void FileSystemWatcher_File_Changed_LastWrite()
        {
            using (var testDirectory = new TempDirectory(GetTestFilePath()))
            using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
            using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
            {
                Action action = () => Directory.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10));

                WatcherChangeTypes expected = WatcherChangeTypes.Changed;
                ExpectEvent(watcher, expected, action, expectedPath: file.Path);
            }
        }
 public void OnEnable()
 {
     #if UNITY_EDITOR
     if (Application.isEditor) {
         sceneFileWatcher = new FileSystemWatcher("Assets", "*.unity");
         sceneFileWatcher.IncludeSubdirectories = true;
         sceneFileWatcher.NotifyFilter = NotifyFilters.LastWrite;
         sceneFileWatcher.EnableRaisingEvents = true;
         sceneFileWatcher.Changed += OnSceneFileWatcher_Changed;
     }
     #endif
 }
        public void EventsAreNotRasedIfNotMatchingFilter()
        {
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(".");
              string fileName = System.IO.Path.Combine(dir.FullName, Guid.NewGuid().ToString());
              string newFileName = System.IO.Path.Combine(dir.FullName, Guid.NewGuid().ToString());
              try
              {
            AutoResetEvent raised = new AutoResetEvent(false);
            FileSystemWatcher tested = new FileSystemWatcher(dir.FullName);
            tested.Filter = "*.txt";
            tested.EnableRaisingEvents = true;
            int CreateRaised = 0;
            int ChangedRaised = 0;
            int DeletedRaised = 0;
            int RenamedRaised = 0;
            tested.Created += (s, e) => CreateRaised++;
            tested.Changed += (s, e) => ChangedRaised++;
            tested.Deleted += (s, e) => DeletedRaised++;
            tested.Renamed += (s, e) => RenamedRaised++;

            using (System.IO.FileStream file = System.IO.File.Create(fileName))
            {
              byte[] data = Encoding.UTF8.GetBytes("somedata");
              file.Write(data, 0, data.Length);
              file.Flush();
              file.Close();
            };
            Thread.Sleep(100);
            using (System.IO.FileStream file = System.IO.File.OpenWrite(fileName))
            {
              byte[] data = Encoding.UTF8.GetBytes("somedata");
              file.Write(data, 0, data.Length);
              file.Flush();
              file.Close();
            };
            Thread.Sleep(100);
            System.IO.File.Move(fileName, newFileName);
            Thread.Sleep(100);
            System.IO.File.Delete(newFileName);
            Thread.Sleep(100);

            Assert.AreEqual(0, CreateRaised);
            Assert.AreEqual(0, ChangedRaised);
            Assert.AreEqual(0, DeletedRaised);
            Assert.AreEqual(0, RenamedRaised);
              }
              finally
              {
            System.IO.File.Delete(fileName);
            System.IO.File.Delete(newFileName);
              }
        }
Example #25
0
 public void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     fileSystemWatcher.Dispose();
       fileSystemWatcher = new System.IO.FileSystemWatcher();
       fileSystemWatcher.Path = pathLabel.Text;
       fileSystemWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
      | NotifyFilters.FileName | NotifyFilters.DirectoryName;
       fileSystemWatcher.Changed += new FileSystemEventHandler(OnChanged);
       fileSystemWatcher.Created += new FileSystemEventHandler(OnChanged);
       fileSystemWatcher.Deleted += new FileSystemEventHandler(OnChanged);
       fileSystemWatcher.EnableRaisingEvents = true;
       updateProgress();
 }
Example #26
0
	public void OnEnable()
	{
		LoadData();

		_watcher = new FileSystemWatcher();
		_watcher.Path = Path.GetDirectoryName(DATA_FILE_PATH);
		_watcher.Filter = Path.GetFileName(DATA_FILE_PATH);
		_watcher.EnableRaisingEvents = true;
		_watcher.Changed += (object sender, FileSystemEventArgs e) => 
		{
			_needsLoadData = true;
		};
	}
        [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/216
        public void FileSystemWatcher_Directory_Create()
        {
            using (var testDirectory = new TempDirectory(GetTestFilePath()))
            using (var watcher = new FileSystemWatcher(testDirectory.Path))
            {
                string dirName = Path.Combine(testDirectory.Path, "dir");
                watcher.Filter = Path.GetFileName(dirName);

                Action action = () => Directory.CreateDirectory(dirName);
                Action cleanup = () => Directory.Delete(dirName);

                ExpectEvent(watcher, WatcherChangeTypes.Created, action, cleanup, dirName);
            }
        }
Example #28
0
    public static void FileSystemWatcher_Deleted()
    {
        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            var handler = new FileSystemEventHandler((o, e) => { });

            // add / remove
            watcher.Deleted += handler;
            watcher.Deleted -= handler;

            // shouldn't throw
            watcher.Deleted -= handler;
        }
    }
        public void FileSystemWatcher_File_Create()
        {
            using (var testDirectory = new TempDirectory(GetTestFilePath()))
            using (var watcher = new FileSystemWatcher(testDirectory.Path))
            {
                string fileName = Path.Combine(testDirectory.Path, "file");
                watcher.Filter = Path.GetFileName(fileName);

                Action action = () => File.Create(fileName).Dispose();
                Action cleanup = () => File.Delete(fileName);

                ExpectEvent(watcher, WatcherChangeTypes.Created, action, cleanup, fileName);
            }
        }
    public static void FileSystemWatcher_Changed_LastWrite_Directory()
    {
        using (var dir = Utility.CreateTestDirectory())
        using (var watcher = new FileSystemWatcher("."))
        {
            watcher.Filter = Path.GetFileName(dir.Path);
            AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed);

            watcher.EnableRaisingEvents = true;
            Directory.SetLastWriteTime(dir.Path, DateTime.Now + TimeSpan.FromSeconds(10));

            Utility.ExpectEvent(eventOccured, "changed");
        }
    }
        internal static void Load()
        {
            int    num;
            bool   flag;
            object loadLock = IniSettings.LoadLock;

            Monitor.Enter(loadLock);
            try
            {
                try
                {
                    if (IniSettings.iniw != null)
                    {
                        IniSettings.iniw.Dispose();
                        IniSettings.iniw = null;
                    }
                    if (!Directory.Exists(IniSettings.SettingsFileDir))
                    {
                        Directory.CreateDirectory(IniSettings.SettingsFileDir);
                    }
                    IniFile nIFile         = IniSettings.GetINIFile();
                    string  pROCESSPATHKEY = "bDebugMode";
                    string  value          = nIFile.GetValue("Translation", pROCESSPATHKEY, null);
                    if (value == null || !bool.TryParse(value, out flag))
                    {
                        flag = false;
                        nIFile.WriteValue("Translation", pROCESSPATHKEY, flag);
                    }
                    IniSettings.DebugMode = flag;
                    pROCESSPATHKEY        = "sLanguage";
                    value = nIFile.GetValue("Translation", pROCESSPATHKEY, null);
                    IniSettings.Language = value;
                    if (value != IniSettings.Language)
                    {
                        nIFile.WriteValue("Translation", pROCESSPATHKEY, IniSettings.Language);
                    }
                    pROCESSPATHKEY = "bFindImage";
                    value          = nIFile.GetValue("Translation", pROCESSPATHKEY, null);
                    if (value == null || !bool.TryParse(value, out flag))
                    {
                        flag = false;
                        nIFile.WriteValue("Translation", pROCESSPATHKEY, flag);
                    }
                    IniSettings.FindImage = flag;
                    pROCESSPATHKEY        = "bFindAudio";
                    value = nIFile.GetValue("Translation", pROCESSPATHKEY, null);
                    if (value == null || !bool.TryParse(value, out flag))
                    {
                        flag = false;
                        nIFile.WriteValue("Translation", pROCESSPATHKEY, flag);
                    }
                    IniSettings.FindAudio = flag;
                    pROCESSPATHKEY        = "bDumpAudioByLevel";
                    value = nIFile.GetValue("Translation", pROCESSPATHKEY, null);
                    if (value == null || !bool.TryParse(value, out flag))
                    {
                        flag = true;
                        nIFile.WriteValue("Translation", pROCESSPATHKEY, flag);
                    }
                    IniSettings.DumpAudioByLevel = flag;
                    pROCESSPATHKEY = "bFindText";
                    value          = nIFile.GetValue("Translation", pROCESSPATHKEY, null);
                    if (value == null || !bool.TryParse(value, out flag))
                    {
                        flag = false;
                        nIFile.WriteValue("Translation", pROCESSPATHKEY, flag);
                    }
                    IniSettings.FindText = flag;
                    pROCESSPATHKEY       = "bDumpTextByLevel";
                    value = nIFile.GetValue("Translation", pROCESSPATHKEY, null);
                    if (value == null || !bool.TryParse(value, out flag))
                    {
                        flag = true;
                        nIFile.WriteValue("Translation", pROCESSPATHKEY, flag);
                    }
                    IniSettings.DumpTextByLevel = flag;
                    pROCESSPATHKEY = "bUseRegEx";
                    value          = nIFile.GetValue("Translation", pROCESSPATHKEY, null);
                    if (value == null || !bool.TryParse(value, out flag))
                    {
                        flag = true;
                        nIFile.WriteValue("Translation", pROCESSPATHKEY, flag);
                    }
                    IniSettings.UseRegEx = flag;
                    pROCESSPATHKEY       = "bUseTextPrediction";
                    value = nIFile.GetValue("Translation", pROCESSPATHKEY, null);
                    if (value == null || !bool.TryParse(value, out flag))
                    {
                        flag = true;
                        nIFile.WriteValue("Translation", pROCESSPATHKEY, flag);
                    }
                    IniSettings.UseTextPrediction = flag;
                    pROCESSPATHKEY = "bUseCopy2Clipboard";
                    value          = nIFile.GetValue("Translation", pROCESSPATHKEY, null);
                    if (value == null || !bool.TryParse(value, out flag))
                    {
                        flag = false;
                        nIFile.WriteValue("Translation", pROCESSPATHKEY, flag);
                    }
                    IniSettings.UseCopy2Clipboard = flag;
                    pROCESSPATHKEY = "iCopy2ClipboardTime(ms)";
                    value          = nIFile.GetValue("Translation", pROCESSPATHKEY, null);
                    if (value == null || !int.TryParse(value, out num))
                    {
                        num = 250;
                        nIFile.WriteValue("Translation", pROCESSPATHKEY, num);
                    }
                    IniSettings.Copy2ClipboardTime = num;
                    pROCESSPATHKEY          = IniSettings.PROCESSPATHKEY;
                    value                   = nIFile.GetValue("Translation", pROCESSPATHKEY, null);
                    IniSettings.ProcessPath = value;
                    if (value != IniSettings.ProcessPath)
                    {
                        nIFile.WriteValue("Translation", pROCESSPATHKEY, IniSettings.ProcessPath);
                    }
                    IniSettings.initialized = true;
                    try
                    {
                        Action <IniFile> action = IniSettings.LoadSettings;
                        if (action != null)
                        {
                            action(nIFile);
                        }
                    }
                    catch (Exception exception)
                    {
                        IniSettings.Error(string.Concat("LoadSettings:\n", exception.ToString()));
                    }
                    IniSettings.WatchTextFiles();
                }
                catch (Exception exception1)
                {
                    IniSettings.Error(string.Concat("LoadSettings:\n", exception1.ToString()));
                }
            }
            finally
            {
                Monitor.Exit(loadLock);
            }
        }
Example #32
0
 public UploadFileSystemWatcher(string folder)
 {
     _watcher = CreateFileSystemWatcher(folder);
 }
Example #33
0
        static void Main(string[] args)
        {
            //Check if software already runs, if so kill this instance
            if (Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)).Length > 1)
            {
                DoDebug("ACC is already running, killing this proccess");
                MessageBox.Show("ACC is already running.", "Already running | " + messageBoxTitle + "");
                Process.GetCurrentProcess().Kill();
            }
            SetupDataFolder();
            if (File.Exists(logFilePath))
            {
                File.WriteAllText(logFilePath, string.Empty);
            }

            DoDebug("[ACC begun (v" + softwareVersion + ")]");
            ConfigSetup();

            if (checkForUpdates)
            {
                ACC_Updater updater = new ACC_Updater();
                updater.Check();
            }
            if (File.Exists(Path.Combine(dataFolderLocation, "updated.txt")))
            {
                string installerPath = File.ReadAllText(Path.Combine(dataFolderLocation, "updated.txt"));
                if (installerPath != String.Empty)
                {
                    if (File.Exists(installerPath))
                    {
                        File.Delete(installerPath);
                    }
                }
                File.Delete(Path.Combine(dataFolderLocation, "updated.txt"));
                MessageBox.Show("ACC has been updated to version v" + softwareVersion + "!", "Updated | " + messageBoxTitle, MessageBoxButtons.OK);
            }

            //On console close: hide NotifyIcon
            Application.ApplicationExit += new EventHandler(OnApplicationExit);
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            //If it's the first time:
            if (!File.Exists(Path.Combine(dataFolderLocation, "first_time.txt")))
            {
                if (!File.Exists(@startupFolder + @"\" + @startShortcutName))
                {
                    DialogResult dialogResult = MessageBox.Show("Thanks for using " + messageBoxTitle + "! Do you want this software to automatically open when Windows starts (recommended)? Click \"Yes\"", "Open on startup? | " + messageBoxTitle, MessageBoxButtons.YesNo);
                    if (dialogResult == DialogResult.Yes)
                    {
                        CreateStartupLink();
                        MessageBox.Show("Good choice! ACC is now fully operational, happy computer-controlling!", "Wuu! | " + messageBoxTitle + "");
                    }
                    else if (dialogResult == DialogResult.No)
                    {
                        MessageBox.Show("Alrighty. If you regret and want ACC to open automatically you always right-click on " + messageBoxTitle + " in the tray and click \"Open on startup\"!", "Aww | " + messageBoxTitle + "");
                    }
                }
                CreateFirstTimeFile();
            }

            //Create shortcut folder if doesn't exist
            if (!Directory.Exists(shortcutLocation))
            {
                Directory.CreateDirectory(shortcutLocation);

                //Create example-file
                using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
                    sw.WriteLine("This is an example file.");
                    sw.WriteLine("If you haven't already, make your assistant open this file!");
                }
            }

            //If a startup link is (still) not created, add trayMenu item for it
            if (!File.Exists(Path.Combine(startupFolder, startShortcutName)))
            {
                sysIcon.AddOpenOnStartupMenu();
            }

            foreach (string file in Directory.GetFiles(currentLocation, "*." + actionFileExtension))
            {
                ClearFile(file);
            }

            /* WATCHER */
            FileSystemWatcher watcher   = new FileSystemWatcher();
            string            checkPath = actionFilePath;

            watcher.Path         = (String.IsNullOrEmpty(checkPath) ? currentLocation : (Directory.Exists(checkPath) ? checkPath : currentLocation));
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                   | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.Filter              = "*.txt";
            watcher.Changed            += new FileSystemEventHandler(ActionChecker.FileFound);
            watcher.EnableRaisingEvents = true;
            /* END WATCHER */

            DoDebug("\n[" + messageBoxTitle + "] Initiated. \nCurrent location: " + currentLocation);
            DoDebug("Listening for actions to execute...");

            Application.EnableVisualStyles();
            Application.Run(sysIcon);
        }
        protected override void LiveLogListen(CancellationToken stopEvt, LiveLogXMLWriter output)
        {
            using (ILogMedia media = new SimpleFileMedia(
                       LogMedia.FileSystemImpl.Instance,
                       SimpleFileMedia.CreateConnectionParamsFromFileName(fileName)))
                using (FileSystemWatcher watcher = new FileSystemWatcher(Path.GetDirectoryName(fileName),
                                                                         Path.GetFileName(fileName)))
                    using (AutoResetEvent fileChangedEvt = new AutoResetEvent(true))
                    {
                        IMessagesSplitter splitter = new MessagesSplitter(
                            new StreamTextAccess(media.DataStream, Encoding.ASCII, TextStreamPositioningParams.Default),
                            RegexFactory.Instance.Create(@"^(?<body>.+)$", ReOptions.Multiline)
                            );

                        watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
                        watcher.Changed     += delegate(object sender, FileSystemEventArgs e)
                        {
                            fileChangedEvt.Set();
                        };
                        //watcher.EnableRaisingEvents = true;

                        long         lastLinePosition = 0;
                        long         lastStreamLength = 0;
                        WaitHandle[] events           = new WaitHandle[] { stopEvt.WaitHandle, fileChangedEvt };

                        var capture = new TextMessageCapture();

                        for (; ;)
                        {
                            if (WaitHandle.WaitAny(events, 250, false) == 0)
                            {
                                break;
                            }

                            media.Update();

                            if (media.Size == lastStreamLength)
                            {
                                continue;
                            }

                            lastStreamLength = media.Size;

                            DateTime lastModified = media.LastModified;

                            splitter.BeginSplittingSession(new FileRange.Range(0, lastStreamLength), lastLinePosition, MessagesParserDirection.Forward);
                            try
                            {
                                for (; ;)
                                {
                                    if (!splitter.GetCurrentMessageAndMoveToNextOne(capture))
                                    {
                                        break;
                                    }
                                    lastLinePosition = capture.BeginPosition;

                                    XmlWriter writer = output.BeginWriteMessage(false);
                                    writer.WriteStartElement("m");
                                    writer.WriteAttributeString("d", Listener.FormatDate(lastModified));
                                    writer.WriteString(capture.MessageHeader);
                                    writer.WriteEndElement();
                                    output.EndWriteMessage();
                                }
                            }
                            finally
                            {
                                splitter.EndSplittingSession();
                            }
                        }
                    }
        }
Example #35
0
        public static void main()
        {
            log.Debug("D2MP starting...");
            var notifyThread = new Thread(delegate() {
                using (notifier = new notificationForm())
                {
                    notifier.Visible = true;
                    Application.Run();
                }
            });

            notifyThread.SetApartmentState(ApartmentState.STA);
            notifyThread.Start();
            ourDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            File.WriteAllText(Path.Combine(ourDir, "version.txt"), ClientCommon.Version.ClientVersion);
            var iconThread = new Thread(delegate()
            {
                using (icon = new ProcessIcon())
                {
                    icon.Display();
                    icon.showNotification = delegate { notifier.Invoke(new MethodInvoker(delegate { notifier.Fade(1); notifier.hideTimer.Start(); })); };
                    Application.Run();
                }
            });

            iconThread.SetApartmentState(ApartmentState.STA);
            iconThread.Start();

            try
            {
                var steam = new SteamFinder();
                if (!Directory.Exists(Settings.steamDir) || !Directory.Exists(Settings.dotaDir))
                {
                    Settings.steamDir = steam.FindSteam(true);
                    Settings.dotaDir  = steam.FindDota(true);
                }

                if (Settings.steamDir == null || Settings.dotaDir == null)
                {
                    log.Fatal("Steam/dota was not found!");
                    return;
                }
                log.Debug("Steam found: " + Settings.steamDir);
                log.Debug("Dota found: " + Settings.dotaDir);

                addonsDir = Path.Combine(Settings.dotaDir, @"dota\addons\");
                d2mpDir   = Path.Combine(Settings.dotaDir, @"dota\d2moddin\");
                modDir    = Path.Combine(addonsDir, "d2moddin");
                if (!Directory.Exists(addonsDir))
                {
                    Directory.CreateDirectory(addonsDir);
                }
                if (!Directory.Exists(d2mpDir))
                {
                    Directory.CreateDirectory(d2mpDir);
                }
                if (!Directory.Exists(modDir))
                {
                    Directory.CreateDirectory(modDir);
                }

                {
                    string[] dirs = Directory.GetDirectories(d2mpDir);
                    int      i    = 0;
                    foreach (string modName in dirs.Select(Path.GetFileName))
                    {
                        log.Debug("Found mod: " + modName + " detecting version...");
                        string infoPath    = Path.Combine(d2mpDir, modName + @"\addoninfo.txt");
                        string versionFile = "";
                        if (File.Exists(infoPath))
                        {
                            versionFile = File.ReadAllText(infoPath);
                        }
                        Match match = Regex.Match(versionFile, @"(addonversion)(\s+)(\d+\.)?(\d+\.)?(\d+\.)?(\*|\d+)",
                                                  RegexOptions.IgnoreCase);
                        if (match.Success)
                        {
                            string version = match.Groups.Cast <Group>()
                                             .ToList()
                                             .Skip(3)
                                             .Aggregate("", (current, part) => current + part.Value);
                            log.Debug(modName + "=" + version);
                            mods.Add(new ClientMod {
                                name = modName, version = version
                            });
                        }
                        else
                        {
                            log.Error("Can't find version info for mod: " + modName + ", not including");
                        }
                        i++;
                    }
                }

                //Detect user
                string          config  = File.ReadAllText(Path.Combine(Settings.steamDir, @"config\config.vdf"));
                MatchCollection matches = Regex.Matches(config, "\"\\d{17}\"");
                string          steamid;
                steamids = new List <string>();
                if (matches.Count > 0)
                {
                    foreach (Match match in matches)
                    {
                        steamid = match.Value.Substring(1).Substring(0, match.Value.Length - 2);
                        log.Debug("Steam ID detected: " + steamid);
                        steamids.Add(steamid);
                    }
                }
                else
                {
                    log.Fatal("Could not detect steam ID.");
                    return;
                }

                //Modify gameinfo.txt
                ModGameInfo();

                log.Debug("Starting shutdown file watcher...");
                string pathToShutdownFile = Path.Combine(ourDir, "d2mp.pid");
                File.WriteAllText(pathToShutdownFile, "Delete this file to shutdown D2MP.");

                var watcher = new FileSystemWatcher();
                watcher.Path         = ourDir;
                watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                       | NotifyFilters.FileName;
                watcher.Filter              = "d2mp.pid";
                watcher.Deleted            += (sender, args) => { shutDown = true; };
                watcher.EnableRaisingEvents = true;

                try
                {
                    SetupClient();
                    client.Open();
                }
                catch (Exception ex)
                {
                    notifier.Notify(4, "Server error", "Can't connect to the lobby server!");
                    //icon.DisplayBubble("Can't connect to the lobby server!");
                }
                while (!shutDown)
                {
                    Thread.Sleep(100);
                }
                client.Close();
            }
            catch (Exception ex)
            {
                log.Fatal("Overall error in the program", ex);
            }
            //UnmodGameInfo();
            shutDown = true;
            Application.Exit();
        }
Example #36
0
 /// <summary>
 ///     Default constructor
 /// </summary>
 public ExplorerControl()
 {
     Nodes    = new ObservableCollection <INode>();
     _watcher = CreateWatcher();
 }
Example #37
0
        private async Task CreateLibraryWatchers()
        {
            Debug.Assert(_libWatchers != null, "Should not create watchers when suppressed");

            IReadOnlyList <string> paths = null;

            if (_factory.Configuration.SearchPaths.Any())
            {
                paths = _factory.Configuration.SearchPaths;
            }

            if (paths == null)
            {
                try {
                    paths = (await PythonLibraryPath.GetDatabaseSearchPathsAsync(_factory.Configuration, null))
                            .Select(p => p.Path)
                            .ToArray();
                } catch (InvalidOperationException) {
                    return;
                }
            }

            paths = paths
                    .Where(Directory.Exists)
                    .OrderBy(p => p.Length)
                    .ToList();

            var watching = new List <string>();
            var watchers = new List <FileSystemWatcher>();

            foreach (var path in paths)
            {
                if (watching.Any(p => PathUtils.IsSubpathOf(p, path)))
                {
                    continue;
                }

                FileSystemWatcher watcher = null;
                try {
                    watcher = new FileSystemWatcher {
                        IncludeSubdirectories = true,
                        Path         = path,
                        NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite
                    };
                    watcher.Created            += OnChanged;
                    watcher.Deleted            += OnChanged;
                    watcher.Changed            += OnChanged;
                    watcher.Renamed            += OnRenamed;
                    watcher.EnableRaisingEvents = true;

                    watching.Add(path);
                    watchers.Add(watcher);
                } catch (IOException) {
                    // Raced with directory deletion. We normally handle the
                    // library being deleted by disposing the watcher, but this
                    // occurs in response to an event from the watcher. Because
                    // we never got to start watching, we will just dispose
                    // immediately.
                    watcher?.Dispose();
                } catch (ArgumentException ex) {
                    watcher?.Dispose();
                    Debug.WriteLine("Error starting FileSystemWatcher:\r\n{0}", ex);
                }
            }

            List <FileSystemWatcher> oldWatchers;

            lock (_libWatchers) {
                oldWatchers = _libWatchers.ToList();
                _libWatchers.Clear();
                _libWatchers.AddRange(watchers);
            }

            foreach (var oldWatcher in oldWatchers)
            {
                oldWatcher.EnableRaisingEvents = false;
                oldWatcher.Dispose();
            }
        }
            private unsafe void ProcessEvents(int numEvents,
                                              byte **eventPaths,
                                              Interop.EventStream.FSEventStreamEventFlags[] eventFlags,
                                              FSEventStreamEventId[] eventIds,
                                              FileSystemWatcher watcher)
            {
                // Since renames come in pairs, when we find the first we need to search for the next one. Once we find it, we'll add it to this
                // list so when the for-loop comes across it, we'll skip it since it's already been processed as part of the original of the pair.
                List <FSEventStreamEventId> handledRenameEvents = null;

                Memory <char>[] events = new Memory <char> [numEvents];
                ParseEvents();

                for (long i = 0; i < numEvents; i++)
                {
                    ReadOnlySpan <char> path = events[i].Span;
                    Debug.Assert(path[path.Length - 1] != '/', "Trailing slashes on events is not supported");

                    // Match Windows and don't notify us about changes to the Root folder
                    if (_fullDirectory.Length >= path.Length && path.Equals(_fullDirectory.AsSpan(0, path.Length), StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    WatcherChangeTypes eventType = 0;
                    // First, we should check if this event should kick off a re-scan since we can't really rely on anything after this point if that is true
                    if (ShouldRescanOccur(eventFlags[i]))
                    {
                        watcher.OnError(new ErrorEventArgs(new IOException(SR.FSW_BufferOverflow, (int)eventFlags[i])));
                        break;
                    }
                    else if ((handledRenameEvents != null) && (handledRenameEvents.Contains(eventIds[i])))
                    {
                        // If this event is the second in a rename pair then skip it
                        continue;
                    }
                    else if (CheckIfPathIsNested(path) && ((eventType = FilterEvents(eventFlags[i])) != 0))
                    {
                        // The base FileSystemWatcher does a match check against the relative path before combining with
                        // the root dir; however, null is special cased to signify the root dir, so check if we should use that.
                        ReadOnlySpan <char> relativePath = ReadOnlySpan <char> .Empty;
                        if (!path.Equals(_fullDirectory, StringComparison.OrdinalIgnoreCase))
                        {
                            // Remove the root directory to get the relative path
                            relativePath = path.Slice(_fullDirectory.Length);
                        }

                        // Raise a notification for the event
                        if (((eventType & WatcherChangeTypes.Changed) > 0))
                        {
                            watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Changed, relativePath);
                        }
                        if (((eventType & WatcherChangeTypes.Created) > 0))
                        {
                            watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Created, relativePath);
                        }
                        if (((eventType & WatcherChangeTypes.Deleted) > 0))
                        {
                            watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, relativePath);
                        }
                        if (((eventType & WatcherChangeTypes.Renamed) > 0))
                        {
                            // Find the rename that is paired to this rename, which should be the next rename in the list
                            long pairedId = FindRenameChangePairedChange(i, eventFlags);
                            if (pairedId == long.MinValue)
                            {
                                // Getting here means we have a rename without a pair, meaning it should be a create for the
                                // move from unwatched folder to watcher folder scenario or a move from the watcher folder out.
                                // Check if the item exists on disk to check which it is
                                // Don't send a new notification if we already sent one for this event.
                                if (DoesItemExist(path, IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile)))
                                {
                                    if ((eventType & WatcherChangeTypes.Created) == 0)
                                    {
                                        watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Created, relativePath);
                                    }
                                }
                                else if ((eventType & WatcherChangeTypes.Deleted) == 0)
                                {
                                    watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, relativePath);
                                }
                            }
                            else
                            {
                                // Remove the base directory prefix and add the paired event to the list of
                                // events to skip and notify the user of the rename
                                ReadOnlySpan <char> newPathRelativeName = events[pairedId].Span.Slice(_fullDirectory.Length);
                                watcher.NotifyRenameEventArgs(WatcherChangeTypes.Renamed, newPathRelativeName, relativePath);

                                // Create a new list, if necessary, and add the event
                                if (handledRenameEvents == null)
                                {
                                    handledRenameEvents = new List <FSEventStreamEventId>();
                                }
                                handledRenameEvents.Add(eventIds[pairedId]);
                            }
                        }
                    }

                    ArraySegment <char> underlyingArray;
                    if (MemoryMarshal.TryGetArray(events[i], out underlyingArray))
                    {
                        ArrayPool <char> .Shared.Return(underlyingArray.Array);
                    }
                }

                this._context = ExecutionContext.Capture();

                void ParseEvents()
                {
                    for (int i = 0; i < events.Length; i++)
                    {
                        int byteCount = 0;
                        Debug.Assert(eventPaths[i] != null);
                        byte *temp = eventPaths[i];

                        // Finds the position of null character.
                        while (*temp != 0)
                        {
                            temp++;
                            byteCount++;
                        }

                        Debug.Assert(byteCount > 0, "Empty events are not supported");
                        events[i] = new Memory <char>(ArrayPool <char> .Shared.Rent(Encoding.UTF8.GetMaxCharCount(byteCount)));
                        int charCount;

                        // Converting an array of bytes to UTF-8 char array
                        charCount = Encoding.UTF8.GetChars(new ReadOnlySpan <byte>(eventPaths[i], byteCount), events[i].Span);
                        events[i] = events[i].Slice(0, charCount);
                    }
                }
            }
Example #39
0
        public UnityEditorProtocol(Lifetime lifetime, ILogger logger, UnityHost host,
                                   IScheduler dispatcher, IShellLocks locks, ISolution solution,
                                   ISettingsStore settingsStore, JetBrains.Application.ActivityTrackingNew.UsageStatistics usageStatistics,
                                   UnitySolutionTracker unitySolutionTracker, IThreading threading,
                                   UnityVersion unityVersion, NotificationsModel notificationsModel,
                                   IHostProductInfo hostProductInfo)
        {
            myPluginInstallations = new JetHashSet <FileSystemPath>();

            myComponentLifetime  = lifetime;
            myLogger             = logger;
            myDispatcher         = dispatcher;
            myLocks              = locks;
            mySolution           = solution;
            myUsageStatistics    = usageStatistics;
            myThreading          = threading;
            myUnityVersion       = unityVersion;
            myNotificationsModel = notificationsModel;
            myHostProductInfo    = hostProductInfo;
            myHost = host;
            myBoundSettingsStore = settingsStore.BindToContextLive(lifetime, ContextRange.Smart(solution.ToDataContext()));
            mySessionLifetimes   = new SequentialLifetimes(lifetime);

            if (solution.GetData(ProjectModelExtensions.ProtocolSolutionKey) == null)
            {
                return;
            }

            unitySolutionTracker.IsUnityProject.View(lifetime, (lf, args) =>
            {
                if (!args)
                {
                    return;
                }

                var solFolder = mySolution.SolutionDirectory;
                AdviseModelData(lifetime);

                // todo: consider non-Unity Solution with Unity-generated projects
                var protocolInstancePath = solFolder.Combine("Library/ProtocolInstance.json");
                protocolInstancePath.Directory.CreateDirectory();

                var watcher          = new FileSystemWatcher();
                watcher.Path         = protocolInstancePath.Directory.FullPath;
                watcher.NotifyFilter = NotifyFilters.LastWrite; //Watch for changes in LastWrite times
                watcher.Filter       = protocolInstancePath.Name;

                // Add event handlers.
                watcher.Changed += OnChanged;
                watcher.Created += OnChanged;

                lf.Bracket(() => { }, () =>
                {
                    watcher.Dispose();
                });

                watcher.EnableRaisingEvents = true; // Begin watching.
                // connect on start of Rider
                CreateProtocols(protocolInstancePath);
            });
        }
Example #40
0
        private static void UpdateAssemblyWatchers()
        {
            string platformName = SharedRuntimeState.GetPlatformName();
            if (SharedRuntimeState.CurrentRuntime == EDotNetRuntime.Mono &&
                !string.IsNullOrEmpty(platformName) && platformName.ToLower() == "mac")
            {
                // libmono-native-compat.dylib (required by FileSystemWatcher) either doesn't load or is corrupted?
                // It crashes the Mono runtime when doing a symbol lookup (not sure which symbol)
                //
                // abort_with_payload
                // dyld::fastBindLazySymbol(ImageLoader**, unsigned long)
                // dyld_stub_binder
                // ---- managed frames  ----
                // mono_jit_runtime_invoke
                return;
            }

            string[] assemblyPaths = SharedRuntimeState.GetHotReloadAssemblyPaths();
            if (assemblyPaths != null)
            {
                HashSet<string> newAssemblyPaths = new HashSet<string>();
                HashSet<string> removedAssemblyPaths = new HashSet<string>();

                foreach (string assemblyPath in assemblyWatchers.Keys)
                {
                    if (!assemblyPaths.Contains(assemblyPath))
                    {
                        removedAssemblyPaths.Add(assemblyPath);
                    }
                }

                foreach (string assemblyPath in assemblyPaths)
                {
                    if (!assemblyWatchers.ContainsKey(assemblyPath))
                    {
                        newAssemblyPaths.Add(assemblyPath);
                    }
                }

                foreach (string assemblyPath in removedAssemblyPaths)
                {
                    assemblyWatchers[assemblyPath].Dispose();
                    assemblyWatchers.Remove(assemblyPath);
                }

                foreach (string assemblyPath in newAssemblyPaths)
                {
                    if (Directory.Exists(Path.GetDirectoryName(assemblyPath)))
                    {
                        FileSystemWatcher assemblyWatcher = new FileSystemWatcher();
                        assemblyWatcher.Path = Path.GetDirectoryName(assemblyPath);
                        assemblyWatcher.Filter = Path.GetFileName(assemblyPath);
                        assemblyWatcher.NotifyFilter = NotifyFilters.LastWrite;//NotifyFilters.CreationTime;
                        assemblyWatcher.EnableRaisingEvents = true;
                        assemblyWatcher.Changed += AssemblyWatcher_Changed;

                        assemblyWatchers.Add(assemblyPath, assemblyWatcher);
                    }
                }
            }

            if (assemblyWatchers.Count == 0)
            {
                SharedRuntimeState.LogWarning("No assembly watchers active for hotreload (\"USharpRuntime reload\" command can be used instead)");
            }
        }
        public void FileSystemWatcher_File_Create_ForceLoopRestart(bool useExistingWatchers)
        {
            ExecuteWithRetry(() =>
            {
                FileSystemWatcher[] watchers  = new FileSystemWatcher[64];
                FileSystemWatcher[] watchers1 = new FileSystemWatcher[64];

                try
                {
                    string fileName = Path.Combine(TestDirectory, "file");
                    AutoResetEvent[] autoResetEvents = new AutoResetEvent[64];
                    for (var i = 0; i < watchers.Length; i++)
                    {
                        watchers[i]        = new FileSystemWatcher(TestDirectory);
                        watchers[i].Filter = Path.GetFileName(fileName);
                        autoResetEvents[i] = WatchCreated(watchers[i], new[] { fileName }).EventOccured;
                        watchers[i].EnableRaisingEvents = true;
                    }

                    File.Create(fileName).Dispose();
                    Assert.True(WaitHandle.WaitAll(autoResetEvents, WaitForExpectedEventTimeout_NoRetry));

                    File.Delete(fileName);
                    for (var i = 0; i < watchers.Length; i++)
                    {
                        watchers[i].EnableRaisingEvents = false;
                    }

                    File.Create(fileName).Dispose();
                    Assert.False(WaitHandle.WaitAll(autoResetEvents, WaitForUnexpectedEventTimeout));

                    File.Delete(fileName);

                    if (useExistingWatchers)
                    {
                        for (var i = 0; i < watchers.Length; i++)
                        {
                            watchers[i].EnableRaisingEvents = true;
                        }

                        File.Create(fileName).Dispose();
                        Assert.True(WaitHandle.WaitAll(autoResetEvents, WaitForExpectedEventTimeout_NoRetry));
                    }
                    else
                    {
                        AutoResetEvent[] autoResetEvents1 = new AutoResetEvent[64];
                        for (var i = 0; i < watchers1.Length; i++)
                        {
                            watchers1[i]        = new FileSystemWatcher(TestDirectory);
                            watchers1[i].Filter = Path.GetFileName(fileName);
                            autoResetEvents1[i] = WatchCreated(watchers1[i], new[] { fileName }).EventOccured;
                            watchers1[i].EnableRaisingEvents = true;
                        }

                        File.Create(fileName).Dispose();
                        Assert.True(WaitHandle.WaitAll(autoResetEvents1, WaitForExpectedEventTimeout_NoRetry));
                    }
                }
                finally
                {
                    for (var i = 0; i < watchers.Length; i++)
                    {
                        watchers[i]?.Dispose();
                        watchers1[i]?.Dispose();
                    }
                }
            });
        }
Example #42
0
 /// <summary>
 /// Removes the watcher from list.
 /// </summary>
 /// <param name="watcher">The watcher.</param>
 private void RemoveWatcherFromList(FileSystemWatcher watcher)
 {
     _fileSystemWatchers.TryRemove(watcher.Path, out var removed);
 }
Example #43
0
        /// <summary>
        /// Parses the database configuration file and loads the list of connection configurations.
        /// </summary>
        private static void ParseConfig()
        {
            connections.Clear();

            if (!File.Exists(ConfigPath))
            {
                CreateConfig();
            }

            var xml = new XmlDocument();

            try
            {
                xml.Load(ConfigPath);
            }
            catch (XmlException e)
            {
                SMLog.Error($"Failed reading database configuration from {ConfigPath}: {e.Message}");
                return;
            }

            var defaultDriver         = DatabaseDriver.SQLite;
            var defaultDriverElements = xml.GetElementsByTagName("DefaultDriver");

            if ((defaultDriverElements.Count > 0) && "mysql".EqualsCaseInsensitive(defaultDriverElements[0].InnerText))
            {
                defaultDriver = DatabaseDriver.MySQL;
            }

            foreach (XmlElement element in xml.GetElementsByTagName("Connection"))
            {
                if (!element.HasAttribute("Name"))
                {
                    continue;
                }

                var name = element.GetAttribute("Name");
                if (connections.ContainsKey(name))
                {
                    continue;
                }

                var driver         = defaultDriver;
                var driverElements = element.GetElementsByTagName("Driver");
                if (driverElements.Count > 0)
                {
                    if ("sqlite".EqualsCaseInsensitive(driverElements[0].InnerText))
                    {
                        driver = DatabaseDriver.SQLite;
                    }
                    else if ("mysql".EqualsCaseInsensitive(driverElements[0].InnerText))
                    {
                        driver = DatabaseDriver.MySQL;
                    }
                    else
                    {
                        continue;
                    }
                }

                var databaseElements = element.GetElementsByTagName("Database");
                if (databaseElements.Count == 0)
                {
                    continue;
                }

                var database = databaseElements[0].InnerText;

                if (driver == DatabaseDriver.MySQL)
                {
                    var hostElements = element.GetElementsByTagName("Host");
                    if (hostElements.Count == 0)
                    {
                        continue;
                    }

                    var host = hostElements[0].InnerText;

                    var userElements = element.GetElementsByTagName("User");
                    if (userElements.Count == 0)
                    {
                        continue;
                    }

                    var user = userElements[0].InnerText;

                    var pass         = string.Empty;
                    var passElements = element.GetElementsByTagName("Pass");
                    if (passElements.Count > 0)
                    {
                        pass = passElements[0].InnerText;
                    }

                    var port         = 3306u;
                    var portElements = element.GetElementsByTagName("Port");
                    if (passElements.Count > 0)
                    {
                        uint.TryParse(portElements[0].InnerText, out port);
                    }

                    var connection = new ConnectionInfo(DatabaseDriver.MySQL, database, host, user, pass, port);
                    connections.Add(name, connection);
                }
                else
                {
                    var connection = new ConnectionInfo(DatabaseDriver.SQLite, database);
                    connections.Add(name, connection);
                }
            }

            if (watcher == null)
            {
                watcher = new FileSystemWatcher(Path.GetDirectoryName(ConfigPath), Path.GetFileName(ConfigPath))
                {
                    NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite,
                };
                watcher.Changed            += OnConfigFileChanged;
                watcher.Deleted            += OnConfigFileChanged;
                watcher.Renamed            += OnConfigFileChanged;
                watcher.EnableRaisingEvents = true;
            }
        }
Example #44
0
        /// <summary>
        /// Starts the watching path.
        /// </summary>
        /// <param name="path">The path.</param>
        private void StartWatchingPath(string path)
        {
            if (!_fileSystem.DirectoryExists(path))
            {
                // Seeing a crash in the mono runtime due to an exception being thrown on a different thread
                Logger.LogInformation("Skipping realtime monitor for {0} because the path does not exist", path);
                return;
            }

            if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
            {
                if (path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase) || path.StartsWith("smb://", StringComparison.OrdinalIgnoreCase))
                {
                    // not supported
                    return;
                }
            }

            if (_environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Android)
            {
                // causing crashing
                return;
            }

            // Already being watched
            if (_fileSystemWatchers.ContainsKey(path))
            {
                return;
            }

            // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
            Task.Run(() =>
            {
                try
                {
                    var newWatcher = new FileSystemWatcher(path, "*")
                    {
                        IncludeSubdirectories = true
                    };

                    newWatcher.InternalBufferSize = 65536;

                    newWatcher.NotifyFilter = NotifyFilters.CreationTime |
                                              NotifyFilters.DirectoryName |
                                              NotifyFilters.FileName |
                                              NotifyFilters.LastWrite |
                                              NotifyFilters.Size |
                                              NotifyFilters.Attributes;

                    newWatcher.Created += watcher_Changed;
                    newWatcher.Deleted += watcher_Changed;
                    newWatcher.Renamed += watcher_Changed;
                    newWatcher.Changed += watcher_Changed;
                    newWatcher.Error   += watcher_Error;

                    if (_fileSystemWatchers.TryAdd(path, newWatcher))
                    {
                        newWatcher.EnableRaisingEvents = true;
                        Logger.LogInformation("Watching directory " + path);
                    }
                    else
                    {
                        DisposeWatcher(newWatcher, false);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "Error watching path: {path}", path);
                }
            });
        }
Example #45
0
        public static void RvExtension(StringBuilder output, int outputSize,
                                       [MarshalAs(UnmanagedType.LPStr)] string function)
        {
            // Force rpt update
            if (function == "updateLogsList")
            {
                Task.Run(UpdateLogsList);

                output.Append("true");
                return;
            }

            // Force rpt scan
            if (function == "scanRPTFiles")
            {
                Task.Run(ScanRPTFiles);

                output.Append("true");
                return;
            }

            // Return logs count
            if (function == "getLogsListCount")
            {
                int count = logsList.Count();
                output.Append("" + count);
                return;
            }

            // Return next log
            if (function == "getLog")
            {
                if (logsList.Count() > 0)
                {
                    string log = logsList.First();
                    logsList.RemoveAt(0);

                    output.Append(log);
                }
                else
                {
                    output.Append("");
                }

                return;
            }

            // Start watching rpt
            if (function == "missionPreviewStart")
            {
                logsList.Clear();
                ScanRPTFiles();

                if (rptWatcher == null)
                {
                    rptWatcher = new FileSystemWatcher(logsDirPath);
                    rptWatcher.NotifyFilter = NotifyFilters.Attributes
                                              | NotifyFilters.CreationTime
                                              | NotifyFilters.DirectoryName
                                              | NotifyFilters.FileName
                                              | NotifyFilters.LastAccess
                                              | NotifyFilters.LastWrite
                                              | NotifyFilters.Security
                                              | NotifyFilters.Size;

                    rptWatcher.Changed += OnRPTChanged;
                    rptWatcher.Created += OnRPTCreated;
                    rptWatcher.Deleted += OnRPTDeleted;
                    rptWatcher.Renamed += OnRPTRenamed;

                    rptWatcher.Filter = "*.rpt";
                    rptWatcher.IncludeSubdirectories = false;
                }

                rptWatcher.EnableRaisingEvents = true;

                output.Append("true");
                return;
            }

            // Stop watching rpt
            if (function == "missionPreviewEnd")
            {
                if (rptWatcher != null)
                {
                    rptWatcher.EnableRaisingEvents = false;
                }
                logsList.Clear();

                output.Append("true");
                return;
            }
        }
Example #46
0
    static void observeSection(string iniPath, string section)
    {
        var uintRegex = new Regex(
            @"\A\d+\z",
            RegexOptions.Compiled
            );

        if (!getIniSections(iniPath).Contains(section))
        {
            MessageBox.Show(
                string.Format("This sections is deleted: {0}", section),
                Program.APPLICATION_NAME,
                MessageBoxButtons.OK,
                MessageBoxIcon.Hand
                );

            return;
        }

        var pattern = getIniValue(iniPath, section, "pattern", "*");

        var inDir = getIniValue(iniPath, section, "input_dir", string.Empty);

        if (inDir == string.Empty)
        {
            MessageBox.Show(
                string.Format(
                    "input_dir is not defined (section: {0})",
                    section
                    ),
                Program.APPLICATION_NAME,
                MessageBoxButtons.OK,
                MessageBoxIcon.Hand
                );

            return;
        }

        inDir = Environment.ExpandEnvironmentVariables(inDir);

        if (!Path.IsPathRooted(inDir))
        {
            inDir = Path.Combine(getExeDir(), inDir);
        }

        if (!Directory.Exists(inDir))
        {
            MessageBox.Show(
                string.Format(
                    "input_dir is defined but not exists:\n{0}",
                    inDir
                    ),
                Program.APPLICATION_NAME,
                MessageBoxButtons.OK,
                MessageBoxIcon.Hand
                );
        }

        var outDir = getIniValue(iniPath, section, "output_dir", string.Empty);

        if (outDir == string.Empty)
        {
            MessageBox.Show(
                string.Format(
                    "output_dir is not defined (section: {0})",
                    section
                    ),
                Program.APPLICATION_NAME,
                MessageBoxButtons.OK,
                MessageBoxIcon.Hand
                );

            return;
        }

        outDir = Environment.ExpandEnvironmentVariables(outDir);

        if (!Path.IsPathRooted(outDir))
        {
            outDir = Path.Combine(getExeDir(), outDir);
        }

        if (!Directory.Exists(outDir))
        {
            if (
                getBoolByString(
                    getIniValue(
                        iniPath,
                        section,
                        "create_output_dir",
                        string.Empty
                        ).ToLower(),
                    false
                    )
                )
            {
                Directory.CreateDirectory(outDir);
            }
            else
            {
                MessageBox.Show(
                    string.Format(
                        "output_dir is defined but not exists:\n{0}",
                        inDir
                        ),
                    Program.APPLICATION_NAME,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Hand
                    );
            }
        }

        ImageCodecInfo    imageCodecInfo    = null;
        EncoderParameters encoderParameters = null;
        var extension = string.Empty;

        switch (
            getIniValue(
                iniPath,
                section,
                "type",
                string.Empty
                ).ToLower()
            )
        {
        case "jpeg":
        case "jpg":
            var qualityStr = getIniValue(
                iniPath,
                section,
                "quality",
                string.Empty
                );

            if (qualityStr == string.Empty)
            {
                MessageBox.Show(
                    string.Format(
                        "quality is not defined (section: {0})",
                        section
                        ),
                    Program.APPLICATION_NAME,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Hand
                    );

                return;
            }

            if (!uintRegex.IsMatch(qualityStr))
            {
                MessageBox.Show(
                    string.Format(
                        "invalid quality (section: {0})",
                        section
                        ),
                    Program.APPLICATION_NAME,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Hand
                    );

                return;
            }

            var quality = Int32.Parse(qualityStr);

            if (100 < quality)
            {
                MessageBox.Show(
                    string.Format(
                        "quality is out of range (0-100) (section: {0})",
                        section
                        ),
                    Program.APPLICATION_NAME,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Hand
                    );

                return;
            }

            imageCodecInfo             = getImageCodecInfo(ImageFormat.Jpeg.Guid);
            encoderParameters          = new EncoderParameters(1);
            encoderParameters.Param[0] = new EncoderParameter(
                System.Drawing.Imaging.Encoder.Quality,
                quality
                );

            extension = "jpg";

            break;

        case "png":
            imageCodecInfo = getImageCodecInfo(ImageFormat.Png.Guid);

            extension = "png";

            break;

        case "":                 // string.Empty
            MessageBox.Show(
                string.Format(
                    "type is not defined (section: {0})",
                    section
                    ),
                Program.APPLICATION_NAME,
                MessageBoxButtons.OK,
                MessageBoxIcon.Hand
                );

            return;

        default:
            MessageBox.Show(
                string.Format(
                    "type is not valid (only jpg or png) (section: {0})",
                    section
                    ),
                Program.APPLICATION_NAME,
                MessageBoxButtons.OK,
                MessageBoxIcon.Hand
                );

            return;
        }

        var maxLongSide = 0;
        var maxWidth    = 0;
        var maxHeight   = 0;

        {
            var maxLongSideStr = getIniValue(
                iniPath,
                section,
                "max_long_side",
                "0"
                );

            if (!uintRegex.IsMatch(maxLongSideStr))
            {
                MessageBox.Show(
                    string.Format(
                        "invalid max_long_side value (section: {0})",
                        section
                        ),
                    Program.APPLICATION_NAME,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Hand
                    );

                return;
            }

            maxLongSide = Int32.Parse(maxLongSideStr);

            var maxWidthStr = getIniValue(
                iniPath,
                section,
                "max_width",
                "0"
                );

            if (!uintRegex.IsMatch(maxWidthStr))
            {
                MessageBox.Show(
                    string.Format(
                        "invalid max_width value (section: {0})",
                        section
                        ),
                    Program.APPLICATION_NAME,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Hand
                    );

                return;
            }

            maxWidth = Int32.Parse(maxWidthStr);

            var maxHeightStr = getIniValue(
                iniPath,
                section,
                "max_height",
                "0"
                );

            if (!uintRegex.IsMatch(maxHeightStr))
            {
                MessageBox.Show(
                    string.Format(
                        "invalid max_height value (section: {0})",
                        section
                        ),
                    Program.APPLICATION_NAME,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Hand
                    );

                return;
            }

            maxHeight = Int32.Parse(maxHeightStr);
        }


        // nolimitation
        if (maxLongSide == 0)
        {
            maxLongSide = Int32.MaxValue;
        }

        if (maxWidth == 0)
        {
            maxWidth = Int32.MaxValue;
        }

        if (maxHeight == 0)
        {
            maxHeight = Int32.MaxValue;
        }

        var observe = false;
        var observeFileReadDelayMs = 0;
        var oneshot = false;

        switch (
            getIniValue(
                iniPath,
                section,
                "mode",
                string.Empty
                ).ToLower()
            )
        {
        case "oneshot":
            oneshot = true;
            break;

        case "both":
            oneshot = true;
            goto case "observe";

        case "observe":
            observe = true;

            var observeFileReadDelayMsStr = getIniValue(
                iniPath,
                section,
                "observe_file_read_delay_ms",
                "1000"
                );

            if (!uintRegex.IsMatch(observeFileReadDelayMsStr))
            {
                MessageBox.Show(
                    string.Format(
                        "invalid observe_file_read_delay_ms value (section: {0})",
                        section
                        ),
                    Program.APPLICATION_NAME,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Hand
                    );

                return;
            }

            observeFileReadDelayMs = Int32.Parse(observeFileReadDelayMsStr);

            break;

        case "":                 // string.Empty
            MessageBox.Show(
                string.Format(
                    "mode is not defined (section: {0})",
                    section
                    ),
                Program.APPLICATION_NAME,
                MessageBoxButtons.OK,
                MessageBoxIcon.Hand
                );

            return;

        default:
            MessageBox.Show(
                string.Format(
                    "mode is not valid (section: {0})",
                    section
                    ),
                Program.APPLICATION_NAME,
                MessageBoxButtons.OK,
                MessageBoxIcon.Hand
                );

            return;
        }

        if (oneshot)
        {
            var pOpt = new ParallelOptions();
            pOpt.MaxDegreeOfParallelism = Environment.ProcessorCount;

            Console.WriteLine(string.Format(
                                  "OneShot ({0} threads): Process files...",
                                  pOpt.MaxDegreeOfParallelism
                                  ));

            Parallel.ForEach(Directory.GetFiles(inDir, pattern), pOpt, f => {
                var newF = getDestFileName(f, outDir, extension);

                if (File.Exists(newF))
                {
                    return;
                }

                resizeImage(
                    f,
                    newF,
                    maxWidth,
                    maxHeight,
                    maxLongSide,
                    imageCodecInfo,
                    encoderParameters
                    );
            });
        }

        if (observe)
        {
            var watcher = new FileSystemWatcher();

            watcher.Path         = inDir;
            watcher.Filter       = pattern;
            watcher.NotifyFilter = NotifyFilters.FileName;

            watcher.Created += new FileSystemEventHandler(
                async(source, e) => {
                Console.WriteLine(
                    string.Format(
                        "Convert Scheduled: {0}",
                        Path.GetFileName(e.FullPath)
                        )
                    );


                await Task.Delay(observeFileReadDelayMs);

                resizeImage(
                    e.FullPath,
                    getDestFileName(e.FullPath, outDir, extension),
                    maxWidth,
                    maxHeight,
                    maxLongSide,
                    imageCodecInfo,
                    encoderParameters
                    );
            }
                );

            Console.WriteLine("Observing... (Press enter key to exit)");
            watcher.EnableRaisingEvents = true;

            Console.ReadLine();
        }
    }
        private static void AttachModulesWatcher(string moduleFolder, bool includeSubdirectories, IApplicationLifetime applicationLifetime)
        {
            if (!Directory.Exists(moduleFolder))
            {
                //Do nothing for none existant folders
                return;
            }
            FileSystemWatcher fileWatcher;
            RestartReason     restartReason = new RestartReason();

            if (includeSubdirectories)
            {
                fileWatcher = new FileSystemWatcher(moduleFolder);
                // watch for everything
                fileWatcher.NotifyFilter          = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                fileWatcher.IncludeSubdirectories = includeSubdirectories;
                fileWatcher.Filter = "*.*";
                // Add event handlers.
                fileWatcher.Changed += new FileSystemEventHandler(OnChanged);
                fileWatcher.Created += new FileSystemEventHandler(OnChanged);
                fileWatcher.Deleted += new FileSystemEventHandler(OnChanged);
                fileWatcher.Renamed += new RenamedEventHandler(OnRenamed);

                // Begin watching...
                fileWatcher.EnableRaisingEvents = true;
            }
            else //only for the files
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(moduleFolder);
                foreach (FileInfo file in directoryInfo.GetFiles())
                {
                    fileWatcher              = new FileSystemWatcher();
                    fileWatcher.Path         = directoryInfo.FullName;
                    fileWatcher.Filter       = file.Name;
                    fileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
                    // Add event handlers.
                    fileWatcher.Changed += new FileSystemEventHandler(OnChanged);
                    fileWatcher.Created += new FileSystemEventHandler(OnChanged);
                    fileWatcher.Deleted += new FileSystemEventHandler(OnChanged);
                    fileWatcher.Renamed += new RenamedEventHandler(OnRenamed);
                    // Begin watching...
                    fileWatcher.EnableRaisingEvents = true;
                }
            }

            void OnChanged(object source, FileSystemEventArgs e)
            {
                //Bug in Docker which will trigger OnChanged during StartUp (How to fix?)
                AppDomain.CurrentDomain.UnhandledException -= AppDomain_OnUnhandledException;
                AppDomain.CurrentDomain.AssemblyResolve    -= AppDomain_OnAssemblyResolve;
                restartReason.Reason      = "File Changed";
                restartReason.Description = $"ChangeType: {e.ChangeType} file {e.FullPath}";
                RestartApplication(applicationLifetime, restartReason);
            }

            void OnRenamed(object source, RenamedEventArgs e)
            {
                AppDomain.CurrentDomain.UnhandledException -= AppDomain_OnUnhandledException;
                AppDomain.CurrentDomain.AssemblyResolve    -= AppDomain_OnAssemblyResolve;
                restartReason.Reason      = "File Renamed";
                restartReason.Description = $"Renaming from {e.OldFullPath} to {e.FullPath}";
                RestartApplication(applicationLifetime, restartReason);
            }
        }
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            SetupDataFolder();
            if (File.Exists(logFilePath))
            {
                File.WriteAllText(logFilePath, string.Empty);
            }
            else
            {
                CreateLogFile();
            }

            //Check if software already runs, if so kill this instance
            var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull));

            if (otherACCs.Length > 1)
            {
                //DoDebug("ACC is already running, killing this proccess");
                //MessageBox.Show("ACC is already running.", "Already running | " + messageBoxTitle + "");
                //Process.GetCurrentProcess().Kill();

                Process.GetCurrentProcess();

                //Try kill the _other_ process instead
                foreach (Process p in otherACCs)
                {
                    if (p.Id != Process.GetCurrentProcess().Id)
                    {
                        p.Kill();
                        DoDebug("Other ACC instance was running. Killed it.");
                    }
                }
            }

            DoDebug("[ACC begun (v" + softwareVersion + ")]");
            AnalyticsSettings.SetupAnalyticsAsync();

            if (Properties.Settings.Default.CheckForUpdates)
            {
                if (HasInternet())
                {
                    new Thread(() => {
                        new ACC_Updater().Check();
                    }).Start();
                }
                else
                {
                    DoDebug("Couldn't check for new update as PC does not have access to the internet");
                }
            }

            //"updated.txt" not created. Use registry instead (for 1.1.0)

            /*if (File.Exists(Path.Combine(dataFolderLocation, "updated.txt"))) {
             *  File.Delete(Path.Combine(dataFolderLocation, "updated.txt"));
             *  new AboutVersion().Show();
             * }*/

            //On console close: hide NotifyIcon
            Application.ApplicationExit += new EventHandler(OnApplicationExit);
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            //Check if software starts with Windows
            if (!Properties.Settings.Default.StartWithWindows)
            {
                sysIcon.AddOpenOnStartupMenu();
            }

            //Create shortcut folder if doesn't exist
            if (!Directory.Exists(shortcutLocation))
            {
                Directory.CreateDirectory(shortcutLocation);
            }
            if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt")))
            {
                //Create example-file
                using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
                    sw.WriteLine("This is an example file.");
                    sw.WriteLine("If you haven't already, make your assistant open this file!");
                }
            }

            //Delete all old action files
            if (Directory.Exists(CheckPath()))
            {
                foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension))
                {
                    ClearFile(file);
                }
            }

            //SetupListener();
            watcher = new FileSystemWatcher()
            {
                Path         = CheckPath(),
                NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                               | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                Filter = "*." + Properties.Settings.Default.ActionFileExtension,
                EnableRaisingEvents = true
            };
            watcher.Changed += new FileSystemEventHandler(ActionChecker.FileFound);
            watcher.Created += new FileSystemEventHandler(ActionChecker.FileFound);

            DoDebug("\n[" + messageBoxTitle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions");

            Application.EnableVisualStyles();
            sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon;

            RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);

            if (Registry.GetValue(key.Name + "\\AssistantComputerControl", "FirstTime", null) == null)
            {
                key.CreateSubKey("AssistantComputerControl");
                key = key.OpenSubKey("AssistantComputerControl", true);
                key.SetValue("FirstTime", false);

                Properties.Settings.Default.HasCompletedTutorial = true;
                Properties.Settings.Default.Save();

                ShowGettingStarted();

                DoDebug("Starting setup guide");
            }
            else
            {
                if (!Properties.Settings.Default.HasCompletedTutorial)
                {
                    ShowGettingStarted();
                    DoDebug("Didn't finish setup guide last time, opening again");
                }
            }
            SetRegKey("ActionFolder", CheckPath());
            SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension);

            Application.Run();
        }
Example #49
0
        public void Processor(object data)
        {
            string path = (string)data;

            using (var w = new FileSystemWatcher {
                Path = path,
                IncludeSubdirectories = _args.Recursive,
                Filter = "*.*"
            }) {
                w.Error += new ErrorEventHandler(OnWatcherError);

                // Parse "events" argument
                WatcherChangeTypes changes = 0;
                if (_args.Events.Contains("create"))
                {
                    changes |= WatcherChangeTypes.Created;
                }
                if (_args.Events.Contains("modify"))
                {
                    changes |= WatcherChangeTypes.Changed;
                }
                if (_args.Events.Contains("delete"))
                {
                    changes |= WatcherChangeTypes.Deleted;
                }
                if (_args.Events.Contains("move"))
                {
                    changes |= WatcherChangeTypes.Renamed;
                }

                // Main loop
                if (!_args.Quiet)
                {
                    Console.Error.WriteLine(
                        "===> {0} for {1} in {2}{3} for {4}",
                        _args.Monitor ? "Monitoring" : "Watching",
                        changes,
                        path,
                        _args.Recursive ? " -r" : "",
                        String.Join(", ", _args.Events.ToArray())
                        );
                }
                w.EnableRaisingEvents = true;
                while (true)
                {
                    var e = w.WaitForChanged(changes);
                    _mutex.WaitOne();
                    if (_eventOccured)
                    {
                        _mutex.ReleaseMutex();
                        break;
                    }
                    if (null != _args.Exclude && _args.Exclude.IsMatch(System.IO.Path.GetFullPath(e.Name)))
                    {
                        _mutex.ReleaseMutex();
                        continue;
                    }
                    if (WatcherChangeTypes.Renamed.Equals(e.ChangeType))
                    {
                        Output(Console.Out, _args.Format, w, Change.MOVED_FROM, e.OldName);
                        Output(Console.Out, _args.Format, w, Change.MOVED_TO, e.Name);
                    }
                    else
                    {
                        Output(Console.Out, _args.Format, w, Changes[e.ChangeType], e.Name);
                    }
                    if (!_args.Monitor)
                    {
                        _eventOccured = true;
                        _semaphore.Release();
                    }
                    _mutex.ReleaseMutex();
                }
            }
        }
Example #50
0
        static int Main(string[] args)
        {
            var botType     = BotType.Discord;
            var shard       = 0;
            var totalShards = 1;

            if (args != null)
            {
                foreach (string arg in args)
                {
                    var argParts = arg.Split(new[] { ':' }, 2);

                    switch (argParts[0])
                    {
                    case "/?":
                        Console.WriteLine("dotnet UB3RB0T.dll [/t:type] [/s:shard]");
                        Console.WriteLine("/t:type \t The type of bot to create. [Irc, Discord]");
                        Console.WriteLine("/s:shard \t The shard for this instance (Discord only)");
                        Console.WriteLine("/c:path \t The path to botconfig.json");
                        return(0);

                    case "/t":
                        if (!Enum.TryParse(argParts[1], /* ignoreCase */ true, out botType))
                        {
                            throw new ArgumentException("Invalid bot type specified.");
                        }

                        break;

                    case "/c":
                        Environment.SetEnvironmentVariable(JsonConfig.PathEnvironmentVariableName, argParts[1]);
                        break;

                    case "/s":
                        shard = int.Parse(argParts[1]);
                        break;

                    case "/st":
                        totalShards = int.Parse(argParts[1]);
                        break;
                    }
                }
            }

            // Logging
            levelSwitch = new LoggingLevelSwitch
            {
                MinimumLevel = BotConfig.Instance.LogEventLevel
            };

            var logConfiguration = new LoggerConfiguration()
                                   .MinimumLevel.ControlledBy(levelSwitch)
                                   .Enrich.WithProperty("Shard", shard.ToString().PadLeft(2))
                                   .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Error,
                                                    outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3} {Shard}] {Message:lj}{NewLine}{Exception}");

            if (!string.IsNullOrWhiteSpace(BotConfig.Instance.LogsPath))
            {
                logConfiguration.WriteTo.File($"{BotConfig.Instance.LogsPath}\\{botType}_shard{shard}_.txt",
                                              buffered: true,
                                              rollingInterval: RollingInterval.Day,
                                              flushToDiskInterval: TimeSpan.FromSeconds(5));
            }

            Log.Logger = logConfiguration.CreateLogger();

            // setup a watcher for configs
            var watcher = new FileSystemWatcher
            {
                Path         = JsonConfig.ConfigRootPath,
                NotifyFilter = NotifyFilters.LastWrite,
                Filter       = "*.json",
            };

            watcher.Changed += (source, e) =>
            {
                _ = ReloadConfigs();
            };

            watcher.EnableRaisingEvents = true;

            int exitCode = (int)ExitCode.Success;
            // Convert to async main method
            var instanceCount = 0;

            do
            {
                try
                {
                    using (var bot = Bot.Create(botType, shard, totalShards, instanceCount))
                    {
                        BotInstance = bot;
                        // Handle clean shutdown when possible
                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                        {
                            SetConsoleCtrlHandler((ctrlType) =>
                            {
                                bot.StopAsync().GetAwaiter().GetResult();
                                return(true);
                            }, true);
                        }

                        Log.Information($"Starting shard {shard}");

                        exitCode = bot.StartAsync().GetAwaiter().GetResult();
                    }
                }
                catch (Exception ex)
                {
                    Log.Fatal(ex, "Failure in bot loop");
                }

                instanceCount++;
            } while (exitCode == (int)ExitCode.UnexpectedError); // re-create the bot on failures.  Only exit if a clean shutdown occurs.

            Log.CloseAndFlush();

            Log.Fatal("Game over man, {{GameOver}}", "game over!");

            return(exitCode);
        }
Example #51
0
        private void StartWatch()
        {
            try
            {
                FileInfo targetFile = new FileInfo(options.File);

                previousSeekPosition = 0;

                fileSystemWatcher = new FileSystemWatcher();
                fileSystemWatcher.IncludeSubdirectories = false;
                fileSystemWatcher.Path   = targetFile.DirectoryName;
                fileSystemWatcher.Filter = targetFile.Name;

                fileSystemWatcher.Created            += new FileSystemEventHandler(OnFileCreated);
                fileSystemWatcher.Deleted            += new FileSystemEventHandler(OnFileDeleted);
                fileSystemWatcher.Renamed            += new RenamedEventHandler(OnFileRenamed);
                fileSystemWatcher.Changed            += new FileSystemEventHandler(OnFileChanged);
                fileSystemWatcher.EnableRaisingEvents = true;

                if (targetFile.Exists)
                {
                    while (targetFile.Length > readBytesCount && readLineCount < options.OutputLines)
                    {
                        ReadFile();
                    }
                }
                else
                {
                    if (!options.IsSetRetry)
                    {
                        throw new CommandLineException(string.Format(CultureInfo.CurrentCulture,
                                                                     "No such file -- {0}", options.File));
                    }
                }

                if (options.IsSetFollow)
                {
                    if (monitoringFileTimer == null)
                    {
                        monitoringFileTimer = new Timer((TimerCallback)OnMonitoringTimerCallback, options.File,
                                                        TimeSpan.Zero, TimeSpan.FromSeconds(options.SleepInterval));
                    }
                }
                else
                {
                    Terminate();
                }
            }
            catch (CommandLineException ex)
            {
                RaiseCommandLineException(this, ex);
            }
            catch (ArgumentException)
            {
                signal.Reset();
                if (!signal.WaitOne(TimeSpan.FromSeconds(5)))
                {
                    RestartWatch();
                }
            }
        }
Example #52
0
 protected override void OnDispose()
 {
     _watcher.EnableRaisingEvents = false;
     _watcher.Dispose();
     _watcher = null;
 }
            /// <summary>
            ///    Анализ решения
            /// </summary>
            /// <param name="isHangout">
            ///    true, если время, отведенное для анализа вышло, а процесс все еще не завершен, false - если
            ///    процесс завершился
            /// </param>
            /// <param name="devenvExitCode"></param>
            /// <returns>true, если процесс анализа прошел успешно, false - в противном случае</returns>
            public bool ProcessAnalysis(out bool isHangout, out int devenvExitCode)
            {
                const string errorDetectedSuffix = ".plog.exception_messages.txt";

                try
                {
                    ConfigureAnalisysProcess();
                    var start = DateTime.Now;
                    _analyzerProcess.Start();
                    var runningQuota = TimeSpan.FromMinutes(ApplicationConfigReader.Instance.HangTime).Duration();

                    var plogPath = Path.GetDirectoryName(_plog);
                    Debug.Assert(plogPath != null, "plogPath != null");

                    var destinationPlog  = Path.GetFileName(_plog);
                    var plogCreatedEvent = new ManualResetEventSlim();
                    var plogWatcher      = new FileSystemWatcher(plogPath, "*.plog")
                    {
                        EnableRaisingEvents   = true,
                        IncludeSubdirectories = false,
                        NotifyFilter          = NotifyFilters.FileName
                    };
                    plogWatcher.Created += (sender, args) =>
                    {
                        var createdName = args.Name;
                        if (string.Equals(createdName, destinationPlog))
                        {
                            plogCreatedEvent.Set();
                        }
                    };

                    var destinationErrorPlog = string.Format("{0}{1}", Path.GetFileNameWithoutExtension(_plog), errorDetectedSuffix);
                    var errorCreatedEvent    = new ManualResetEventSlim();
                    var errorWatcher         = new FileSystemWatcher(plogPath, string.Format("*{0}", errorDetectedSuffix))
                    {
                        EnableRaisingEvents   = true,
                        IncludeSubdirectories = false,
                        NotifyFilter          = NotifyFilters.FileName
                    };
                    errorWatcher.Created += (sender, args) =>
                    {
                        var createdName = args.Name;
                        if (string.Equals(destinationErrorPlog, createdName))
                        {
                            errorCreatedEvent.Set();
                        }
                    };

                    var waitingIndex = WaitHandle.WaitAny(
                        new[]
                    {
                        plogCreatedEvent.WaitHandle,
                        errorCreatedEvent.WaitHandle
                    }, TimeSpan.FromMinutes(ApplicationConfigReader.Instance.HangTime));

                    var plogAppeared = waitingIndex == 0;
                    if (plogAppeared)
                    {
                        plogAppeared = AnalyzerUtilities.WaitForFileReleased(_plog, start, runningQuota);
                        AppEventLogger.Log(
                            string.Format("File {0} is {1}", _plog, (plogAppeared ? "Released" : "Time out")),
                            plogAppeared ? EventLogEntryType.SuccessAudit : EventLogEntryType.FailureAudit);
                    }

                    isHangout = !plogAppeared;
                    ProcessUtils.MandatoryKill(_analyzerProcess);
                    devenvExitCode = default(int);
                    return(!isHangout);
                }
                catch (Exception ex)
                {
                    AppEventLogger.Log(
                        string.Format("Error message: {0}. Stack trace: {1}{2}{3}", ex.Message, ex.StackTrace,
                                      Environment.NewLine, ToString()), EventLogEntryType.Error);
                    devenvExitCode = default(int);
                    return(isHangout = !File.Exists(_plog));
                }
            }
Example #54
0
        string targetPath = @"temp";          //папка создается в дебаге

        public FileWatcher(string path)
        {
            TextWatcher      = new FileSystemWatcher();
            TextWatcher.Path = path;
        }
Example #55
0
        async static Task <int> Main(string[] args)
        {
            var app = new CommandLineApplication();

            app.HelpOption();
            app.Command("analyze", cmd =>
            {
                var filesArg = cmd.Argument("files", "Raw profiling input files to process", true).IsRequired();

                cmd.OnExecuteAsync(async ct =>
                {
                    int exitCode = 0;
                    foreach (var filePath in filesArg.Values)
                    {
                        if (!File.Exists(filePath))
                        {
                            Console.Error.WriteLine($"File does not exist: {filePath}");
                            exitCode = 1;
                            continue;
                        }

                        try
                        {
                            await AnalyzeFile(filePath);
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine($"Error processing file '{filePath}': {e}");
                            exitCode = 1;
                        }
                    }

                    return(exitCode);
                });
            });

            app.Command("watch", cmd =>
            {
                var dirARg = cmd.Argument("directory", "A directory to watch for new files to process");

                cmd.OnExecuteAsync(async ct =>
                {
                    string watchDirectory = dirARg.Value ?? Environment.GetEnvironmentVariable("MTGPROFILER_DATADIR");
                    if (string.IsNullOrEmpty(watchDirectory))
                    {
                        Console.Error.WriteLine("Watch dir was not specified or found in environment variable MTG_PROFILER_DATA_DIR");
                        return(1);
                    }
                    else if (!Directory.Exists(watchDirectory))
                    {
                        Console.Error.WriteLine($"Directory does not exist {watchDirectory}");
                        return(1);
                    }

                    Console.WriteLine($"Watching {watchDirectory} for changes...");
                    using var watch = new FileSystemWatcher(watchDirectory, "*.bin");

                    var pending = new Queue <(string filePath, int retry)>();
                    while (true)
                    {
                        var info = watch.WaitForChanged(WatcherChangeTypes.All, 2_000);
                        string inputFilePath;
                        int retry;
                        if (info.TimedOut)
                        {
                            if (!pending.TryDequeue(out var item))
                            {
                                continue;
                            }

                            inputFilePath = item.filePath;
                            retry         = item.retry;
                        }
                        else
                        {
                            if (info.ChangeType == WatcherChangeTypes.Deleted)
                            {
                                continue;
                            }

                            inputFilePath = Path.Combine(watchDirectory, info.Name);
                            retry         = 0;
                        }

                        try
                        {
                            using var fs = File.OpenRead(inputFilePath);
                        }
                        catch (Exception)
                        {
                            if (retry < 3)
                            {
                                pending.Enqueue((inputFilePath, retry + 1));
                            }

                            continue;
                        }

                        string name = Path.GetFileName(inputFilePath);
                        try
                        {
                            Console.WriteLine($"Analyzing {name}");
                            string outputFile = await AnalyzeFile(inputFilePath);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"Error processing file {name}");
                            Console.WriteLine($"Exception details: {e}");
                        }
                    }
Example #56
0
        public virtual void Initialize()
        {
            SparklePlugin.PluginsPath = PluginsPath;
            InstallProtocolHandler();

            // Create the SparkleShare folder and add it to the bookmarks
            if (CreateSparkleShareFolder())
            {
                AddToBookmarks();
            }

            if (FirstRun)
            {
                this.config.SetConfigOption("notifications", bool.TrueString);
            }
            else
            {
                string keys_path     = Path.GetDirectoryName(this.config.FullPath);
                string key_file_path = "";

                foreach (string file_name in Directory.GetFiles(keys_path))
                {
                    if (file_name.EndsWith(".key"))
                    {
                        key_file_path = Path.Combine(keys_path, file_name);
                        SparkleKeys.ImportPrivateKey(key_file_path);

                        break;
                    }
                }

                if (!string.IsNullOrEmpty(key_file_path))
                {
                    string public_key_file_path = key_file_path + ".pub";
                    string link_code_file_path  = Path.Combine(FoldersPath, CurrentUser.Name + "'s link code.txt");

                    // Create an easily accessible copy of the public
                    // key in the user's SparkleShare folder
                    if (File.Exists(public_key_file_path) && !File.Exists(link_code_file_path))
                    {
                        File.Copy(public_key_file_path, link_code_file_path, true);
                    }

                    CurrentUser.PublicKey = File.ReadAllText(public_key_file_path);
                }

                SparkleKeys.ListPrivateKeys();
            }

            // Watch the SparkleShare folder
            this.watcher = new FileSystemWatcher()
            {
                Filter = "*",
                IncludeSubdirectories = false,
                Path = FoldersPath
            };

            watcher.Deleted += OnFolderActivity;
            watcher.Created += OnFolderActivity;
            watcher.Renamed += OnFolderActivity;

            watcher.EnableRaisingEvents = true;
        }
Example #57
0
        bool EnsureInternalSetup(string solutionPath, ref IDictionary <string, object> properties)
        {
            if (solutionPath.IsNullOrEmpty())
            {
                if (BranchWatcher != null)
                {
                    DisposeFileWatcher(BranchWatcher);
                    BranchWatcher = null;
                }

                return(false);
            }

            var solution_directory = Path.GetDirectoryName(solutionPath);

            // try to find <solution directory>/.hg/branch if nolders above solution file

            var mercurial_parent_directory = solution_directory;
            var mercurial_directory        = Path.Combine(mercurial_parent_directory, ".hg");
            var mercurial_branch           = Path.Combine(mercurial_directory, "branch");

            while (!mercurial_parent_directory.IsNullOrEmpty() && !File.Exists(mercurial_branch))
            {
                mercurial_parent_directory = Path.GetDirectoryName(mercurial_parent_directory);

                if (mercurial_parent_directory.IsNullOrEmpty())
                {
                    break;
                }

                mercurial_directory = Path.Combine(mercurial_parent_directory, ".hg");
                mercurial_branch    = Path.Combine(mercurial_directory, "branch");
            }

            if (!File.Exists(mercurial_branch))
            {
                return(false);
            }

            properties.Add("hg:branchPath", mercurial_branch);

            //# Update File Watcher

            // dispose old file watcher if it's been used to watch different location
            if (BranchWatcher != null && BranchWatcher.Path != mercurial_directory)
            {
                DisposeFileWatcher(BranchWatcher);
                BranchWatcher = null;
            }

            // create new file watcher if needed
            if (BranchWatcher == null)
            {
                BranchWatcher = new FileSystemWatcher(mercurial_directory, "branch");
                BranchWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
                BranchWatcher.Changed     += BranchWatcher_Changed;
                // VisualHg seems to delete old branch file, create temporary new file (e.g. branch-23123), write to this new file and then rename it to branch
                BranchWatcher.Renamed += BranchWatcher_Renamed;

                BranchWatcher.EnableRaisingEvents = true;
            }

            return(true);
        }
Example #58
0
        private void RunAllTests()
        {
            Trace.WriteLine("Running all tests...");

            int    expectedPassedTests = 2;
            string testResultsFilePath = null;

            using (TempFile testResultsFile = new TempFile())
            {
                if (this.visualStudioVersion == "2010")
                {
                    expectedPassedTests = 3;
                    string testResultsPath = Path.Combine(this.solutionDirectory.DirectoryPath, "TestResults");

                    // directory must exist for FileSystemWatcher
                    Directory.CreateDirectory(testResultsPath);

                    AutoResetEvent autoResetEvent = new AutoResetEvent(false);

                    FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(testResultsPath, "*.trx");
                    fileSystemWatcher.Created += (sender, args) =>
                    {
                        Trace.WriteLine(string.Format("File created Name: '{0}' FullPath: '{1}' ChangeType: '{2}'", args.Name, args.FullPath, args.ChangeType));
                        testResultsFilePath = args.FullPath;
                    };
                    fileSystemWatcher.Changed += (sender, args) =>
                    {
                        Trace.WriteLine(string.Format("File changed Name: '{0}' FullPath: '{1}' ChangeType: '{2}'", args.Name, args.FullPath, args.ChangeType));
                        autoResetEvent.Set();
                    };

                    fileSystemWatcher.EnableRaisingEvents = true;

                    this.dte.ExecuteCommand("Test.RunAllTestsInSolution");

                    autoResetEvent.WaitOne();
                }
                else
                {
                    // Activate "Test Explorer" window
                    const string testExplorerGuid = "{E1B7D1F8-9B3C-49B1-8F4F-BFC63A88835D}";

                    Window testExplorerWindow = this.dte.Windows.Item(testExplorerGuid);
                    testExplorerWindow.Activate();

                    this.ExecuteCommand("TestExplorer.RunAllTests");

                    // read the tests window output
                    string output = this.GetTestsOutput();
                    while (!output.Contains("Run test finished"))
                    {
                        Trace.WriteLine(output);
                        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
                        output = this.GetTestsOutput();
                    }

                    Match testsRunMatch = Regex.Match(output, @"Run test finished: (\d+)");
                    Assert.IsTrue(testsRunMatch.Success, output);
                    Assert.IsNotNull(testsRunMatch, output);
                    Assert.IsNotNull(testsRunMatch.Groups, output);
                    Assert.AreEqual(expectedPassedTests, testsRunMatch.Groups.Count, output);
                    Group  testsRunGroup  = testsRunMatch.Groups[1];
                    string testsRunString = testsRunGroup.Value;
                    Assert.AreEqual(expectedPassedTests.ToString(), testsRunString, output);
                    int testsRun = Int32.Parse(testsRunString);
                    Assert.AreEqual(expectedPassedTests, testsRun, output);

                    // results file must not exist
                    File.Delete(testResultsFile.FilePath);

                    string   fileName  = string.Format(@"C:\Program Files (x86)\Microsoft Visual Studio {0}.0\Common7\IDE\MSTest.exe", this.visualStudioVersionNumber);
                    string[] arguments =
                    {
                        string.Format("/testcontainer:{0}", Path.Combine(this.testProjectPath, "bin", "Debug", string.Format("{0}.dll", ProjectName))),
                        string.Format("/resultsfile:{0}",   testResultsFile.FilePath)
                    };

                    RunResult runResult = ProcessRunner.Run(fileName, string.Join(" ", arguments));
                    Assert.AreEqual(0, runResult.ExitCode, string.Join(Environment.NewLine, new { runResult.StandardOutput, runResult.StandardError }));

                    testResultsFilePath = testResultsFile.FilePath;
                }

                // Deserialize TestRunType object from the trx file
                // To support a new version of visual studio:
                // 1. xsd.exe "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Xml\Schemas\vstst.xsd" /c /namespace:CUITe.IntegrationTests.NuGet.VisualStudio2015
                // 2. Manually fix runtime errors "There was an error reflecting property 'Items'. ---> System.InvalidOperationException: Member 'GenericTestType.Items' hides inherited member 'BaseTestType.Items', but has different custom attributes."
                // See http://stackoverflow.com/a/10872961/90287
                // 3. Replace "[][]" with "[]" in generated class
                int testsPassedCount;
                switch (this.visualStudioVersionNumber)
                {
                case "10":
                    testsPassedCount = this.GetNumberOfPassedTestsInVisualStudio2010(testResultsFilePath);
                    break;

                case "11":
                    testsPassedCount = this.GetNumberOfPassedTestsInVisualStudio2012(testResultsFilePath);
                    break;

                case "12":
                    testsPassedCount = this.GetNumberOfPassedTestsInVisualStudio2013(testResultsFilePath);
                    break;

                case "14":
                    testsPassedCount = this.GetNumberOfPassedTestsInVisualStudio2015(testResultsFilePath);
                    break;

                default:
                    throw new NotSupportedException(this.visualStudioVersionNumber);
                }

                Assert.AreEqual(expectedPassedTests, testsPassedCount, File.ReadAllText(testResultsFilePath));
            }
        }
Example #59
0
 private void StartFileSystemWatcher(string uploadPath)
 {
     _watcher = new FileSystemWatcher(uploadPath);
     _watcher.EnableRaisingEvents = true;
     _watcher.Created            += new FileSystemEventHandler(watcher_Created);
 }
Example #60
0
 public FileWatcher(string path = "", string filter = "*.*")
 {
     _fsw = new FileSystemWatcher(path, filter);
 }