/// <summary>
        /// Install an executable as a service.
        /// </summary>
        /// <param name="assemblyPath">The path to the executable.</param>
        /// <param name="serviceName">The name of the service.</param>
        /// <param name="displayName">THe display name of the service.</param>
        /// <param name="description">The description of the service.</param>
        /// <param name="startType">The startup type.</param>
        /// <param name="userName">The username to run as.</param>
        /// <param name="password">The password of the user.</param>
        /// <param name="dependancies"></param>
        public static void InstallService(string assemblyPath, string serviceName, string displayName, string description,
			ServiceStartMode startType, string userName = "", string password = "", IEnumerable<string> dependancies = null)
        {
            using (var procesServiceInstaller = new ServiceProcessInstaller())
            {
                if (string.IsNullOrEmpty(userName))
                {
                    procesServiceInstaller.Account = ServiceAccount.LocalSystem;
                }
                else
                {
                    procesServiceInstaller.Account = ServiceAccount.User;
                    procesServiceInstaller.Username = userName;
                    procesServiceInstaller.Password = password;
                }

                using (var installer = new ServiceInstaller())
                {
                    var cmdline = new[] { string.Format("/assemblypath={0}", assemblyPath) };
                    var context = new InstallContext(string.Empty, cmdline);

                    installer.Context = context;
                    installer.DisplayName = displayName;
                    installer.Description = description;
                    installer.ServiceName = serviceName;
                    installer.StartType = startType;
                    installer.Parent = procesServiceInstaller;

                    if (dependancies != null)
                    {
                        installer.ServicesDependedOn = dependancies.ToArray();
                    }

                    IDictionary state = new Hashtable();

                    try
                    {
                        installer.Install(state);
                        installer.Commit(state);
                    }
                    catch (Exception ex)
                    {
                        installer.Rollback(state);
                        throw new Exception("Failed to install the service.", ex);
                    }
                }
            }
        }
        public static ServiceController Create(string machineName, string serviceName, string displayName,
                                               ServiceType serviceType, ServiceStartMode startType,
                                               ServiceErrorControl errorControl, string binaryPathName,
                                               string loadOrderGroup, string[] dependencies, string serviceStartName,
                                               string password)
        {
            var hScManager = OpenSCManager(machineName, null, ScmAccessRights.CreateService);
            if (hScManager == IntPtr.Zero)
            {
                throw new Win32Exception();
            }
            try
            {
                var dependencyList = dependencies == null || dependencies.Length == 0
                                         ? null
                                         : string.Join("\0", dependencies);
                var hService = CreateService(hScManager, serviceName, displayName, ServiceAccessRights.AllAccess,
                                             serviceType, startType, errorControl, binaryPathName, loadOrderGroup,
                                             IntPtr.Zero, dependencyList, serviceStartName, password);
                if (hService == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }
                CloseServiceHandle(hService);

                return new ServiceController(serviceName, machineName);
            }
            finally
            {
                CloseServiceHandle(hScManager);
            }
        }
