Dispose() public méthode

public Dispose ( ) : void
Résultat void
Exemple #1
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <returns><see langword="true"/> if the task ran successfully;
        /// otherwise <see langword="false"/>.</returns>
        public override bool Execute()
        {
            Service controller = null;

            try
            {
                controller = GetServiceController();
                if (controller != null)
                {
                    Log.LogMessage(Properties.Resources.ServiceStatus,
                                   _displayName, _machineName, _status);
                }
                else
                {
                    Log.LogMessage(Properties.Resources.ServiceNotFound,
                                   _serviceName, _machineName);
                }
            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(ex);
                return(false);
            }
            finally
            {
                if (controller != null)
                {
                    controller.Dispose();
                }
            }

            return(true);
        }
 /// <summary>
 /// Returns a flag that highlights whether the
 /// window service with a particular name is 
 /// running.
 /// </summary>
 /// <param name="name">Name of the windows service
 /// to check.</param>
 /// <returns>True if running, otherwise false.</returns>
 private static bool Running(string serviceName)
 {
     var service = new ServiceController(serviceName);
     var result = (service.Status == ServiceControllerStatus.Running);
     service.Dispose();
     return result;
 }
Exemple #3
0
 /// <summary>
 /// Checks to see if the Mongo DB service is currently running.
 /// </summary>
 /// <returns>True if currently running, otherwise false.</returns>
 public static bool Running()
 {
     var service = new ServiceController(MongoServiceName);
     var result = (service.Status == ServiceControllerStatus.Running);
     service.Dispose();
     return result;
 }
Exemple #4
0
        public static void Main(string[] args)
        {
            Eager.Initalize();
            var service = new ServiceController("fogservice");
            const string logName = "Update Helper";

            Log.Entry(logName, "Shutting down service...");
            //Stop the service
            if (service.Status == ServiceControllerStatus.Running)
                service.Stop();

            service.WaitForStatus(ServiceControllerStatus.Stopped);

            Log.Entry(logName, "Killing remaining FOG processes...");
            if (Process.GetProcessesByName("FOGService").Length > 0)
                foreach (var process in Process.GetProcessesByName("FOGService"))
                    process.Kill();

            Log.Entry(logName, "Applying MSI...");
            ApplyUpdates();

            //Start the service

            Log.Entry(logName, "Starting service...");
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running);
            service.Dispose();

            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + @"\updating.info"))
                File.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\updating.info");
        }
Exemple #5
0
        public void BasicInstallTest()
        {
            ServiceController controler;
            if (!ShonInstaller.HasServiceInstallationRigths())
                Assert.Ignore("Need admin rigthts for this test");
            try
            {
                ShonInstaller.InstallService("toto");

                // sleep to ensure status is propagated
                var watch = new Stopwatch();
                while (watch.ElapsedMilliseconds < 1000)
                {
                    Thread.Sleep(100);
                    controler = new ServiceController("toto");
                    try
                    {
                        if (ServiceControllerStatus.Stopped == controler.Status)
                        {
                            break;
                        }
                    }
                    catch
                    {
                    }
                    finally
                    {
                        controler.Dispose();
                    }
                }
                controler = new ServiceController("toto");
                try
                {
                    Assert.AreEqual(ServiceControllerStatus.Stopped, controler.Status);
                }
                catch
                {
                    Assert.Fail("Service not found, installation failed");
                }
                finally
                {
                    controler.Dispose();
                }
            }
            finally
            {
                ShonInstaller.UninstallService("toto");
            }
            Thread.Sleep(100);
            try
            {
                Assert.AreEqual(ServiceControllerStatus.Stopped, controler.Status);
                Assert.Fail("Service found,should have been uninstalled");
            }
            catch
            {
            }
        }
 public void Dispose()
 {
     if (_serviceController != null)
     {
         _serviceController.Dispose();
         _serviceController = null;
     }
     Process = null;
 }
Exemple #7
0
        void MyServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
        {
            ServiceController controller = new ServiceController(this.ServiceName);
            try {
                controller.Start();

            } finally {
                controller.Dispose();
            }
        }
