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(); } } }
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); } }
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); }
/// <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 != null) { existingService.SetFailureActions(FailureActions); existingService.SetFailureActionFlag(true); } else { existingService.SetFailureActionFlag(false); } 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 (FailureActions != null) { svc.SetFailureActions(FailureActions); svc.SetFailureActionFlag(true); } else { svc.SetFailureActionFlag(false); } if (StartImmediately) { svc.Start(); return(1); } else { return(0); } } } else { throw errorException; } } }
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); } }