Beispiel #3
0
        //private char NULL_VALUE = char(0);
        public static ServiceReturnCode Create(string machineName, string serviceName, string serviceDisplayName,
                                               string serviceLocation, ServiceStartMode startMode, string userName,
                                               string password, string[] dependencies)
        {
            if (userName != null && userName.IndexOf('\\') < 0)
            {
                userName = "******" + userName;
            }

            try
            {
                const string methodName = "Create";

                var parameters = new object[]
                                     {
                                         serviceName, // Name
                                         serviceDisplayName, // Display Name
                                         serviceLocation, // Path Name | The Location "E:\somewhere\something"
                                         Convert.ToInt32(ServiceType.OwnProcess), // ServiceType
                                         Convert.ToInt32(ErrorControl.UserNotified), // Error Control
                                         startMode.ToString(), // Start Mode
                                         false, // Desktop Interaction
                                         userName, // StartName | Username
                                         password, // StartPassword |Password
                                         null, // LoadOrderGroup | Service Order Group
                                         null, // LoadOrderGroupDependencies | Load Order Dependencies
                                         dependencies //  ServiceDependencies
                                     };
                return (ServiceReturnCode) WmiHelper.InvokeStaticMethod(machineName, CLASSNAME, methodName, parameters);
            }
            catch
            {
                return ServiceReturnCode.UnknownFailure;
            }
        }
        public static void ChangeStartMode(this ServiceController svc, ServiceStartMode mode)
        {
            var scManagerHandle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);
            fail_if(scManagerHandle == IntPtr.Zero, "Open Service Manager Error");

            var serviceHandle = OpenService(
                scManagerHandle,
                svc.ServiceName,
                SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG);

            fail_if(serviceHandle == IntPtr.Zero, "Open Service Error");

            var success = ChangeServiceConfig(
                serviceHandle,
                SERVICE_NO_CHANGE,
                (uint) mode,
                SERVICE_NO_CHANGE,
                null,
                null,
                IntPtr.Zero,
                null,
                null,
                null,
                null);

            fail_if(!success, "failed to change start-up mode to '{0}' of '{1}'", mode, svc.ServiceName);

            CloseServiceHandle(serviceHandle);
            CloseServiceHandle(scManagerHandle);
        }
        protected WindowsServiceInstallerBase(ServiceStartMode startMode, ServiceAccount account, string serviceName, string description)
        {
            _installer.StartType = startMode;
            _processInstaller.Account = account;
            _installer.Description = description;
            _installer.ServiceName = serviceName;

            Installers.Add(_installer);
            Installers.Add(_processInstaller);
        }
        //construction takes place here
        public BackgroundServiceInstaller(string serviceName, ServiceStartMode startMode, string userName, string password)
            : base()
        {
            //define static members
            BackgroundServiceInstaller.m_serviceName = serviceName;
            BackgroundServiceInstaller.m_startMode = startMode;
            BackgroundServiceInstaller.m_userName = userName;
            BackgroundServiceInstaller.m_password = password;

            //run installer
            this.Install();
        }
 protected AbstractInstallerHost(ServiceDescription description, ServiceStartMode startMode,
     IEnumerable<string> dependencies, Credentials credentials,
     IEnumerable<Action> preActions, IEnumerable<Action> postActions, bool sudo)
 {
     _startMode = startMode;
     _postActions = postActions;
     _preActions = preActions;
     _credentials = credentials;
     _dependencies = dependencies;
     _description = description;
     Sudo = sudo;
 }
 protected ServiceInstallerExt(ServiceAccount account, ServiceStartMode startMode)
 {
     Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
     var serviceProcessInstaller = new ServiceProcessInstaller
     {
         Account = account
     };
     var serviceInstaller = new ServiceInstaller
     {
         StartType = startMode
     };
     PrepareNames(serviceInstaller);
     Installers.Add(serviceInstaller);
     Installers.Add(serviceProcessInstaller);
 }
 // Set service's start mode in the registry
 static void SetStartMode(this ServiceController service, ServiceStartMode startMode)
 {
     Console.WriteLine("Setting service '{0}' to '{1}'", service.ServiceName, startMode);
     try
     {
         using (RegistryKey key = Registry.LocalMachine.OpenSubKey(string.Format(@"SYSTEM\CurrentControlSet\Services\{0}", service.ServiceName), true))
         {
             key.SetValue("Start", startMode.Value(), RegistryValueKind.DWord);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("Exception opening registry key for service '{0}':\n{1}\n{2}", service.ServiceName, e.Message, e.StackTrace);
     }
 }
Beispiel #10
0
 /// <summary>
 /// Sets the start mode of a service.
 /// </summary>
 /// <param name="serviceHandle">A handle to the service.</param>
 /// <param name="startMode">The new start mode of the service.</param>
 public static void SetServiceStartMode(SafeHandle serviceHandle, ServiceStartMode startMode)
 {
     ChangeServiceConfig(
         serviceHandle,
         SERVICE_NO_CHANGE, // serviceType
         (uint)startMode,
         SERVICE_NO_CHANGE, // errorControl
         null, // binaryPath
         null, // loadOrderGroup
         null, // dependencies
         null,  // serviceStartName
         null,  // password
         null // displayName
         );
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ServiceType"></param>
        /// <param name="StartMode"></param>
        /// <param name="ServiceName"></param>
        /// <param name="DisplayName"></param>
        /// <param name="Description"></param>
        /// <param name="Account"></param>
        /// <param name="Username"></param>
        /// <param name="Password"></param>
        public ServiceInstallerAttribute(Type ServiceType, 
            ServiceStartMode StartMode, string ServiceName, string DisplayName, string Description,
            ServiceAccount Account, string Username, string Password)
        {
            this.ServiceType = ServiceType;

            this.StartMode = StartMode;
            this.ServiceName = ServiceName;
            this.DisplayName = DisplayName;
            this.Description = Description;

            this.Account = Account;
            this.Username = Username;
            this.Password = Password;
        }
Beispiel #12
0
 public Service(string name, string description, string displayName, ServiceStartMode startMode,
                ServiceTypeEnum serviceType, DateTimeOffset nameKeyLastWrite, DateTimeOffset?parametersKeyLastWrite,
                string group, string imagePath, string serviceDll, string reqPrivs)
 {
     Name                   = name;
     Description            = description;
     DisplayName            = displayName;
     StartMode              = startMode;
     ServiceType            = serviceType;
     NameKeyLastWrite       = nameKeyLastWrite.UtcDateTime;
     ParametersKeyLastWrite = parametersKeyLastWrite?.UtcDateTime;
     Group                  = group;
     ImagePath              = imagePath;
     ServiceDLL             = serviceDll;
     RequiredPrivileges     = reqPrivs;
 }
        static int Main(string[] args)
        {
            string cfgPath = "service-policy.cfg";

            if (args.Length > 0)
            {
                cfgPath = args[0];
            }

            using (var cfg = new StreamReader(cfgPath))
            {
                while (!cfg.EndOfStream)
                {
                    var line = cfg.ReadLine();

                    if (line.Trim().StartsWith("#"))
                    {
                        continue;
                    }

                    var tokens = line.Split(':');

                    if (tokens.Length < 2)
                    {
                        continue;
                    }

                    string serviceName = tokens[0].Trim();
                    tokens[1] = tokens[1].Trim();
                    // Capitalize the first letter to make sure it matches enum members.
                    var mode = new string(tokens[1].ToCharArray().Select((c, index) => index == 0 ? char.ToUpperInvariant(c) : char.ToLowerInvariant(c)).ToArray());

                    try
                    {
                        ServiceStartMode  startMode = (ServiceStartMode)Enum.Parse(typeof(ServiceStartMode), mode);
                        ServiceController service   = new ServiceController(serviceName);
                        service.SetStartMode(startMode);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Exception: {0}\n{1}", e.Message, e.StackTrace);
                        continue;
                    }
                }
            }
            return(0);
        }
            public static void InstallService(
                [Argument("serviceName", Description = "The service name to install as.")] string svcName,
                [Argument("displayName", Description = "The display name of the service.")] string displayName,
                [Argument("startupType", Description = "The service startup type: Automatic, Manual, or Disabled.")] ServiceStartMode startupType,
                [Argument("serviceAccount", Description = "The service account: LocalService, NetworkService, or LocalSystem.")] ServiceAccount serviceAccount,
                [Argument("command", Description = "The command to run as a service.")] string commandName,
                [Argument("arguments", DefaultValue = null, Description = "The arguments required to run the command.")] string[] arguments,
                ICommandInterpreter ci,
                [Argument("executable", Visible = false), System.ComponentModel.DefaultValue(null)]
                string executable
                )
            {
                ICommand cmd;

                if (!ci.TryGetCommand("RunAsService", out cmd))
                {
                    throw new ApplicationException(
                              "You must add typeof(ServiceCommands) to the commands or provide your own RunAsService command.");
                }
                if (!ci.TryGetCommand(commandName, out cmd))
                {
                    throw new ApplicationException("The command name '" + commandName + "' was not found.");
                }
                if (String.IsNullOrEmpty(svcName))
                {
                    throw new ArgumentNullException("svcName");
                }

                string        exe  = Path.GetFullPath(executable ?? new Uri(Constants.EntryAssembly.Location).AbsolutePath);
                List <string> args = new List <string>();

                args.Add("RunAsService");
                args.Add("/serviceName=" + svcName);
                args.Add(commandName);
                args.AddRange(arguments ?? new string[0]);

                using (
                    SvcControlManager scm = SvcControlManager.Create(svcName, displayName, false, startupType, exe,
                                                                     args.ToArray(),
                                                                     SvcControlManager.NT_AUTHORITY.Account(
                                                                         serviceAccount), null))
                {
                    args.RemoveRange(0, 2);
                    args.Insert(0, Path.GetFileName(exe));
                    scm.SetDescription(ArgumentList.EscapeArguments(args.ToArray()));
                }
            }
Beispiel #15
0
        public static void ChangeStartMode(ServiceController svc, ServiceStartMode mode)
        {
            var scManagerHandle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);

            if (scManagerHandle == IntPtr.Zero)
            {
                int nError         = Marshal.GetLastWin32Error();
                var win32Exception = new Win32Exception(nError);
                throw new ExternalException("Access Denied To Open Service Manager " + win32Exception.Message);
            }

            var serviceHandle = OpenService(
                scManagerHandle,
                svc.ServiceName,
                SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG);

            if (serviceHandle == IntPtr.Zero)
            {
                int nError         = Marshal.GetLastWin32Error();
                var win32Exception = new Win32Exception(nError);
                throw new ExternalException("Open Service Error " + win32Exception.Message);
            }

            var result = ChangeServiceConfig(
                serviceHandle,
                SERVICE_NO_CHANGE,
                (uint)mode,
                SERVICE_NO_CHANGE,
                null,
                null,
                IntPtr.Zero,
                null,
                null,
                null,
                null);

            if (result == false)
            {
                int nError         = Marshal.GetLastWin32Error();
                var win32Exception = new Win32Exception(nError);
                throw new ExternalException("Could not change service start type: " + win32Exception.Message);
            }

            CloseServiceHandle(serviceHandle);
            CloseServiceHandle(scManagerHandle);
        }
        // Convert start mode to registry value
        static int Value(this ServiceStartMode mode)
        {
            switch (mode)
            {
            case ServiceStartMode.Automatic:
                return(2);

            case ServiceStartMode.Manual:
                return(3);

            case ServiceStartMode.Disabled:
                return(4);

            default:
                return(-1);
            }
        }
        private static uint GetSratModeFlag(ServiceStartMode startMode)
        {
            switch (startMode)
            {
            case ServiceStartMode.Automatic:
                return(SERVICE_AUTO_START);

            case ServiceStartMode.Manual:
                return(SERVICE_DEMAND_START);

            case ServiceStartMode.Disabled:
                return(SERVICE_DISABLED);

            default:
                throw new InvalidEnumArgumentException();
            }
        }
Beispiel #18
0
        private static string ConvertSreviceStartModeToString(ServiceStartMode startType)
        {
            switch (startType)
            {
            case ServiceStartMode.Automatic:
                return("auto");

            case ServiceStartMode.Disabled:
                return("disabled");

            case ServiceStartMode.Manual:
                return("manual");

            default:
                throw new NotSupportedException(string.Format("Service start mode '{0}' is not supported.", startType));
            }
        }
Beispiel #19
0
        public void SetServiceSartMode(string ServiceName, ServiceStartMode startMode)
        {
            PropertyDataCollection outParams;
            long returnValue;

            var inParamsCollection = new List<PropertyDataObject>();
            inParamsCollection.Add(new PropertyDataObject() { Name = "StartMode", Value = Enum.GetName(typeof(ServiceStartMode), startMode) });

            _handler.Handle("ChangeStartMode", inParamsCollection, out outParams);

            returnValue = long.Parse(outParams["ReturnValue"].Value.ToString());

            if (returnValue != 0)
            {
                throw new ProcessInstrumentationException(@"{0} {1}.", ExceptionMessages.Win32_ServiceControlFail, _errorMessageProvider.GetErrorMessage(ErrorMessageProvider.ErrorClass.Win32_Service_Create, returnValue));
            }
        }
Beispiel #20
0
        /// <summary>
        /// Конвертация <see cref="ServiceStartMode"/> to <see cref="ServiceBootFlag"/>.
        /// </summary>
        /// <param name="startMode"><see cref="ServiceStartMode"/> mode.</param>
        /// <returns><see cref="ServiceBootFlag"/> flag.</returns>
        public static ServiceBootFlag ToServiceBootFlag(this ServiceStartMode startMode)
        {
            switch (startMode)
            {
            case ServiceStartMode.Manual:
                return(ServiceBootFlag.DemandStart);

            case ServiceStartMode.Automatic:
                return(ServiceBootFlag.AutoStart);

            case ServiceStartMode.Disabled:
                return(ServiceBootFlag.Disabled);

            default:
                throw new ArgumentOutOfRangeException(nameof(startMode), startMode, null);
            }
        }
Beispiel #21
0
        public WindowsService(string serviceName, string serviceDescription, ServiceStartMode startType = ServiceStartMode.Automatic)
        {
            this.ServiceName                 = serviceName;
            this.EventLog.Log                = "Windows";
            this.CanHandlePowerEvent         = true;
            this.CanHandleSessionChangeEvent = true;
            this.CanPauseAndContinue         = true;
            this.CanShutdown                 = true;
            this.CanStop = true;

            _serviceName        = serviceName;
            _serviceDescription = serviceDescription;
            _startType          = startType;

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomainUnhandledException);
            log4net.Config.XmlConfigurator.Configure();
            _logger = LogManager.GetLogger(this.GetType());
        }