Exemple #8
0
        /// <summary>
        /// Starts the Mongo.
        /// </summary>
        public static void Start()
        {
            var service = new ServiceController(MongoServiceName);

            if (service.Status == ServiceControllerStatus.Running)
            {
                service.Dispose();
                return;
            }

            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(MongoTimeout);
                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            finally
            {
                service.Dispose();
            }
        }
        void StopService()
        {
            System.ServiceProcess.ServiceController serverContorler = new ServiceController(this.aidServiceInstaller.ServiceName);

            if (serverContorler != null)
            {
                if (serverContorler.CanStop)
                {
                    serverContorler.Stop();
                    serverContorler.Dispose();
                }

            }
        }
        void StartService()
        {
            System.ServiceProcess.ServiceController serverContorler = new ServiceController(this.aidServiceInstaller.ServiceName);

            if (serverContorler != null)
            {
                if (serverContorler.Status != ServiceControllerStatus.Running)
                {
                    serverContorler.Start();
                    serverContorler.Dispose();
                }

            }

        }
        /// <summary>
        /// Starts a windows service.
        /// </summary>
        /// <param name="name">Name of the windows service.</param>
        private static void Start(string serviceName)
        {
            var service = new ServiceController(serviceName);

            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(Timeout);
                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            finally
            {
                service.Dispose();
            }
        }
Exemple #12
0
 public void Install()
 {
     ServiceController controler;
     string file = typeof(Shon.Host).Assembly.Location;
     if (file.Contains(" "))
     {
         file = '"' + file + '"';
     }
     ProcessStartInfo start = new ProcessStartInfo(file, "/install");
     start.UseShellExecute = true;
     start.Verb = "runas";
     using (Process process = Process.Start(start))
     {
         // run install
     }
     // sleep to ensure status is propagated
     Stopwatch watch = new Stopwatch();
     watch.Start();
     while (watch.ElapsedMilliseconds < 1000)
     {
         controler = new ServiceController("toto");
         Thread.Sleep(50);
         controler.Refresh();
         try
         {
             if (ServiceControllerStatus.Stopped == controler.Status)
             {
                 break;
             }
             if (ServiceControllerStatus.Running == controler.Status)
             {
                 controler.Stop();
             }
         }
         catch
         {
             // exception is raised if service not ready
         }
         finally
         {
             controler.Dispose();
         }
     }
     controler = new ServiceController("toto");
     Assert.AreEqual(ServiceControllerStatus.Stopped, controler.Status);
 }
Exemple #13
0
        private void ButtonDel_Click(object sender, EventArgs e)
        {
            if (ListViewExistedServices.SelectedItems.Count > 0)
            {
                var Item = ListViewExistedServices.SelectedItems[0];

                foreach (var Serv in ArrayOfServices)
                {
                    if (Serv.DisplayName == Item.SubItems[0].Text)
                    {
                        DialogResult Rez = MessageBox.Show("Вы действительно хотите удалить службу сервера 1С " + Environment.NewLine + "\"" + Serv.DisplayName + "\" ?", "УДАЛЕНИЕ службы сервера 1С", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

                        if (Rez == DialogResult.Yes)
                        {
                            bool StopError = false;
                            try
                            {
                                var sc = new System.ServiceProcess.ServiceController(Serv.Name);
                                if (sc.Status == ServiceControllerStatus.Running)
                                {
                                    sc.Stop();
                                    sc.WaitForStatus(ServiceControllerStatus.Stopped);
                                }
                                sc.Dispose();
                            }
                            catch (Exception)
                            {
                                StopError = true;
                            }
                            //var Result = ObjTec.Services.ServiceInstaller.UninstallService(Serv.Name)
                        }


                        RefreshListService();
                    }
                }
            }
            else
            {
                MessageBox.Show("Необходимо выделить строку со службой сервера 1С, которую требуется изменить.");
            }
        }
 public static bool DoesServiceExist(string serviceName)
 {
     ServiceController service = null;
     string status = "";
     try {
         service = new ServiceController(serviceName);
         status = service.Status.ToString();
         return true;
     }
     catch (InvalidOperationException)
     {
         return false;
     }
     finally
     {
         if (service != null)
         {
             service.Dispose();
         }
     }
 }
Exemple #15
0
		/// <summary>
		/// Starts service if it's stopped. Returns True if service was started.
		/// </summary>
		public bool StartServiceIfNeeded(string serviceName, int timeout = 30)
		{
			Ensure.That(() => serviceName).IsNotNullOrEmpty();
			if (ServiceIsRunning(serviceName))
				return false;

			ServiceController sc = null;
			try
			{
				sc = new ServiceController(serviceName);
				if (sc.Status == ServiceControllerStatus.Stopped)
				{
					WriteStatus($"Starting {serviceName}");
					sc.Start();
					sc.WaitForStatus(ServiceControllerStatus.Running);
				}
				if (sc.Status == ServiceControllerStatus.StartPending)
				{
					WriteStatus($"Starting {serviceName}");
					sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(timeout));
				}
			}
			catch (Exception ex)
			{
				WriteException(ex);
				WriteStatus($"Failed to start service {serviceName} more information exists in the activity log.");
				return false;
			}
			finally
			{
				if (sc != null)
					sc.Dispose();
			}


			WriteStatus($"Service {serviceName} has started.");
			return true;
		}
