コード例 #1
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);
            }
        }
コード例 #2
0
        /// <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
                          );
            }
        }
コード例 #3
0
ファイル: Service.cs プロジェクト: fvneerden/ASTool
        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);
        }
コード例 #4
0
ファイル: Service.cs プロジェクト: fvneerden/ASTool
        static bool StartService(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)
                        {
                            if (Win32ServiceInterop.StartServiceW(h, 0, IntPtr.Zero) == true)
                            {
                                bResult = true;
                            }
                            else
                            {
                                opt.LogError("Start feature: can't start Service: " + ServiceName);
                            }
                        }
                        else
                        {
                            opt.LogError("Start feature: can't open Service: " + ServiceName);
                        }
                    }
                    else
                    {
                        opt.LogError("Start feature: can't open ServiceManager");
                    }
                }
                else
                {
                    opt.LogError("Start feature: this service is not available on the current platform");
                }
            }
            catch (Exception ex)
            {
                opt.LogError("Start feature: exception: " + ex.Message);
            }
            return(bResult);
        }
コード例 #5
0
 private void StopService(ServiceListViewItem serviceListViewItem)
 {
     try
     {
         using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect))
         {
             using (ServiceHandle serviceHandle = scm.OpenService(serviceListViewItem.ServiceName, Advapi32.ServiceAccessRights.Stop))
             {
                 serviceHandle.Stop();
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
コード例 #6
0
        private static int RunInstallAndReturnExitCode(InstallOptions opts)
        {
            //Check Admin right
            if (!DaemonMasterUtils.IsElevated())
            {
                Console.WriteLine("You must start the program with admin rights.");
                return(1);
            }

            //------------------------

            if (string.IsNullOrWhiteSpace(opts.ServiceName))
            {
                Console.WriteLine("The given service name is invalid.");
                return(-1);
            }

            var serviceDefinition = new DmServiceDefinition(opts.ServiceName)
            {
                BinaryPath  = opts.FullPath,
                DisplayName = opts.DisplayName
            };

            try
            {
                CheckAndSetCommonArguments(ref serviceDefinition, opts);

                //Install service
                using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.CreateService))
                {
                    scm.CreateService(serviceDefinition);
                }

                //Save arguments in registry
                RegistryManagement.SaveInRegistry(serviceDefinition);

                Console.WriteLine("Successful!");
                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(1);
            }
        }
コード例 #7
0
        /// <summary>
        /// Installs the service.
        /// </summary>
        /// <param name="DisplayName">Service display name.</param>
        /// <param name="Description">Service description.</param>
        /// <param name="StartType">How the service should be started.</param>
        /// <param name="StartImmediately">If the service should be started immediately.</param>
        /// <param name="FailureActions">Service failure actions.</param>
        /// <param name="Credentials">Credentials to use when running service.</param>
        /// <returns>
        /// Return code:
        ///
        /// 0: Installed, not started.
        /// 1: Installed, started.
        /// 2: Updated, not started.
        /// 3: Updated, started.
        /// </returns>
        /// <exception cref="Exception">If service could not be installed.</exception>
        public int Install(string DisplayName, string Description, ServiceStartType StartType, bool StartImmediately,
                           ServiceFailureActions FailureActions, Win32ServiceCredentials Credentials)
        {
            string Path = Assembly.GetExecutingAssembly().Location.Replace(".dll", ".exe");

            try
            {
                using (ServiceControlManager mgr = ServiceControlManager.Connect(null, null, ServiceControlManagerAccessRights.All))
                {
                    if (mgr.TryOpenService(this.serviceName, ServiceControlAccessRights.All, out ServiceHandle existingService,
                                           out Win32Exception errorException))
                    {
                        using (existingService)
                        {
                            existingService.ChangeConfig(DisplayName, Path, ServiceType.Win32OwnProcess,
                                                         StartType, ErrorSeverity.Normal, Credentials);

                            if (!string.IsNullOrEmpty(Description))
                            {
                                existingService.SetDescription(Description);
                            }

                            if (!(FailureActions is null))
                            {
                                existingService.SetFailureActions(FailureActions);
                                existingService.SetFailureActionFlag(true);
                            }
                            else
                            {
                                existingService.SetFailureActionFlag(false);
                            }

                            if (StartImmediately)
                            {
                                existingService.Start(throwIfAlreadyRunning: false);
                                return(3);
                            }
                            else
                            {
                                return(2);
                            }
                        }
コード例 #8
0
ファイル: Service.cs プロジェクト: fvneerden/ASTool
        static bool InstallService(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))
                    {
                        string host = Process.GetCurrentProcess().MainModule.FileName;
                        host += " --import --service --configfile " + opt.ConfigFile;
                        ServiceHandle h = mgr.CreateService(ServiceName, ServiceDescription, host, ServiceType.Win32OwnProcess, ServiceStartType.AutoStart, ErrorSeverity.Normal, Win32ServiceCredentials.LocalSystem);
                        if (h != null)
                        {
                            bResult = true;
                        }
                        else
                        {
                            opt.LogError("Install feature: can't create Service: " + ServiceName);
                        }
                    }
                    else
                    {
                        opt.LogError("Install feature: can't open ServiceManager");
                    }
                }
                else
                {
                    opt.LogError("Install feature: this service is not available on the current platform");
                }
            }
            catch (Exception ex)
            {
                opt.LogError("Install feature: exception: " + ex.Message);
            }
            return(bResult);
        }