Beispiel #22
0
        private void InitServiceManager()
        {
            AddLog("InitServiceManager starting");

            if (Settings.IsValueSet(LockedSettingName))
            {
                ServiceStartMode StartType = IsSettingLock ? ServiceStartMode.Disabled : ServiceStartMode.Manual;

                foreach (string ServiceName in MonitoredServiceList)
                {
                    StoreServiceStartType(StartTypeTable, ServiceName, StartType);
                }
            }

            UpdateTimer = SafeTimer.Create(OnUpdate, CheckInterval, Logger);

            AddLog("InitServiceManager done");
        }
Beispiel #23
0
        public static void ChangeStartMode(ServiceController svc, ServiceStartMode mode)
        {
            var managerHandle = OpenSCManager(null, null, ServiceControlManagerAllAccess);

            if (managerHandle == IntPtr.Zero)
            {
                throw new ExternalException("Open Service Manager Error");
            }

            var serviceHandle = OpenService(
                managerHandle,
                svc.ServiceName,
                ServiceQueryConfig | ServiceChangeConfig);

            if (serviceHandle == IntPtr.Zero)
            {
                throw new ExternalException("Open Service Error");
            }

            var result = ChangeServiceConfig(
                serviceHandle,
                ServiceNoChange,
                (uint)mode,
                ServiceNoChange,
                null,
                null,
                IntPtr.Zero,
                null,
                null,
                null,
                null);

            if (result == false)
            {
                var error          = Marshal.GetLastWin32Error();
                var win32Exception = new Win32Exception(error);
                throw new ExternalException("Could not change service start type: "
                                            + win32Exception.Message);
            }

            CloseServiceHandle(serviceHandle);
            CloseServiceHandle(managerHandle);
        }
        public bool SetStartupType(ServiceStartMode startMode)
        {
            if (startMode == _serviceController.StartType)
            {
                return(true);
            }

            //Doing this via Management Object allows for real-time service change
            //The new Windows Update Medic Service is pretty harsh on the access control
            bool doneRealtime = SetStartModeViaManagementObject(startMode);

            if (!doneRealtime)
            {
                //If this is done via registry, then a reboot is required
                SetStartModeViaRegistry(startMode);
            }
            _serviceController.Refresh();
            return(doneRealtime);
        }
        public static void ModifyStartMode(ServiceController svc, ServiceStartMode mode)
        {
            var scManagerHandle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);

            if (scManagerHandle == IntPtr.Zero)
            {
                throw new ExternalException("An error occured in the Open Service Manager.");
            }

            var serviceHandle = OpenService(
                scManagerHandle,
                svc.ServiceName,
                SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG);

            if (serviceHandle == IntPtr.Zero)
            {
                throw new ExternalException("An error occured in the Service.");
            }

            var result = ChangeServiceConfig(
                serviceHandle,
                SERVICE_NO_CHANGE,
                (uint)mode,
                SERVICE_NO_CHANGE,
                null,
                null,
                IntPtr.Zero,
                null,
                null,
                null,
                null);

            if (result == false)
            {
                var nError         = Marshal.GetLastWin32Error();
                var win32Exception = new Win32Exception(nError);
                throw new ExternalException("Failed to modify service start type: "
                                            + win32Exception.Message);
            }

            CloseServiceHandle(serviceHandle);
            CloseServiceHandle(scManagerHandle);
        }
