Ejemplo n.º 1
0
        /// <summary>
        /// Checks the status of the given controller, and if it isn't the requested state,
        /// performs the given action, and checks the state again.
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="status"></param>
        /// <param name="changeStatus"></param>
        public static void ChangeServiceStatus(ServiceController controller, ServiceControllerStatus status, Action changeStatus)
        {
            if (controller.Status == status)
            {
                Console.Out.WriteLine(controller.ServiceName + " status is good: " + Enum.GetName(typeof(ServiceControllerStatus), status));
                return;
            }

               Console.Out.WriteLine((controller.ServiceName + " status is NOT " + Enum.GetName(typeof(ServiceControllerStatus), status) + ". Changing status..."));

            try
            {
                changeStatus();
            }
            catch (Win32Exception exception)
            {
                ThrowUnableToChangeStatus(controller.ServiceName, status, exception);
            }
            catch (InvalidOperationException exception)
            {
                ThrowUnableToChangeStatus(controller.ServiceName, status, exception);
            }

            var timeout = TimeSpan.FromSeconds(3);
            controller.WaitForStatus(status, timeout);
            if (controller.Status == status)
                Console.Out.WriteLine((controller.ServiceName + " status changed successfully."));
            else
                ThrowUnableToChangeStatus(controller.ServiceName, status);
        }
        public void InitializeTrayIconAndProperties()
        {
            serviceStatus = _serviceManager.GetServiceStatus();

            //Set the Tray icon
            if (serviceStatus == ServiceControllerStatus.Running)
                notifyTrayIcon.Icon = Properties.Resources.TrayIconRunning;
            else if (serviceStatus == ServiceControllerStatus.Stopped)
                notifyTrayIcon.Icon = Properties.Resources.TrayIconStopped;
            else
                notifyTrayIcon.Icon = Properties.Resources.TrayIconActive;

            //Setup context menu options
            trayContextMenu = new ContextMenuStrip();
            trayContextMenu.Items.Add(new ToolStripMenuItem() { Name = ActionConstants.REFRESH, Text = "Refresh Status" });
            trayContextMenu.Items.Add("-");

            _startServiceItem = new ToolStripMenuItem() { Enabled = ServiceControllerStatus.Stopped.Equals(serviceStatus), Name = ActionConstants.START_SERVICE, Text = "Start Service" };
            trayContextMenu.Items.Add(_startServiceItem);

            _stopServiceItem = new ToolStripMenuItem() { Enabled = ServiceControllerStatus.Running.Equals(serviceStatus), Name = ActionConstants.STOP_SERVICE, Text = "Stop Service" };
            trayContextMenu.Items.Add(_stopServiceItem);

            trayContextMenu.Items.Add("-");
            trayContextMenu.Items.Add(new ToolStripMenuItem() { Name = ActionConstants.SHOW_LOGS, Text = "Show Logs" });
            trayContextMenu.Items.Add("-");

            trayContextMenu.Items.Add(new ToolStripMenuItem() { Name = "actionExit", Text = "Exit" });

            trayContextMenu.ItemClicked += trayContextMenu_ItemClicked;

            //Initialize the tray icon here
            this.notifyTrayIcon.ContextMenuStrip = trayContextMenu;
        }
Ejemplo n.º 3
0
        bool ControlService(ServiceControllerStatus status, Action<ServiceController> controlAction)
        {
            if (controller.Status == status)
            {
                log.Debug("The {0} service is already in the requested state: {1}", controller.ServiceName, status);
                return false;
            }

            log.Debug("Setting the {0} service to {1}", controller.ServiceName, status);

            try
            {
                controlAction(controller);
            }
            catch (Exception ex)
            {
                string message = string.Format("The {0} service could not be set to {1}", controller.ServiceName, status);
                throw new InvalidOperationException(message, ex);
            }

            controller.WaitForStatus(status, timeout);
            if (controller.Status == status)
            {
                log.Debug("The {0} service was set to {1} successfully", controller.ServiceName, status);
            }
            else
            {
                string message = string.Format("A timeout occurred waiting for the {0} service to be {1}",
                                               controller.ServiceName,
                                               status);
                throw new InvalidOperationException(message);
            }

            return true;
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 获取服务列表
        /// </summary>
        /// <returns></returns>
        public static IList<ServiceInformation> GetServiceList(string contains, ServiceControllerStatus status)
        {
            IList<ServiceInformation> servicelist = new List<ServiceInformation>();
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.Status != status) continue;
                if (string.IsNullOrEmpty(contains))
                {
                    servicelist.Add(new ServiceInformation(s.ServiceName));
                }
                else
                {
                    if (s.ServiceName != null && s.ServiceName.ToLower().Contains(contains.ToLower()))
                    {
                        servicelist.Add(new ServiceInformation(s.ServiceName));
                    }
                    else if (s.DisplayName != null && s.DisplayName.ToLower().Contains(contains.ToLower()))
                    {
                        servicelist.Add(new ServiceInformation(s.ServiceName));
                    }
                }
            }

            return servicelist;
        }