コード例 #9
0
        private void RemoveDaemon(ServiceListViewItem serviceListViewItem)
        {
            MessageBoxResult result = MessageBox.Show(_resManager.GetString("msg_warning_delete"), _resManager.GetString("question"),
                                                      MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result != MessageBoxResult.Yes)
            {
                return;
            }

            try
            {
                using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect))
                {
                    using (ServiceHandle serviceHandle = scm.OpenService(serviceListViewItem.ServiceName, Advapi32.ServiceAccessRights.AllAccess))
                    {
                        serviceHandle.DeleteService();
                    }
                }
                _processCollection.Remove(_processCollection.Single(i => i.ServiceName == serviceListViewItem.ServiceName));

                //MessageBox.Show(_resManager.GetString("the_service_deletion_was_successful"),
                //    _resManager.GetString("success"), MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (ServiceNotStoppedException)
            {
                result = MessageBox.Show(_resManager.GetString("you_must_stop_the_service_first"),
                                         _resManager.GetString("information"), MessageBoxButton.YesNo, MessageBoxImage.Information);

                if (result == MessageBoxResult.Yes)
                {
                    StopService(serviceListViewItem);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(_resManager.GetString("the_service_deletion_was_unsuccessful") + "\n" + ex.Message, _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #10
0
        /// <summary>
        /// Creates the or update a windows service.
        /// Note that the service is not restarted due to changes in its configuration
        /// </summary>
        /// <param name="serviceDefinition">The service definition.</param>
        /// <param name="startImmediately">if set to <c>true</c> the service will be started immediatly after updating. Has no effect if the service is already running.</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 CreateOrUpdateService(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))
                {
                    if (mgr.TryOpenService(serviceDefinition.ServiceName
                                           , ServiceControlAccessRights.All
                                           , out ServiceHandle existingService
                                           , out System.ComponentModel.Win32Exception errorException)
                        )
                    {
                        using (existingService)
                        {
                            DoUpdateService(existingService, serviceDefinition, startImmediately);
                        }
                    }
                    else
                    {
                        if (errorException.NativeErrorCode == KnownWin32ErrorCoes.ERROR_SERVICE_DOES_NOT_EXIST)
                        {
                            DoCreateService(mgr, serviceDefinition, startImmediately);
                        }
                        else
                        {
                            throw errorException;
                        }
                    }
                }
コード例 #11
0
        private void KillService(ServiceListViewItem serviceListViewItem)
        {
            try
            {
                using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect))
                {
                    using (ServiceHandle serviceHandle = scm.OpenService(serviceListViewItem.ServiceName, Advapi32.ServiceAccessRights.UserDefinedControl | Advapi32.ServiceAccessRights.QueryStatus))
                    {
                        if (serviceHandle.QueryServiceStatus().currentState == Advapi32.ServiceCurrentState.Stopped)
                        {
                            return;
                        }

                        try
                        {
                            serviceHandle.ExecuteCommand((int)ServiceCommands.ServiceKillProcessAndStop);
                            serviceHandle.WaitForStatus(Advapi32.ServiceCurrentState.Stopped, TimeSpan.FromSeconds(2));
                        }
                        catch (TimeoutException)
                        {
                            if (KillChildProcessJob.IsSupportedWindowsVersion && serviceListViewItem.ServicePid != null)
                            {
                                Process process = Process.GetProcessById((int)serviceListViewItem.ServicePid);
                                process.Kill();
                            }
                            else
                            {
                                MessageBox.Show(_resManager.GetString("cannot_kill_service", CultureInfo.CurrentUICulture), _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #12
0
        private void StartService(ServiceListViewItem serviceListViewItem, bool inUserSession = false)
        {
            try
            {
                if (inUserSession)
                {
                    //Write username where the service should start the process
                    RegistryManagement.WriteSessionUsername(serviceListViewItem.ServiceName, WindowsIdentity.GetCurrent().Name);
                }

                using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect))
                {
                    using (ServiceHandle serviceHandle = scm.OpenService(serviceListViewItem.ServiceName, Advapi32.ServiceAccessRights.Start))
                    {
                        serviceHandle.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #13
0
        public static ActionResult DeleteAllServices(Session session)
        {
            string appFolder = session.CustomActionData["APPDIR"];

            if (string.IsNullOrWhiteSpace(appFolder) || !Directory.Exists(appFolder))
            {
                session.Log("AppFolder is null or invalid.");
                return(ActionResult.Failure);
            }

            session.Log("Beginning the uninstall of all services.");

            try
            {
                using (ServiceControlManager controlManager = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect))
                {
                    //Get all services for this installation
                    List <string> serviceNameList = new List <string>();
                    using (RegistryKey mainKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\", RegistryKeyPermissionCheck.ReadSubTree))
                    {
                        if (mainKey == null)
                        {
                            return(ActionResult.Failure);
                        }

                        foreach (string serviceName in mainKey.GetSubKeyNames())
                        {
                            using (RegistryKey key = mainKey.OpenSubKey(serviceName, RegistryKeyPermissionCheck.ReadSubTree))
                            {
                                //If the key invalid, skip this service
                                if (key == null)
                                {
                                    continue;
                                }

                                //Get the exe path of the service to determine later if its a service from DaemonMaster
                                string serviceExePath = Convert.ToString(key.GetValue("ImagePath") ?? string.Empty);


                                if (string.IsNullOrWhiteSpace(serviceExePath) || !DaemonMasterUtils.ComparePaths(serviceExePath, appFolder + ServiceControlManager.DmServiceFileName)) //Not possible to use ServiceControlManager.DmServiceExe because the AppDomain changed here => so that we need to rebuilt the path.
                                {
                                    continue;
                                }

                                serviceNameList.Add(serviceName);
                            }
                        }
                    }

                    foreach (string serviceName in serviceNameList)
                    {
                        using (ServiceHandle service = controlManager.OpenService(serviceName, Advapi32.ServiceAccessRights.AllAccess))
                        {
                            session.Log("Try to delete " + serviceName);

                            try
                            {
                                Advapi32.ServiceStatusProcess serviceStatus = service.QueryServiceStatus();

                                if (serviceStatus.currentState != Advapi32.ServiceCurrentState.Stopped)
                                {
                                    session.Log("Try killing " + serviceName + " service.");
                                    service.ExecuteCommand((int)ServiceCommands.ServiceKillProcessAndStop);

                                    try
                                    {
                                        service.WaitForStatus(Advapi32.ServiceCurrentState.Stopped, TimeSpan.FromSeconds(5));
                                    }
                                    catch (TimeoutException)
                                    {
                                        session.Log("Terminate " + serviceName + " service.");
                                        Process process = Process.GetProcessById((int)serviceStatus.processId);
                                        process.Kill();
                                    }
                                }

                                service.DeleteService();
                                session.Log("Deleted " + serviceName + " service successful.");
                            }
                            catch (Exception e)
                            {
                                session.Log("Deletion of " + serviceName + " failed.\n" + e.Message + "\n" + e.StackTrace);
                                //continue
                            }
                        }
                    }
                }

                session.Log("Uninstall of all services was successful.");
                return(ActionResult.Success);
            }
            catch (Exception e)
            {
                session.Log(e.Message + "\n" + e.StackTrace);
                return(ActionResult.Failure);
            }
        }
コード例 #14
0
        private void ApplyConfiguration()
        {
            try
            {
                //Only set right it is not a build in account
                if (!Equals(_tempServiceConfig.Credentials, ServiceCredentials.LocalSystem) &&
                    !Equals(_tempServiceConfig.Credentials, ServiceCredentials.LocalService) &&
                    !Equals(_tempServiceConfig.Credentials, ServiceCredentials.NetworkService) &&
                    !Equals(_tempServiceConfig.Credentials, ServiceCredentials.NoChange) &&
                    !ServiceCredentials.IsVirtualAccount(_tempServiceConfig.Credentials)) //Normally all NT SERVICE\\... service has that right, so no need to add it.
                {
                    string username = _tempServiceConfig.Credentials.Username;
                    if (string.IsNullOrWhiteSpace(username))
                    {
                        username = TextBoxUsername.Text;
                    }

                    using (LsaPolicyHandle lsaWrapper = LsaPolicyHandle.OpenPolicyHandle())
                    {
                        bool hasRightToStartAsService = lsaWrapper.EnumeratePrivileges(username).Any(x => x.Buffer == "SeServiceLogonRight");
                        if (!hasRightToStartAsService)
                        {
                            MessageBoxResult result = MessageBox.Show(_resManager.GetString("logon_as_a_service", CultureInfo.CurrentUICulture), _resManager.GetString("question", CultureInfo.CurrentUICulture), MessageBoxButton.YesNo, MessageBoxImage.Question);
                            if (result != MessageBoxResult.Yes)
                            {
                                return;
                            }

                            //Give the account the right to start as service
                            lsaWrapper.AddPrivileges(username, "SeServiceLogonRight");
                        }
                    }
                }

                if (_createNewService)
                {
                    using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.CreateService))
                    {
                        scm.CreateService(_tempServiceConfig);

                        ////When no exception has been throwed show up a message (no longer)
                        //MessageBox.Show(
                        //    _resManager.GetString("the_service_installation_was_successful", CultureInfo.CurrentUICulture),
                        //    _resManager.GetString("success", CultureInfo.CurrentUICulture), MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                else
                {
                    using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect))
                    {
                        using (ServiceHandle serviceHandle = scm.OpenService(_tempServiceConfig.ServiceName, Advapi32.ServiceAccessRights.AllAccess))
                        {
                            serviceHandle.ChangeConfig(_tempServiceConfig);
                        }
                    }
                }


                //Save settings in registry after no error is occured
                RegistryManagement.SaveInRegistry(_tempServiceConfig);

                DialogResult = true;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    _resManager.GetString("the_service_installation_was_unsuccessful",
                                          CultureInfo.CurrentUICulture) + "\n" + ex.Message, "Error", MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }
コード例 #15
0
ファイル: ServiceHost.cs プロジェクト: ikvm/IoTGateway
        /// <summary>
        /// Installs the service.
        /// </summary>
        /// <param name="DisplayName">Service display name.</param>
        /// <param name="Description">Service description.</param>
        /// <param name="StartType">How the service should be started.</param>
        /// <param name="StartImmediately">If the service should be started immediately.</param>
        /// <param name="Credentials">Credentials to use when running service.</param>
        /// <returns>
        /// Return code:
        ///
        /// 0: Installed, not started.
        /// 1: Installed, started.
        /// 2: Updated, not started.
        /// 3: Updated, started.
        /// </returns>
        /// <exception cref="Exception">If service could not be installed.</exception>
        public int Install(string DisplayName, string Description, ServiceStartType StartType, bool StartImmediately, Win32ServiceCredentials Credentials)
        {
            string Path = Assembly.GetExecutingAssembly().Location.Replace(".dll", ".exe");

            try
            {
                using (ServiceControlManager mgr = ServiceControlManager.Connect(null, null, ServiceControlManagerAccessRights.All))
                {
                    if (mgr.TryOpenService(this.serviceName, ServiceControlAccessRights.All, out ServiceHandle existingService,
                                           out Win32Exception errorException))
                    {
                        using (existingService)
                        {
                            existingService.ChangeConfig(DisplayName, Path, ServiceType.Win32OwnProcess,
                                                         StartType, ErrorSeverity.Normal, Credentials);

                            if (!string.IsNullOrEmpty(Description))
                            {
                                existingService.SetDescription(Description);
                            }

                            /*if (serviceFailureActions != null)
                             * {
                             *      existingService.SetFailureActions(serviceFailureActions);
                             *      existingService.SetFailureActionFlag(failureActionsOnNonCrashFailures);
                             * }*/

                            if (StartImmediately)
                            {
                                existingService.Start(throwIfAlreadyRunning: false);
                                return(3);
                            }
                            else
                            {
                                return(2);
                            }
                        }
                    }
                    else
                    {
                        if (errorException.NativeErrorCode == Win32.ERROR_SERVICE_DOES_NOT_EXIST)
                        {
                            using (ServiceHandle svc = mgr.CreateService(this.serviceName, DisplayName, Path, ServiceType.Win32OwnProcess,
                                                                         StartType, ErrorSeverity.Normal, Credentials))
                            {
                                if (!string.IsNullOrEmpty(Description))
                                {
                                    svc.SetDescription(Description);
                                }

                                /*if (serviceFailureActions != null)
                                 * {
                                 *      svc.SetFailureActions(serviceFailureActions);
                                 *      svc.SetFailureActionFlag(failureActionsOnNonCrashFailures);
                                 * }*/

                                if (StartImmediately)
                                {
                                    svc.Start();
                                    return(1);
                                }
                                else
                                {
                                    return(0);
                                }
                            }
                        }
                        else
                        {
                            throw errorException;
                        }
                    }
                }
コード例 #16
0
        private static int RunEditReturnExitCode(EditOptions opts)
        {
            //Check Admin right
            if (!DaemonMasterUtils.IsElevated())
            {
                Console.WriteLine("You must start the program with admin rights.");
                return(1);
            }

            //------------------------

            DmServiceDefinition serviceDefinition;

            try
            {
                if (string.IsNullOrWhiteSpace(opts.ServiceName))
                {
                    Console.WriteLine("The given service name is invalid.");
                    return(-1);
                }

                string realServiceName = opts.ServiceName;
                if (!RegistryManagement.IsDaemonMasterService(realServiceName))
                {
                    realServiceName = "DaemonMaster_" + realServiceName; //Check for the name of the old system TODO: remove later
                    if (!RegistryManagement.IsDaemonMasterService(realServiceName))
                    {
                        Console.WriteLine("Cannot found a DaemonMaster service with the given name.");
                        return(-1);
                    }
                }

                //Load data from registry
                serviceDefinition = RegistryManagement.LoadFromRegistry(realServiceName);
            }
            catch (Exception)
            {
                Console.WriteLine("Cannot found a service with the given service name."); //"\n" + e.Message + "\n StackTrace: " + e.StackTrace);
                return(1);
            }

            try
            {
                CheckAndSetCommonArguments(ref serviceDefinition, opts);

                //Edit service
                using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect))
                {
                    using (ServiceHandle service = scm.OpenService(serviceDefinition.ServiceName, Advapi32.ServiceAccessRights.AllAccess))
                    {
                        if (service.QueryServiceStatus().currentState != Advapi32.ServiceCurrentState.Stopped)
                        {
                            Console.WriteLine("Service is not stopped, please stop it first.");
                            return(1);
                        }

                        service.ChangeConfig(serviceDefinition);
                    }
                }

                //Save arguments in registry
                RegistryManagement.SaveInRegistry(serviceDefinition);

                Console.WriteLine("Successful!");
                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(1);
            }
        }