Beispiel #26
0
        public static void ChangeStartMode(ServiceController svc, ServiceStartMode mode)
        {
            //var scManagerHandle = OpenSCManager(null, null, SC_MANAGER_CONNECT + SC_MANAGER_ENUMERATE_SERVICE);
            var scManagerHandle = OpenSCManager(null, null, ScManagerAllAccess);
            if (scManagerHandle == IntPtr.Zero)
            {
                throw new ExternalException("Open Service Manager Error");
            }

            var serviceHandle = OpenService(
                scManagerHandle,
                svc.ServiceName,
                ServiceQueryConfig | ServiceChangeConfig);

            if (serviceHandle == IntPtr.Zero)
            {
                throw new ExternalException("Open Service Error");
            }

            var result = ChangeServiceConfig(
                serviceHandle,
                ServiceNoChange,
                (uint) mode,
                ServiceNoChange,
                null,
                null,
                IntPtr.Zero,
                null,
                null,
                null,
                null);

            if (result == false)
            {
                int nError = Marshal.GetLastWin32Error();
                var win32Exception = new Win32Exception(nError);
                throw new ExternalException("Could not change service start type: "
                                            + win32Exception.Message);
            }

            CloseServiceHandle(serviceHandle);
            CloseServiceHandle(scManagerHandle);
        }
        public static void Run(CommandLineParameters options)
        {
            var installUtilArguments = new List<string>();
            installUtilArguments.Add(Assembly.GetExecutingAssembly().Location);
            installUtilArguments.Add("/LogToConsole=true");
            DelayedAutoStart = options.DelayedAutoStart;

            ServiceAccount serviceAccount;
            Enum.TryParse(options.ServiceAccount, true, out serviceAccount);
            Account = serviceAccount;

            ServiceStartMode startType;
            Enum.TryParse(options.StartType, true, out startType);
            StartType = startType;

            if(options.UninstallWindowsService)
                installUtilArguments.Add("/u");

            ManagedInstallerClass.InstallHelper(installUtilArguments.ToArray());
        }
Beispiel #28
0
        public NtServiceDescriptor(string serviceName, string serviceExecutablePath, ServiceAccount serviceAccount, ServiceStartMode serviceStartMode, string serviceDisplayName = null, string serviceUserName = null, string servicePassword = null)
        {
            if (string.IsNullOrEmpty(serviceName))
            {
                throw new ArgumentException("Argument can't be null nor empty.", "serviceName");
            }

            if (string.IsNullOrEmpty(serviceExecutablePath))
            {
                throw new ArgumentException("Argument can't be null nor empty.", "serviceExecutablePath");
            }

            ServiceName           = serviceName;
            ServiceExecutablePath = serviceExecutablePath;
            ServiceAccount        = serviceAccount;
            ServiceStartMode      = serviceStartMode;
            ServiceDisplayName    = serviceDisplayName ?? serviceName;
            ServiceUserName       = serviceUserName;
            ServicePassword       = servicePassword;
        }
        public NtServiceDescriptor(string serviceName, string serviceExecutablePath, ServiceAccount serviceAccount, ServiceStartMode serviceStartMode, string serviceDisplayName = null, string serviceUserName = null, string servicePassword = null)
        {
            if (string.IsNullOrEmpty(serviceName))
              {
            throw new ArgumentException("Argument can't be null nor empty.", "serviceName");
              }

              if (string.IsNullOrEmpty(serviceExecutablePath))
              {
            throw new ArgumentException("Argument can't be null nor empty.", "serviceExecutablePath");
              }

              ServiceName = serviceName;
              ServiceExecutablePath = serviceExecutablePath;
              ServiceAccount = serviceAccount;
              ServiceStartMode = serviceStartMode;
              ServiceDisplayName = serviceDisplayName ?? serviceName;
              ServiceUserName = serviceUserName;
              ServicePassword = servicePassword;
        }
Beispiel #30
0
    public static bool ChangeStartMode(ServiceController svc, ServiceStartMode mode, out int error)
    {
        bool result = false;

        error = 0;

        var scManagerHandle = OpenSCManager(null, null, ScManagerAllAccess);

        if (scManagerHandle != IntPtr.Zero)
        {
            var serviceHandle = OpenService(scManagerHandle, svc.ServiceName, ServiceQueryConfig | ServiceChangeConfig);
            if (serviceHandle != IntPtr.Zero)
            {
                result = ChangeServiceConfig(
                    serviceHandle,
                    ServiceNoChange,
                    (uint)mode,
                    ServiceNoChange,
                    null,
                    null,
                    IntPtr.Zero,
                    null,
                    null,
                    null,
                    null);

                if (!result)
                {
                    error = Marshal.GetLastWin32Error();
                }

                int hResult = CloseServiceHandle(serviceHandle);
                Debug.Assert(hResult == 0, "Failed to close the service");

                hResult = CloseServiceHandle(scManagerHandle);
                Debug.Assert(hResult == 0, "Failed to close the service manager");
            }
        }

        return(result);
    }
Beispiel #31
0
        public static bool ChangeStartModeT(ServiceController svc, ServiceStartMode mode)
        {
            var scManagerHandle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);

            if (scManagerHandle == IntPtr.Zero)
            {
                return(false);
            }

            var serviceHandle = OpenService(
                scManagerHandle,
                svc.ServiceName,
                SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG);

            if (serviceHandle == IntPtr.Zero)
            {
                return(false);
            }

            var result = ChangeServiceConfig(
                serviceHandle,
                SERVICE_NO_CHANGE,
                (uint)mode,
                SERVICE_NO_CHANGE,
                null,
                null,
                IntPtr.Zero,
                null,
                null,
                null,
                null);

            if (result == false)
            {
                return(false);
            }

            CloseServiceHandle(serviceHandle);
            CloseServiceHandle(scManagerHandle);
            return(true);
        }
Beispiel #32
0
        private ServiceStartMode GetServiceStartMode()
        {
            ServiceStartMode toReturn    = ServiceStartMode.Manual;
            bool             targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable);

            try
            {
                ManagementObject wmi = this.RetrieveManagementObject(targetLocal);

                string startMode = wmi.Properties["StartMode"].Value.ToString().Trim();
                switch (startMode)
                {
                case "Auto":
                    toReturn = ServiceStartMode.Automatic;
                    break;

                case "Boot":
                    toReturn = ServiceStartMode.Boot;
                    break;

                case "Disabled":
                    toReturn = ServiceStartMode.Disabled;
                    break;

                case "Manual":
                    toReturn = ServiceStartMode.Manual;
                    break;

                case "System":
                    toReturn = ServiceStartMode.System;
                    break;
                }
            }
            catch (Exception ex)
            {
                this.Log.LogError(String.Format(CultureInfo.CurrentCulture, "An error occurred in GetServiceStartMode of {0} on '{1}'.  Message: {2}", this.ServiceDisplayName, this.MachineName, ex.Message));
                throw;
            }

            return(toReturn);
        }
        private ServiceStartMode toServiceStartMode(StartMode startMode)
        {
            ServiceStartMode serviceStartMode = default(ServiceStartMode);

            switch (startMode)
            {
            case StartMode.Automatic:
                serviceStartMode = ServiceStartMode.Automatic;
                break;

            case StartMode.Disabled:
                serviceStartMode = ServiceStartMode.Disabled;
                break;

            case StartMode.Manual:
                serviceStartMode = ServiceStartMode.Manual;
                break;
            }

            return(serviceStartMode);
        }