Exemple #16
0
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }

                if (m_Utils.DownloadLock())
                {
                    m_Utils.DownloadUnLock();
                }

                if (serviceControllerDwnld != null)
                {
                    serviceControllerDwnld.Close();
                    serviceControllerDwnld.Dispose();
                    serviceControllerDwnld = null;
                }
            }
            base.Dispose(disposing);
        }
Exemple #17
0
        //Disable all Xinput controllers presented by SCP
        public void Lock_XI_Devices()
        {
            string strClassGUID = "{d61ca365-5af4-4486-998b-9db4734c6ca3}";
            Guid ClassGUID = new Guid(strClassGUID);
            //find all "Xbox 360 Controller for Windows" pads and disable them
            ManagementObjectSearcher objSearcher = new ManagementObjectSearcher("Select * from Win32_PnPSignedDriver WHERE ClassGuid = '" + strClassGUID + "' AND DeviceName = 'Xbox 360 Controller for Windows'");

            ManagementObjectCollection objCollection = objSearcher.Get();

            List<string> objdeviceids = new List<string>();
            foreach (ManagementObject cobj in objCollection)
            {
                string Local = (string)cobj["Location"];
                //Dealing with X360 controllers outside of
                //SCP is untested and might cause a crash
                if (Local.Contains("SCP Virtual X360 Bus"))
                    objdeviceids.Add((string)cobj["DeviceID"]);
            }

            //Stop Service to allow us to disable needed X360 controllers
            //Stopping the service effectivly unplugs the emulated X360
            //controller, but we can still disable and re-enable it
            //If we do this while the service is running, the program will
            //crash
            ServiceController sc = new ServiceController("SCP DSx Service");
            try
            {
                sc.Stop();
                sc.WaitForStatus(ServiceControllerStatus.Stopped);

                foreach (string objdeviceid in objdeviceids)
                {
                    if (objdeviceid != "")
                    {
                        DeviceHelper.SetDeviceEnabled(ClassGUID, objdeviceid, false, false);
                        lockedDevices.Add(new DeviceID(ClassGUID, objdeviceid));
                    }
                }

                //Restart service
                sc.Start();
                sc.WaitForStatus(ServiceControllerStatus.Running);
            }
            finally
            {
                sc.Dispose();
            }
        }
        /// <summary>
        /// Changes the status and start-up properties for a service
        /// </summary>
        /// <param name="sc">ServiceController instance</param>
        /// <param name="newStatus"></param>
        /// <param name="newStart"></param>
        private static void ChangeServiceProperties(ServiceController sc, StatusType newStatus, StartType newStart)
        {
            try {

                //
                Log.AppendString( logfile, sc.DisplayName + Environment.NewLine );

                // Save the old running status for logging
                string oldStatus = sc.Status.ToString();

                // Change Service running status to 'newStatus'
                switch ( newStatus ) {

                    case StatusType.Start: {

                            if ( sc.Status != ServiceControllerStatus.Running && sc.Status != ServiceControllerStatus.StartPending ) {
                                sc.Start();
                                sc.WaitForStatus( ServiceControllerStatus.Running, new TimeSpan( 0, 0, iServiceChangeTimeout ) );
                                iServiceChangedCount++;
                            }

                        }
                        break;

                    case StatusType.Stop: {

                            if ( sc.Status != ServiceControllerStatus.Stopped && sc.Status != ServiceControllerStatus.StopPending ) {
                                sc.Stop();
                                sc.WaitForStatus( ServiceControllerStatus.Stopped, new TimeSpan( 0, 0, iServiceChangeTimeout ) );
                                iServiceChangedCount++;
                            }

                        }
                        break;

                }

                sc.Refresh();

                // Log status change
                if ( oldStatus.Equals( sc.Status.ToString(), StringComparison.CurrentCultureIgnoreCase ) ) {

                    Log.AppendString( logfile, "Status: '" + sc.Status.ToString() + "' (not changed)" + Environment.NewLine );

                }
                else {

                    Log.AppendString( logfile, "Status changed from '" + oldStatus + "' to '" + sc.Status.ToString() + "'" + Environment.NewLine );

                }

                // Get old start-up type
                object oldStart = RegistryCleaner.GetValue( Registry.LocalMachine, @"SYSTEM\CurrentControlSet\Services\" + sc.ServiceName, "Start" );
                if ( oldStart != null ) {

                    // Set start-up type
                    if ( (int)newStart != (int)oldStart ) {

                        RegistryCleaner.SetValue( Registry.LocalMachine, @"SYSTEM\CurrentControlSet\Services\" + sc.ServiceName, "Start", (int)newStart );
                        Log.AppendString( logfile, "Start-up changed from '" + ( (StartType)oldStart ).ToString() + "' to '" + newStart.ToString() + "'" + Environment.NewLine );
                        iServiceChangedCount++;

                    }
                    else {

                        Log.AppendString( logfile, "Start-up: '" + ( (StartType)oldStart ).ToString() + "' (not changed)" + Environment.NewLine );

                    }

                }

                Log.AppendString( logfile, Environment.NewLine );

            }
            catch ( Exception ex ) {

                Log.AppendException( logfile, ex );

            }
            finally {

                if ( sc != null ) {

                    sc.Close();
                    sc.Dispose();
                    sc = null;

                }

            }
        }
        public static void SetServiceRecoveryOptions(
            string serviceName, [NotNull] ServiceRecoveryOptions recoveryOptions)
        {
            if (recoveryOptions == null)
                throw new ArgumentNullException("recoveryOptions");

            bool requiresShutdownPriveleges =
                recoveryOptions.FirstFailureAction == ServiceRecoveryAction.RestartComputer ||
                recoveryOptions.SecondFailureAction == ServiceRecoveryAction.RestartComputer ||
                recoveryOptions.SubsequentFailureAction == ServiceRecoveryAction.RestartComputer;
            if (requiresShutdownPriveleges)
                GrantShutdownPrivileges();

            int actionCount = 3;
            var restartServiceAfter = (uint)TimeSpan.FromMinutes(
                                                                 recoveryOptions.RestartServiceWaitMinutes).TotalMilliseconds;

            IntPtr failureActionsPointer = IntPtr.Zero;
            IntPtr actionPointer = IntPtr.Zero;

            ServiceController controller = null;
            try
            {
                // Open the service
                controller = new ServiceController(serviceName);

                // Set up the failure actions
                var failureActions = new SERVICE_FAILURE_ACTIONS();
                failureActions.dwResetPeriod = (int)TimeSpan.FromDays(recoveryOptions.ResetFailureCountWaitDays).TotalSeconds;
                failureActions.cActions = (uint)actionCount;
                failureActions.lpRebootMsg = recoveryOptions.RestartSystemMessage;

                // allocate memory for the individual actions
                actionPointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SC_ACTION))*actionCount);
                ServiceRecoveryAction[] actions = {
                                                  	recoveryOptions.FirstFailureAction,
                                                  	recoveryOptions.SecondFailureAction,
                                                  	recoveryOptions.SubsequentFailureAction
                                                  };
                for (int i = 0; i < actions.Length; i++)
                {
                    ServiceRecoveryAction action = actions[i];
                    SC_ACTION scAction = GetScAction(action, restartServiceAfter);
                    Marshal.StructureToPtr(scAction, (IntPtr)((Int64)actionPointer + (Marshal.SizeOf(typeof(SC_ACTION)))*i), false);
                }
                failureActions.lpsaActions = actionPointer;

                string command = recoveryOptions.RunProgramCommand;
                if (command != null)
                    failureActions.lpCommand = command;

                failureActionsPointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SERVICE_FAILURE_ACTIONS)));
                Marshal.StructureToPtr(failureActions, failureActionsPointer, false);

                // Make the change
                bool success = ChangeServiceConfig2(controller.ServiceHandle.DangerousGetHandle(),
                                                    SERVICE_CONFIG_FAILURE_ACTIONS,
                                                    failureActionsPointer);

                // Check that the change occurred
                if (!success)
                    throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to change the Service configuration.");
            }
            finally
            {
                if (failureActionsPointer != IntPtr.Zero)
                    Marshal.FreeHGlobal(failureActionsPointer);

                if (actionPointer != IntPtr.Zero)
                    Marshal.FreeHGlobal(actionPointer);

                if (controller != null)
                {
                    controller.Dispose();
                }

                //log.Debug(m => m("Done setting service recovery options."));
            }
        }
