Beispiel #1
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);
        }
Beispiel #2
0
        public void Session_Variable()
        {
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .RegisterResources()
                           .GetProcesses()
                           .Pop()
                           .Push <IVariableService, MockVariableService>()
                           .GetValue(SessionManager.VariableName, s =>
            {
                var session = new RestartManagerSession(s);
                session.RegisterResources(files: new[] { @"C:\ShouldNotExist.txt" });

                return(session);
            })
                           .Pop();

            using (fixture.UseServices(services))
            {
                var output = fixture.Create()
                             .AddCommand(CommandName)
                             .AddStatement()
                             .AddCommand("Stop-RestartManagerSession")
                             .Invoke <IProcessInfo>();

                var expected = MockRestartManagerService.GetDefaultProcessesInfo(RebootReason.None);
                Assert.Equal(expected, output, ProcessComparer.Default);
            }

            services.Verify();
        }
        /// <inheritdoc/>
        protected override void EndProcessing()
        {
            base.EndProcessing();

            var session = SessionManager.GetVariable(Services, SessionState.PSVariable);

            if (session != null && !session.IsDisposed)
            {
                if (Force)
                {
                    session.Dispose();
                }
                else
                {
                    throw new ActiveSessionException();
                }
            }

            session = new RestartManagerSession(Services);
            SessionManager.SetVariable(Services, SessionState.PSVariable, session);

            if (PassThru)
            {
                WriteObject(session);
            }
        }
Beispiel #4
0
        public void Register_All_Pipeline()
        {
            var path = typeof(RegisterResourceCommand).Assembly.Location;
            var file = new
            {
                Path        = path,
                LiteralPath = $@"Microsoft.PowerShell.Core\FileSystem::{path}",
            };
            var process       = Process.GetCurrentProcess();
            var processInfo   = new ProcessAdapter(process);
            var uniqueProcess = new RM_UNIQUE_PROCESS(processInfo);
            var service       = new
            {
                ServiceName = "ServiceApp",
            };

            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .RegisterResources(files: new[] { path }, processes: new[] { uniqueProcess }, services: new[] { "ServiceApp" })
                           .Pop();

            using (var session = new RestartManagerSession(services))
            {
                fixture.Create()
                .AddCommand(CommandName)
                .AddParameter("Session", session)
                .Invoke(new object[] { file, process, service });
            }

            services.Verify();
        }
        /// <summary>
        /// Finds a running Windows Explorer instance and causes it restart.
        /// </summary>
        public static void RestartExplorer()
        {
            if (OperatingSystemVersions.IsSupported(OperatingSystemVersion.WindowsVista))
            {
                using (var rm = new RestartManagerSession())
                {
                    rm.RegisterProcess(Process.GetProcessesByName("explorer"));
                    rm.Shutdown(RestartManagerSession.ShutdownType.Normal);
                    rm.Restart();
                }
            }
            else
            {
                Process[] processes = Process.GetProcessesByName("explorer");

                foreach (Process process in processes)
                {
                    process.Kill();
                }

                foreach (Process process in processes)
                {
                    process.Start();
                }
            }
        }