Beispiel #34
0
        private void resetForm()
        {
            username    = null;
            password    = null;
            displayName = "User Defined Service";
            serviceName = "User Defined Service";
            startType   = ServiceStartMode.Automatic;
            path        = null;

            serviceDisplayNameTB.Text        = "";
            serviceNameTB.Text               = "";
            serviceStartTypeCB.SelectedIndex = 0;
            serviceAccountCB.Checked         = false;
            usernameTB.Text = "";
            passwordTB.Text = "";
            pathTB.Text     = "";
            userAccountInformationGB.Enabled = false;
            servicesListCB.Items.Clear();
            allServicesCB.Items.Clear();
            runListCB.Items.Clear();
            stopRestartListCB.Items.Clear();
            foreach (ServiceController service in ServiceController.GetServices())
            {
                service.Refresh();
                servicesListCB.Items.Add(service.ServiceName);
                allServicesCB.Items.Add(service.ServiceName);
                if (service.Status != ServiceControllerStatus.Running)
                {
                    runListCB.Items.Add(service.ServiceName);
                }
                else
                {
                    stopRestartListCB.Items.Add(service.ServiceName);
                }
            }
            allServicesCB.SelectedIndex     = 0;
            servicesListCB.SelectedIndex    = 0;
            runListCB.SelectedIndex         = 0;
            stopRestartListCB.SelectedIndex = 0;
        }
Beispiel #35
0
        public static void ChangeStartMode(ServiceController svc, ServiceStartMode mode)
        {
            var scManagerHandle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);

            if (scManagerHandle == IntPtr.Zero)
            {
                throw new ExternalException("Open Service Manager Error");
            }

            var serviceHandle = OpenService(
                scManagerHandle,
                svc.ServiceName,
                SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG);

            if (serviceHandle == IntPtr.Zero)
            {
                throw new ExternalException("Open Service Error");
            }

            var result = ChangeServiceConfig(
                serviceHandle,
                SERVICE_NO_CHANGE,
                (uint)mode,
                SERVICE_NO_CHANGE,
                null,
                null,
                IntPtr.Zero,
                null,
                null,
                null,
                null);

            if (result == false)
            {
                throw new ExternalException("Could not change service start type");
            }

            CloseServiceHandle(serviceHandle);
            CloseServiceHandle(scManagerHandle);
        }
Beispiel #36
0
        public static (ServiceConfiguration ServiceConfiguration, string BinaryPath) ReadServiceConfiguration(SafeServiceHandle serviceHandle, string serviceName)
        {
            NativeMethods.ServiceConfigurationInfo ServiceConfiguration = ReadServiceConfiguration(serviceHandle);

            (ServiceAccount Account, string?Username) = ServiceController.ConvertWindowsUsernameToServiceConfiguration(ServiceConfiguration.lpServiceStartName);

            ServiceStartMode StartMode = ReadServiceDelayedAutoStartConfiguration(serviceHandle)
                                ? ServiceStartMode.AutomaticDelayedStart
                                : (ServiceStartMode)ServiceConfiguration.dwStartType;

            return(
                new ServiceConfiguration
            {
                ServiceName = serviceName,
                DisplayName = ServiceConfiguration.lpDisplayName,
                Description = ReadServiceDescription(serviceHandle),
                StartMode = StartMode,
                Account = Account,
                Username = Username
            },
                ServiceConfiguration.lpBinaryPathName ?? string.Empty);
        }
Beispiel #37
0
        private void ChangeStartMode(string serviceName, ServiceStartMode mode)
        {
            var scManagerHandle = NativeMethods.Service.OpenSCManager(null, null, NativeMethods.Service.SC_MANAGER_ALL_ACCESS);

            if (scManagerHandle == IntPtr.Zero)
            {
                throw new ExternalException("Open Service Manager Error");
            }

            var serviceHandle = NativeMethods.Service.OpenService(scManagerHandle, serviceName, NativeMethods.Service.SERVICE_QUERY_CONFIG | NativeMethods.Service.SERVICE_CHANGE_CONFIG);

            if (serviceHandle == IntPtr.Zero)
            {
                throw new ExternalException("Open Service Error");
            }

            var result = NativeMethods.Service.ChangeServiceConfig(
                serviceHandle,
                NativeMethods.Service.SERVICE_NO_CHANGE,
                (uint)mode,
                NativeMethods.Service.SERVICE_NO_CHANGE,
                null,
                null,
                IntPtr.Zero,
                null,
                null,
                null,
                null);

            if (result == false)
            {
                var nError         = Marshal.GetLastWin32Error();
                var win32Exception = new Win32Exception(nError);
                throw new ExternalException("Could not change service start type: " + win32Exception.Message);
            }

            NativeMethods.Service.CloseServiceHandle(serviceHandle);
            NativeMethods.Service.CloseServiceHandle(scManagerHandle);
        }
        private void LoadOriginalStartMode()
        {
            using (RegistryKey serviceKey = Registry.LocalMachine.OpenSubKey(SERVICES_REG_KEY + Name))
            {
                object original = serviceKey.GetValue(SERVICE_ORIGINAL_START_VALUE_NAME, null);

                if (original == null)
                {
                    SaveOriginalStartMode();
                    original = serviceKey.GetValue(SERVICE_ORIGINAL_START_VALUE_NAME, null);
                }

                if (original != null)
                {
                    OriginalStartMode = (ServiceStartMode)original;
                }
                else
                {
                    StaticViewModel.AddDebugMessage("Unable to determin original start mode");
                }
            }
        }
Beispiel #39
0
        public static void ChangeStartMode(ServiceController svc, ServiceStartMode mode)
        {
            var scManagerHandle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);
            if (scManagerHandle == IntPtr.Zero)
            {
                throw new ExternalException("Open Service Manager Error");
            }

            var serviceHandle = OpenService(
                scManagerHandle,
                svc.ServiceName,
                SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG);

            if (serviceHandle == IntPtr.Zero)
            {
                throw new ExternalException("Open Service Error");
            }

            var result = ChangeServiceConfig(
                serviceHandle,
                SERVICE_NO_CHANGE,
                (uint)mode,
                SERVICE_NO_CHANGE,
                null,
                null,
                IntPtr.Zero,
                null,
                null,
                null,
                null);

            if (result == false)
            {
                int nError = Marshal.GetLastWin32Error();
                var win32Exception = new Win32Exception(nError);
                throw new ExternalException("Could not change service start type: "
                    + win32Exception.Message);
            }
        }
