Exemplo n.º 1
0
 // Start is called before the first frame update
 void Start()
 {
     //インスタンス生成
     restart = new RestartManager(player, text);
     //初期時間を設定
     timeText.text = "残り時間:" + limit + "秒";
 }
        public void Work()
        {
            var commands = _store.GetCommands();

            _logger.Log(string.Format("Command count {0}", commands.Count));
            if (commands.Count == 0)
            {
                RestartManager.NoCommandsFoundRestartCheck(_logger);
                LogManager.ShouldBeLogging = false;
                return;
            }

            LogManager.ShouldBeLogging = true;
            foreach (var command in commands)
            {
                if (CommandsController.ProcessCommands)
                {
                    ProcessCommand(command);
                }
                else
                {
                    _logger.Log(string.Format("Bypassing command {0}", command.name));
                }
            }

            RestartManager.CommandsRunRestartCheck(_logger);
        }
Exemplo n.º 3
0
        public static void GetLockingProcesses_WhenGivenEmptyFileInfoCollection_ReturnsEmptyResult()
        {
            var arg    = new List <FileInfo>();
            var result = RestartManager.GetLockingProcesses(arg);

            Assert.AreEqual(0, result.Count);
        }
Exemplo n.º 4
0
    public static void GetLockingProcesses_WhenGivenEmptyFileInfoCollection_ReturnsEmptyResult()
    {
        var arg    = Array.Empty <FileInfo>();
        var result = RestartManager.GetLockingProcesses(arg);

        Assert.That(result, Is.Empty);
    }
Exemplo n.º 5
0
        public void TestBasicRestartManager()
        {
            //Start up all the little dandies
            StartService(TestHelpers.TestService);
            RestartManagerSession manager = new RestartManagerSession();

            manager.StartSession();
            System.Threading.Thread.Sleep(1000);
            manager.RegisterResources(new List <string>()
            {
                ReplacementFileServicePath
            });

            //Look for the processes locking on our poor file
            RM_REBOOT_REASON rebootReason = default(RM_REBOOT_REASON);
            var processes = RestartManager.RmProcessToNetProcess(manager.GetList(ref rebootReason));

            //Make sure it's the service we expect.
            var serviceExecutable = GetServiceExecutablePath(TestHelpers.TestService);

            Assert.IsTrue(processes.Count > 0 && processes.Any(x => x.MainModule.FileName.ToLower() == serviceExecutable.ToLower()));

            manager.EndSession();
            StopService(TestHelpers.TestService);
        }
