Exemplo n.º 1
0
        public void EnumDependentServices()
        {
            using (var scm = ServiceControlManager.OpenServiceControlManager(null, SCM_ACCESS.SC_MANAGER_CREATE_SERVICE | SCM_ACCESS.SC_MANAGER_ENUMERATE_SERVICE))
            {
                // Just pick the first service to be dependency
                var dependentServiceNames = scm.EnumServicesStatus(SERVICE_TYPE.SERVICE_WIN32, SERVICE_STATE_FLAGS.SERVICE_STATE_ALL).Select(ss => ss.ServiceName).Take(1).ToList();

                var path = typeof(DummyService).Assembly.Location;

                using (scm.CreateService(
                           DummyService.DisplayName,
                           DummyService.DisplayName,
                           SERVICE_ACCESS.SERVICE_ALL_ACCESS,
                           SERVICE_TYPE.SERVICE_WIN32_OWN_PROCESS,
                           SERVICE_START_TYPE.SERVICE_AUTO_START,
                           SERVICE_ERROR_CONTROL.SERVICE_ERROR_NORMAL,
                           path,
                           "",
                           IntPtr.Zero,
                           dependentServiceNames,
                           null,
                           null))
                {
                }

                using (var service = scm.OpenService(dependentServiceNames.First(), SERVICE_ACCESS.SERVICE_ENUMERATE_DEPENDENTS))
                {
                    var serviceName = service.EnumDependentServices(SERVICE_STATE_FLAGS.SERVICE_STATE_ALL).Select(ss => ss.ServiceName).First();

                    Assert.That(serviceName, Is.EqualTo(DummyService.DisplayName));
                }
            }
        }
Exemplo n.º 2
0
 public void OpenControlServiceManager()
 {
     // Just checking for a lack of exceptions at this stage
     using (ServiceControlManager.OpenServiceControlManager(null, 0))
     {
     }
 }
Exemplo n.º 3
0
        public void CreateServiceFailure()
        {
            // Create should CreateServiceFailure() WithOperator insufficient permissions
            var scm = ServiceControlManager.OpenServiceControlManager(null, 0);

            Assert.That(() => CreateDummyService(scm), Throws.TypeOf <Win32Exception>().With.Property("NativeErrorCode").EqualTo(ERROR_ACCESS_DENIED));
        }
        public void CalculateServiceName80Chars()
        {
            RunnerSettings settings = new RunnerSettings();

            settings.AgentName = "thisiskindofalongrunnername12";
            settings.ServerUrl = "https://example.githubusercontent.com/12345678901234567890123456789012345678901234567890";
            settings.GitHubUrl = "https://github.com/myorganizationexample/myrepoexample";

            string serviceNamePattern        = "actions.runner.{0}.{1}";
            string serviceDisplayNamePattern = "GitHub Actions Runner ({0}.{1})";

            using (TestHostContext hc = CreateTestContext())
            {
                ServiceControlManager scm = new ServiceControlManager();

                scm.Initialize(hc);
                scm.CalculateServiceName(
                    settings,
                    serviceNamePattern,
                    serviceDisplayNamePattern,
                    out string serviceName,
                    out string serviceDisplayName);

                // Verify name is still equal to 80 characters
                Assert.Equal(80, serviceName.Length);

                var serviceNameParts = serviceName.Split('.');

                // Verify nothing has been shortened out
                Assert.Equal("actions", serviceNameParts[0]);
                Assert.Equal("runner", serviceNameParts[1]);
                Assert.Equal("myorganizationexample-myrepoexample", serviceNameParts[2]); // '/' has been replaced with '-'
                Assert.Equal("thisiskindofalongrunnername12", serviceNameParts[3]);
            }
        }
        public void CalculateServiceNameSanitizeOutOfRangeChars()
        {
            RunnerSettings settings = new RunnerSettings();

            settings.AgentName = "name";
            settings.ServerUrl = "https://example.githubusercontent.com/12345678901234567890123456789012345678901234567890";
            settings.GitHubUrl = "https://github.com/org!@$*+[]()/repo!@$*+[]()";

            string serviceNamePattern        = "actions.runner.{0}.{1}";
            string serviceDisplayNamePattern = "GitHub Actions Runner ({0}.{1})";

            using (TestHostContext hc = CreateTestContext())
            {
                ServiceControlManager scm = new ServiceControlManager();

                scm.Initialize(hc);
                scm.CalculateServiceName(
                    settings,
                    serviceNamePattern,
                    serviceDisplayNamePattern,
                    out string serviceName,
                    out string serviceDisplayName);

                var serviceNameParts = serviceName.Split('.');

                // Verify service name parts are sanitized correctly
                Assert.Equal("actions", serviceNameParts[0]);
                Assert.Equal("runner", serviceNameParts[1]);
                Assert.Equal("org----------repo---------", serviceNameParts[2]); // Chars replaced with '-'
                Assert.Equal("name", serviceNameParts[3]);
            }
        }