Exemple #20
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <returns><see langword="true"/> if the task ran successfully;
        /// otherwise <see langword="false"/>.</returns>
        public override bool Execute()
        {
            bool    result     = true;
            Service controller = null;

            try
            {
                controller = GetServiceController();
                if (controller == null)
                {
                    throw new Exception(string.Format(Properties.Resources.ServiceNotFound,
                                                      ServiceName, MachineName));
                }


                ServiceControllerStatus desiredStatus = DetermineDesiredStatus();
                ServiceControllerStatus currentStatus = controller.Status;

                if (currentStatus == desiredStatus && _action != ServiceActions.Restart)
                {
                    Log.LogMessage(Properties.Resources.ServiceStatus,
                                   DisplayName, MachineName, currentStatus);

                    return(true);
                }

                switch (_action)
                {
                case ServiceActions.Start:
                    result = StartService(controller);
                    break;

                case ServiceActions.Pause:
                    result = PauseService(controller);
                    break;

                case ServiceActions.Continue:
                    result = ContinueService(controller);
                    break;

                case ServiceActions.Stop:
                    result = StopService(controller);
                    break;

                case ServiceActions.Restart:
                    result = RestartService(controller);
                    break;
                }

                // refresh current service status
                controller.Refresh();
                base.Status = controller.Status.ToString();

                Log.LogMessage(Properties.Resources.ServiceStatus,
                               DisplayName, MachineName, Status);
            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(ex);
                return(false);
            }
            finally
            {
                if (controller != null)
                {
                    controller.Dispose();
                }
            }

            return(result);
        }