Exemplo n.º 6
0
        public static void GetLockingProcesses_WhenLockingOnPathAndGivenDirectory_ReturnsCorrectProcess()
        {
            var tmpFilePath = Path.GetTempFileName();
            var tmpDirPath  = Path.GetDirectoryName(tmpFilePath);

            tmpDirPath = Path.Combine(tmpDirPath, Guid.NewGuid().ToString());

            var tmpDir = new DirectoryInfo(tmpDirPath);

            tmpDir.Create();
            var tmpDirFile = Path.Combine(tmpDirPath, Path.GetFileName(tmpFilePath));

            File.Move(tmpFilePath, tmpDirFile);

            using (var file = File.Open(tmpDirFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
            {
                var lockingProcs = RestartManager.GetLockingProcesses(tmpDir);
                var process      = Process.GetCurrentProcess();

                var lockingId = lockingProcs.Single().ProcessId;
                var currentId = process.Id;

                Assert.AreEqual(currentId, lockingId);
            }

            tmpDir.Delete(true);
        }
Exemplo n.º 7
0
        private void OpenPath(string path)
        {
            if (!File.Exists(path))
            {
                MessageBox.Show(path + " is not a valid file path");
                return;
            }

            Title = DefaultTitle + " - " + path;
            ListViewProcess.Items.Clear();

            try
            {
                using var session = RestartManager.CreateSession();
                session.RegisterFile(path);
                var processes = session.GetProcessesLockingResources();
                if (processes.Count == 0)
                {
                    MessageBox.Show("The file is not locked");
                }
                else
                {
                    foreach (var process in processes)
                    {
                        ListViewProcess.Items.Add(process);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occured: " + ex);
            }
        }
        /// <summary>
        ///   Attempts to remove marked package directories that were unable to be fully deleted
        ///   during the original uninstall.
        /// </summary>
        public async Task DeleteMarkedPackageDirectoriesAsync(INuGetProjectContext projectContext)
        {
            foreach (var directory in GetPackageDirectoriesMarkedForDeletion())
            {
                string    failedPath  = null;
                bool      isFailedDir = false;
                Exception failedEx    = null;

                if (await Task.Run(() => DeleteDirectoryRecursive(directory, out failedPath, out isFailedDir, out failedEx)))
                {
                    continue;
                }

                if (failedPath != null)
                {
                    var lockerMsg = string.Empty;
                    var lockers   = RestartManager.FindLockerProcesses(failedPath);

                    if (lockers.Length > 0)
                    {
                        lockerMsg =
                            $"\nThe {(isFailedDir ? "folder" : "file")} which threw an exception is locked by processes: {string.Join("; ", lockers.Select(l => l.strAppName))}";
                    }

                    LogTo.Warning(
                        $"Failed to deleted package directory marked for deletion: '{directory}'.\nDeleting {failedPath} threw an exception (see below).{lockerMsg}\n\n{failedEx}");
                }

                LogTo.Warning($"Failed to delete package directory marked for deletion: '{directory}'.");
            }
        }
Exemplo n.º 9
0
    public static void GetLockingProcesses_WhenLockingOnPathAndGivenString_ReturnsNonEmptyLockingSet()
    {
        using var tmpPath = new TemporaryFile();
        using var _       = tmpPath.FileInfo.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
        var lockingProcs = RestartManager.GetLockingProcesses(tmpPath.FilePath);

        Assert.That(lockingProcs, Is.Not.Empty);
    }
Exemplo n.º 10
0
    public static void GetLockingProcesses_WhenLockingOnPath_ReturnsCorrectNumberOfLocks()
    {
        using var tmpPath = new TemporaryFile();
        using var _       = tmpPath.FileInfo.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
        var lockingProcs = RestartManager.GetLockingProcesses(tmpPath.FileInfo);

        Assert.That(lockingProcs, Has.One.Items);
    }
Exemplo n.º 11
0
    /// <summary>
    /// Retrieves the set of processes that are currently locking the file (if any).
    /// </summary>
    /// <param name="fileInfo">A file to test.</param>
    /// <returns>A set of processes that hold a lock on <paramref name="fileInfo"/>.</returns>
    /// <exception cref="ArgumentNullException"><paramref name="fileInfo"/> is <c>null</c>.</exception>
    public static IReadOnlyCollection <IProcessInfo> GetLockingProcesses(this FileInfo fileInfo)
    {
        if (fileInfo == null)
        {
            throw new ArgumentNullException(nameof(fileInfo));
        }

        return(RestartManager.GetLockingProcesses(fileInfo.FullName));
    }
Exemplo n.º 12
0
    public static void GetLockingProcesses_WhenLockingOnPathAndGivenDirectory_ReturnsNonEmptyLockingSet()
    {
        using var tmpDir = new TemporaryDirectory();
        var tmpFile = new FileInfo(Path.Combine(tmpDir.DirectoryPath, Path.GetRandomFileName()));

        using var _ = tmpFile.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
        var lockingProcs = RestartManager.GetLockingProcesses(tmpDir.DirectoryInfo);

        Assert.That(lockingProcs, Is.Not.Empty);
    }
Exemplo n.º 13
0
    public static void GetLockingProcesses_WhenLockingOnPathAndGivenString_ReturnsCorrectProcess()
    {
        using var tmpPath = new TemporaryFile();
        using var _       = tmpPath.FileInfo.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
        var lockingProcs = RestartManager.GetLockingProcesses(tmpPath.FilePath);
        var process      = Process.GetCurrentProcess();

        var lockingId = lockingProcs.Single().ProcessId;
        var currentId = process.Id;

        Assert.That(currentId, Is.EqualTo(lockingId));
    }
Exemplo n.º 14
0
 private void Restart_Click(object sender, RoutedEventArgs e)
 {
     ThreadPool.QueueUserWorkItem((state) =>
     {
         var rm = new RestartManager();
         rm.RestartExplorerProcesses((s) =>
         {
             AppendText("Windows Explorer was stopped...");
         }, false, out Exception error);
         AppendText("Windows Explorer was restarted...");
     });
 }
Exemplo n.º 15
0
 // Use this for initialization
 void Awake()
 {
     if (r)
     {
         Destroy(r);
     }
     else
     {
         r = this;
         DontDestroyOnLoad(gameObject);
     }
 }
Exemplo n.º 16
0
        public static void GetLockingProcesses_WhenLockingOnPathAndGivenString_ReturnsNonEmptyLockingSet()
        {
            var tmpPath = Path.GetTempFileName();

            using (var file = File.Open(tmpPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
            {
                var lockingProcs = RestartManager.GetLockingProcesses(tmpPath);
                Assert.IsTrue(lockingProcs.Count > 0);
            }

            File.Delete(tmpPath);
        }
Exemplo n.º 17
0
        public static void GetLockingProcesses_WhenLockingOnPath_ReturnsCorrectNumberOfLocks()
        {
            var tmpPath = new FileInfo(Path.GetTempFileName());

            using (var file = tmpPath.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
            {
                var lockingProcs = RestartManager.GetLockingProcesses(tmpPath);
                Assert.AreEqual(1, lockingProcs.Count);
            }

            tmpPath.Delete();
        }
Exemplo n.º 18
0
        static void Main()
        {
            Initializer             = new callback.CBFSShell.Cbshellboost();
            Initializer.ProductGUID = ProductID;

            Console.WriteLine("CBFS Shell Samples - SevenZip Folder - Copyright (C) 2021-2022 Callback Technologies, Inc. All rights reserved.");
            Console.WriteLine("CBFS Shell Runtime Version " + typeof(ShellContext).Assembly.GetInformationalVersion());
            Console.WriteLine();

            Console.WriteLine("Press a key:");
            Console.WriteLine();
            Console.WriteLine("   '1' Register the native proxy, file associations, and run this sample.");
            Console.WriteLine("   '2' Unregister the native proxy and file associations.");
            Console.WriteLine("   '3' Restart Windows Explorer.");
            Console.WriteLine();
            Console.WriteLine("   Any other key will exit.");
            Console.WriteLine();
            var key = Console.ReadKey(true);

            switch (key.KeyChar)
            {
            case '1':
                Register(true);
                // Important - Initialize must be called before using ShellBoost (except the calls to Install and Uninstall methods)
                Initializer.Initialize();

                Run();
                break;

            case '2':
                Initializer.PerUserInstallation = true;
                Initializer.Uninstall();
                UnregisterAsVirtualFolder(".7z");
                Console.WriteLine("Unregistered");
                break;

            case '3':
                var rm = new RestartManager();
                rm.RestartExplorerProcesses((state) =>
                {
                    Console.WriteLine("Explorer was stopped. Press any key to restart it ...");
                    Console.ReadKey(true);
                }, false, out Exception error);

                if (error != null)
                {
                    Console.WriteLine("An error has occurred in restart manager: " + error);
                }
                break;
            }
        }
Exemplo n.º 19
0
    /// <summary>
    /// Determines whether the file is locked by any process.
    /// </summary>
    /// <param name="fileInfo">A file to test.</param>
    /// <returns><c>true</c> if any processes hold a lock on the file, otherwise <c>false</c>.</returns>
    /// <exception cref="ArgumentNullException"><paramref name="fileInfo"/> is <c>null</c>.</exception>
    public static bool IsFileLocked(this FileInfo fileInfo)
    {
        if (fileInfo == null)
        {
            throw new ArgumentNullException(nameof(fileInfo));
        }

        if (!Platform.SupportsRestartManager)
        {
            return(IsSimpleFileLocked(fileInfo));
        }

        return(RestartManager.GetLockingProcesses(fileInfo.FullName).Count > 0);
    }
Exemplo n.º 20
0
        public void IsFileLocked_False()
        {
            var path = Path.GetTempFileName();

            try
            {
                var actual = RestartManager.IsFileLocked(path);
                Assert.False(actual);
            }
            finally
            {
                File.Delete(path);
            }
        }
Exemplo n.º 21
0
    public static void GetLockingProcesses_WhenLockingOnPathAndGivenDirectory_ReturnsCorrectProcess()
    {
        using var tmpDir = new TemporaryDirectory();
        var tmpFile = new FileInfo(Path.Combine(tmpDir.DirectoryPath, Path.GetRandomFileName()));

        using var _ = tmpFile.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
        var lockingProcs = RestartManager.GetLockingProcesses(tmpDir.DirectoryInfo);
        var process      = Process.GetCurrentProcess();

        var lockingId = lockingProcs.Single().ProcessId;
        var currentId = process.Id;

        Assert.That(currentId, Is.EqualTo(lockingId));
    }
Exemplo n.º 22
0
 private static void runProgram()
 {
     try
     {
         RestartManager rs          = new RestartManager();
         ServiceHost    serviceHost = new ServiceHost(typeof(RestartManager));
         serviceHost.Open();
         LogManager.Instance.WriteInfo("RestarterServices Server Started...........");
     }
     catch (Exception ex)
     {
         LogManager.Instance.WriteError("Error while trying load RestarterServices agent : " + ex.Message);
     }
 }
Exemplo n.º 23
0
    void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(gameObject);
            return;
        }

        DontDestroyOnLoad(gameObject);
        story         = GetComponent <StorySegment>();
        story.enabled = false;
    }
Exemplo n.º 24
0
    /// <summary>
    /// When an exception is thrown due to a lock held on a file, this method will rethrow an exception with more information on which files were locked and which processes were holding the lock.
    /// </summary>
    /// <param name="exception">The exception that was thrown due to a lock held on a file.</param>
    /// <param name="fileNames">A collection of file paths that could have been locked upon.</param>
    /// <returns><c>false</c> if the exception was not held due to a lock on a file, or if there are no locked files.</returns>
    /// <exception cref="ArgumentNullException"><paramref name="exception"/> or <paramref name="fileNames"/> is <c>null</c>.</exception>
    /// <exception cref="ArgumentException">An entry of the <paramref name="fileNames"/> collection is <c>null</c>.</exception>
    public static bool RethrowWithLockingInformation(this Exception exception, IEnumerable <string> fileNames)
    {
        if (exception == null)
        {
            throw new ArgumentNullException(nameof(exception));
        }
        if (fileNames == null)
        {
            throw new ArgumentNullException(nameof(fileNames));
        }
        if (fileNames.Any(f => f == null))
        {
            throw new ArgumentException("A null filename was provided.", nameof(fileNames));
        }

        if (exception is not IOException ioex || !ioex.IsFileLocked())
        {
            return(false);
        }

        var lockers = RestartManager.GetLockingProcesses(fileNames);

        if (lockers.Count == 0)
        {
            return(false);
        }

        const int max     = 10;
        var       builder = new StringBuilder();

        builder.Append(exception.Message);
        builder.Append(' ');

        var message = FormatLockingMessage(lockers, fileNames, max);

        builder.Append(message);

        // Unable to set HResult *and* InnerException via public methods/ctors.
        // Must use reflection to set the HResult while using the ctor to set the InnerException.
        // Nasty but necessary.
        var ex      = new IOException(builder.ToString(), exception);
        var hresult = Marshal.GetHRForException(exception);

        SetHResultMethod?.Invoke(ex, new object[] { hresult });

        throw ex;
    }
Exemplo n.º 25
0
        public void IsFileLocked_True()
        {
            var path = Path.GetTempFileName();

            try
            {
                using (File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
                {
                    var actual = RestartManager.IsFileLocked(path);
                    Assert.True(actual);
                }
            }
            finally
            {
                File.Delete(path);
            }
        }
Exemplo n.º 26
0
        public void TestRestartManagerFakeFiles()
        {
            RestartManagerSession manager = new RestartManagerSession();

            manager.StartSession();
            manager.RegisterResources(new List <string>()
            {
                "REALLYNOTAFILE"
            });

            RM_REBOOT_REASON rebootReason = default(RM_REBOOT_REASON);
            var processes = RestartManager.RmProcessToNetProcess(manager.GetList(ref rebootReason));

            Assert.IsTrue(processes.Count == 0);

            manager.EndSession();
        }
Exemplo n.º 27
0
        public void GetProcessesLockingFile()
        {
            var path = Path.GetTempFileName();

            try
            {
                using (File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
                {
                    var processes = RestartManager.GetProcessesLockingFile(path);
                    Assert.Equal(_currentProcessId, processes.Single().Id);
                }
            }
            finally
            {
                File.Delete(path);
            }
        }
Exemplo n.º 28
0
        public static void GetLockingProcesses_WhenLockingOnPathAndGivenString_ReturnsCorrectProcess()
        {
            var tmpPath = Path.GetTempFileName();

            using (var file = File.Open(tmpPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
            {
                var lockingProcs = RestartManager.GetLockingProcesses(tmpPath);
                var process      = Process.GetCurrentProcess();

                var lockingId = lockingProcs.Single().ProcessId;
                var currentId = process.Id;

                Assert.AreEqual(currentId, lockingId);
            }

            File.Delete(tmpPath);
        }
Exemplo n.º 29
0
        static void Main()
        {
            Console.WriteLine("ShellBoost Samples - SevenZip Folder - Copyright (C) 2017-" + DateTime.Now.Year + " Aelyo Softworks. All rights reserved.");
            Console.WriteLine("ShellBoost Runtime Version " + typeof(ShellContext).Assembly.GetInformationalVersion());
            Console.WriteLine();

            Console.WriteLine("Press a key:");
            Console.WriteLine();
            Console.WriteLine("   '1' Register the native proxy, file associations, and run this sample.");
            Console.WriteLine("   '2' Unregister the native proxy and file associations.");
            Console.WriteLine("   '3' Restart Windows Explorer.");
            Console.WriteLine();
            Console.WriteLine("   Any other key will exit.");
            Console.WriteLine();
            var key = Console.ReadKey(true);

            switch (key.KeyChar)
            {
            case '1':
                Run();
                break;

            case '2':
                ShellFolderServer.UnregisterNativeDll(RegistrationMode.User);
                UnregisterAsVirtualFolder(".7z");
                Console.WriteLine("Unregistered");
                break;

            case '5':
                var rm = new RestartManager();
                rm.RestartExplorerProcesses((state) =>
                {
                    Console.WriteLine("Explorer was stopped. Press any key to restart it ...");
                    Console.ReadKey(true);
                }, false, out Exception error);

                if (error != null)
                {
                    Console.WriteLine("An error has occurred in restart manager: " + error);
                }
                break;
            }
        }
Exemplo n.º 30
0
        public void TestRestartManagerManualShutdown()
        {
            var ReplacementProcessCopy = ReplacementProcess + "2";

            File.Copy(ReplacementProcess, ReplacementProcessCopy, true);

            //Start up the service and TRY to move the file. It should fail
            Process proc = Process.Start(ReplacementProcess);

            //We're hoping this will fail, as the process SHOULD be holding onto this guy
            MyAssert.ThrowsException(() => File.Copy(ReplacementProcessCopy, ReplacementProcess, true));

            //Now startup the restart manager and lets hope the process will be restarted.
            RestartManagerExtendedSession manager = new RestartManagerExtendedSession();

            manager.ManualRestartProcesses.Add(ReplacementProcess);
            manager.StartSession();
            manager.RegisterResources(new List <string>()
            {
                ReplacementProcess
            });

            RM_REBOOT_REASON rebootReason = default(RM_REBOOT_REASON);
            var processes = RestartManager.RmProcessToNetProcess(manager.GetList(ref rebootReason));

            Assert.IsTrue(rebootReason == RM_REBOOT_REASON.RmRebootReasonNone);
            Assert.IsTrue(processes.Count > 0);

            //After shutdown, the file should be copyable
            manager.Shutdown();
            ThreadingServices.WaitOnAction(() => File.Copy(ReplacementProcessCopy, ReplacementProcess, true), TimeSpan.FromSeconds(3));

            //Now try to restart everything
            manager.Restart();

            //We're hoping this will fail, as the service SHOULD be holding onto this guy again
            MyAssert.ThrowsException(() => ThreadingServices.WaitOnAction(() => File.Copy(ReplacementProcessCopy, ReplacementProcess, true), TimeSpan.FromSeconds(2)));

            manager.EndSession();

            System.Diagnostics.Process.GetProcessesByName(ReplacementProcess.Replace(".exe", "")).ToList().ForEach(x => x.Kill());
        }