Beispiel #40
0
        /// <summary>
        /// Set start mode of the service.
        /// </summary>
        /// <param name="start"></param>
        /// <returns></returns>
        public ServiceCreateTask StartMode(ServiceStartMode start)
        {
            string arg;

            switch (start)
            {
            case ServiceStartMode.DelayedAuto:
            {
                arg = "Delayed-Auto";
                break;
            }

            default:
            {
                arg = start.ToString();
                break;
            }
            }

            WithArguments($"start={arg}");
            return(this);
        }
        /// <summary> Creates the specified service and returns a SvcControlManager for the service created </summary>
        public static SvcControlManager Create(string serviceName, string displayName, bool interactive,
                                               ServiceStartMode startupType, string exePath, string[] arguments,
                                               string accountName, string password)
        {
            exePath = ArgumentList.EscapeArguments(new string[] { Check.NotEmpty(exePath) });
            if (arguments != null && arguments.Length > 0)
            {
                exePath = String.Format("{0} {1}", exePath, ArgumentList.EscapeArguments(arguments));
            }

            using (SCMHandle hScm = new SCMHandle(SCM_ACCESS.SC_MANAGER_CREATE_SERVICE))
            {
                IntPtr hSvc = Win32.CreateService(
                    hScm,
                    serviceName,
                    displayName ?? serviceName,
                    ServiceAccessRights.SERVICE_ALL_ACCESS,
                    SC_SERVICE_TYPE.SERVICE_WIN32_OWN_PROCESS |
                    (interactive ? SC_SERVICE_TYPE.SERVICE_INTERACTIVE_PROCESS : 0),
                    startupType,
                    SC_SERVICE_ERROR_CONTROL.SERVICE_ERROR_NORMAL,
                    exePath,
                    null,
                    null,
                    null,
                    accountName,
                    password);

                if (hSvc == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                Win32.CloseServiceHandle(hSvc);
            }

            return(new SvcControlManager(serviceName));
        }
Beispiel #42
0
        private void SetStartMode(ServiceStartMode eStartMode)
        {
            if (m_bStartModeAvailable && (eStartMode == m_eStartMode))
            {
                return;
            }

            CheckControlPermission();

            IntPtr oServiceHandle = GetServiceHandle(WindowsServicesHelper.SERVICE_QUERY_CONFIG | WindowsServicesHelper.SERVICE_CHANGE_CONFIG);

            try
            {
                if (!WindowsServicesHelper.ChangeServiceConfig(
                        oServiceHandle,
                        WindowsServicesHelper.SERVICE_NO_CHANGE,
                        (int)eStartMode,
                        WindowsServicesHelper.SERVICE_NO_CHANGE,
                        null,
                        null,
                        IntPtr.Zero,
                        null,
                        null,
                        null,
                        null
                        ))
                {
                    throw CreateSafeWin32Exception();
                }

                m_eStartMode          = eStartMode;
                m_bStartModeAvailable = true;
            }
            finally
            {
                WindowsServicesHelper.CloseServiceHandle(oServiceHandle);
            }
        }
Beispiel #43
0
        public static void SafeChangeStartMode(string serviceName, ServiceStartMode mode)
        {
            ServiceController service = GetService(serviceName);

            if (service == null)
            {
                return;
            }

            string strMode = mode.ToString().ToUpper().TrimStart("SERVICESTARTMODE.");

            try
            {
                if (WinSrvHelper.GetStartupType(service) != strMode)
                {
                    ChangeStartMode(service, mode);  // 将服务设置为 自动启动
                }
            }
            catch (Exception ex)
            {
                NLogHelper.Error(ex);
            }
        }
Beispiel #44
0
        private static string GetStartModeCommandString(ServiceStartMode serviceStartMode)
        {
            switch (serviceStartMode)
            {
            case ServiceStartMode.Boot:
                return("boot");

            case ServiceStartMode.System:
                return("system");

            case ServiceStartMode.Automatic:
                return("auto");

            case ServiceStartMode.Manual:
                return("demand");

            case ServiceStartMode.Disabled:
                return("disabled");

            default:
                return(string.Empty);
            }
        }
Beispiel #45
0
        static bool isFabricHostSvcManual()
        {
            using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default))
            {
                using (RegistryKey key = hklm.OpenSubKey(WindowsFabricHostSvcKey))
                {
                    if (key == null)
                    {
                        return(false);
                    }

                    // get service start options
                    object o = key.GetValue("Start");
                    if (o != null && o is int)
                    {
                        ServiceStartMode startValue = (ServiceStartMode)o;
                        return(startValue == ServiceStartMode.Manual);
                    }

                    return(false);
                }
            }
        }
Beispiel #46
0
        public static void ChangeServiceStartType(string serviceName, ServiceStartMode startType = ServiceStartMode.Manual)
        {
            //Console.WriteLine($"Mudando o serviço '{serviceName}' para '{startType}'");

            try
            {
                var sc = new ServiceController(serviceName);

                if (sc.CanStop)
                {
                    sc.Stop();
                }

                var key = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{sc.ServiceName}", true);
                key.SetValue("Start", (int)startType);

                Console.WriteLine($"Serviço '{serviceName}' alterado para '{startType}'");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Erro mudando o serviço '{serviceName}' para '{startType}'\n\n[[[\n\n{e}\n\n]]]\n");
            }
        }
Beispiel #47
0
		public SetServiceCommand()
		{
			string[] strArrays = new string[1];
			strArrays[0] = ".";
			this.computername = strArrays;
			this.startupType = ServiceStartMode.Manual | ServiceStartMode.Automatic | ServiceStartMode.Disabled;
		}
Beispiel #48
0
		public NewServiceCommand()
		{
			this.startupType = ServiceStartMode.Automatic;
		}
 public WinServiceCreateOptions WithStartMode(ServiceStartMode mode)
 {
     _startMode = mode;
     return this;
 }
Beispiel #50
0
		private static uint GetSratModeFlag(ServiceStartMode startMode)
		{
			switch (startMode)
			{
			case ServiceStartMode.Automatic:
				return SERVICE_AUTO_START;
			case ServiceStartMode.Manual:
				return SERVICE_DEMAND_START;
			case ServiceStartMode.Disabled:
				return SERVICE_DISABLED;
			default:
				throw new InvalidEnumArgumentException();
			}
		}
Beispiel #51
0
		public static void InstallService(string serviceName, string displayName, string servicePath, ServiceStartMode startMode, ServiceAccountDescriptor accountDescriptor)
		{
			uint startModeFlag = GetSratModeFlag(startMode);
			string accountName, password;
			GetAccountFields(accountDescriptor, out accountName, out password);
			if (accountDescriptor.AccountType == ServiceAccount.User)
				AccountRights.SetRights(accountDescriptor.AccountName, "SeServiceLogonRight", true);
			IntPtr hSCMHandle = IntPtr.Zero, hServHandle = IntPtr.Zero;
			try
			{
				hSCMHandle = OpenSCManager(null, null, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE);
				if (hSCMHandle == IntPtr.Zero)
					throw new Win32Exception();
				hServHandle = CreateService(hSCMHandle,
											serviceName,
											displayName,
											SC_MANAGER_CREATE_SERVICE,
											SERVICE_WIN32_OWN_PROCESS,
											startModeFlag,
											SERVICE_ERROR_NORMAL,
											servicePath,
											null,
											UIntPtr.Zero,
											null,
											accountName,
											password);
				if (hServHandle == IntPtr.Zero)
					throw new Win32Exception();
			}
			finally
			{
				if (hServHandle != IntPtr.Zero)
					CloseServiceHandle(hServHandle);
				if (hSCMHandle != IntPtr.Zero)
					CloseServiceHandle(hSCMHandle);
			}
		}