Beispiel #6
0
        public void Register_All_Parameter()
        {
            var path          = typeof(RegisterResourceCommand).Assembly.Location;
            var process       = Process.GetCurrentProcess();
            var processInfo   = new ProcessAdapter(process);
            var uniqueProcess = new RM_UNIQUE_PROCESS(processInfo);

            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .RegisterResources(files: new[] { path }, processes: new[] { uniqueProcess }, services: new[] { "ServiceApp" })
                           .Pop();

            using (var session = new RestartManagerSession(services))
            {
                fixture.Create()
                .AddCommand(CommandName)
                .AddParameter("Path", path)
                .AddParameter("Process", process)
                .AddParameter("ServiceName", "ServiceApp")
                .AddParameter("Session", session)
                .Invoke();
            }

            services.Verify();
        }
        public void Overrides_Disposed_Session()
        {
            RestartManagerSession original = null;
            var services = new MockContainer()
                           .Push <IRestartManagerService, MockRestartManagerService>()
                           .StartSession()
                           .Pop()
                           .Push <IVariableService, MockVariableService>()
                           .GetValue(SessionManager.VariableName, s => original = new RestartManagerSession(s))
                           .Pop();

            original.Dispose();
            using (fixture.UseServices(services))
            {
                using (original)
                {
                    var sut = fixture.Create()
                              .AddCommand(CommandName)
                              .AddParameter("PassThru");

                    using (var session = sut.Invoke <RestartManagerSession>().Single())
                    {
                        Assert.Equal(0, session.SessionId);
                        Assert.Equal("123abc", session.SessionKey);
                        Assert.NotSame(original, session);

                        services.Verify <IVariableService>(x => x.SetValue(SessionManager.VariableName, session));
                    }
                }
            }

            services.Verify();
        }
        public void Overrides_Session_Throws()
        {
            RestartManagerSession session = null;
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .Pop()
                           .Push <IVariableService, MockVariableService>()
                           .GetValue(SessionManager.VariableName, s => session = new RestartManagerSession(s))
                           .Pop();

            using (fixture.UseServices(services))
            {
                using (session)
                {
                    var sut = fixture.Create()
                              .AddCommand(CommandName)
                              .AddParameter("PassThru");

                    var ex = Assert.Throws <CmdletInvocationException>(() => sut.Invoke());
                    Assert.IsType <ActiveSessionException>(ex.InnerException);
                }
            }

            services.Verify();
        }
Beispiel #9
0
        public void GetParameterOrVariable_No_Services()
        {
            RestartManagerSession session = null;
            var actual = SessionManager.GetParameterOrVariable(null, ref session, fixture.Variables);

            Assert.Same(sessionVariable, actual);
        }
Beispiel #10
0
        public void GetParameterOrVariable_No_Service()
        {
            var services = new MockContainer();

            RestartManagerSession session = null;
            var actual = SessionManager.GetParameterOrVariable(services, ref session, fixture.Variables);

            Assert.Same(sessionVariable, actual);
        }
Beispiel #11
0
        public void GetParameterOrVariable_Mocked()
        {
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IVariableService, MockVariableService>()
                           .GetValue(SessionManager.VariableName, sessionService)
                           .Pop();

            RestartManagerSession session = null;
            var actual = SessionManager.GetParameterOrVariable(services, ref session, fixture.Variables);

            Assert.Same(sessionService, actual);
        }
Beispiel #12
0
        public SessionManagerTests(RunspaceFixture fixture)
        {
            this.fixture = fixture;

            var services = new MockContainer()
                           .Push <IRestartManagerService>()
                           .Pop();

            sessionService  = new RestartManagerSession(services);
            sessionVariable = new RestartManagerSession(services);

            fixture.Variables.Set(SessionManager.VariableName, sessionVariable);
        }
Beispiel #13
0
        public void Ends_Session()
        {
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .Pop();

            using (var session = new RestartManagerSession(services))
            {
                fixture.Create()
                .AddCommand(CommandName)
                .AddParameter("Session", session)
                .Invoke();
            }

            services.Verify <IRestartManagerService>(x => x.EndSession(0), Times.Once);
        }
Beispiel #14
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();
        }
Beispiel #15
0
        public void Register_Service_Parameter()
        {
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .RegisterResources(services: new[] { "ServiceApp" })
                           .Pop();

            using (var session = new RestartManagerSession(services))
            {
                fixture.Create()
                .AddCommand(CommandName)
                .AddParameter("ServiceName", "ServiceApp")
                .AddParameter("Session", session)
                .Invoke();
            }

            services.Verify();
        }
