using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.Agent;
using Microsoft.SqlServer.Management.Smo.Wmi;

namespace WMIConfig
{
    class Program
    {
        static void Main(string[] args)
        {
            //Declare and create an instance of the ManagedComputer object that represents the WMI Provider services.
            ManagedComputer mc = new ManagedComputer();
            //Iterate through each service registered with the WMI Provider.
            Service svc;
            foreach (Service svc2 in mc.Services)
                Console.WriteLine(svc2.Name);

            svc = mc.Services["SQLSERVERAGENT"];
            foreach (Property p in svc.Properties)
                Console.WriteLine("{0} write:{1}", p.Name, p.Writable);

            Console.ReadLine();

            

            //Reference the Microsoft SQL Server service.
            svc = mc.Services["MSSQLSERVER"];
            //Stop the service if it is running and report on the status continuously until it has stopped.
            if (svc.ServiceState == ServiceState.Running) 
            {
                svc.Stop();

                Console.WriteLine(String.Format("{0} service state is {1}", svc.Name, svc.ServiceState));
                while (String.Format("{0}", svc.ServiceState) != "Stopped")
                {
                    Console.WriteLine(String.Format("{0}", svc.ServiceState));
                    svc.Refresh();
                }

                Console.WriteLine(String.Format("{0} service state is {1}", svc.Name, svc.ServiceState));
                //Start the service and report on the status continuously until it has started.
                svc.Start();
                while (String.Format("{0}", svc.ServiceState) != "Running")
                {
                    Console.WriteLine(String.Format("{0}", svc.ServiceState));
                    svc.Refresh();
                }
                Console.WriteLine(String.Format("{0} service state is {1}", svc.Name, svc.ServiceState));
            }
            else
                Console.WriteLine("SQL Server service is not running.");
            
        }
    }
}