Beispiel #52
0
        /// <summary>
        /// This routine updates the start mode of the provided service.
        /// Add Reference to System.Management .net Assembly
        /// </summary>
        /// <param name="serviceName">Name of the service to be updated</param>
        /// <param name="serviceStart"></param>
        /// <param name="errorMsg">If applicable, error message assoicated with exception</param>
        /// <returns>Success or failure.  False is returned if service is not found.</returns>
        private static bool SetServiceStartupMode(string serviceName, ServiceStartMode serviceStart, out string errorMsg)
        {
            uint success = 1;
            errorMsg = string.Empty;
            string startMode = serviceStart.ToString();

            string filter =
                String.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName);

            var query = new ManagementObjectSearcher(filter);

            try
            {
                ManagementObjectCollection services = query.Get();

                foreach (ManagementObject service in services)
                {
                    ManagementBaseObject inParams = service.GetMethodParameters("ChangeStartMode");
                    inParams["startmode"] = startMode;

                    ManagementBaseObject outParams =
                        service.InvokeMethod("ChangeStartMode", inParams, null);
                    if (outParams != null) success = Convert.ToUInt16(outParams.Properties["ReturnValue"].Value);
                }
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                throw;
            }
            return (success == 0);
        }
Beispiel #53
0
		public static void InstallService(string serviceName, string displayName, ServiceStartMode startMode, ServiceAccountDescriptor accountDescriptor)
		{
			string servicePath = Assembly.GetExecutingAssembly().Location;
			InstallService(serviceName, displayName, servicePath, startMode, accountDescriptor);
		}
 private static extern IntPtr CreateService(IntPtr hScManager, string serviceName, string displayName,
                                            ServiceAccessRights desiredAccess, ServiceType serviceType,
                                            ServiceStartMode startType, ServiceErrorControl errorControl,
                                            string binaryPathName, string loadOrderGroup, IntPtr tagId,
                                            string dependencies, string serviceStartName, string password);
Beispiel #55
0
        //Builder (Hereda el constructor base)
        public ServiceMonitor(string monitorName,string target, string remoteMachine, string username, string password, string domain,
            ServiceState? state, ServiceStatus? status, ServiceStartMode? startMode, bool critic)
            : base(monitorName, target, remoteMachine, username, password, domain)
        {
            this.wantedState = state;
            this.wantedStatus = status;
            this.wantedStartMode = startMode;

            this.actualState = null;
            this.actualStatus = null;
            this.actualStartMode = null;

            this.critic = critic;
            this.mode = Mode.service;
        }
        private static string ConvertSreviceStartModeToString(ServiceStartMode startType)
        {
            switch (startType)
              {
            case ServiceStartMode.Automatic:
              return "auto";

            case ServiceStartMode.Disabled:
              return "disabled";

            case ServiceStartMode.Manual:
              return "manual";

            default:
              throw new NotSupportedException(string.Format("Service start mode '{0}' is not supported.", startType));
              }
        }