Exemple #21
0
 private void toolStripMenuItem11_Click(object sender, EventArgs e)
 {
     if (firewall == 0) {
         ServiceController sc = new ServiceController("MpsSvc");
         try {
             sc.Start();
         } catch {
             MessageBox.Show("У Вас нет доступа к управлению Брандмауэром",
                 "Отказано в доступе", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         sc.Dispose();
     } else {
         ServiceController sc = new ServiceController("MpsSvc");
         try {
             sc.Stop();
         } catch {
             MessageBox.Show("У Вас нет доступа к управлению Брандмауэром",
                 "Отказано в доступе", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         sc.Dispose();
     }
 }
        public static void StopService(string serviceName, int timeoutMilliseconds)
        {
            ServiceController service = null;
            try
            {
                service = new ServiceController(serviceName);
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
            }
            catch
            {
                // ...
            }
            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }
            }
        }
        /// <summary>
        /// Stops the windows service.
        /// </summary>
        /// <param name="serviceName">Name of the windows service.</param>
        private void StopService(string serviceName)
        {
            var service = new ServiceController(serviceName);

            if (service.Status == ServiceControllerStatus.Stopped)
            {
                service.Dispose();
                return;
            }

            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(Timeout);
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
            }
            catch { }

            service.Dispose();
        }
Exemple #24
0
 public static void StartService(string serviceName, string serverName, int timeoutSec)
 {
     try
     {
         ServiceController service = new ServiceController(serviceName, serverName);
         if (service.Status == ServiceControllerStatus.Stopped || service.Status == ServiceControllerStatus.StartPending)
         {
             try
             {
                 if (service.Status == ServiceControllerStatus.Stopped)
                 {
                     Log.Info("argustv: service {0} is stopped, so we try start it now...", serviceName);
                     service.Start();
                 }
                 service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, timeoutSec));
             }
             catch (Exception ex)
             {
                 Log.Error("argustv: starting service {0} failed, {1}", serviceName, ex.Message);
             }
         }
         Log.Info("argustv: service {0} - current status: {1}", serviceName, service.Status.ToString());
         service.Close();
         service.Dispose();
     }
     catch
     {
         Log.Info("argustv: service {0} not found on {1}", serviceName, serverName);
     }
 }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            string dir = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
            string svc = Path.Combine(dir, "ConnectifyService.exe");
            string cli = Path.Combine(dir, "Connectify.exe");
            bool isService = false;
            if (File.Exists(svc) && File.Exists(cli)) {
                RegistryKey runKey = null;
                try {
                    // Remove the client autorun
                    runKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                    runKey.DeleteValue("Connectify", false);

                } catch (Exception) {
                } finally {
                    if (runKey != null)
                        runKey.Close();
                }

                TaskService ts = null;
                try {
                    // Remove service scheduled task if it exists
                    ts = new TaskService();
                    foreach (Task t in ts.RootFolder.Tasks) {
                        if (t.Name.StartsWith("Connectify")) {
                            ts.RootFolder.DeleteTask(t.Name);
                            break;
                        }
                    }
                } catch (Exception) {
                } finally {
                    if (ts != null)
                        ts.Dispose();
                }

                ServiceController service = null;
                ManagementObject classInstance = null;
                ManagementBaseObject inParams = null;
                try {
                    // Set the service to run manually if it exists
                    service = new ServiceController("Connectify");
                    if (service != null) {
                        isService = true;
                        classInstance = new ManagementObject("root\\CIMV2", "Win32_Service.Name='Connectify'", null);
                        inParams = classInstance.GetMethodParameters("ChangeStartMode");
                        inParams["StartMode"] = "Manual";
                        classInstance.InvokeMethod("ChangeStartMode", inParams, null);
                    }
                } catch (Exception) {
                } finally {
                    if (inParams != null)
                        inParams.Dispose();
                    if (classInstance != null)
                        classInstance.Dispose();
                }

                try {
                    if (isService) {
                        // Stop the service if it happens to be running
                        service.Stop();
                    } else {
                        // Kill services if they happen to be running
                        foreach (Process p in Process.GetProcessesByName("ConnectifyService")) {
                            p.Kill();
                            p.WaitForExit();
                        }
                        foreach (Process p in Process.GetProcessesByName("Connectifyd")) {
                            p.Kill();
                            p.WaitForExit();
                        }
                    }
                } catch (Exception) {
                }

                Process daemon = null;
                try {
                    if (isService) {
                        // Start the service
                        service.Start();
                        service.WaitForStatus(ServiceControllerStatus.Running);
                    } else {
                        // Launch the service & client
                        daemon = Process.Start(svc);
                        daemon.WaitForInputIdle();
                    }
                } catch (Exception) {
                }

                // Launch the client
                Process client = Process.Start(cli);

                // Wait for client to quit
                client.WaitForExit();

                try {
                    if (isService) {
                        // Stop the service
                        service.Stop();
                    } else {
                        // Kill services
                        daemon.Kill();
                        daemon.WaitForExit();
                        foreach (Process p in Process.GetProcessesByName("Connectifyd")) {
                            p.Kill();
                        }
                    }
                } catch (Exception) {
                } finally {
                    if (service != null)
                        service.Dispose();
                }
            }
        }