Exemplo n.º 6
0
 public static extern bool GetServiceKeyName
 (
     ServiceControlManager serviceControlManager,
     string displayName,
     IntPtr serviceName,
     ref uint bytesNeeded
 );
        public void CalculateServiceNameLimitsServiceNameTo80Chars()
        {
            RunnerSettings settings = new RunnerSettings();

            settings.AgentName = "thisisareallyreallylongbutstillvalidagentname";
            settings.ServerUrl = "https://example.githubusercontent.com/12345678901234567890123456789012345678901234567890";
            settings.GitHubUrl = "https://github.com/myreallylongorganizationexample/myreallylongrepoexample";

            string serviceNamePattern        = "actions.runner.{0}.{1}";
            string serviceDisplayNamePattern = "GitHub Actions Runner ({0}.{1})";

            using (TestHostContext hc = CreateTestContext())
            {
                ServiceControlManager scm = new ServiceControlManager();

                scm.Initialize(hc);
                scm.CalculateServiceName(
                    settings,
                    serviceNamePattern,
                    serviceDisplayNamePattern,
                    out string serviceName,
                    out string serviceDisplayName);

                // Verify name has been shortened to 80 characters
                Assert.Equal(80, serviceName.Length);

                var serviceNameParts = serviceName.Split('.');

                // Verify that each component has been shortened to a sensible length
                Assert.Equal("actions", serviceNameParts[0]);                                       // Never shortened
                Assert.Equal("runner", serviceNameParts[1]);                                        // Never shortened
                Assert.Equal("myreallylongorganizationexample-myreallylongr", serviceNameParts[2]); // First 45 chars, '/' has been replaced with '-'
                Assert.Equal("thisisareallyreally", serviceNameParts[3]);                           // Remainder of unused chars
            }
        }