Ejemplo n.º 5
0
        public SysTray()
        {
            InitSystrayForm();

            _lastStatus = CurrentStatus;

            Initialize();
        }
Ejemplo n.º 6
0
 private void RestoreService(ServiceControllerStatus previousStatus)
 {
     if (previousStatus == ServiceControllerStatus.Running) {
         controller.Start();
     } else if (previousStatus == ServiceControllerStatus.Paused) {
         controller.Pause();
     }
 }
Ejemplo n.º 7
0
		private void serviceTimer_Tick (object sender, EventArgs e) {
			try {
				lastError = null;
				lastStatus  = serviceController.Status;
			} catch (Exception ex) {
				lastStatus = ServiceControllerStatus.Paused;
				lastError = ex;
			}
			UpdateStatus ();
		}
Ejemplo n.º 8
0
        private static void ThrowUnableToChangeStatus(string serviceName, ServiceControllerStatus status, Exception exception)
        {
            var message = "Unable to change " + serviceName + " status to " + Enum.GetName(typeof(ServiceControllerStatus), status);

            if (exception == null)
            {
                throw new InvalidOperationException(message);
            }

            throw new InvalidOperationException(message, exception);
        }
Ejemplo n.º 9
0
		static ServiceStatus ToServiceStatus(ServiceControllerStatus status)
		{
			switch (status)
			{
				case ServiceControllerStatus.StopPending:
					return ServiceStatus.Stopped;
				case ServiceControllerStatus.Stopped:
					return ServiceStatus.Stopped;
				default:
				return ServiceStatus.Started;
			}
		}
Ejemplo n.º 10
0
		private bool CheckStatus(ServiceControllerStatus status)
		{
			try
			{
				this.service.Refresh();
				return this.service.Status == status;
			}
			catch (InvalidOperationException)
			{
				return false;
			}
		}
Ejemplo n.º 11
0
        private bool CanStartService(System.ServiceProcess.ServiceController service)
        {
            if (!checkBoxEnabled.Checked || service == null)
            {
                return(false);
            }

            ServiceControllerStatus status = service.Status;

            return(status != ServiceControllerStatus.Running &&
                   status != ServiceControllerStatus.StartPending &&
                   status != ServiceControllerStatus.ContinuePending);
        }
Ejemplo n.º 12
0
        private bool CanStopService(System.ServiceProcess.ServiceController service)
        {
            if (!checkBoxEnabled.Checked || service == null)
            {
                return(false);
            }

            ServiceControllerStatus status = service.Status;

            return(service.CanStop &&
                   status != ServiceControllerStatus.Stopped &&
                   status != ServiceControllerStatus.StopPending);
        }
Ejemplo n.º 13
0
        internal static void Start(string ServiceName)
        {
            using (ServiceController controller = new ServiceController(ServiceName))
            {
                controller.Refresh();
                ServiceControllerStatus status = controller.Status;

                if (status == System.ServiceProcess.ServiceControllerStatus.Stopped)
                {
                    controller.Start();
                }
            }
        }