Beispiel #57
0
        static void SafeMain(string[] args)
        {
            AddERExcludedApplication(Process.GetCurrentProcess().MainModule.ModuleName);
            Console.WriteLine("TraceSpy Service - " + (Environment.Is64BitProcess ? "64" : "32") + "-bit - Build Number " + Assembly.GetExecutingAssembly().GetInformationalVersion());
            Console.WriteLine("Copyright (C) SoftFluent S.A.S 2012-" + DateTime.Now.Year + ". All rights reserved.");

            var token = Extensions.GetTokenElevationType();
            if (token != TokenElevationType.Full)
            {
                Console.WriteLine("");
                Console.WriteLine("Warning: token elevation type (UAC level) is " + token + ". You may experience access denied errors from now on. You may fix these errors if you restart with Administrator rights or without UAC.");
                Console.WriteLine("");
            }

            OptionHelp = CommandLineUtilities.GetArgument(args, "?", false);
            if (!OptionHelp)
            {
                OptionHelp = CommandLineUtilities.GetArgument(args, "h", false);
                if (!OptionHelp)
                {
                    OptionHelp = CommandLineUtilities.GetArgument(args, "help", false);
                }
            }
            OptionService = CommandLineUtilities.GetArgument(args, "s", false);

            if (!OptionService)
            {
                if (OptionHelp)
                {
                    Console.WriteLine("Format is " + Assembly.GetExecutingAssembly().GetName().Name + ".exe [options]");
                    Console.WriteLine("[options] can be a combination of the following:");
                    Console.WriteLine("    /?                     Displays this help");
                    Console.WriteLine("    /i                     Installs the <name> service");
                    Console.WriteLine("    /k                     Kills this process on any exception");
                    Console.WriteLine("    /u                     Uninstalls the <name> service");
                    Console.WriteLine("    /t                     Displays traces on the console");
                    Console.WriteLine("    /l:<name>              Locale used");
                    Console.WriteLine("                           default is " + CultureInfo.CurrentCulture.LCID);
                    Console.WriteLine("    /name:<name>           (Un)Installation uses <name> for the service name");
                    Console.WriteLine("                           default is \"" + DefaultName + "\"");
                    Console.WriteLine("    /displayName:<dname>   (Un)Installation uses <dname> for the display name");
                    Console.WriteLine("                           default is \"" + DefaultDisplayName + "\"");
                    Console.WriteLine("    /description:<desc.>   Installation ses <desc.> for the service description");
                    Console.WriteLine("                           default is \"" + DefaultDisplayName + "\"");
                    Console.WriteLine("    /startType:<type>      Installation uses <type> for the service start mode");
                    Console.WriteLine("                           default is \"" + ServiceStartMode.Manual + "\"");
                    Console.WriteLine("                           Values are " + ServiceStartMode.Automatic + ", " + ServiceStartMode.Disabled + " or " + ServiceStartMode.Manual);
                    Console.WriteLine("    /user:<name>           Name of the account under which the service should run");
                    Console.WriteLine("                           default is Local System");
                    Console.WriteLine("    /password:<text>       Password to the account name");
                    Console.WriteLine("    /config:<path>         Path to the configuration file");
                    Console.WriteLine("    /dependson:<list>      A comma separated list of service to depend on");
                    Console.WriteLine("");
                    Console.WriteLine("Examples:");
                    Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Name + " /i /name:MyService /displayName:\"My Service\" /startType:Automatic");
                    Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Name + " /u /name:MyOtherService");
                    return;
                }
            }

            OptionTrace = CommandLineUtilities.GetArgument(args, "t", false);
            OptionKillOnException = CommandLineUtilities.GetArgument(args, "k", false);
            OptionInstall = CommandLineUtilities.GetArgument(args, "i", false);
            OptionStartType = (ServiceStartMode)CommandLineUtilities.GetArgument(args, "starttype", ServiceStartMode.Manual);
            OptionLcid = CommandLineUtilities.GetArgument<string>(args, "l", null);
            OptionUninstall = CommandLineUtilities.GetArgument(args, "u", false);
            OptionAccount = (ServiceAccount)CommandLineUtilities.GetArgument(args, "user", ServiceAccount.User);
            OptionPassword = CommandLineUtilities.GetArgument<string>(args, "password", null);
            OptionUser = CommandLineUtilities.GetArgument<string>(args, "user", null);
            string dependsOn = CommandLineUtilities.GetArgument<string>(args, "dependson", null);
            if (!string.IsNullOrEmpty(dependsOn))
            {
                OptionDependsOn = dependsOn.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            }
            else
            {
                OptionDependsOn = null;
            }
            OptionConfigPath = CommandLineUtilities.GetArgument<string>(args, "config", null);
            if (!string.IsNullOrEmpty(OptionConfigPath) && !Path.IsPathRooted(OptionConfigPath))
            {
                OptionConfigPath = Path.GetFullPath(OptionConfigPath);
            }
            _configuration = ServiceSection.Get(OptionConfigPath);

            OptionDisplayName = CommandLineUtilities.GetArgument(args, "displayname", DefaultDisplayName);
            OptionDescription = CommandLineUtilities.GetArgument(args, "description", DefaultDescription);

            if (OptionInstall)
            {
                ServiceInstaller si = new ServiceInstaller();
                ServiceProcessInstaller spi = new ServiceProcessInstaller();
                si.ServicesDependedOn = OptionDependsOn;
                Console.WriteLine("OptionAccount=" + OptionAccount);
                Console.WriteLine("OptionUser="******"Password cannot be empty if Account is set to User.");
                            return;
                        }

                        spi.Username = OptionUser;
                        spi.Password = OptionPassword;
                    }
                }
                else
                {
                    spi.Account = OptionAccount;
                }

                si.Parent = spi;
                si.DisplayName = OptionDisplayName;
                si.Description = OptionDescription;
                si.ServiceName = OptionName;
                si.StartType = OptionStartType;
                si.Context = new InstallContext(Assembly.GetExecutingAssembly().GetName().Name + ".install.log", null);

                string asmpath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, AppDomain.CurrentDomain.FriendlyName);

                // TODO: add instance specific parameters here (ports, etc...)
                string binaryPath = "\"" + asmpath + "\""       // exe path
                    + " /s"                                     // we run as a service
                    + " /name:" + OptionName;                    // our name

                if (!string.IsNullOrEmpty(OptionConfigPath))
                {
                    binaryPath += " /c:\"" + OptionConfigPath + "\"";
                }

                si.Context.Parameters["assemblypath"] = binaryPath;

                IDictionary stateSaver = new Hashtable();
                si.Install(stateSaver);

                // see remarks in the function
                FixServicePath(si.ServiceName, binaryPath);
                return;
            }

            if (OptionUninstall)
            {
                ServiceInstaller si = new ServiceInstaller();
                ServiceProcessInstaller spi = new ServiceProcessInstaller();
                si.Parent = spi;
                si.ServiceName = OptionName;

                si.Context = new InstallContext(Assembly.GetExecutingAssembly().GetName().Name + ".uninstall.log", null);
                si.Uninstall(null);
                return;
            }

            if (!OptionService)
            {
                if (OptionTrace)
                {
                    Trace.Listeners.Add(new ConsoleListener());
                }

                if (!string.IsNullOrEmpty(OptionLcid))
                {
                    Extensions.SetCurrentThreadCulture(OptionLcid);
                }

                Console.WriteLine("Console Mode");
                Console.WriteLine("Service Host name: " + OptionName);
                WindowsIdentity identity = WindowsIdentity.GetCurrent();
                Console.WriteLine("Service Host identity: " + (identity != null ? identity.Name : "null"));
                Console.WriteLine("Service Host bitness: " + (IntPtr.Size == 4 ? "32-bit" : "64-bit"));
                Console.WriteLine("Service Host display name: '" + OptionDisplayName + "'");
                Console.WriteLine("Service Host event log source: " + _service.EventLog.Source);
                Console.WriteLine("Service Host trace enabled: " + OptionTrace);
                Console.WriteLine("Service Host administrator mode: " + IsAdministrator());

                string configPath = OptionConfigPath;
                if (configPath == null)
                {
                    configPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
                }
                Console.WriteLine("Service Host config file path: " + configPath);
                Console.WriteLine("Service Host current locale: " + Thread.CurrentThread.CurrentCulture.LCID + " (" + Thread.CurrentThread.CurrentCulture.Name + ")");

                Console.Title = OptionDisplayName;

                ConsoleControl cc = new ConsoleControl();
                cc.Event += OnConsoleControlEvent;

                _service.InternalStart(args);
                if (!_stopping)
                {
                    _service.InternalStop();
                }
                else
                {
                    int maxWaitTime = Configuration.ConsoleCloseMaxWaitTime;
                    if (maxWaitTime <= 0)
                    {
                        maxWaitTime = Timeout.Infinite;
                    }
                    _closed.WaitOne(maxWaitTime, Configuration.WaitExitContext);
                }
                return;
            }

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] { _service };
            Run(ServicesToRun);
        }
Beispiel #58
0
 public InstallHost(ServiceDescription description, ServiceStartMode startMode, IEnumerable<string> dependencies,
     Credentials credentials, IEnumerable<Action> preActions, IEnumerable<Action> postActions, bool sudo)
     : base(description, startMode, dependencies, credentials, preActions, postActions, sudo)
 {
 }
Beispiel #59
0
 public static void SetStartupType(string serviceName, ServiceStartMode mode)
 {
     //if (startupType != "Automatic" && startupType != "Manual" && startupType != "Disabled") ;
     //throw new Exception("The valid values are Automatic, Manual or Disabled");
     if(serviceName!=null)
     {
         ////construct the management path
         //string path="Win32_Service.Name='"+serviceName+"'";
         //ManagementPath p=new ManagementPath(path);
         ////construct the management object
         //ManagementObject ManagementObj=new ManagementObject(p);
         ////we will use the invokeMethod method of the ManagementObject class
         //object[] parameters=new object[1];
         //parameters[0]=mode.ToString();
         //var result=ManagementObj.InvokeMethod("ChangeStartMode",parameters);
         //return Enum.Parse(typeof(string),result.ToString());
         var svc = new ServiceController(serviceName);
         ChangeStartMode(svc, ServiceStartMode.Automatic);
     }
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ServiceType"></param>
        /// <param name="StartMode"></param>
        /// <param name="ServiceName"></param>
        /// <param name="DisplayName"></param>
        /// <param name="Description"></param>
        public ServiceInstallerAttribute(Type ServiceType, 
            ServiceStartMode StartMode, string ServiceName, string DisplayName, string Description)
            : this(ServiceType, StartMode, ServiceName, DisplayName, Description, ServiceAccount.User, null, null)
        {

        }