Exemple #1
0
        public void RestartService(string serviceName, TimeSpan timeout)
        {
            CmdHelper cmd = new CmdHelper();
            CommandExecutionResult result = cmd.ExecuteCommand2(
                @"cmd /c sc \\{0} stop {1}".FormatWith(this.machine, serviceName),
                this.userName,
                this.password,
                this.Domain);

            if (result.ExitCode == 0)
            {
                DateTime start = DateTime.Now;
                while (!this.GetServiceStatus(serviceName).Equals("Stopped", StringComparison.OrdinalIgnoreCase))
                {
                    if (DateTime.Now.Subtract(start) < timeout)
                    {
                        System.Threading.Thread.Sleep(2000);
                    }
                    else
                    {
                        throw new Exception("Timeout after {0} when stopping service {1} on machine {2}.".FormatWith(timeout.ToString(), serviceName, this.machine));
                    }
                }

                CommandExecutionResult resultStart = cmd.ExecuteCommand2(
                    "cmd /c sc \\{0} start {1}".FormatWith(this.machine, serviceName),
                    this.userName,
                    this.password,
                    this.Domain);
                if (result.ExitCode == 0)
                {
                    start = DateTime.Now;
                    while (!this.GetServiceStatus(serviceName).Equals("running", StringComparison.OrdinalIgnoreCase))
                    {
                        if (DateTime.Now.Subtract(start) < timeout)
                        {
                            System.Threading.Thread.Sleep(2000);
                        }
                        else
                        {
                            throw new Exception("Timeout after {0} when starting service {1} on machine {2}.".FormatWith(timeout.ToString(), serviceName, this.machine));
                        }
                    }
                }
                else
                {
                    throw new Exception("Failed to start service {0} on machine {1} after stopped it.\r\n{2}".FormatWith(serviceName, this.machine, resultStart.ToSerializedXmlString()));
                }
            }
            else
            {
                throw new Exception("Failed to stop service {0} on machine {1}.\r\n{2}".FormatWith(serviceName, this.machine, result.ToSerializedXmlString()));
            }
        }