Ejemplo n.º 14
0
 public static bool CheckServiceExists(string serviceName)
 {
     try
     {
         ServiceController       sc2    = new ServiceController(serviceName);
         ServiceControllerStatus status = sc2.Status;
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Ejemplo n.º 15
0
        public override void WaitForStatus(ServiceControllerStatus desiredStatus)
        {
            if (statusSetter == null && Status == desiredStatus)
            {
                return;
            }

            statusSetter.Join();
            if (status != desiredStatus)
            {
                throw new ApplicationException();
            }
        }
Ejemplo n.º 16
0
        //private void Monitor(Object source, System.Timers.ElapsedEventArgs e)

        private void MServico()
        {
            ServiceController sc = reg.SC(servico);

            ServiceControllerStatus scSt = sc.Status;

            if (sc.Status == ServiceControllerStatus.Running)
            {
                //lblStatus.Invoke((MethodInvoker)(() => lblStatus.Text = "Aguarde. Parando o Serviço"));
                lblStatus.Text = "Aguarde. Parando o Serviço";
                try
                {
                    sc.Stop();
                    while (sc.Status != ServiceControllerStatus.Stopped)
                    {
                        //lblStatus.Invoke((MethodInvoker)(() => lblStatus.Text = "Parando..."));
                        lblStatus.Text = "Parando...";
                        sc.WaitForStatus(ServiceControllerStatus.Stopped);
                        sc.Refresh();
                    }
                    //lblStatus.Invoke((MethodInvoker)(() => lblStatus.Text = "Serviço Parado com Sucesso!"));
                    lblStatus.Text = "Serviço Parado com Sucesso!";
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Erro:" + ex);
                }
            }

            else
            {
                //lblStatus.Invoke((MethodInvoker)(() => lblStatus.Text = "Aguarde. Iniciando o Serviço SQL..."));
                lblStatus.Text = "Aguarde. Iniciando o Serviço SQL...";
                try
                {
                    sc.Start();
                    while (sc.Status != ServiceControllerStatus.Running)
                    {
                        //lblStatus.Invoke((MethodInvoker)(() => lblStatus.Text = "Iniciando..."));
                        lblStatus.Text = "Iniciando...";
                        sc.WaitForStatus(ServiceControllerStatus.Running);
                        sc.Refresh();
                    }
                    //lblStatus.Invoke((MethodInvoker)(() => lblStatus.Text = "Serviço iniciado com sucesso."));
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Erro:" + ex);
                }
            }
        }
Ejemplo n.º 17
0
 private void StopService()
 {
     using (ServiceController controller = new ServiceController(Constants.SERVICE_NAME, "."))
     {
         ServiceControllerStatus status = controller.Status;
         if (status == ServiceControllerStatus.Running)
         {
             controller.Stop();
             controller.WaitForStatus(ServiceControllerStatus.Stopped);
             this.timer.Stop();
         }
     }
     this.UpdateServiceStatus();
 }
Ejemplo n.º 18
0
        private void btnCheckExistMSSQL_Click(object sender, EventArgs e)
        {
            bool bResult = ServiceHelper.ExistSqlServerService("MSSQLSERVER");

            if (bResult == true)
            {
                ServiceControllerStatus status = ServiceHelper.GetSqlServerServiceStatus("MSSQLSERVER");
                MessageDialog.ShowErrorMsgBox("MSSQLSERVER服务运行状态:" + status.ToString());
            }
            else
            {
                MessageDialog.ShowErrorMsgBox("不存在MSSQLSERVER服务");
            }
        }
        //Get service status
        //Expected status result is Running i.e. 4
        private ServiceControllerStatus GetServiceStatus(string serviceName)
        {
            ServiceControllerStatus serviceControllerStatus = ServiceControllerStatus.Stopped;

            try
            {
                using (ServiceController sc = new ServiceController(serviceName))
                {
                    serviceControllerStatus = sc.Status;
                }
            }
            catch (Exception) {  }
            return(serviceControllerStatus);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Updates the status of a single service
        /// </summary>
        private void RefreshStatus()
        {
            bool isInstalled = false;
            ServiceControllerStatus status = ServiceControllerStatus.Stopped;
            BackgroundWorker        worker = new BackgroundWorker();

            worker.DoWork += (s, dwe) =>
            {
                isInstalled = ServiceController.GetServices(Controller.MachineName).Any(svc => svc.ServiceName == _serviceName);
                if (isInstalled)
                {
                    Controller.Refresh();
                    status = Controller.Status;
                }
            };
            worker.RunWorkerCompleted += (s, rwe) =>
            {
                if (isInstalled)
                {
                    switch (status)
                    {
                    case ServiceControllerStatus.Running:
                        lblStatus.Foreground = Brushes.LimeGreen;
                        lblStatus.Content    = "Running";
                        btnStop.IsEnabled    = true;
                        btnStart.IsEnabled   = false;
                        break;

                    default:
                        lblStatus.Foreground = Brushes.Red;
                        lblStatus.Content    = "Stopped";
                        btnStop.IsEnabled    = false;
                        btnStart.IsEnabled   = true;
                        break;
                    }
                    btnInstall.IsEnabled   = false;
                    btnUninstall.IsEnabled = true;
                }
                else
                {
                    lblStatus.Foreground   = Brushes.Red;
                    lblStatus.Content      = "Not installed";
                    btnStart.IsEnabled     = false;
                    btnStop.IsEnabled      = false;
                    btnInstall.IsEnabled   = true;
                    btnUninstall.IsEnabled = false;
                }
            };
            worker.RunWorkerAsync();
        }
Ejemplo n.º 21
0
        public static ServiceControllerStatus GetServiceStatus(string serviceName)
        {
            ServiceControllerStatus retVal = ServiceControllerStatus.Stopped;

            using (ServiceController sc = getServiceController(serviceName))
            {
                if (sc != null)
                {
                    retVal = sc.Status;
                }
            }

            return(retVal);
        }
Ejemplo n.º 22
0
 public static bool TryGetStatus(out ServiceControllerStatus status)
 {
     status = ServiceControllerStatus.Stopped;
     try
     {
         ServiceController bmservice = new ServiceController("bitmoose");
         status = bmservice.Status;
         return(true);
     }
     catch (InvalidOperationException)
     {
     }
     return(false);
 }
Ejemplo n.º 23
0
        private static ServiceController GetServiceController(string serviceName)
        {
            ServiceController service = new ServiceController(serviceName);

            try
            {
                ServiceControllerStatus status = service.Status;
            }
            catch
            {
                service = null;
            }
            return(service);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Wait to status of a service
        /// </summary>
        /// <param name="service">Service controller</param>
        /// <param name="nextServStatus">Desired service status</param>
        /// <returns>True if the service status is the desired</returns>
        public bool StatusCheck(ServiceController service, ServiceControllerStatus nextServStatus)
        {
            service.Refresh();
            do
            {
                System.Threading.Thread.Sleep(1000);
                service.Refresh();
            } while (service.Status.Equals(ServiceControllerStatus.ContinuePending) ||
                     service.Status.Equals(ServiceControllerStatus.PausePending) ||
                     service.Status.Equals(ServiceControllerStatus.StartPending) ||
                     service.Status.Equals(ServiceControllerStatus.StopPending));

            return(service.Status == nextServStatus);
        }
Ejemplo n.º 25
0
        private void ServiceCommand(string serviceName, ServiceCommandType commandType)
        {
            Console.WriteLine(String.Format("ServiceCommand: {0}, CommandType: {1}", serviceName, commandType.ToString()));

            if (Utilities.IsInstalledWindowsService(serviceName))
            {
                ServiceController       service = new ServiceController(serviceName);
                ServiceControllerStatus stat    = ServiceControllerStatus.Running;
                try
                {
                    stat = service.Status;
                }
                catch (Exception ex)
                {
                    LogWriter.WriteLogEntry(ex);
                }

                if (commandType == ServiceCommandType.Stop)
                {
                    if (stat != ServiceControllerStatus.Stopped)
                    {
                        try
                        {
                            if (service.CanStop)
                            {
                                service.Stop();
                            }
                        }
                        catch (Exception ex)
                        {
                            LogWriter.WriteLogEntry(ex);
                        }
                    }
                }
                else if (commandType == ServiceCommandType.Start)
                {
                    if (stat != ServiceControllerStatus.Running)
                    {
                        try
                        {
                            service.Start();
                        }
                        catch (Exception ex)
                        {
                            LogWriter.WriteLogEntry(ex);
                        }
                    }
                }
            }
        }
        public static string Format(ServiceControllerStatus status)
        {
            switch (status)
            {
            case ServiceControllerStatus.Running:
                return(Resources.GetServiceInfoRunning);

            case ServiceControllerStatus.Stopped:
                return(Resources.GetServiceInfoStopped);

            default:
                return(status.ToString().Substring(0, 1));
            }
        }
Ejemplo n.º 27
0
 private static bool IsInstalled()
 {
     using (ServiceController controller = new ServiceController("ValheimBackupService"))
     {
         try
         {
             ServiceControllerStatus status = controller.Status;
         } catch
         {
             return(false);
         }
         return(true);
     }
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Set button states(enabled, disabled)
        /// </summary>
        public void SetButtonStates()
        {
            if (!Visible)
            {
                return;
            }

            if (InvokeRequired)
            {
                Invoke((SetButtonStatesCallback)SetButtonStates);
            }
            else
            {
                ServiceControllerStatus serviceStatus = Program.serviceController.Status;

                lblCurrentStatus.Text = serviceStatus.ToString();
                lblStartupMode.Text   = ServiceInfo.GetSeviceStartupMode();
                lblTimeStarted.Text   = Program.GetServiceStartedTime();

                LoadSettings();
                SetStateAndLastCheck();

                btnQuickCheck.Enabled = ((serviceStatus == ServiceControllerStatus.Running) && lblCurrentState.Text == "Idle");

                if (imageList != null)
                {
                    switch (serviceStatus)
                    {
                    case ServiceControllerStatus.Running:
                        pbStatus.Image       = imageList.Images[1];
                        btnStartStop.Text    = "Stop";
                        btnStartStop.Enabled = true;
                        break;

                    case ServiceControllerStatus.Stopped:
                        pbStatus.Image       = imageList.Images[0];
                        btnStartStop.Text    = "Start";
                        btnStartStop.Enabled = true;
                        break;

                    default:
                        pbStatus.Image       = imageList.Images[2];
                        btnStartStop.Text    = "Paused";
                        btnStartStop.Enabled = false;
                        break;
                    }
                }
            }
        }
Ejemplo n.º 29
0
 private void StatusChecking(object state)
 {
     previousStatus = _serviceController.Status;
     while (true)
     {
         _serviceController.Refresh();
         if (previousStatus != _serviceController.Status)
         {
             if (StatusChangingEvent != null)
                 StatusChangingEvent(this, EventArgs.Empty);
             previousStatus = _serviceController.Status;
         }
         Thread.Sleep(500);
     }
 }
Ejemplo n.º 30
0
 private void WaitIfNeeded(bool wait, int timeout, ServiceController sc, ServiceControllerStatus targetStatus)
 {
     if (wait)
     {
         if (timeout > 0)
         {
             TimeSpan ts = new TimeSpan(0, 0, 0, timeout);
             sc.WaitForStatus(targetStatus, ts);
         }
         else
         {
             sc.WaitForStatus(targetStatus);
         }
     }
 }
        /// <summary>
        /// WaitForStatus method implementation
        /// </summary>
        public void WaitForStatus(ServiceControllerStatus desiredStatus, TimeSpan timeout)
        {
            TimeSpan duration = new TimeSpan(0, 0, 0);

            while (this.Status != desiredStatus)
            {
                Open();
                Thread.Sleep(1000);
                duration.Add(new TimeSpan(0, 0, 1));
                if (timeout < duration)
                {
                    break;
                }
            }
        }
Ejemplo n.º 32
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 private static bool IsInstalled()
 {
     using (ServiceController controller = new ServiceController(Global.SERVICE_NAME))
     {
         try
         {
             ServiceControllerStatus status = controller.Status;
         }
         catch
         {
             return(false);
         }
         return(true);
     }
 }
Ejemplo n.º 33
0
        private bool PreRunCheck(ServiceControllerStatus targetStatus)
        {
            switch (targetStatus)
            {
            case ServiceControllerStatus.Stopped:
                return(_svcController.CanStop);

            case ServiceControllerStatus.Paused:
                return(_svcController.CanPauseAndContinue);

            case ServiceControllerStatus.Running:
            default:
                return(true);
            }
        }
Ejemplo n.º 34
0
 private static bool IsInstalled()
 {
     using (var controller = new ServiceController("Rust Service Host"))
     {
         try
         {
             ServiceControllerStatus status = controller.Status;
         }
         catch
         {
             return(false);
         }
         return(true);
     }
 }
Ejemplo n.º 35
0
 public bool IsServiceInstalled()
 {
     using (ServiceController controller = new ServiceController(SERVICE_NAME))
     {
         try
         {
             ServiceControllerStatus status = controller.Status;
         }
         catch
         {
             return(false);
         }
         return(true);
     }
 }
Ejemplo n.º 36
0
 public NTService(ServiceController service,
                  ServiceControllerStatus StatusBefore,
                  int intStartOrder,
                  int intStopOrder,
                  string strServiceName
                  )
 {
     this.service      = service;
     this.StatusBefore = StatusBefore;
     // initial after status equal to before status
     this.StatusAfter    = StatusBefore;
     this.intStartOrder  = intStartOrder;
     this.intStopOrder   = intStopOrder;
     this.strServiceName = strServiceName;
 }
        private void RegisterServiceNames(String ServiceName, ServiceControllerStatus Status)
        {
            ServiceLogger.Logger.Info("Started " + System.Reflection.MethodInfo.GetCurrentMethod().Name + "for Service '" + ServiceName + "'");

            if (!_services.ContainsKey(ServiceName))
            {
                _services.Add(ServiceName, Status);
            }
            else
            {
                _services[ServiceName] = Status;
            }

            ServiceLogger.Logger.Info("Completed " + System.Reflection.MethodInfo.GetCurrentMethod().Name);
        }
Ejemplo n.º 38
0
 internal static bool IsInstalled()
 {
     using (ServiceController controller = new ServiceController(ServiceName))
     {
         try
         {
             ServiceControllerStatus status = controller.Status;
         }
         catch
         {
             return(false);
         }
         return(true);
     }
 }
Ejemplo n.º 39
0
        /// Used by the GetServicesInGroup method.
        private ServiceController(string machineName, Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS status)
        {
            if (!CheckMachineName(machineName))
            {
                throw new ArgumentException(SR.Format(SR.BadMachineName, machineName));
            }

            _machineName      = machineName;
            _name             = status.serviceName;
            _displayName      = status.displayName;
            _commandsAccepted = status.controlsAccepted;
            _status           = (ServiceControllerStatus)status.currentState;
            _type             = status.serviceType;
            _statusGenerated  = true;
        }
Ejemplo n.º 40
0
 protected bool ServiceExists()
 {
     try
     {
         using (var c = new ServiceController(ServiceName, MachineName))
         {
             ServiceControllerStatus currentStatus = c.Status;
             return(true);
         }
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
Ejemplo n.º 41
0
 private void waitServiceStatus(ServiceControllerStatus status)
 {
     while (true)
     {
         try
         {
             DCTR_servise.WaitForStatus(status, TimeSpan.FromMilliseconds(500));
             break;
         }
         catch (System.ServiceProcess.TimeoutException)
         {
             continue;
         }
     }
 }
Ejemplo n.º 42
0
 /// <summary>
 /// Maps the status of eam service to value specified in resources.
 /// </summary>
 /// <param name="status"></param>
 /// <returns></returns>
 public static String TranslateServiceStatus(ServiceControllerStatus status)
 {
     if (status == ServiceControllerStatus.Running)
         return Resources.Strings.EAMservice_Running;
     if (status == ServiceControllerStatus.Stopped)
         return Resources.Strings.EAMservice_Stop;
     if (status == ServiceControllerStatus.ContinuePending)
         return Resources.Strings.EAMservice_ContinuePending;
     if (status == ServiceControllerStatus.Paused)
         return Resources.Strings.EAMservice_Paused;
     if (status == ServiceControllerStatus.PausePending)
         return Resources.Strings.EAMservice_PausePending;
     if (status == ServiceControllerStatus.StartPending)
         return Resources.Strings.EAMservice_StartPending;
     if (status == ServiceControllerStatus.StopPending)
         return Resources.Strings.EAMservice_StopPending;
     return "";
 }
 internal ServiceController(string machineName, System.ServiceProcess.NativeMethods.ENUM_SERVICE_STATUS_PROCESS status)
 {
     this.machineName = ".";
     this.name = "";
     this.displayName = "";
     this.eitherName = "";
     if (!SyntaxCheck.CheckMachineName(machineName))
     {
         throw new ArgumentException(Res.GetString("BadMachineName", new object[] { machineName }));
     }
     this.machineName = machineName;
     this.name = status.serviceName;
     this.displayName = status.displayName;
     this.commandsAccepted = status.controlsAccepted;
     this.status = (ServiceControllerStatus) status.currentState;
     this.type = status.serviceType;
     this.statusGenerated = true;
 }
Ejemplo n.º 44
0
        /// <summary>
        /// Checks the status of the given controller, and if it isn't the requested state,
        /// performs the given action, and checks the state again.
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="status"></param>
        /// <param name="changeStatus"></param>
        public static void ChangeServiceStatus(ServiceController controller, ServiceControllerStatus status, Action changeStatus)
        {
            if (controller.Status == status)
            {
                Logger.Debug(controller.ServiceName + " status is good: " + Enum.GetName(typeof(ServiceControllerStatus), status));
                return;
            }

            Logger.Debug(controller.ServiceName + " status is NOT " + Enum.GetName(typeof(ServiceControllerStatus), status) + ". Changing status...");

            changeStatus();

            var timeout = TimeSpan.FromSeconds(3);
            controller.WaitForStatus(status, timeout);
            if (controller.Status == status)
                Logger.Debug(controller.ServiceName + " status changed successfully.");
            else
                throw new InvalidOperationException("Unable to change " + controller.ServiceName + " status to " + Enum.GetName(typeof(ServiceControllerStatus), status));
        }
Ejemplo n.º 45
0
		private Task<bool> TrySetStatus(ServiceControllerStatus status, Action method)
		{
			return Task.Run(() =>
			{
				var timeSpan = TimeSpan.FromSeconds(WaitTime);

				try
				{
					method();
					this.service.WaitForStatus(status, timeSpan);
				}
				catch (System.ServiceProcess.TimeoutException) { }
				catch (InvalidOperationException)
				{
					Task.Delay(timeSpan).Wait(); // force-wait
				}

				return this.CheckStatus(status);
			});
		}
Ejemplo n.º 46
0
		internal ServiceHelper(string servcieName, string serviceFilename)
		{
			_serviceFilename = serviceFilename;
			_serviceName = servcieName;
			_service = new ServiceController(_serviceName);

			_logger = FileLogger.GetLogger("InstallationLog.txt");
			try
			{
				// actually we need to try access ANY of service properties
				// at least once to trigger an exception
				// not neccessarily its name
				_status = _service.Status;
				_isInstalled = true;
			}
			catch (InvalidOperationException)
			{
				_isInstalled = false;
			}
			

		}
Ejemplo n.º 47
0
        /// <summary>
        /// Change the service status
        /// </summary>
        /// <param name="sc"></param>
        /// <param name="newStatus"></param>
        public static void RunServer(ServiceController sc, ServiceControllerStatus newStatus)
        {
            try
              {
            if (sc.Status == newStatus)
              return;

            // TODO: Need better waiting mechanism (ideally show a progress bar here...)
            // for now wait 30 seconds and confirm the new status afterward.
            var waitAmount = new TimeSpan(0, 0, 30);

            switch (newStatus)
            {
              case ServiceControllerStatus.Running:
            //Status("Starting server, please wait...");
            sc.Start();
            sc.WaitForStatus(newStatus, waitAmount);
            break;

              case ServiceControllerStatus.Stopped:
            //Status("Stopping server, please wait...");
            sc.Stop();
            sc.WaitForStatus(newStatus, waitAmount);
            break;

              default:
            throw new Exception("Unsupported action = " + newStatus.ToString());
            }

            if (sc.Status != newStatus)
              throw new ApplicationException("Service is not " + newStatus);

              }
              catch (Exception ex)
              {
            Debug.WriteLine(ex.Message);
            throw;
              }
        }
Ejemplo n.º 48
0
 public static bool StopStartServices(string serviceName, ServiceControllerStatus status)
 {
     bool result = false;
     try
     {
         ServiceController sc = new ServiceController(serviceName);
         if (status == ServiceControllerStatus.StopPending)
         {
             if (sc.Status != ServiceControllerStatus.Stopped)
                 sc.Stop();
         }
         else if (status == ServiceControllerStatus.StartPending)
         {
             if (sc.Status != ServiceControllerStatus.Running)
                 sc.Start();
         }
         result = true;
     }
     catch (Exception)
     {
       
     }
     return result;
 }
Ejemplo n.º 49
0
        internal void MonitorService()
        {
            serviceStatus = ServiceControllerStatus.Stopped;
            System.Threading.Thread.Sleep(3000);

            bool first = true;

            while (RunMonitor)
            {
                try
                {
                    ServiceControllerStatus status = PVServiceManager.GetServiceStatus();

                    if (status != serviceStatus || first || ForceRefresh)
                    {
                        SynchronizationContext.Post(new SendOrPostCallback(delegate
                                                                            {
                                                                                ServiceStatusChangeNotification(status);
                                                                            }), null);

                        //ServiceStatusChangeNotification(svc.Status);
                        first = ForceRefresh; // avoid race - do it twice
                        ForceRefresh = false;
                    }
                    serviceStatus = status;
                }
                catch (Exception)
                {
                    SynchronizationContext.Post(new SendOrPostCallback(delegate
                        {
                            ServiceStatusChangeNotification(ServiceControllerStatus.Stopped);
                        }), null);
                }
                System.Threading.Thread.Sleep(3000);
            }
        }
 private void HandleServiceState(ServiceControllerStatus _status)
 {
     switch (_status)
     {
         case ServiceControllerStatus.Stopped:
             btnStartStopService.Content = "Start";
             lblServiceState.Content = "Service Stopped";
             lblServiceState.Foreground = System.Windows.Media.Brushes.Red;
             break;
         case ServiceControllerStatus.Running:
             btnStartStopService.Content = "Stop";
             lblServiceState.Content = "Service Started";
             lblServiceState.Foreground = System.Windows.Media.Brushes.Green;
             break;
         case ServiceControllerStatus.StartPending:
             btnStartStopService.Content = "Stop";
             lblServiceState.Content = "Service Starting";
             lblServiceState.Foreground = System.Windows.Media.Brushes.Teal;
             break;
         default:
             lblServiceState.Foreground = System.Windows.Media.Brushes.Teal;
             lblServiceState.Content = "Service " + _status.ToString();
             break;
     }
 }
Ejemplo n.º 51
0
 private bool IsRunning()
 {
     if (mediaServer == null || serviceController == null) return false;
     ServiceController serviceController2 = new ServiceController("AV Media Server");
     serviceStatus = serviceController2.Status;
     return (serviceStatus == ServiceControllerStatus.Running);
 }
Ejemplo n.º 52
0
        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();
        }
Ejemplo n.º 53
0
        public MainForm(string[] args)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            OpenSource.UPnP.DText p = new OpenSource.UPnP.DText();
            p.ATTRMARK = "=";
            string[] filePaths = new string[1];

            foreach(string arg in args)
            {
                p[0] = arg;
                switch(p[1].ToUpper())
                {
                    case "-UDN":
                        MediaServerCore.CustomUDN = p[2];
                        break;
                    case "-CACHETIME":
                        MediaServerCore.CacheTime = int.Parse(p[2]);
                        break;
                    case "-INMPR":
                        MediaServerCore.INMPR = !(p[2].ToUpper()=="NO");
                        break;
                }
            }

            // Setup the UI
            transfersSplitter.Visible = viewTransfersPanelMenuItem.Checked;
            transfersListView.Visible = viewTransfersPanelMenuItem.Checked;

            try
            {
                serviceController = new ServiceController("UPnP Media Server");
                serviceStatus = serviceController.Status;
                OpenSource.Utilities.EventLogger.Log(this,System.Diagnostics.EventLogEntryType.Information,"Service control mode...");
            }
            catch (System.InvalidOperationException)
            {
                serviceController = null;
                serviceStatus = ServiceControllerStatus.Stopped;
                OpenSource.Utilities.EventLogger.Log(this,System.Diagnostics.EventLogEntryType.Information,"Stand alone mode...");
            }

            if (serviceController != null)
            {
                // Service controller mode
                serviceMenuItem.Visible = true;

                // Pause State
                pauseServerMenuItem.Visible = false;

                System.Collections.Specialized.ListDictionary channelProperties = new System.Collections.Specialized.ListDictionary();
                channelProperties.Add("port", 12330);
                HttpChannel channel = new HttpChannel(channelProperties,
                    new SoapClientFormatterSinkProvider(),
                    new SoapServerFormatterSinkProvider());
                ChannelServices.RegisterChannel(channel, false);
                OpenSource.Utilities.EventLogger.Log(this,System.Diagnostics.EventLogEntryType.Information,"RegisterChannel");

                if (serviceStatus == ServiceControllerStatus.Running)
                {
                    OpenSource.Utilities.EventLogger.Log(this,System.Diagnostics.EventLogEntryType.Information,"RegisterWellKnownClientType");
                    RemotingConfiguration.RegisterWellKnownClientType(
                        typeof(UPnPMediaServer),
                        "http://localhost:12329/UPnPMediaServer/UPnPMediaServer.soap"
                        );
                    registeredServerType = true;
                }
            }
            else
            {
                // Stand alone mode
                if (registeredServerType == true || standAloneMode == true) return;

                standAloneMode = true;
                serviceMenuItem.Visible = false;

                // Stand alone mode
                mediaServerCore = new MediaServerCore("Media Server (" + System.Windows.Forms.SystemInformation.ComputerName + ")");
                this.mediaServerCore.OnDirectoriesChanged += new MediaServerCore.MediaServerCoreEventHandler(this.Sink_OnDirectoriesChanged);
                mediaServer = new UPnPMediaServer();

                // Pause State
                pauseServerMenuItem.Checked = this.mediaServerCore.IsPaused;
            }

            UpdateServiceUI();

            foreach(string arg in args)
            {
                p[0] = arg;
                switch(p[1].ToUpper())
                {
                    case "-P":
                        filePaths[0] = p[2];
                        try
                        {
                            this.AddDirs(filePaths);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                        break;
                }
            }
        }
 private void HandleServiceState(ServiceControllerStatus _status)
 {
     switch (_status)
     {
         case ServiceControllerStatus.Stopped:
             triggerButton.Content = UI.Start;
             stateLabel.Content = UI.ServiceStopped;
             stateLabel.Foreground = Brushes.Red;
             break;
         case ServiceControllerStatus.Running:
             triggerButton.Content = UI.Stop;
             stateLabel.Content = UI.ServiceStarted;
             stateLabel.Foreground = Brushes.Green;
             break;
         case ServiceControllerStatus.StartPending:
             triggerButton.Content = UI.Stop;
             stateLabel.Content = UI.ServiceStartingFixed;
             stateLabel.Foreground = Brushes.Teal;
             break;
         default:
             triggerButton.Foreground = Brushes.Teal;
             stateLabel.Content = UI.ServiceUnknown;
             stateLabel.Foreground = Brushes.Teal;
             break;
     }
 }
        private ServiceControllerProxy CreateMockedController(
            ServiceControllerStatus? status = ServiceControllerStatus.Running)
        {
            var mockController = new Mock<ServiceControllerProxy>();

            if (status != null)
            {
                mockController.Setup(m => m.Status).Returns(status.Value);
            }
            else
            {
                mockController.Setup(m => m.Status).Throws(new InvalidOperationException());
            }

            return mockController.Object;
        }
Ejemplo n.º 56
0
        internal void StartService(bool useEvents)
        {
            serviceStatus = ServiceControllerStatus.StartPending;

            if (useEvents && PVPublisherManager.ServiceExists)
            {
                try
                {
                    if (PVPublisherManager.GetServiceStatus() == ServiceControllerStatus.Stopped)
                        PVPublisherManager.StartService();
                }
                catch (Exception)
                {
                }
            }

            try
            {
                PVServiceManager.StartService();
                PVServiceManager.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(30000));
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 57
0
        internal void StopService(bool useEvents)
        {
            serviceStatus = ServiceControllerStatus.StopPending;

            if (!useEvents && PVPublisherManager.ServiceExists)
            {
                // leave publisher running unless emit events has been turned off
                // this prevents clients to publisher from failing when the service is offline for maint
                try
                {
                    if (PVPublisherManager.GetServiceStatus() == ServiceControllerStatus.Running)
                        PVPublisherManager.StopService();
                }
                catch (Exception)
                {
                }
            }

            try
            {
                PVServiceManager.StopService();
                PVServiceManager.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(120000));
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 58
0
 private void HandleServiceState(ServiceControllerStatus _status)
 {
     switch (_status)
     {
         case ServiceControllerStatus.Stopped:
             btnStartStopService.Content = UI.Start;
             lblServiceState.Content = UI.ServiceStopped;
             lblServiceState.Foreground = Brushes.Red;
             break;
         case ServiceControllerStatus.Running:
             btnStartStopService.Content = UI.Stop;
             lblServiceState.Content = UI.ServiceStarted;
             lblServiceState.Foreground = Brushes.Green;
             break;
         case ServiceControllerStatus.StartPending:
             btnStartStopService.Content = UI.Stop;
             lblServiceState.Content = UI.ServiceStarting;
             lblServiceState.Foreground = Brushes.Teal;
             break;
         default:
             lblServiceState.Foreground = Brushes.Teal;
             lblServiceState.Content = UI.ServiceUnknown;
             break;
     }
 }
 private static bool CheckServiceStatusDoesNotEqual(string _serviceName, ServiceControllerStatus _status)
 {
     var output = false;
     try
     {
         using (var sc = new ServiceController(_serviceName))
             output = (sc.Status != _status);
     }
     catch
     {
         output = false;
     }
     return output;
 }
Ejemplo n.º 60
0
 private static void ThrowUnableToChangeStatus(string serviceName, ServiceControllerStatus status)
 {
     ThrowUnableToChangeStatus(serviceName, status, null);
 }