public void TestMergeMessageWithParametersCallsMerge() { var merged = false; var service = new ServiceController() { Settings = { ServiceUpdateCore = false }, Packages = new MockServicePackageManager() { PackageInstalled = (sender, uri, packageId) => { merged = true; } } }; service.SignalMessage(new ServiceMessage() { Name = "merge", Arguments = new Dictionary<string, string>() { { "uri", "localhost" }, { "packageid", "id" } } }); Assert.IsTrue(merged); service.Dispose(); }
private void CheckServiceStatus() { try { ServiceController sc = new ServiceController("OSAE"); switch (sc.Status) { case ServiceControllerStatus.Running: serviceLabel.Text = "Running"; break; case ServiceControllerStatus.Stopped: serviceLabel.Text = "Stopped"; break; case ServiceControllerStatus.Paused: serviceLabel.Text = "Paused"; break; case ServiceControllerStatus.StopPending: serviceLabel.Text = "Stopping"; break; case ServiceControllerStatus.StartPending: serviceLabel.Text = "Starting"; break; default: serviceLabel.Text = "Status Changing"; break; } } catch (Exception exc) { serviceLabel.Text = "Could not find service"; } }
protected void Page_Load(object sender, EventArgs e) { if (Request.Headers["User-Agent"] != null && (Request.Browser["IsMobileDevice"] == "true" || Request.UserAgent.ToUpper().Contains("MIDP") || Request.UserAgent.ToUpper().Contains("CLDC") || Request.UserAgent.ToLower().Contains("iphone") || Request.UserAgent.ToLower().Contains("avant") || Request.UserAgent.ToLower().Contains("nokia") || Request.UserAgent.ToLower().Contains("pda") || Request.UserAgent.ToLower().Contains("moto") || Request.UserAgent.ToLower().Contains("windows ce") || Request.UserAgent.ToLower().Contains("hand") || Request.UserAgent.ToLower().Contains("mobi") || Request.UserAgent.ToUpper().Contains("HTC") || Request.UserAgent.ToLower().Contains("sony") || Request.UserAgent.ToLower().Contains("panasonic") || Request.UserAgent.ToLower().Contains("blackberry") || Request.UserAgent.ToLower().Contains("240x320") || Request.UserAgent.ToLower().Contains("voda"))) { Response.Redirect("mobile/index.aspx"); } OSAEObjectCollection screens = OSAEObjectManager.GetObjectsByType("SCREEN"); this.SetSessionTimeout(); foreach (OSAEObject s in screens) { HtmlGenericControl li = new HtmlGenericControl("li"); ddlScreens.Controls.Add(li); HtmlGenericControl anchor = new HtmlGenericControl("a"); anchor.Attributes.Add("href", "screens.aspx?id="+s.Name); anchor.InnerText = s.Name; li.Controls.Add(anchor); } ServiceController sc = new ServiceController("OSAE"); if (sc.Status != ServiceControllerStatus.Running) { cog.ImageUrl = "~/Images/cog_red.png"; cog.ToolTip = "OSA service is not running."; } }
public void ConstructWithServiceName() { var controller = new ServiceController(_testService.TestServiceName); Assert.Equal(_testService.TestServiceName, controller.ServiceName); Assert.Equal(_testService.TestServiceDisplayName, controller.DisplayName); Assert.Equal(_testService.TestMachineName, controller.MachineName); Assert.Equal(ServiceType.Win32OwnProcess, controller.ServiceType); }
public void TestServiceProxyType() { var service = new ServiceController(); Assert.AreEqual(typeof(ServiceLoaderProxy), service.ServiceLoaderProxyType); service.Dispose(); }
public void TestMonitoringIsEnabled() { var service = new ServiceController(); Assert.IsTrue(AppDomain.MonitoringIsEnabled); service.Dispose(); }
/// <summary> /// Instantiate a new master server instance. /// </summary> /// <param name="ServiceObject">Optionally supplies the associated /// service instance, else null if the program is not running in /// service mode.</param> public NWMasterServer(ServiceController ServiceObject) { this.ServiceObject = ServiceObject; QueryCombineTimer = new System.Timers.Timer(QUERY_COMBINE_INTERVAL); QueryCombineTimer.AutoReset = false; QueryCombineTimer.Elapsed += new ElapsedEventHandler(QueryCombineTimer_Elapsed); }
/// <summary> /// Inject alternative container and strategy for resolving Service Types /// </summary> public ServiceManager(Container container, ServiceController serviceController) { if (serviceController == null) throw new ArgumentNullException("serviceController"); this.Container = container ?? new Container(); this.ServiceController = serviceController; }
public void TestInitalServiceStateIsStopped() { var service = new ServiceController(); Assert.AreEqual(ServiceStatusType.Stopped, service.Observer.Status); service.Dispose(); }
protected override void OnAfterInstall(System.Collections.IDictionary savedState) { ServiceConfigurator.SetRecoveryOptions(ServiceName()); using (ServiceController pc = new ServiceController(ServiceName())) { pc.Start(); } }
public void With_ServiceStackFunq() { var serviceController = new ServiceController(); serviceController.Register(() => new BasicService()); var request = new BasicRequest(); Console.WriteLine("With_TypedArguments(): {0}", Measure(() => serviceController.Execute(request), Times)); }
public void Can_execute_BasicService() { var serviceController = new ServiceController(); serviceController.Register(() => new BasicService()); var result = serviceController.Execute(new BasicRequest()) as BasicRequestResponse; Assert.That(result, Is.Not.Null); }
public void TestNopMessageReturnsTrue() { var service = new ServiceController(); Assert.IsTrue(service.SignalMessage(new ServiceMessage() { Name = "nop" })); service.Dispose(); }
public NewConnection() { InitializeComponent(); communicator = ServiceController.Communicator; serverVariables = new ServerVariables(); DataContext = serverVariables; OnDialogContentRequest += NewConnection_OnDialogContentRequest; }
public void Can_execute_RestTestService() { var serviceController = new ServiceController(); serviceController.Register(() => new RestTestService()); var result = serviceController.Execute(new RestTest()) as RestTestResponse; Assert.That(result, Is.Not.Null); Assert.That(result.MethodName, Is.EqualTo("Execute")); }
public void TestJunkMessageReturnsFalse() { var service = new ServiceController(); Assert.IsFalse(service.SignalMessage(new ServiceMessage() { Name = "junk" })); service.Dispose(); }
public void With_Expressions() { var requestType = typeof(BasicRequest); var serviceController = new ServiceController(); serviceController.Register(requestType, typeof(BasicService)); var request = new BasicRequest(); Console.WriteLine("With_Expressions(): {0}", Measure(() => serviceController.Execute(request), Times)); }
protected Service(ServiceType type, string id, ServiceController controller) { if (type == null) throw new ArgumentNullException ("type"); if (id == null) throw new ArgumentNullException ("id"); if (id.Length == 0) throw new ArgumentException ("The id cannot be an empty string.", "id"); if (controller == null) throw new ArgumentNullException ("controller"); this.type = type; this.id = id; this.controller = controller; }
public void NativeFunq_Perf() { var serviceController = new ServiceController(); RegisterServices(serviceController, GetNativeFunqTypeFactory()); StoreAndGetCustomers(serviceController); var request = new GetCustomer { CustomerId = 2 }; Console.WriteLine("NativeFunq_Perf(): {0}", Measure(() => serviceController.Execute(request), Times)); }
public static void EnumerateDeviceService() { ServiceController[] devices = ServiceController.GetDevices(); Assert.True(devices.Length != 0); ServiceController actual = new ServiceController(devices[0].ServiceName, "."); Assert.Equal(devices[0].Status, actual.Status); Assert.Equal(devices[0].ServiceName, actual.ServiceName); Assert.Equal(devices[0].DisplayName, actual.DisplayName); Assert.Equal(devices[0].ServiceType, actual.ServiceType); Assert.Equal(devices[0].MachineName, actual.MachineName); }
public static void StopService(string server, string service) { Console.WriteLine("About to stop the {0} Service", service); ServiceController svcCtrl; if (server.Length != 0) svcCtrl = new ServiceController(server, service); else svcCtrl = new ServiceController(service); svcCtrl.Stop(); }
public void TestNonNullProperties() { var service = new ServiceController(); Assert.IsNotNull(service.Observer); Assert.IsNotNull(service.Polling); Assert.IsNotNull(service.WriteConfig); Assert.IsNotNull(service.Arguments); Assert.IsNotNull(service.Settings); Assert.IsNotNull(service.Packages); service.Dispose(); }
public void Can_execute_BasicService_from_dynamic_Type() { var requestType = typeof(BasicRequest); var serviceController = new ServiceController(); serviceController.Register(requestType, typeof(BasicService)); object request = Activator.CreateInstance(requestType); var result = serviceController.Execute(request) as BasicRequestResponse; Assert.That(result, Is.Not.Null); }
public void TestMergeMessageReturnsTrue() { var service = new ServiceController() { Settings = { ServiceUpdateCore = false } }; Assert.IsTrue(service.SignalMessage(new ServiceMessage() { Name = "merge" })); service.Dispose(); }
public void Easy_syntax_love() { ServiceController controller = null; ActorFactory<ServiceController> factory = StateMachineActorFactory.Create<ServiceWorkflow, ServiceController>(inbox => { controller = new ServiceController(inbox); return controller; }, x => { x.AccessCurrentState(s => s.CurrentState); x.Initially() .When(e => e.Started) .Then(i => i.OnStart()) .TransitionTo(s => s.Running); x.During(s => s.Running) .When(e => e.Stopped) .Then(i => i.OnStop()) .Finalize() .When(e => e.Paused) .Then(i => i.OnPause) .TransitionTo(s => s.Idle); x.During(s => s.Idle) .When(e => e.Started) .TransitionTo(s => s.Running); }); ActorInstance service = factory.GetActor(); service.Send(new Pause()); service.Send(new Start()); service.Send(new Start()); service.Send(new Stop()); try { controller.Started.WaitUntilCompleted(2.Seconds()).ShouldBeTrue("Never received start"); controller.Paused.WaitUntilCompleted(2.Seconds()).ShouldBeTrue("Never received pause"); controller.Stopped.WaitUntilCompleted(2.Seconds()).ShouldBeTrue("Never received stop"); } finally { service.Exit(); } }
public void TestConfigWriteDispatchedBeginDelegateCalled() { var begin = false; var service = new ServiceController() { ServiceLoaderProxy = new MockServiceLoaderProxy(), WriteServiceConfigBegin = controller => begin = true }; service.WriteServiceConfig(); Assert.IsTrue(begin); service.Dispose(); }
public void TestConfigWriteDispatchedEndDelegateCalled() { var end = false; var service = new ServiceController() { ServiceLoaderProxy = new MockServiceLoaderProxy(), WriteServiceConfigEnd = controller => end = true }; service.WriteServiceConfig(); Assert.IsTrue(end); service.Dispose(); }
public void TestFromStoppedEndsAsStarted() { var service = new ServiceController() { Packages = new MockServicePackageManager(), Observer = { Status = ServiceStatusType.Stopped }, ServiceLoaderProxyType = typeof(MockServiceLoaderProxy) }; service.MergePackage("localhost", "id"); Assert.AreEqual(ServiceStatusType.Started, service.Observer.Status); service.Dispose(); }
public void TestObservableStarted() { var service = new ServiceController() { Packages = new MockServicePackageManager(), Settings = { ServiceUpdateCore = false }, ServiceLoaderProxyType = typeof(MockServiceLoaderProxy) }; service.ExecuteMessage(new ServiceMessage()); Assert.AreEqual(ServiceStatusType.Started, service.Observer.Status); service.Dispose(); }
public void TestMethodCalledExecuteMessage() { var service = new ServiceController() { Packages = new MockServicePackageManager(), Settings = { ServiceUpdateCore = false }, ServiceLoaderProxyType = typeof(MockServiceLoaderProxy) }; service.ExecuteMessage(new ServiceMessage()); Assert.IsTrue(((MockServiceLoaderProxy)service.ServiceLoaderProxy).OnExecuteMessage); service.Dispose(); }
/// <summary> /// 启动 /// </summary> /// <param name="server">服务器</param> /// <param name="mode">模式</param> /// <returns>是否成功</returns> public bool Start(Models.Server server, Models.Mode mode) { if (!File.Exists("bin\\Redirector.exe")) { return(false); } // 生成驱动文件路径 var driver = String.Format("{0}\\drivers\\netfilter2.sys", Environment.SystemDirectory); // 检查驱动是否存在 if (!File.Exists(driver)) { // 生成系统版本 var version = $"{Environment.OSVersion.Version.Major.ToString()}.{Environment.OSVersion.Version.Minor.ToString()}"; // 检查系统版本并复制对应驱动 try { switch (version) { case "10.0": File.Copy("bin\\Win-10.sys", driver); Utils.Logging.Info("已复制 Win10 驱动"); break; case "6.3": case "6.2": File.Copy("bin\\Win-8.sys", driver); Utils.Logging.Info("已复制 Win8 驱动"); break; case "6.1": case "6.0": File.Copy("bin\\Win-7.sys", driver); Utils.Logging.Info("已复制 Win7 驱动"); break; default: Utils.Logging.Info($"不支持的系统版本:{version}"); return(false); } } catch (Exception e) { Utils.Logging.Info("复制驱动文件失败"); Utils.Logging.Info(e.ToString()); return(false); } // 注册驱动文件 var result = nfapinet.NFAPI.nf_registerDriver("netfilter2"); if (result != nfapinet.NF_STATUS.NF_STATUS_SUCCESS) { Utils.Logging.Info($"注册驱动失败,返回值:{result}"); return(false); } } try { var service = new ServiceController("netfilter2"); if (service.Status == ServiceControllerStatus.Stopped) { service.Start(); } } catch (Exception e) { Utils.Logging.Info(e.ToString()); var result = nfapinet.NFAPI.nf_registerDriver("netfilter2"); if (result != nfapinet.NF_STATUS.NF_STATUS_SUCCESS) { Utils.Logging.Info($"注册驱动失败,返回值:{result}"); return(false); } } var processes = ""; foreach (var proc in mode.Rule) { processes += proc; processes += ","; } processes = processes.Substring(0, processes.Length - 1); Instance = MainController.GetProcess(); Instance.StartInfo.FileName = "bin\\Redirector.exe"; var fallback = ""; if (server.Type != "Socks5") { fallback = $"-r 127.0.0.1:{Global.Settings.Socks5LocalPort} -p \"{processes}\""; } else { var result = Utils.DNS.Lookup(server.Hostname); if (result == null) { Utils.Logging.Info("无法解析服务器 IP 地址"); return(false); } fallback = $"-r {result.ToString()}:{server.Port} -p \"{processes}\""; if (!String.IsNullOrWhiteSpace(server.Username) && !String.IsNullOrWhiteSpace(server.Password)) { fallback += $" -username \"{server.Username}\" -password \"{server.Password}\""; } } Instance.StartInfo.Arguments = fallback + $" -t {Global.Settings.RedirectorTCPPort}"; Instance.OutputDataReceived += OnOutputDataReceived; Instance.ErrorDataReceived += OnOutputDataReceived; State = Models.State.Starting; Instance.Start(); Instance.BeginOutputReadLine(); Instance.BeginErrorReadLine(); var IsFallback = false; for (int i = 0; i < 1000; i++) { Thread.Sleep(10); if (State == Models.State.Started) { return(true); } if (State == Models.State.Stopped) { if (!IsFallback) { IsFallback = true; Stop(); Utils.Logging.Info($"尝试去除 \"-t {Global.Settings.RedirectorTCPPort}\" 参数后启动 \"bin\\Redirector.exe\""); Instance.StartInfo.Arguments = FallBackArg; Utils.Logging.Info($"当前 \"bin\\Redirector.exe\" 启动参数为 \"{Instance.StartInfo.Arguments}\""); Global.Settings.RedirectorTCPPort = 2800; Instance.CancelOutputRead(); Instance.CancelErrorRead(); Instance.OutputDataReceived += OnOutputDataReceived; Instance.ErrorDataReceived += OnOutputDataReceived; State = Models.State.Starting; Instance.Start(); Instance.BeginOutputReadLine(); Instance.BeginErrorReadLine(); } else { Utils.Logging.Info("NF 进程启动失败"); Stop(); return(false); } } } Utils.Logging.Info("NF 进程启动超时"); Stop(); return(false); }
// The main entry point for the process static void Main(params string[] args) { #if (!DEBUG) if (System.Environment.UserInteractive) { string parameter = string.Concat(args); ServiceController svc = ServiceController.GetServices().Where(s => s.ServiceName == "OpenThermGateway2MQTTService").FirstOrDefault(); switch (parameter) { case "--install": if (svc == null) { ManagedInstallerClass.InstallHelper(new string[] { "/LogFile=", Assembly.GetExecutingAssembly().Location }); } break; case "--uninstall": if (svc != null) { ManagedInstallerClass.InstallHelper(new string[] { "/u", "/LogFile=", Assembly.GetExecutingAssembly().Location }); } break; case "--start": if (svc != null) { if (svc.Status == ServiceControllerStatus.Stopped) { svc.Start(); } } break; case "--stop": if (svc != null) { if (svc.Status == ServiceControllerStatus.Running) { svc.Stop(); } } break; case "--pause": if (svc != null) { if (svc.Status == ServiceControllerStatus.Running) { svc.Pause(); } } break; case "--continue": if (svc != null) { if (svc.Status == ServiceControllerStatus.Paused) { svc.Continue(); } } break; } } else { ServiceBase.Run(new OpenThermGateway2MQTTService()); } #else OpenThermGateway2MQTTService service = new OpenThermGateway2MQTTService(); service.OnStart(args); System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); #endif }
/// <summary> /// Main entry point of the application. /// </summary> static void Main(string[] args) { try { // Initialize the service to start ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new ServiceNowTeamFoundationSyncService() }; // In interactive mode ? if (Environment.UserInteractive) { // In debug mode ? if (System.Diagnostics.Debugger.IsAttached) { // Simulate the services execution RunInteractiveServices(ServicesToRun); } else { try { bool hasCommands = false; // Having an interactive command? if (HasCommand(args, "interactive")) { // Simulate the services execution RunInteractiveServices(ServicesToRun); } // Having an install command ? if (HasCommand(args, "install")) { ManagedInstallerClass.InstallHelper(new String[] { typeof(Program).Assembly.Location }); hasCommands = true; } // Having a start command ? if (HasCommand(args, "start")) { foreach (var service in ServicesToRun) { ServiceController sc = new ServiceController(service.ServiceName); sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)); } hasCommands = true; } // Having a stop command ? if (HasCommand(args, "stop")) { foreach (var service in ServicesToRun) { ServiceController sc = new ServiceController(service.ServiceName); sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)); } hasCommands = false; } // Having an uninstall command ? if (HasCommand(args, "uninstall")) { ManagedInstallerClass.InstallHelper(new String[] { "/u", typeof(Program).Assembly.Location }); hasCommands = true; } // If we don't have commands we print usage message if (!hasCommands) { Console.WriteLine("Usage : {0} [command] [command ...]", Environment.GetCommandLineArgs()); Console.WriteLine("Commands : "); Console.WriteLine(" - interactive : Run the service in interactive mode"); Console.WriteLine(" - install : Install the services"); Console.WriteLine(" - uninstall : Uninstall the services"); Console.WriteLine(" - start : start the services"); Console.WriteLine(" - stop : stop the services"); } } catch (Exception ex) { var oldColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error : {0}", ex.GetBaseException().Message); Console.ForegroundColor = oldColor; } } } else { // Normal service execution ServiceBase.Run(ServicesToRun); } } catch { } }
public async Task StartContainersAsync(IExecutionContext executionContext, object data) { Trace.Entering(); ArgUtil.NotNull(executionContext, nameof(executionContext)); List <ContainerInfo> containers = data as List <ContainerInfo>; ArgUtil.NotNull(containers, nameof(containers)); // Check whether we are inside a container. // Our container feature requires to map working directory from host to the container. // If we are already inside a container, we will not able to find out the real working direcotry path on the host. #if OS_WINDOWS // service CExecSvc is Container Execution Agent. ServiceController[] scServices = ServiceController.GetServices(); if (scServices.Any(x => String.Equals(x.ServiceName, "cexecsvc", StringComparison.OrdinalIgnoreCase) && x.Status == ServiceControllerStatus.Running)) { throw new NotSupportedException(StringUtil.Loc("AgentAlreadyInsideContainer")); } #else var initProcessCgroup = File.ReadLines("/proc/1/cgroup"); if (initProcessCgroup.Any(x => x.IndexOf(":/docker/", StringComparison.OrdinalIgnoreCase) >= 0)) { throw new NotSupportedException(StringUtil.Loc("AgentAlreadyInsideContainer")); } #endif #if OS_WINDOWS // Check OS version (Windows server 1803 is required) object windowsInstallationType = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "InstallationType", defaultValue: null); ArgUtil.NotNull(windowsInstallationType, nameof(windowsInstallationType)); object windowsReleaseId = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ReleaseId", defaultValue: null); ArgUtil.NotNull(windowsReleaseId, nameof(windowsReleaseId)); executionContext.Debug($"Current Windows version: '{windowsReleaseId} ({windowsInstallationType})'"); if (int.TryParse(windowsReleaseId.ToString(), out int releaseId)) { if (!windowsInstallationType.ToString().StartsWith("Server", StringComparison.OrdinalIgnoreCase) || releaseId < 1803) { throw new NotSupportedException(StringUtil.Loc("ContainerWindowsVersionRequirement")); } } else { throw new ArgumentOutOfRangeException(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ReleaseId"); } #endif // Check docker client/server version DockerVersion dockerVersion = await _dockerManger.DockerVersion(executionContext); ArgUtil.NotNull(dockerVersion.ServerVersion, nameof(dockerVersion.ServerVersion)); ArgUtil.NotNull(dockerVersion.ClientVersion, nameof(dockerVersion.ClientVersion)); #if OS_WINDOWS Version requiredDockerVersion = new Version(17, 6); #else Version requiredDockerVersion = new Version(17, 12); #endif if (dockerVersion.ServerVersion < requiredDockerVersion) { throw new NotSupportedException(StringUtil.Loc("MinRequiredDockerServerVersion", requiredDockerVersion, _dockerManger.DockerPath, dockerVersion.ServerVersion)); } if (dockerVersion.ClientVersion < requiredDockerVersion) { throw new NotSupportedException(StringUtil.Loc("MinRequiredDockerClientVersion", requiredDockerVersion, _dockerManger.DockerPath, dockerVersion.ClientVersion)); } // Clean up containers left by previous runs executionContext.Debug($"Delete stale containers from previous jobs"); var staleContainers = await _dockerManger.DockerPS(executionContext, $"--all --quiet --no-trunc --filter \"label={_dockerManger.DockerInstanceLabel}\""); foreach (var staleContainer in staleContainers) { int containerRemoveExitCode = await _dockerManger.DockerRemove(executionContext, staleContainer); if (containerRemoveExitCode != 0) { executionContext.Warning($"Delete stale containers failed, docker rm fail with exit code {containerRemoveExitCode} for container {staleContainer}"); } } executionContext.Debug($"Delete stale container networks from previous jobs"); int networkPruneExitCode = await _dockerManger.DockerNetworkPrune(executionContext); if (networkPruneExitCode != 0) { executionContext.Warning($"Delete stale container networks failed, docker network prune fail with exit code {networkPruneExitCode}"); } // Create local docker network for this job to avoid port conflict when multiple agents run on same machine. // All containers within a job join the same network await CreateContainerNetworkAsync(executionContext, _containerNetwork); containers.ForEach(container => container.ContainerNetwork = _containerNetwork); foreach (var container in containers) { await StartContainerAsync(executionContext, container); } foreach (var container in containers.Where(c => !c.IsJobContainer)) { await ContainerHealthcheck(executionContext, container); } }
static void Main(string[] args) { //Added by Tejaswi for testing // ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http; PrintLogo(); PortBridgeAgentSection settings = ConfigurationManager.GetSection("portBridgeAgent") as PortBridgeAgentSection; if (settings != null) { serviceNamespace = settings.ServiceNamespace; issuerName = settings.IssuerName; issuerSecret = settings.IssuerSecret; } if (!ParseCommandLine(args)) { PrintUsage(); return; } PortBridgeClientForwarderHost host = new PortBridgeClientForwarderHost(); if (settings != null && settings.PortMappings.Count > 0) { foreach (PortMappingElement mapping in settings.PortMappings) { List <IPRange> firewallRules = new List <IPRange>(); if (mapping.FirewallRules != null && mapping.FirewallRules.Count > 0) { foreach (FirewallRuleElement rule in mapping.FirewallRules) { if (!string.IsNullOrEmpty(rule.SourceRangeBegin) && !string.IsNullOrEmpty(rule.SourceRangeEnd)) { firewallRules.Add(new IPRange(IPAddress.Parse(rule.SourceRangeBegin), IPAddress.Parse(rule.SourceRangeEnd))); } else if (!string.IsNullOrEmpty(rule.Source)) { firewallRules.Add(new IPRange(IPAddress.Parse(rule.Source))); } } } if (mapping.LocalTcpPort.HasValue) { if (!string.IsNullOrEmpty(mapping.LocalPipe) || !string.IsNullOrEmpty(mapping.RemotePipe)) { throw new ConfigurationErrorsException(string.Format("LocalTcpPort {0} defined with incompatible other settings", mapping.LocalTcpPort.Value)); } else if (!mapping.RemoteTcpPort.HasValue) { throw new ConfigurationErrorsException(string.Format("LocalTcpPort {0} does not have a matching RemoteTcpPort defined", mapping.LocalTcpPort.Value)); } host.Forwarders.Add(new TcpClientConnectionForwarder(serviceNamespace, issuerName, issuerSecret, mapping.TargetHost, mapping.LocalTcpPort.Value, mapping.RemoteTcpPort.Value, mapping.BindTo, useHybrid, firewallRules)); } if (!string.IsNullOrEmpty(mapping.LocalPipe)) { if (mapping.LocalTcpPort.HasValue || mapping.RemoteTcpPort.HasValue) { throw new ConfigurationErrorsException(string.Format("LocalPipe {0} defined with incompatible other settings", mapping.LocalPipe)); } else if (string.IsNullOrEmpty(mapping.RemotePipe)) { throw new ConfigurationErrorsException(string.Format("LocalPipe {0} does not have a matching RemotePipe defined", mapping.LocalPipe)); } host.Forwarders.Add(new NamedPipeClientConnectionForwarder(serviceNamespace, issuerName, issuerSecret, mapping.TargetHost, mapping.LocalPipe, mapping.RemotePipe, useHybrid)); } } } else { List <IPRange> firewallRules = new List <IPRange>(); firewallRules.Add(new IPRange(IPAddress.Loopback)); host.Forwarders.Add(new TcpClientConnectionForwarder(serviceNamespace, issuerName, issuerSecret, cmdlineTargetHost, fromPort, toPort, null, useHybrid, firewallRules)); } if (!runOnConsole) { ServiceController sc = new ServiceController("PortBridgeAgentService"); try { var status = sc.Status; } catch (SystemException) { runOnConsole = true; } } if (runOnConsole) { try { host.Open(); Console.WriteLine("Press [ENTER] to exit."); Console.ReadLine(); host.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } else { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new PortBridgeAgentService(host) }; ServiceBase.Run(ServicesToRun); } }
public void ConstructWithDisplayName() { var controller = new ServiceController(_testService.TestServiceDisplayName); AssertExpectedProperties(controller); }
public virtual object ExecuteMessage(IMessage dto, IRequest req) { return(ServiceController.ExecuteMessage(dto, req)); }
public unsafe void Install() { string username = Username; string password = Password; if (ServiceCommandLine == null) { string processName = Process.GetCurrentProcess().MainModule.FileName; string entryPointName = System.Reflection.Assembly.GetEntryAssembly().Location; string arguments = ServiceName; // if process and entry point aren't the same then we are running hosted so pass // in the entrypoint as the first argument if (!string.Equals(processName, entryPointName, StringComparison.OrdinalIgnoreCase)) { arguments = $"\"{entryPointName}\" {arguments}"; } ServiceCommandLine = $"\"{processName}\" {arguments}"; } // Build servicesDependedOn string string servicesDependedOn = null; if (ServicesDependedOn.Length > 0) { StringBuilder buff = new StringBuilder(); for (int i = 0; i < ServicesDependedOn.Length; ++i) { //The servicesDependedOn need to be separated by a null buff.Append(ServicesDependedOn[i]); buff.Append('\0'); } // an extra null at the end indicates end of list. buff.Append('\0'); servicesDependedOn = buff.ToString(); } // Open the service manager using (var serviceManagerHandle = new SafeServiceHandle(Interop.Advapi32.OpenSCManager(null, null, Interop.Advapi32.ServiceControllerOptions.SC_MANAGER_ALL))) { if (serviceManagerHandle.IsInvalid) { throw new InvalidOperationException("Cannot open Service Control Manager"); } // Install the service using (var serviceHandle = new SafeServiceHandle(Interop.Advapi32.CreateService(serviceManagerHandle, ServiceName, DisplayName, Interop.Advapi32.ServiceAccessOptions.ACCESS_TYPE_ALL, Interop.Advapi32.ServiceTypeOptions.SERVICE_TYPE_WIN32_OWN_PROCESS, (int)StartType, Interop.Advapi32.ServiceStartErrorModes.ERROR_CONTROL_NORMAL, ServiceCommandLine, null, IntPtr.Zero, servicesDependedOn, username, password))) { if (serviceHandle.IsInvalid) { throw new Win32Exception("Cannot create service"); } // A local variable in an unsafe method is already fixed -- so we don't need a "fixed { }" blocks to protect // across the p/invoke calls below. if (Description.Length != 0) { Interop.Advapi32.SERVICE_DESCRIPTION serviceDesc = new Interop.Advapi32.SERVICE_DESCRIPTION(); serviceDesc.description = Marshal.StringToHGlobalUni(Description); bool success = Interop.Advapi32.ChangeServiceConfig2(serviceHandle, Interop.Advapi32.ServiceConfigOptions.SERVICE_CONFIG_DESCRIPTION, ref serviceDesc); Marshal.FreeHGlobal(serviceDesc.description); if (!success) { throw new Win32Exception("Cannot set description"); } } // Start the service after creating it using (ServiceController svc = new ServiceController(ServiceName)) { if (svc.Status != ServiceControllerStatus.Running) { svc.Start(); if (!ServiceName.StartsWith("PropagateExceptionFromOnStart")) { svc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(120)); } } } } } }
/// <summary> /// 检查服务存在的存在性 /// </summary> /// <param name="serviceName">服务名</param> /// <returns>存在返回 true,否则返回 false;</returns> public static bool IsServiceIsExisted(string serviceName) { ServiceController[] services = ServiceController.GetServices(); return(services.Any(s => s.ServiceName.ToLower() == serviceName.ToLower())); }
private void OnTimer(object sender, System.Timers.ElapsedEventArgs args) { EventLog.WriteEntry("FastIR Agent: check for order...", EventLogEntryType.Information); //Get keys P.URL = ReadKey("URL"); P.Port = ReadKey("Port"); P.APIKey = ReadKey("APIKey"); P.lpk = ReadKey("PUBLIC_SSL"); string exe = Process.GetCurrentProcess().MainModule.FileName; P.ApplicationPath = Path.GetDirectoryName(exe); // if (P.Port.Equals(null) || P.URL.Equals(null) || P.lpk.Equals(null) || P.APIKey.Equals(null)) { EventLog.WriteEntry("FastIR Agent: Bad URL, Port, or SSL Public key in the configuration...", EventLogEntryType.Error); ServiceController sc = new ServiceController("FastIR"); sc.Stop(); sc.Close(); } else { EventLog.WriteEntry("FastIR Agent: URL: " + P.URL + ":" + P.Port + ".", EventLogEntryType.Information); NetworkFastIR prop = new NetworkFastIR(P.URL, P.Port, P.lpk); ret r = prop.query(""); if (r.SSL_status) { ReturnJson rj; try { rj = JsonConvert.DeserializeObject <ReturnJson>(r.Web_return); EventLog.WriteEntry("FastIR Agent: Connection established to the server", EventLogEntryType.Information); //Get new FastIR binary string arch = null; if (Environment.Is64BitOperatingSystem) { arch = "x64"; } else { arch = "x86"; } string sha256 = ""; try { sha256 = GetSHA256(P.ApplicationPath + "\\FastIR.exe"); } catch { } string POST = "APIKey=" + P.APIKey + "&sha256=" + sha256 + "&arch=" + arch; r = prop.query("getbinary/", POST); if (r.SSL_status) { try { rj = JsonConvert.DeserializeObject <ReturnJson>(r.Web_return); } catch { rj = null; } if (rj.Equals(null)) { EventLog.WriteEntry("FastIR Agent: bad json from the server", EventLogEntryType.Error); } else if (rj.Return.Equals("KO")) { EventLog.WriteEntry("FastIR Agent: bad request: " + rj.Data, EventLogEntryType.Error); } else { if (rj.Binary.Equals("1")) { EventLog.WriteEntry("FastIR Agent: new FastIR binary available", EventLogEntryType.Information); try { byte[] data = Convert.FromBase64String(rj.Data); File.WriteAllBytes(P.ApplicationPath + "\\FastIR.exe", data); } catch { EventLog.WriteEntry("FastIR Agent: cannot download the new FastIR binary", EventLogEntryType.Error); } } else { EventLog.WriteEntry("FastIR Agent: no new FastIR binary", EventLogEntryType.Information); } } } else { EventLog.WriteEntry("FastIR Agent: Bad SSL or URL", EventLogEntryType.Error); } //Get Order POST = "APIKey=" + P.APIKey + "&hostname=" + Dns.GetHostName(); r = prop.query("getorder/", POST); if (r.SSL_status) { try { rj = JsonConvert.DeserializeObject <ReturnJson>(r.Web_return); } catch { rj = null; } if (rj.Equals(null)) { EventLog.WriteEntry("FastIR Agent: bad json from the server", EventLogEntryType.Error); } else if (rj.Return.Equals("KO")) { EventLog.WriteEntry("FastIR Agent: bad request: " + rj.Data, EventLogEntryType.Error); } else { if (rj.Order.Equals("1")) { EventLog.WriteEntry("FastIR Agent: an order exist for the machine: " + Dns.GetHostName(), EventLogEntryType.Information); try { PECheck pe = new PECheck(); byte[] data = Convert.FromBase64String(rj.Data); File.WriteAllBytes(P.ApplicationPath + "\\FastIR.conf", data); EventLog.WriteEntry("FastIR Agent: the new config file is created.", EventLogEntryType.Information); if (pe.checkfile(P.ApplicationPath + "\\FastIR.exe")) { using (Process process = new Process()) { EventLog.WriteEntry("FastIR Agent: execution of the collect.", EventLogEntryType.Information); process.StartInfo.FileName = P.ApplicationPath + "\\FastIR.exe"; process.StartInfo.Arguments = "--profile " + P.ApplicationPath + "\\FastIR.conf"; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); } } else { EventLog.WriteEntry("FastIR Agent: bad signature.", EventLogEntryType.Error); } } catch { EventLog.WriteEntry("FastIR Agent: cannot download the config file", EventLogEntryType.Error); } } else { EventLog.WriteEntry("FastIR Agent: no order for the machine: " + Dns.GetHostName(), EventLogEntryType.Information); } } } else { EventLog.WriteEntry("FastIR Agent: Bad SSL or URL", EventLogEntryType.Error); } } catch { EventLog.WriteEntry("FastIR Agent: bad json from the server", EventLogEntryType.Error); } } else { EventLog.WriteEntry("FastIR Agent: Bad SSL or URL", EventLogEntryType.Error); } } }
private void Reinstall(ServiceController serviceController, string ravenServerDir, List <string> serviceArgs) { StopInternal(serviceController); UninstallInternal(serviceController); InstallInternal(serviceController, ravenServerDir, serviceArgs); }
public static bool IsServiceInstalled(string serviceName) { var services = ServiceController.GetServices(); return(services.Any(service => service.ServiceName == serviceName)); }
public void FTR2LO_Server() { string _modulename = "FTR2LO_Server"; FTR2LO_Log.FTR2LO_log.do_log(_modulename, (int)FTR2LO_log.LogLevel.DEBUG, "Inside FTR2LO_Server.\n"); AppSettingsReader appsettingsreader = new AppSettingsReader(); try { Uri baseAddr = new Uri("http://localhost:41433/WCFService1"); localHost = new ServiceHost(typeof(FTR2LO), baseAddr); localHost.AddServiceEndpoint(typeof(IFTR2LO), new WSHttpBinding(), "FTR2LO_InternalService"); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; localHost.Description.Behaviors.Add(smb); localHost.Open(); FTR2LO_Log.FTR2LO_log.do_log(_modulename, (int)FTR2LO_log.LogLevel.DEBUG, "Internal Service Host started"); } catch (Exception ex) { FTR2LO_Log.FTR2LO_log.do_log(_modulename, (int)FTR2LO_log.LogLevel.DEBUG, "Problem starting Internal Service Host. Exception: " + ex.ToString()); } // log the status of LO service string service_status_lo = GetWindowsServiceStatus(Convert.ToString(appsettingsreader.GetValue("LOservicename", String.Empty.GetType()))); FTR2LO_Log.FTR2LO_log.do_log(_modulename, (int)FTR2LO_Log.FTR2LO_log.LogLevel.DEBUG, "Lights-Out Service status: " + service_status_lo); string service_status_ftr = GetWindowsServiceStatus(Convert.ToString(appsettingsreader.GetValue("FTRservicename", String.Empty.GetType()))); string service_status_ftr_old = ""; FTR2LO_Log.FTR2LO_log.do_log(_modulename, (int)FTR2LO_Log.FTR2LO_log.LogLevel.DEBUG, "Argus TV Service status: " + service_status_ftr); //Loop and wait until FTR services is running int countdown = 30; int counter = countdown; while (true) { // break if FTR is not installed (because maybe it is installed remotely) if (service_status_ftr == "Not installed.") { break; } System.Threading.Thread.Sleep(1000); // break if FTR services is running if (service_status_ftr == ServiceControllerStatus.Running.ToString()) { break; } counter = counter - 1; if (counter <= 0) { counter = countdown; TimeSpan timeout = TimeSpan.FromMilliseconds(60 * 1000); FTR2LO_Log.FTR2LO_log.do_log(_modulename, (int)FTR2LO_Log.FTR2LO_log.LogLevel.DEBUG, "Trying to start Argus TV Service ...."); ServiceController FTRservicecontroller = new ServiceController(Convert.ToString(appsettingsreader.GetValue("FTRservicename", String.Empty.GetType()))); try { FTRservicecontroller.Start(); FTRservicecontroller.WaitForStatus(ServiceControllerStatus.Running, timeout); } catch (Exception ex) { FTR2LO_Log.FTR2LO_log.do_log(_modulename, (int)FTR2LO_Log.FTR2LO_log.LogLevel.DEBUG, "Exception starting Argus TV Service\n" + ex.ToString()); } finally { if (FTRservicecontroller != null) { ((IDisposable)FTRservicecontroller).Dispose(); } } } service_status_ftr_old = service_status_ftr; service_status_ftr = GetWindowsServiceStatus(Convert.ToString(appsettingsreader.GetValue("FTRservicename", String.Empty.GetType()))); // check if status of FTR has changed and if so, update log file if (!(service_status_ftr == service_status_ftr_old)) { FTR2LO_Log.FTR2LO_log.do_log(_modulename, (int)FTR2LO_Log.FTR2LO_log.LogLevel.DEBUG, "Argus TV Service status: " + service_status_ftr); } } // timer1 is for scheduled run of ftr2lo_main() FTR2LO_Log.FTR2LO_log.do_log(_modulename, (int)FTR2LO_log.LogLevel.INFO, "Setting refresh timer to " + Ftr2LoService.config.RefreshIntervalInMins + " minutes."); this.timer1.AutoReset = true; this.timer1.Interval = 60000 * Convert.ToInt32(Ftr2LoService.config.RefreshIntervalInMins); // this.timer1.Interval = 1000 * 60 * Convert.ToInt32(appsettingsreader.GetValue("scheduledIntervalInMinutes", Int32.MaxValue.GetType())); this.timer1.Enabled = true; this.timer1.Elapsed += new ElapsedEventHandler(onTimer1Elapsed); this.timer1.Start(); InitializeServiceChannelFactories(Ftr2LoService.config.ServerName, Convert.ToInt32(Ftr2LoService.config.ServerPort)); //InitializeEventListener(); //comment this out to remove the event listener try { ftr2lo_main(); } catch (Exception ex) { FTR2LO_Log.FTR2LO_log.do_log(_modulename, (int)FTR2LO_log.LogLevel.DEBUG, "Problem calling ftr2lo_main() from FTR2LO_Server.\n" + ex.ToString()); } stopFlag.WaitOne(); //the following is called when the service is finally stopped FTR2LO_Log.FTR2LO_log.do_log(_modulename, (int)FTR2LO_log.LogLevel.DEBUG, "Stopping...."); /*{ * if (serviceHost != null) * ((IDisposable)serviceHost).Dispose(); * }*/ //the following is called when the service is finally stopped FTR2LO_Log.FTR2LO_log.do_log(_modulename, (int)FTR2LO_log.LogLevel.DEBUG, "Stopped."); this.Dispose(); }
public void Start_NullArg_ThrowsArgumentNullException() { var controller = new ServiceController(_testService.TestServiceName); Assert.Throws <ArgumentNullException>(() => controller.Start(new string[] { null })); }
/// <summary> /// 服务监控构造函数 /// </summary> /// <param name="serviceName">服务名称</param> public ServiceMonitor(string serviceName) { this.serviceName = serviceName; this.service = new ServiceController(serviceName); }
public Services(string varServiceName = "MSSQLServerOLAPService", string varServer = "localhost") { sc = new ServiceController(varServiceName, varServer); }
protected bool IsExisting() { return(ServiceController.GetServices().Any(serviceController => serviceController.ServiceName.Equals(ServiceName))); }
/// <summary> /// Updates the service status. /// </summary> /// <param name="ServiceName">Name of the service.</param> /// <param name="MachineName">Name of the machine.</param> /// <param name="Status">The status.</param> /// <returns></returns> public ServiceResponse UpdateServiceStatus(string ServiceName, string MachineName, int Status, bool isWebService = false) { Logger.logEvent(LogLevel.INFO, "Entered UpdateServiceStatus"); ServiceResponse objServiceResponse = new ServiceResponse(); objServiceResponse.ServiceName = ServiceName; objServiceResponse.MacineName = MachineName; objServiceResponse.IsWebService = isWebService; objServiceResponse.Result = false; try { ServiceController _service = new ServiceController(ServiceName, MachineName); if (!isWebService) { //if(_service) switch (Status) { case 4: if (_service.Status != ServiceControllerStatus.Running) { _service.Start(); } objServiceResponse.Result = true; break; case 1: if (_service.Status != ServiceControllerStatus.Stopped) { if (_service.CanStop) { _service.Stop(); objServiceResponse.Result = true; } else { objServiceResponse.ErrorMessage = "Cannot Stop service, it is an Unstoppable Service"; Logger.logEvent(LogLevel.ERROR, "Cannot Stop service, it is an Unstoppable Service --> " + _service.DisplayName); } } break; case 7: if (_service.Status != ServiceControllerStatus.Paused) { if (_service.CanPauseAndContinue) { _service.Pause(); objServiceResponse.Result = true; } else { objServiceResponse.ErrorMessage = "Cannot Pause service"; Logger.logEvent(LogLevel.ERROR, "Cannot Pause service --> " + _service.DisplayName); } } break; case 10: if (_service.CanStop) { _service.Stop(); _service.Start(); objServiceResponse.Result = true; } else { objServiceResponse.ErrorMessage = "Cannot Restart service, it is an Unstoppable Service"; Logger.logEvent(LogLevel.ERROR, "Cannot Restart service --> " + _service.DisplayName); } break; default: objServiceResponse.ErrorMessage = "Invalid Status Command"; Logger.logEvent(LogLevel.ERROR, "Error in ServiceRepository.UpdateServiceStatus --> " + "Invalid Status Command"); break; } } else { var server = ServerManager.OpenRemote(MachineName); var site = server.Sites.FirstOrDefault(s => s.Name == ServiceName); switch (Status) { case 4: if (site.State != ObjectState.Started || site.State != ObjectState.Starting) { site.Start(); } objServiceResponse.Result = true; break; case 1: case 7: if (site.State != ObjectState.Stopped || site.State != ObjectState.Stopping) { site.Stop(); objServiceResponse.Result = true; } break; case 10: site.Stop(); site.Start(); objServiceResponse.Result = true; break; default: objServiceResponse.ErrorMessage = "Invalid Status Command"; Logger.logEvent(LogLevel.ERROR, "Error in ServiceRepository.UpdateServiceStatus --> " + "Invalid Status Command"); break; } } } catch (Exception ex) { objServiceResponse.ErrorMessage = ex.Message; Logger.logEvent(LogLevel.ERROR, "Error in ServiceRepository.UpdateServiceStatus --> " + ex.Message); objServiceResponse.Result = false; } return(objServiceResponse); }
static WinServicesHelper() { _scServices = ServiceController.GetServices(); }
private async void btnInstallService_Click(object sender, RoutedEventArgs e) { try { string servicePath = EnVar.AppPath + "rbs.exe"; if (!File.Exists(servicePath)) { MessageBox.Show("Unable to find service. Try reinstalling the application.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } ProcessStartInfo startInfoRegistry = new ProcessStartInfo { FileName = "sc.exe", Arguments = "create \"Runtime Backup Service\" binpath=\"" + servicePath + "\" start=auto ", CreateNoWindow = true, UseShellExecute = true }; Process processRegistry = new Process() { StartInfo = startInfoRegistry }; processRegistry.Start(); await Task.Delay(2000); //Start the service ServiceController service = new ServiceController("Runtime Backup Service", "."); if (service != null && service.Status != ServiceControllerStatus.Running) service.Start(); } catch (Exception ex) { string message = Functions.GetErrorFromException(ex); MessageBox.Show("Failed to install the service. \n" + message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } try { ServiceStatus = "Service is installed"; ServiceColor = "Green"; GeneralSettingHelper generalHelper = new GeneralSettingHelper(); GeneralSetting generalSetting = generalHelper.GetConfig(); if (generalSetting != null) { generalSetting.ServiceInstalled = true; generalHelper.SaveConfig(generalSetting); } btnInstallService.Visibility = Visibility.Collapsed; btnUnInstallService.Visibility = Visibility.Visible; } catch (Exception ex) { string message = Functions.GetErrorFromException(ex); MessageBox.Show("Failed to update service status. \n" + message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
public void RegisterServicesInAssembly(Assembly assembly) { ServiceController.RegisterServicesInAssembly(assembly); }
public static List <ServiceController> GetServices(string[] serviceNameArray) { return(ServiceController.GetServices().Where(s => serviceNameArray.Contains(s.ServiceName)).ToList <ServiceController>()); }
public ServiceController GetService(string serviceName) { return(ServiceController.GetServices().FirstOrDefault(c => String.Equals(c.ServiceName, serviceName, StringComparison.InvariantCultureIgnoreCase))); }
/// <summary> /// Handles service start event. /// </summary> /// <param name="args">Service start arguments.</param> public virtual void Start(string[] args) { string userInput = null; Arguments arguments = new Arguments(string.Join(" ", Arguments.ToArgs(Environment.CommandLine).Where(arg => !arg.StartsWith("--filter=", StringComparison.OrdinalIgnoreCase)).Skip(1))); if (arguments.Exists("OrderedArg1") && arguments.Exists("restart")) { string serviceName = arguments["OrderedArg1"]; if (GSF.Common.IsPosixEnvironment) { string serviceCommand = FilePath.GetAbsolutePath(serviceName); try { Command.Execute(serviceCommand, "stop"); } catch (Exception ex) { WriteLine("Failed to stop the {0} daemon: {1}\r\n", serviceName, ex.Message); } try { Command.Execute(serviceCommand, "start"); } catch (Exception ex) { WriteLine("Failed to restart the {0} daemon: {1}\r\n", serviceName, ex.Message); } } else { // Attempt to access service controller for the specified Windows service ServiceController serviceController = ServiceController.GetServices().SingleOrDefault(svc => string.Compare(svc.ServiceName, serviceName, StringComparison.OrdinalIgnoreCase) == 0); if (serviceController != null) { try { if (serviceController.Status == ServiceControllerStatus.Running) { WriteLine("Attempting to stop the {0} Windows service...", serviceName); serviceController.Stop(); // Can't wait forever for service to stop, so we time-out after 20 seconds serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(20.0D)); if (serviceController.Status == ServiceControllerStatus.Stopped) { WriteLine("Successfully stopped the {0} Windows service.", serviceName); } else { WriteLine("Failed to stop the {0} Windows service after trying for 20 seconds...", serviceName); } // Add an extra line for visual separation of service termination status WriteLine(""); } } catch (Exception ex) { WriteLine("Failed to stop the {0} Windows service: {1}\r\n", serviceName, ex.Message); } } // If the service failed to stop or it is installed as stand-alone debug application, we try to forcibly stop any remaining running instances try { Process[] instances = Process.GetProcessesByName(serviceName); if (instances.Length > 0) { int total = 0; WriteLine("Attempting to stop running instances of the {0}...", serviceName); // Terminate all instances of service running on the local computer foreach (Process process in instances) { process.Kill(); total++; } if (total > 0) { WriteLine("Stopped {0} {1} instance{2}.", total, serviceName, total > 1 ? "s" : ""); } // Add an extra line for visual separation of process termination status WriteLine(""); } } catch (Exception ex) { WriteLine("Failed to terminate running instances of the {0}: {1}\r\n", serviceName, ex.Message); } // Attempt to restart Windows service... if (serviceController != null) { try { // Refresh state in case service process was forcibly stopped serviceController.Refresh(); if (serviceController.Status != ServiceControllerStatus.Running) { serviceController.Start(); } } catch (Exception ex) { WriteLine("Failed to restart the {0} Windows service: {1}\r\n", serviceName, ex.Message); } } } } else { if (arguments.Exists("server")) { // Override default settings with user provided input. m_clientHelper.PersistSettings = false; m_remotingClient.PersistSettings = false; m_remotingClient.ConnectionString = $"Server={arguments["server"]}"; } long lastConnectAttempt = 0; // Connect to service and send commands. while (!string.Equals(userInput, "Exit", StringComparison.OrdinalIgnoreCase)) { try { // Do not reattempt connection too quickly while (DateTime.UtcNow.Ticks - lastConnectAttempt < Ticks.PerSecond) { Thread.Sleep(200); } lastConnectAttempt = DateTime.UtcNow.Ticks; if (!m_authenticationFailure) { // If there has been no authentication // failure, connect normally Connect(); } else { UserInfo userInfo; StringBuilder username = new StringBuilder(); StringBuilder password = new StringBuilder(); // If there has been an authentication failure, // prompt the user for new credentials PromptForCredentials(username, password); try { // Attempt to set network credentials used when attempting AD authentication userInfo = new UserInfo(username.ToString()); userInfo.Initialize(); SetNetworkCredential(new NetworkCredential(userInfo.LoginID, password.ToString())); } catch { // Even if this fails, we can still pass along user credentials } Connect(username.ToString(), password.ToString()); } while (m_authenticated && m_clientHelper.Enabled && !string.Equals(userInput, "Exit", StringComparison.OrdinalIgnoreCase)) { // Wait for a command from the user. userInput = System.Console.ReadLine(); // Write a blank line to the console. WriteLine(); if (!string.IsNullOrWhiteSpace(userInput)) { // The user typed in a command and didn't just hit <ENTER>. switch (userInput.ToUpper()) { case "CLS": // User wants to clear the console window. System.Console.Clear(); break; case "EXIT": // User wants to exit the telnet session with the service. if (m_telnetActive) { userInput = string.Empty; m_clientHelper.SendRequest("Telnet -disconnect"); } break; case "LOGIN": m_authenticated = false; m_authenticationFailure = true; break; default: // User wants to send a request to the service. m_clientHelper.SendRequest(userInput); if (string.Compare(userInput, "Help", StringComparison.OrdinalIgnoreCase) == 0) { DisplayHelp(); } break; } } } m_clientHelper.Disconnect(); } catch (Exception) { // Errors during the outer connection loop // should simply force an attempt to reconnect m_clientHelper.Disconnect(); } } } }
public static bool IsServiceInstalled() { ServiceController srv = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == SERVICE_NAME); return(srv != null); }
private static bool ServiceIsInstalled() { return(ServiceController.GetServices().Count(s => s.ServiceName == ProjectInstaller.SERVICE_NAME) > 0); }
/// <summary> /// /// </summary> /// <param name="controller"></param> /// <returns></returns> private bool StopServiceAndWaitForExit(ServiceController controller) { SERVICE_STATUS_PROCESS ssp = new SERVICE_STATUS_PROCESS(); int ignored; try { // Obtain information about the service, and specifically its hosting process, // from the Service Control Manager. if (!QueryServiceStatusEx(controller.ServiceHandle.DangerousGetHandle(), SC_STATUS_PROCESS_INFO, ref ssp, Marshal.SizeOf(ssp), out ignored)) { WriteConsole(String.Format("Couldn't obtain service:{0} process information....", controller.ServiceName), ConsoleTextColor.Exception); return(false); } // A few quick sanity checks that what the caller wants is *possible*. if (ssp.dwServiceType != SERVICE_WIN32_OWN_PROCESS) { WriteConsole(String.Format("Can't wait for service:{0} process termination! Shared hosting process!!!", controller.ServiceName), ConsoleTextColor.Notify); return(false); } if ((ssp.dwServiceFlags & SERVICE_RUNS_IN_SYSTEM_PROCESS) != 0) { WriteConsole(String.Format("Can't wait for service:{0} process temination! System hosting process!!!", controller.ServiceName), ConsoleTextColor.Notify); return(false); } //throw new Exception( if (ssp.dwProcessId == 0) { WriteConsole(String.Format("Can't wait for service:{0} process temination! Process Id not found...", controller.ServiceName), ConsoleTextColor.Exception); return(false); } // Note: It is possible for the next line to throw an ArgumentException if the // Service Control Manager's information is out-of-date (e.g. due to the process // having *just* been terminated in Task Manager) and the process does not really // exist. This is a race condition. The exception is the desirable result in this // case. using (Process process = Process.GetProcessById(ssp.dwProcessId)) { // EDIT: There is no need for waiting in a separate thread, because MSDN says //"The handles are valid until closed, even after the process or thread they //represent has been terminated." //( http://msdn.microsoft.com/en-us/library/windows/desktop/ms684868%28v=vs.85%29.aspx ), //so to keep things in the same thread, the process HANDLE should be opened from the //process id before the service is stopped, and the Wait should be done after that. // Response to EDIT: What you report is true, but the problem is that the handle // isn't actually opened by Process.GetProcessById. It's only opened within the //.WaitForExit method, which won't return until the wait is complete. Thus, if we // try the wait on the current therad, we can't actually do anything until it's done, //and if we defer the check until after the process has completed, it won't be //possible to obtain a handle to it any more. // The actual wait, using process.WaitForExit, opens a handle with the SYNCHRONIZE // permission only and closes the handle before returning. As long as that handle // is open, the process can be monitored for termination, but if the process exits // before the handle is opened, it is no longer possible to open a handle to the // original process and, worse, though it exists only as a technicality, there is // a race condition in that another process could pop up with the same process ID. // As such, we definitely want the handle to be opened before we ask the service // to close, but since the handle's lifetime is only that of the call to WaitForExit // and while WaitForExit is blocking the thread we can't make calls into the SCM, // it would appear to be necessary to perform the wait on a separate thread. ProcessWaitForExitData threadData = new ProcessWaitForExitData(); Thread processWaitForExitThread = new Thread(ProcessWaitForExitThreadProc); threadData.Process = process; processWaitForExitThread.IsBackground = Thread.CurrentThread.IsBackground; WriteConsole(String.Format("Stopping service:{0} process(s)...", controller.ServiceName), ConsoleTextColor.Normal); processWaitForExitThread.Start(threadData); WriteConsole(String.Format("Service:{0} process(s) ended, stopping service...", controller.ServiceName), ConsoleTextColor.Normal); // Now we ask the service to exit. WriteConsole(String.Format("Executing service:{0} stop request, stopping service...", controller.ServiceName), ConsoleTextColor.Normal); controller.Stop(); // Instead of waiting until the *service* is in the "stopped" state, here we // wait for its hosting process to go away. Of course, it's really that other // thread waiting for the process to go away, and then we wait for the thread // to go away. lock (threadData.Sync) while (!threadData.HasExited) { Monitor.Wait(threadData.Sync); } //if we get here, thread has exited.. WriteConsole(String.Format("Service:{0} process(s) terminated, service stopped...", controller.ServiceName), ConsoleTextColor.Normal); return(true); } } catch (Exception ex) { WriteConsole(String.Format("Exception processing service:{0} process(s)/n {1}", controller.ServiceName, ex.Message), ConsoleTextColor.Exception); return(false); } }
/// <summary> /// 查看指定名称的服务 /// </summary> public static ServiceController GetServiceByName(string serviceName) { return(ServiceController.GetServices().FirstOrDefault(s => s.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase))); }
public void ConstructWithServiceName_ToUpper() { var controller = new ServiceController(_testService.TestServiceName.ToUpperInvariant()); AssertExpectedProperties(controller); }
/// <summary> /// Gets all services. /// </summary> /// <param name="MachineName">Name of the machine.</param> /// <returns></returns> public List <SystemService> GetAllServices(string MachineName) { Logger.logEvent(LogLevel.INFO, "Entered GetAllServices"); List <SystemService> lstServices = new List <SystemService>(); HashSet <string> MachineNameSet = new HashSet <string>(); string[] _machineName = MachineName.Split(','); foreach (string machineName in _machineName) { try { if (MachineNameSet.Contains(machineName.ToLower())) { continue; } else { MachineNameSet.Add(machineName.ToLower()); } ServiceController[] Services = ServiceController.GetServices(machineName); foreach (ServiceController service in Services) { lstServices.Add( new SystemService { ServiceName = service.ServiceName, ServiceStatus = service.Status.ToString(), DisplayName = service.DisplayName, MachineName = service.MachineName, CanPauseAndContinue = service.CanPauseAndContinue, CanShutdown = service.CanShutdown, CanStop = service.CanStop, StatusToBeUpdated = (int)service.Status, IsWebService = false }); } ServerManager manager = ServerManager.OpenRemote(machineName); SiteCollection sc = manager.Sites; foreach (var site in sc) { lstServices.Add( new SystemService { ServiceName = site.Name, ServiceStatus = site.State.ToString(), //ServiceStatus = ((ServiceControllerStatus)IIsEntity.Properties["ServerState"].Value).ToString(), IsWebService = true, MachineName = machineName }); } } catch (System.Runtime.InteropServices.COMException ComException) { Logger.logEvent(LogLevel.ERROR, "Authentication Failed --> user doesn't have enough permissions on server " + machineName + " Message --> " + ComException.Message); } catch (Exception ex) { Logger.logEvent(LogLevel.ERROR, "error in servicerepository.getallservices inner try-catch block--> " + ex.Message); } } return(lstServices); }