Exemplo n.º 8
0
        private void RestartService(ServiceListViewItem serviceListViewItem)
        {
            try
            {
                using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect))
                {
                    using (ServiceHandle serviceHandle = scm.OpenService(serviceListViewItem.ServiceName, Advapi32.ServiceAccessRights.QueryStatus | Advapi32.ServiceAccessRights.Start | Advapi32.ServiceAccessRights.Stop))
                    {
                        Advapi32.ServiceStatusProcess status = serviceHandle.QueryServiceStatus();

                        //Stop service (throws an exception if it is stopped)
                        serviceHandle.Stop();

                        //Wait for stop
                        serviceHandle.WaitForStatus(Advapi32.ServiceCurrentState.Stopped, TimeSpan.FromSeconds(10));

                        //Start service
                        serviceHandle.Start();
                    }
                }
            }
            catch (System.TimeoutException)
            {
                MessageBox.Show(_resManager.GetString("timeout_exception_service_restart"), _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// Creates the service.
        /// </summary>
        /// <param name="serviceDefinition">The service definition.</param>
        /// <param name="startImmediately">if set to <c>true</c> the service will be started immediatly after registering.</param>
        /// <exception cref="ArgumentException">
        /// Thrown when:
        /// BinaryPath of <paramref name="serviceDefinition"/> is null or empty
        /// or
        /// ServiceName of <paramref name="serviceDefinition"/> is null or empty
        /// </exception>
        /// <exception cref="PlatformNotSupportedException">Thrown when run on a non-windows platform.</exception>
        public void CreateService(ServiceDefinition serviceDefinition, bool startImmediately = false)
        {
            if (string.IsNullOrEmpty(serviceDefinition.BinaryPath))
            {
                throw new System.ArgumentException($"Invalid service definition. {nameof(ServiceDefinition.BinaryPath)} must not be null or empty.", nameof(serviceDefinition));
            }
            if (string.IsNullOrEmpty(serviceDefinition.ServiceName))
            {
                throw new System.ArgumentException($"Invalid service definition. {nameof(ServiceDefinition.ServiceName)} must not be null or empty.", nameof(serviceDefinition));
            }

            try
            {
                using (ServiceControlManager mgr = ServiceControlManager.Connect(nativeInterop, machineName
                                                                                 , databaseName, ServiceControlManagerAccessRights.All))
                {
                    DoCreateService(mgr, serviceDefinition, startImmediately);
                }
            }
            catch (System.DllNotFoundException dllException)
            {
                throw new System.PlatformNotSupportedException(
                          nameof(Win32ServiceHost)
                          + " is only supported on Windows with service management API set.", dllException
                          );
            }
        }
        private void DoCreateService(ServiceControlManager serviceControlManager, ServiceDefinition serviceDefinition, bool startImmediately)
        {
            using (ServiceHandle svc = serviceControlManager.CreateService(serviceDefinition.ServiceName, serviceDefinition.DisplayName, serviceDefinition.BinaryPath, ServiceType.Win32OwnProcess,
                                                                           serviceDefinition.AutoStart ? ServiceStartType.AutoStart : ServiceStartType.StartOnDemand, serviceDefinition.ErrorSeverity, serviceDefinition.Credentials))
            {
                string description = serviceDefinition.Description;
                if (!string.IsNullOrEmpty(description))
                {
                    svc.SetDescription(description);
                }

                ServiceFailureActions serviceFailureActions = serviceDefinition.FailureActions;
                if (serviceFailureActions != null)
                {
                    svc.SetFailureActions(serviceFailureActions);
                    svc.SetFailureActionFlag(serviceDefinition.FailureActionsOnNonCrashFailures);
                }

                if (serviceDefinition.AutoStart && serviceDefinition.DelayedAutoStart)
                {
                    svc.SetDelayedAutoStartFlag(true);
                }

                if (startImmediately)
                {
                    svc.Start();
                }
            }
        }
Exemplo n.º 11
0
        public void CalculateServiceNameL0()
        {
            using (TestHostContext tc = CreateTestContext())
            {
                Tracing trace = tc.GetTrace();

                trace.Info("Creating service control manager");
                ServiceControlManager scm = new ServiceControlManager();
                scm.Initialize(tc);
                ServiceNameTest[] tests = new ServiceNameTest[] {
                    new ServiceNameTest {
                        TestName                   = "SystemD Test",
                        ServiceNamePattern         = "vsts.agent.{0}.{1}.{2}.service",
                        ServiceDisplayPattern      = "Azure Pipelines Agent ({0}.{1}.{2})",
                        AgentName                  = "foo",
                        PoolName                   = "pool1",
                        ServerUrl                  = "https://dev.azure.com/bar",
                        ExpectedServiceName        = "vsts.agent.bar.pool1.foo.service",
                        ExpectedServiceDisplayName = "Azure Pipelines Agent (bar.pool1.foo)"
                    },
                    new ServiceNameTest {
                        TestName                   = "Long Agent/Pool Test",
                        ServiceNamePattern         = "vsts.agent.{0}.{1}.{2}.service",
                        ServiceDisplayPattern      = "Azure Pipelines Agent ({0}.{1}.{2})",
                        AgentName                  = new string('X', 40),
                        PoolName                   = new string('Y', 40),
                        ServerUrl                  = "https://dev.azure.com/bar",
                        ExpectedServiceName        = "vsts.agent.bar.YYYYYYYYYYYYYYYYYYYYYYYYY.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.service",
                        ExpectedServiceDisplayName = "Azure Pipelines Agent (bar.YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)"
                    },
                    new ServiceNameTest {
                        TestName                   = "Pool With Unicode Dash Test",
                        ServiceNamePattern         = "vsts.agent.{0}.{1}.{2}.service",
                        ServiceDisplayPattern      = "Azure Pipelines Agent ({0}.{1}.{2})",
                        AgentName                  = "foo",
                        PoolName                   = "pool" + "\u002D" + "1",
                        ServerUrl                  = "https://dev.azure.com/bar",
                        ExpectedServiceName        = "vsts.agent.bar.pool-1.foo.service",
                        ExpectedServiceDisplayName = "Azure Pipelines Agent (bar.pool-1.foo)"
                    },
                };
                foreach (var test in tests)
                {
                    AgentSettings settings = new AgentSettings();
                    settings.ServerUrl = test.ServerUrl;
                    settings.AgentName = test.AgentName;
                    settings.PoolName  = test.PoolName;

                    string serviceName;
                    string serviceDisplayName;

                    scm.CalculateServiceName(settings, test.ServiceNamePattern, test.ServiceDisplayPattern, out serviceName, out serviceDisplayName);

                    Assert.True(string.Equals(serviceName, test.ExpectedServiceName), $"{test.TestName} Service Name Expected: {test.ExpectedServiceName}, Got: {serviceName}");
                    Assert.True(serviceName.Length <= 80, $"{test.TestName} Service Name is <= 80");
                    Assert.True(string.Equals(serviceDisplayName, test.ExpectedServiceDisplayName), $"{test.TestName} Service Display Name Expected: {test.ExpectedServiceDisplayName}, Got: {serviceDisplayName}");
                }
            }
        }
Exemplo n.º 12
0
 public void DeleteService()
 {
     using (var scm = ServiceControlManager.OpenServiceControlManager(null, SCM_ACCESS.SC_MANAGER_CREATE_SERVICE))
         using (var service = ServiceControlManagerTests.CreateDummyService(scm))
         {
             service.Delete();
         }
 }
Exemplo n.º 13
0
 ServiceHandle Win32ServiceInterface.CreateServiceW(ServiceControlManager serviceControlManager, string serviceName, string displayName,
                                                    ServiceControlAccessRights desiredControlAccess, ServiceType serviceType, ServiceStartType startType, ErrorSeverity errorSeverity,
                                                    string binaryPath,
                                                    string loadOrderGroup, IntPtr outUIntTagId, string dependencies, string serviceUserName, string servicePassword)
 {
     return(CreateServiceW(serviceControlManager, serviceName, displayName, desiredControlAccess, serviceType, startType, errorSeverity,
                           binaryPath, loadOrderGroup, outUIntTagId, dependencies, serviceUserName, servicePassword));
 }
        public ServiceUpdateTests()
        {
            serviceControlManager = A.Fake <ServiceControlManager>(o => o.Wrapping(new ServiceControlManager {
                NativeInterop = nativeInterop
            }));

            sut = new ServiceUtils.Win32ServiceManager(TestMachineName, TestDatabaseName, nativeInterop);
        }
Exemplo n.º 15
0
 public void CreateService()
 {
     using (var scm = ServiceControlManager.OpenServiceControlManager(null, SCM_ACCESS.SC_MANAGER_CREATE_SERVICE))
         using (CreateDummyService(scm))
         {
             // Service is cleaned up in TearDown
         }
 }
Exemplo n.º 16
0
 public void EnumServicesStatusEx()
 {
     using (var scm = ServiceControlManager.OpenServiceControlManager(null, SCM_ACCESS.SC_MANAGER_CREATE_SERVICE | SCM_ACCESS.SC_MANAGER_ENUMERATE_SERVICE))
         using (CreateDummyService(scm))
         {
             var service = scm.EnumServicesStatusEx(SERVICE_TYPE.SERVICE_WIN32, SERVICE_STATE_FLAGS.SERVICE_STATE_ALL).First(s => s.ServiceName == DummyService.SvcName);
             Assert.That(service.ServiceStatusProcess.currentState, Is.EqualTo(SERVICE_STATE.SERVICE_STOPPED));
         }
 }
Exemplo n.º 17
0
 public void EnumServicesStatus()
 {
     using (var scm = ServiceControlManager.OpenServiceControlManager(null, SCM_ACCESS.SC_MANAGER_CREATE_SERVICE | SCM_ACCESS.SC_MANAGER_ENUMERATE_SERVICE))
         using (CreateDummyService(scm))
         {
             var services = scm.EnumServicesStatus(SERVICE_TYPE.SERVICE_WIN32, SERVICE_STATE_FLAGS.SERVICE_STATE_ALL);
             Assert.That(services.Count(s => s.ServiceName == DummyService.SvcName), Is.EqualTo(1));
         }
 }
Exemplo n.º 18
0
        static bool StopService(Options opt)
        {
            bool bResult = false;

            try
            {
                bool IsWindows = System.Runtime.InteropServices.RuntimeInformation
                                 .IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows);
                if (IsWindows == true)
                {
                    ServiceControlManager mgr = ServiceControlManager.Connect(Win32ServiceInterop.Wrapper, null, null, ServiceControlManagerAccessRights.All);

                    if ((mgr != null) && (mgr.IsInvalid != true))
                    {
                        ServiceHandle h = mgr.OpenService(ServiceName, ServiceControlAccessRights.All);
                        if (h != null)
                        {
                            ServiceStatusProcess status = new ServiceStatusProcess();
                            uint reason = (uint)StopReasonMinorReasonFlags.SERVICE_STOP_REASON_MINOR_MAINTENANCE |
                                          (uint)StopReasonMajorReasonFlags.SERVICE_STOP_REASON_MAJOR_NONE |
                                          (uint)StopReasonFlags.SERVICE_STOP_REASON_FLAG_UNPLANNED;
                            ServiceStatusParam param = new ServiceStatusParam(reason, status);

                            int s       = Marshal.SizeOf <ServiceStatusParam>();
                            var lpParam = Marshal.AllocHGlobal(s);
                            Marshal.StructureToPtr(param, lpParam, fDeleteOld: false);
                            if (Win32ServiceInterop.ControlServiceExW(h, (uint)ServiceControlCommandFlags.SERVICE_CONTROL_STOP, (uint)ServiceControlCommandReasonFlags.SERVICE_CONTROL_STATUS_REASON_INFO, lpParam) == true)
                            {
                                bResult = true;
                            }
                            else
                            {
                                opt.LogError("Stop feature: can't stop Service: " + ServiceName + " ErrorCode: " + Marshal.GetLastWin32Error().ToString());
                            }
                        }
                        else
                        {
                            opt.LogError("Stop feature: can't open Service: " + ServiceName);
                        }
                    }
                    else
                    {
                        opt.LogError("Stop feature: can't open ServiceManager");
                    }
                }
                else
                {
                    opt.LogError("Stop feature: this service is not available on the current platform");
                }
            }
            catch (Exception ex)
            {
                opt.LogError("Stop feature: exception: " + ex.Message);
            }
            return(bResult);
        }
Exemplo n.º 19
0
        public void OpenControlServiceManagerFailure()
        {
            // ReSharper disable once InconsistentNaming
            const int RPC_S_SERVER_UNAVAILABLE = 1722;

            // Opening the service control manager on a server with an incorrect name (with spaces) throws quickly
            Assert.That(() => ServiceControlManager.OpenServiceControlManager("aa aa", 0),
                        Throws.TypeOf <Win32Exception>()
                        .With.Property("NativeErrorCode").EqualTo(RPC_S_SERVER_UNAVAILABLE));
        }
Exemplo n.º 20
0
 public void GetServiceDisplayName()
 {
     using (var scm = ServiceControlManager.OpenServiceControlManager(null, SCM_ACCESS.SC_MANAGER_CREATE_SERVICE))
     {
         using (CreateDummyService(scm))
         {
         }
         Assert.That(scm.GetServiceDisplayName(DummyService.SvcName), Is.EqualTo(DummyService.DisplayName));
     }
 }
Exemplo n.º 21
0
 public void EnumServicesStatusFailure()
 {
     using (var scm = ServiceControlManager.OpenServiceControlManager(null, 0))
     {
         // ReSharper disable once AccessToDisposedClosure
         Assert.That(() => scm.EnumServicesStatus(SERVICE_TYPE.SERVICE_WIN32, SERVICE_STATE_FLAGS.SERVICE_STATE_ALL).ToList(),
                     Throws.TypeOf <Win32Exception>()
                     .With.Property("NativeErrorCode").EqualTo(ERROR_ACCESS_DENIED));
     }
 }
Exemplo n.º 22
0
        public void StartWithParameters()
        {
            using (var scm = ServiceControlManager.OpenServiceControlManager(null, SCM_ACCESS.SC_MANAGER_CREATE_SERVICE))
                using (var service = ServiceControlManagerTests.CreateDummyService(scm))
                {
                    service.Start(new[] { "Dummy Parameter" });
                    service.WaitForServiceToStart();

                    service.StopServiceAndWait();
                }
        }
Exemplo n.º 23
0
        public static void DeleteDummyServiceIfItExists()
        {
            using (var scm = ServiceControlManager.OpenServiceControlManager(null, SCM_ACCESS.SC_MANAGER_ENUMERATE_SERVICE))
            {
                var services = scm.EnumServicesStatus(SERVICE_TYPE.SERVICE_WIN32, SERVICE_STATE_FLAGS.SERVICE_STATE_ALL);

                foreach (var serviceName in services.Select(serviceStatus => serviceStatus.ServiceName).Where(name => name.StartsWith(DummyService.DisplayName) || name.StartsWith(DummyService.SvcName)))
                {
                    DeleteService(scm, serviceName);
                }
            }
        }
Exemplo n.º 24
0
        public void QueryConfig()
        {
            using (var scm = ServiceControlManager.OpenServiceControlManager(null, SCM_ACCESS.SC_MANAGER_CREATE_SERVICE))
                using (var service = ServiceControlManagerTests.CreateDummyService(scm))
                {
                    var config = service.QueryConfig();

                    Assert.That(config.DisplayName, Is.EqualTo(DummyService.DisplayName));

                    // Service is cleaned up in TearDown
                }
        }
Exemplo n.º 25
0
 public void OpenService()
 {
     // Again just checking for a lack of exceptions at this stage
     using (var scm = ServiceControlManager.OpenServiceControlManager(null, SCM_ACCESS.SC_MANAGER_CONNECT | SCM_ACCESS.SC_MANAGER_ENUMERATE_SERVICE))
     {
         var serviceName = scm.EnumServicesStatus(SERVICE_TYPE.SERVICE_WIN32, SERVICE_STATE_FLAGS.SERVICE_STATE_ALL).Select(ss => ss.ServiceName).First();
         using (scm.OpenService(serviceName, SERVICE_ACCESS.SERVICE_QUERY_STATUS))
         {
             // Service is cleaned up in TearDown
         }
     }
 }
Exemplo n.º 26
0
 internal static extern ServiceHandle CreateServiceW(
     ServiceControlManager serviceControlManager,
     string serviceName,
     string displayName,
     ServiceControlAccessRights desiredControlAccess,
     ServiceType serviceType,
     ServiceStartType startType,
     ErrorSeverity errorSeverity,
     string binaryPath,
     string loadOrderGroup,
     IntPtr outUIntTagId,
     string dependencies,
     string serviceUserName,
     string servicePassword);
Exemplo n.º 27
0
        public void ChangeConfig2()
        {
            using (var scm = ServiceControlManager.OpenServiceControlManager(null, SCM_ACCESS.SC_MANAGER_CREATE_SERVICE | SCM_ACCESS.SC_MANAGER_ENUMERATE_SERVICE))
                using (var service = ServiceControlManagerTests.CreateDummyService(scm))
                {
                    var description = new SERVICE_DESCRIPTION
                    {
                        Description = "A dummy service"
                    };

                    service.ChangeConfig2(ref description);
                    Assert.That(service.QueryConfig2 <SERVICE_DESCRIPTION>().Description, Is.EqualTo("A dummy service"));
                }
        }
Exemplo n.º 28
0
 private void stopDriverButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         using (ServiceControlManager scm = new ServiceControlManager())
         {
             scm.StopDriver(serviceNameTextBox.Text);
         }
         MessageBox.Show("Драйвер остановлен");
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Exemplo n.º 29
0
        public void QueryStatusEx()
        {
            using (var scm = ServiceControlManager.OpenServiceControlManager(null, SCM_ACCESS.SC_MANAGER_CREATE_SERVICE))
                using (var service = ServiceControlManagerTests.CreateDummyService(scm))
                {
                    var status = service.QueryStatusEx();
                    Assert.That(status.currentState, Is.EqualTo(SERVICE_STATE.SERVICE_STOPPED));

                    service.Start();
                    service.WaitForServiceToStart();
                    Assert.That(service.QueryStatusEx().currentState, Is.EqualTo(SERVICE_STATE.SERVICE_RUNNING));

                    service.StopServiceAndWait();
                }
        }
Exemplo n.º 30
0
        public void OpenServiceFailure()
        {
            // Check we get an exception if we try and open a service that doesn't exist

            // ReSharper disable once InconsistentNaming
            const int ERROR_SERVICE_DOES_NOT_EXIST = 1060;

            using (var scm = ServiceControlManager.OpenServiceControlManager(null, SCM_ACCESS.SC_MANAGER_CONNECT))
            {
                // ReSharper disable once AccessToDisposedClosure
                Assert.That(() => scm.OpenService("Non existant service name", SERVICE_ACCESS.SERVICE_QUERY_STATUS),
                            Throws.TypeOf <Win32Exception>()
                            .With.Property("NativeErrorCode").EqualTo(ERROR_SERVICE_DOES_NOT_EXIST));
            }
        }