Exemple #26
0
        private static void RunService(CommandLineParser parser, Action<StringDictionary> environment, ILog logger)
        {
            if (ServiceEnvironmentManagementEx.IsServiceDisabled(parser.Target))
            {
                logger.ErrorFormat("The service '{0}' is disabled. Please enable the service.",
                    parser.Target);
                return;
            }

            var service = new ServiceController(parser.Target);
            try
            {

                if (service.Status != ServiceControllerStatus.Stopped)
                {
                    logger.ErrorFormat(
                        "The service '{0}' is already running. The profiler cannot attach to an already running service.",
                    parser.Target);
                    return;
                }

                // now to set the environment variables
                var profilerEnvironment = new StringDictionary();
                environment(profilerEnvironment);

                var serviceEnvironment = new ServiceEnvironmentManagement();

                try
                {
                    serviceEnvironment.PrepareServiceEnvironment(
                        parser.Target,
                            parser.ServiceEnvironment,
                        (from string key in profilerEnvironment.Keys
                         select string.Format("{0}={1}", key, profilerEnvironment[key])).ToArray());

                    // now start the service
                    var old = service;
                    service = new ServiceController(parser.Target);
                    old.Dispose();

                    if (parser.Target.ToLower().Equals("w3svc"))
                    {
                        // Service will not automatically start
                        if (! TerminateCurrentW3SvcHost(logger) ||
                            !ServiceEnvironmentManagementEx.IsServiceStartAutomatic(parser.Target))
                        {
                            service.Start();
                        }
                    }
                    else
                    {
                        service.Start();
                    }
                    logger.InfoFormat("Service starting '{0}'", parser.Target);
                    service.WaitForStatus(ServiceControllerStatus.Running, parser.ServiceStartTimeout);
                    logger.InfoFormat("Service started '{0}'", parser.Target);
                }
                catch (InvalidOperationException fault)
                {
                    logger.FatalFormat("Service launch failed with '{0}'", fault);
                }
                finally
                {
                    // once the serice has started set the environment variables back - just in case
                    serviceEnvironment.ResetServiceEnvironment();
                }

                // and wait for it to stop
                service.WaitForStatus(ServiceControllerStatus.Stopped);
                logger.InfoFormat("Service stopped '{0}'", parser.Target);

                // Stopping w3svc host
                if (parser.Target.ToLower().Equals("w3svc"))
                {
                    logger.InfoFormat("Stopping svchost to clean up environment variables for w3svc", parser.Target);
                    if (ServiceEnvironmentManagementEx.IsServiceStartAutomatic(parser.Target))
                    {
                        logger.InfoFormat("Please note that the 'w3svc' service may automatically start");
                    }
                    TerminateCurrentW3SvcHost(logger);
                }
            }
            finally
            {
                service.Dispose();
            }
        }
        public static string GetServiceStatus(string serviceName, out EnumServiceStatus serviceStatus)
        {
            ServiceController service = null;
            string status = "";
            serviceStatus = EnumServiceStatus.Unknown;
            try
            {
                service = new ServiceController(serviceName);
                if (service.Status.ToString().ToLower() == "stopped")
                {
                    status = "Installed but stopped";
                    serviceStatus = EnumServiceStatus.ServiceInstalledStopped;
                }

                if (service.Status.ToString().ToLower() == "running")
                {
                    status = "Installed and started";
                    serviceStatus = EnumServiceStatus.ServiceInstalledStarted;
                }
            }
            catch (InvalidOperationException)
            {
                status = "Service not installed";
                serviceStatus = EnumServiceStatus.ServiceNotInstalled;
            }
            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }
            }

            return status;
        }
 /// <summary>
 /// Returns flag notifying if the windows service is running.
 /// </summary>
 /// <param name="serviceName">Windows service being tested.</param>
 /// <returns>True if running, otherwise false.</returns>
 private bool IsTestServiceRunning(string serviceName)
 {
     var service = new ServiceController(serviceName);
     var running = (service.Status == ServiceControllerStatus.Running);
     service.Dispose();
     return running;
 }
        private void UpdateServiceUI()
        {
            if (mediaServer != null && standAloneMode == true)
            {
                serverStatus1.Text = "Serving " + mediaServer.TotalFileCount + " Files in " + mediaServer.TotalDirectoryCount + " Directories";
                serverStatus2.Text = "";
                UpdateDirectoriesUI();
                return;
            }

            if (serviceController == null)
            {
                try
                {
                    serviceController = new ServiceController("AV Media Server");
                    serviceStatus = serviceController.Status;
                }
                catch (System.InvalidOperationException)
                {
                    serverStatus1.Text = "Media Server Service Not Installed";
                    serverStatus2.Text = "Use \"Standalone Mode\" for autonomous operation";
                    serviceController = null;
                    serviceStatus = ServiceControllerStatus.Stopped;
                    return;
                }
            }

            ServiceController serviceController2 = new ServiceController("AV Media Server");
            serviceStatus = serviceController2.Status;
            switch (serviceStatus)
            {
                case ServiceControllerStatus.Running:
                    if (mediaServer == null)
                    {
                        serverStatus1.Text = "Connecting...";
                        serverStatus2.Text = "";
                        Connect();
                    }
                    else
                    {
                        serverStatus1.Text = "Media Server Serving "+mediaServer.TotalFileCount+" Files in "+mediaServer.TotalDirectoryCount+" Directories";
                        serverStatus2.Text = "";
                    }
                    break;
                case ServiceControllerStatus.Stopped:
                    serverStatus1.Text = "Media Server Service is Stopped";
                    serverStatus2.Text = "";
                    break;
                default:
                    serverStatus1.Text = "Media Server Service is " + serviceStatus.ToString();
                    serverStatus2.Text = "";
                    break;
            }
            serviceController2.Close();
            serviceController2.Dispose();
            serviceController2 = null;
            UpdateDirectoriesUI();
        }
        /// <summary>
        /// Restart the Windows Time Service
        /// </summary>
        private static CompletionCode RestartTimeService()
        {
            ServiceController sc = new ServiceController(ControlStrings.W32TimeService);

            if (sc != null)
            {
                // stop the time service
                if (sc.Status != ServiceControllerStatus.Stopped)
                {
                    sc.Stop();
                    sc.WaitForStatus(ServiceControllerStatus.Stopped, ControlStrings.ServiceWaitTime);
                }

                // start the time service
                if (sc.Status == ServiceControllerStatus.Stopped)
                {
                    sc.Start();
                    sc.WaitForStatus(ServiceControllerStatus.Running, ControlStrings.ServiceWaitTime);

                    if (sc.Status == ServiceControllerStatus.Running)
                    {
                        if (sc != null)
                            sc.Dispose();

                        return CompletionCode.Success;
                    }
                }

                if (sc != null)
                    sc.Dispose();

                return CompletionCode.CannotExecuteRequestInvalidState;
            }
            else
            {
                Tracer.WriteError("Chassis Manager RestartTimeService unable to obtain Time Service handle");
                return CompletionCode.UnspecifiedError;
            }
        }
