using System;
using System.Reflection;
using System.Threading;

using Microsoft.SqlServer.Management.Smo.Wmi;

namespace SQLServerStopper
{
    internal class Program
    {
        private const string UsageMessageFormat = @"Usage: {0} <hostname> <instance-name>";
        private const string MissingServiceMessageFormat = @"Unable to find service {0}\{1}";
        private const string ErrorMessageFormat = @"Error: {0}";

        private static readonly TimeSpan TimeToWait = new TimeSpan(0, 1, 0); // 1 minute.

        private const string ServiceNameFormat = @"MSSQL${0}";
        private const int ServicePollInterval = 200 /* ms */;

        private static void Main(string[] args)
        {
            try
            {
                Environment.ExitCode = WrappedMain(args);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(String.Format(ErrorMessageFormat, ex.Message));
                Environment.ExitCode = 1;
            }
        }

        private static int WrappedMain(string[] args)
        {
            if (args.Length != 2)
            {
                Console.Error.WriteLine
                    (String.Format(UsageMessageFormat, Assembly.GetExecutingAssembly().Location));

                return 1;
            }
            else
            {
                return StopSqlServer(args[0], args[1]) ? 0 : 1;
            }
        }

        private static bool StopSqlServer(string hostName, string instanceName)
        {
            ManagedComputer computer = new ManagedComputer(hostName);

         &nbs p;  Service service = computer.Services[String.Format(ServiceNameFormat, instanceName)];

            if (service == null)
            {
                Console.Error.WriteLine
                    (String.Format(MissingServiceMessageFormat, hostName, instanceName));

                return false;
            }

            service.Stop();

            WaitForServiceToStop(service, TimeToWait);

            return true;
        }

        private static void WaitForServiceToStop(Service service, TimeSpan timeToWait)
        {
            DateTime start = DateTime.Now;

            while ((DateTime.Now - start) < timeToWait)
            {
                service.Refresh();

                if (service.ServiceState == ServiceState.Stopped)
                {
                    return;
                < span class='hl sym'>}


                Thread.Sleep(ServicePollInterval);
            }
        }
    }
}