Beispiel #16
0
        public void None_Registered()
        {
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .Pop();

            using (var session = new RestartManagerSession(services))
            {
                var output = fixture.Create()
                             .AddCommand(CommandName)
                             .AddParameter("Session", session)
                             .Invoke <IProcessInfo>();

                Assert.Empty(output);
            }

            services.Verify();
        }
Beispiel #17
0
        public void Register_Path_Argument()
        {
            var path     = typeof(RegisterResourceCommand).Assembly.Location;
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .RegisterResources(files: new[] { path })
                           .Pop();

            using (var session = new RestartManagerSession(services))
            {
                fixture.Create()
                .AddCommand(CommandName)
                .AddArgument(path)
                .AddParameter("Session", session)
                .Invoke();
            }

            services.Verify();
        }
Beispiel #18
0
        public void OnError()
        {
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .RestartProcesses(error: NativeMethods.ERROR_OUTOFMEMORY)
                           .Pop();

            using (var session = new RestartManagerSession(services))
            {
                var sut = fixture.Create()
                          .AddCommand(CommandName)
                          .AddParameter("Session", session);

                var ex = Assert.Throws <CmdletInvocationException>(() => sut.Invoke());
                Assert.IsType <OutOfMemoryException>(ex.InnerException);
            }

            services.Verify();
        }
Beispiel #19
0
        public void Register_Process_Pipeline()
        {
            var process       = Process.GetCurrentProcess();
            var processInfo   = new ProcessAdapter(process);
            var uniqueProcess = new RM_UNIQUE_PROCESS(processInfo);

            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .RegisterResources(processes: new[] { uniqueProcess })
                           .Pop();

            using (var session = new RestartManagerSession(services))
            {
                fixture.Create()
                .AddCommand(CommandName)
                .AddParameter("Session", session)
                .Invoke(new[] { process });
            }

            services.Verify();
        }
Beispiel #20
0
        public void GetParameterOrVariable_Field()
        {
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .Pop()
                           .Push <IVariableService, MockVariableService>()
                           .GetValue(SessionManager.VariableName, sessionService)
                           .Pop();

            var session = new RestartManagerSession(services);

            try
            {
                var actual = SessionManager.GetParameterOrVariable(services, ref session, fixture.Variables);
                Assert.Same(session, actual);
            }
            finally
            {
                session.Dispose();
            }
        }
Beispiel #21
0
        public void Session_Parameter()
        {
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .RestartProcesses()
                           .Pop();

            var onRestartProgress = 0;

            using (var session = new RestartManagerSession(services))
            {
                var sut = fixture.Create()
                          .AddCommand(CommandName)
                          .AddParameter("Session", session);

                sut.Streams.Progress.DataAdded += (source, args) => ++ onRestartProgress;
                sut.Invoke();
            }

            services.Verify();
            Assert.Equal(2, onRestartProgress);
        }
Beispiel #22
0
        public void NonFile_Path_Warns()
        {
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .Pop();

            using (var session = new RestartManagerSession(services))
            {
                var sut = fixture.Create()
                          .AddCommand(CommandName)
                          .AddParameter("PSPath", @"Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software")
                          .AddParameter("Session", session);

                var output = sut.Invoke();
                Assert.Empty(output);

                var warnings = sut.Streams.Warning;
                Assert.Collection(warnings, x => Assert.Equal(Resources.Warning_NoFiles, x.Message));
            }

            services.Verify();
        }
Beispiel #23
0
        public void ProcessRecord_Throws()
        {
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .RegisterResources()
                           .GetProcesses(error: NativeMethods.ERROR_OUTOFMEMORY)
                           .Pop();

            using (var session = new RestartManagerSession(services))
            {
                session.RegisterResources(files: new[] { @"C:\ShouldNotExist.txt" });

                var sut = fixture.Create()
                          .AddCommand(CommandName)
                          .AddParameter("Session", session);

                var ex = Assert.Throws <CmdletInvocationException>(() => sut.Invoke());
                Assert.IsType <OutOfMemoryException>(ex.InnerException);
            }

            services.Verify();
        }