Exemple #31
0
        static void Main(string[] args)
        {
            List<String> services = new List<string>();
            services.AddRange(Properties.Settings.Default.Services.Split(';'));

            while (true) {

                foreach (string service in services) {
                    try {
                        ServiceController sc = new ServiceController(service);

                        Console.WriteLine(DateTime.Now + " Checking status of: {0}", service);
                        Console.WriteLine(DateTime.Now + " Status of service {0} is: {1}", service, sc.Status);

                        switch (sc.Status) {

                            case ServiceControllerStatus.Running:
                            Console.WriteLine(DateTime.Now + " Service {0} is running properly", service);
                            break;

                            case ServiceControllerStatus.Stopped:
                            Console.WriteLine(DateTime.Now + " Start service {0}", sc.ServiceName);
                            sc.Start();
                            sc.WaitForStatus(ServiceControllerStatus.Running);
                            break;

                            case ServiceControllerStatus.Paused:
                            Console.WriteLine(DateTime.Now + " Start service {0}", sc.ServiceName);
                            sc.Start();
                            sc.WaitForStatus(ServiceControllerStatus.Running);
                            break;

                            case ServiceControllerStatus.PausePending:
                            Console.WriteLine(DateTime.Now + " Service {0} is pausing. Wait.", sc.ServiceName);
                            sc.WaitForStatus(ServiceControllerStatus.Paused);
                            Console.WriteLine(DateTime.Now + " Start service {0}", sc.ServiceName);
                            sc.Start();
                            sc.WaitForStatus(ServiceControllerStatus.Running);
                            break;

                            case ServiceControllerStatus.StopPending:
                            Console.WriteLine(DateTime.Now + " Service {0} is stopping. Wait.", sc.ServiceName);
                            sc.WaitForStatus(ServiceControllerStatus.Stopped);
                            Console.WriteLine(DateTime.Now + " Start service {0}", sc.ServiceName);
                            sc.Start();
                            sc.WaitForStatus(ServiceControllerStatus.Running);
                            break;

                            case ServiceControllerStatus.StartPending:
                            Console.WriteLine(DateTime.Now + " Service {0} start pending. Wait.", sc.ServiceName);
                            sc.WaitForStatus(ServiceControllerStatus.Running);
                            break;

                            default:
                            Console.WriteLine(DateTime.Now + " Service {0} is running properly", service);
                            break;
                        }
                        sc.Dispose();
                        sc = null;
                    } catch (Exception e) {
                        Console.WriteLine("Error: {0}\n{1}", e.StackTrace,e.Message);
                    }
                }
                Console.WriteLine(DateTime.Now + " All done. Waiting for {0} sec", Properties.Settings.Default.Delay / 1000);
                System.Threading.Thread.Sleep(Properties.Settings.Default.Delay);
            }
        }
        public static void RestartService(string serviceName, int timeoutMilliseconds)
        {
            ServiceController service = null;
            try
            {
                service = new ServiceController(serviceName);
                int millisec1 = Environment.TickCount;
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

                // count the rest of the timeout
                int millisec2 = Environment.TickCount;
                timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));

                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            catch
            {
                // ...
            }
            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }
            }
        }