/// <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; }
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; }
/// <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; }
public SysTray() { InitSystrayForm(); _lastStatus = CurrentStatus; Initialize(); }
private void RestoreService(ServiceControllerStatus previousStatus) { if (previousStatus == ServiceControllerStatus.Running) { controller.Start(); } else if (previousStatus == ServiceControllerStatus.Paused) { controller.Pause(); } }
private void serviceTimer_Tick (object sender, EventArgs e) { try { lastError = null; lastStatus = serviceController.Status; } catch (Exception ex) { lastStatus = ServiceControllerStatus.Paused; lastError = ex; } UpdateStatus (); }
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); }
static ServiceStatus ToServiceStatus(ServiceControllerStatus status) { switch (status) { case ServiceControllerStatus.StopPending: return ServiceStatus.Stopped; case ServiceControllerStatus.Stopped: return ServiceStatus.Stopped; default: return ServiceStatus.Started; } }
private bool CheckStatus(ServiceControllerStatus status) { try { this.service.Refresh(); return this.service.Status == status; } catch (InvalidOperationException) { return false; } }
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); }
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); }
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(); } } }
public static bool CheckServiceExists(string serviceName) { try { ServiceController sc2 = new ServiceController(serviceName); ServiceControllerStatus status = sc2.Status; return(true); } catch { return(false); } }
public override void WaitForStatus(ServiceControllerStatus desiredStatus) { if (statusSetter == null && Status == desiredStatus) { return; } statusSetter.Join(); if (status != desiredStatus) { throw new ApplicationException(); } }
//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); } } }
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(); }
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); }
/// <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(); }
public static ServiceControllerStatus GetServiceStatus(string serviceName) { ServiceControllerStatus retVal = ServiceControllerStatus.Stopped; using (ServiceController sc = getServiceController(serviceName)) { if (sc != null) { retVal = sc.Status; } } return(retVal); }
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); }
private static ServiceController GetServiceController(string serviceName) { ServiceController service = new ServiceController(serviceName); try { ServiceControllerStatus status = service.Status; } catch { service = null; } return(service); }
/// <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); }
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)); } }
private static bool IsInstalled() { using (ServiceController controller = new ServiceController("ValheimBackupService")) { try { ServiceControllerStatus status = controller.Status; } catch { return(false); } return(true); } }
/// <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; } } } }
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); } }
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; } } }
/// <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); } }
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); } }
private static bool IsInstalled() { using (var controller = new ServiceController("Rust Service Host")) { try { ServiceControllerStatus status = controller.Status; } catch { return(false); } return(true); } }
public bool IsServiceInstalled() { using (ServiceController controller = new ServiceController(SERVICE_NAME)) { try { ServiceControllerStatus status = controller.Status; } catch { return(false); } return(true); } }
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); }
internal static bool IsInstalled() { using (ServiceController controller = new ServiceController(ServiceName)) { try { ServiceControllerStatus status = controller.Status; } catch { return(false); } return(true); } }
/// 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; }
protected bool ServiceExists() { try { using (var c = new ServiceController(ServiceName, MachineName)) { ServiceControllerStatus currentStatus = c.Status; return(true); } } catch (Exception ex) { return(false); } }
private void waitServiceStatus(ServiceControllerStatus status) { while (true) { try { DCTR_servise.WaitForStatus(status, TimeSpan.FromMilliseconds(500)); break; } catch (System.ServiceProcess.TimeoutException) { continue; } } }
/// <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; }
/// <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)); }
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); }); }
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; } }
/// <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; } }
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; }
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; } }
private bool IsRunning() { if (mediaServer == null || serviceController == null) return false; ServiceController serviceController2 = new ServiceController("AV Media Server"); serviceStatus = serviceController2.Status; return (serviceStatus == ServiceControllerStatus.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(); }
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; }
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) { } }
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) { } }
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; }
private static void ThrowUnableToChangeStatus(string serviceName, ServiceControllerStatus status) { ThrowUnableToChangeStatus(serviceName, status, null); }