Beispiel #24
0
        public void ProcessRecord()
        {
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .RegisterResources()
                           .GetProcesses()
                           .Pop();

            using (var session = new RestartManagerSession(services))
            {
                session.RegisterResources(files: new[] { @"C:\ShouldNotExist.txt" });

                var output = fixture.Create()
                             .AddCommand(CommandName)
                             .AddParameter("Session", session)
                             .Invoke <IProcessInfo>();

                var expected = MockRestartManagerService.GetDefaultProcessesInfo(RebootReason.None);
                Assert.Equal(expected, output, ProcessComparer.Default);
            }

            services.Verify();
        }
Beispiel #25
0
        public void EndSession_Throws()
        {
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService, MockRestartManagerService>()
                           .StartSession()
                           .Pop();

            var restartManagerServiceMock = services.Get <IRestartManagerService>();

            restartManagerServiceMock.Setup(x => x.EndSession(0))
            .Throws(new ObjectDisposedException(nameof(RestartManagerSession)))
            .Verifiable();

            using (var session = new RestartManagerSession(services))
            {
                fixture.Create()
                .AddCommand(CommandName)
                .AddParameter("Session", session)
                .Invoke();
            }

            services.Verify();
        }
        public void Force_OnlyRegistered_Parameter()
        {
            var services = new MockContainer(MockBehavior.Strict)
                           .Push <IRestartManagerService>()
                           .ShutdownProcesses(force: true, onlyRegistered: true)
                           .Pop();

            var onShutdownProgress = 0;

            using (var session = new RestartManagerSession(services))
            {
                var sut = fixture.Create()
                          .AddCommand(CommandName)
                          .AddParameter("Force")
                          .AddParameter("OnlyRegistered")
                          .AddParameter("Session", session);

                sut.Streams.Progress.DataAdded += (source, args) => ++ onShutdownProgress;
                sut.Invoke();
            }

            services.Verify();
            Assert.Equal(3, onShutdownProgress);
        }
Beispiel #27
0
        public void TestRestartManagerProcessFileMove()
        {
            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.
            RestartManagerSession manager = new RestartManagerSession();

            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();

            manager.EndSession();
        }
Beispiel #28
0
        /// <summary>
        /// Gets a <see cref="RestartManagerSession"/> from a parameter or from a variable.
        /// </summary>
        /// <param name="services">Optional services to use to resolve variables.</param>
        /// <param name="session">A backing field for a parameter that may reference a <see cref="RestartManagerSession"/>.</param>
        /// <param name="variables">Variables for the current <see cref="Runspace"/>.</param>
        /// <returns>A <see cref="RestartManagerSession"/> from a parameter or from a variable.</returns>
        /// <exception cref="NoSessionException">No <see cref="RestartManagerSession"/> is available.</exception>
        public static RestartManagerSession GetParameterOrVariable(IServiceProvider services, ref RestartManagerSession session, PSVariableIntrinsics variables)
        {
            if (session == null)
            {
                var resolver = services?.GetService <IVariableService>() ?? new RunspaceVariableService(variables);
                session = resolver.GetValue <RestartManagerSession>(VariableName);
            }

            return(session ?? throw new NoSessionException());
        }
Beispiel #29
0
        /// <summary>
        /// Sets the <see cref="RestartManagerSession"/> session variable.
        /// </summary>
        /// <param name="services">Optional services to use to resolve variables.</param>
        /// <param name="variables">Variables for the current <see cref="Runspace"/>.</param>
        /// <param name="session">The <see cref="RestartManagerSession"/> to set.</param>
        public static void SetVariable(IServiceProvider services, PSVariableIntrinsics variables, RestartManagerSession session)
        {
            var resolver = services?.GetService <IVariableService>() ?? new RunspaceVariableService(variables);

            resolver.SetValue(VariableName, session);
        }