Beispiel #1
0
        public static bool CreateService(string serviceName, string displayName, ServiceAccess access,
            ServiceTypes type, ServiceStart start, ServiceError error, string path,
            string orderGroup, string tagId, string dep, string username, string password, string server = null)
        {
            IntPtr manager = IntPtr.Zero;
            IntPtr service = IntPtr.Zero;

            try
            {
                manager = OpenSCManager(server, null, ScmAccess.ScManagerAllAccess);

                if (manager != IntPtr.Zero)
                {
                    service = CreateService(manager, serviceName, displayName, (uint) access, (uint) type, (uint) start,
                        (uint) error, path, orderGroup, tagId, dep, username, password);

                    if (service != IntPtr.Zero)
                    {
                        return true;
                    }
                }
            }
            finally
            {
                if (service != IntPtr.Zero) CloseServiceHandle(service);
                if (manager != IntPtr.Zero) CloseServiceHandle(manager);
            }

            return false;
        }
 public ServiceControllerExMix(ManagementObject managementObject)
 {
     this.service = new ServiceController(managementObject["DisplayName"].ToString(), managementObject["SystemName"].ToString());
     machineName  = managementObject["SystemName"].ToString();
     if (managementObject["StartMode"].ToString() == "Auto")
     {
         serviceStartup = ServiceStart.Automatic;
     }
     else if (managementObject["StartMode"].ToString() == "Manual")
     {
         serviceStartup = ServiceStart.Manual;
     }
     else if (managementObject["StartMode"].ToString() == "Disabled")
     {
         serviceStartup = ServiceStart.Disabled;
     }
     else
     {
         serviceStartup = ServiceStart.Unknown;
     }
     account = managementObject["StartName"].ToString();
     if (managementObject["Description"] != null)
     {
         description = managementObject["Description"].ToString();
     }
     executablePath = managementObject["PathName"].ToString();
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="serviceStart"></param>
        public static void SetServiceStart(String serviceName, ServiceStart serviceStart)
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(
                "SYSTEM\\CurrentControlSet\\Services\\" + serviceName, true);

            key.SetValue("Start", (int)serviceStart);
            key.Close();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static ServiceStart GetServiceStart(String serviceName)
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(
                "SYSTEM\\CurrentControlSet\\Services\\" + serviceName);
            ServiceStart start = (ServiceStart)key.GetValue("Start");

            key.Close();
            return(start);
        }
 private void RefreshInternal()
 {
     displayName = managementObject["DisplayName"].ToString();
     serviceName = managementObject["Name"].ToString();
     if (managementObject["Description"] != null)
     {
         description = managementObject["Description"].ToString();
     }
     if (managementObject["State"].ToString() == "Running")
     {
         status = ServiceControllerStatus.Running;
     }
     else if (managementObject["State"].ToString() == "Stopped")
     {
         status = ServiceControllerStatus.Stopped;
     }
     else if (managementObject["State"].ToString() == "Paused")
     {
         status = ServiceControllerStatus.Paused;
     }
     else if (managementObject["State"].ToString() == "Start Pending")
     {
         status = ServiceControllerStatus.StartPending;
     }
     else if (managementObject["State"].ToString() == "Stop Pending")
     {
         status = ServiceControllerStatus.StopPending;
     }
     else if (managementObject["State"].ToString() == "Pause Pending")
     {
         status = ServiceControllerStatus.PausePending;
     }
     else
     {
         status = ServiceControllerStatus.ContinuePending;
     }
     if (managementObject["StartMode"].ToString() == "Auto")
     {
         serviceStartup = ServiceStart.Automatic;
     }
     else if (managementObject["StartMode"].ToString() == "Manual")
     {
         serviceStartup = ServiceStart.Manual;
     }
     else if (managementObject["StartMode"].ToString() == "Disabled")
     {
         serviceStartup = ServiceStart.Disabled;
     }
     else
     {
         serviceStartup = ServiceStart.Unknown;
     }
     canStop        = (bool)managementObject["AcceptStop"];
     canPause       = (bool)managementObject["AcceptPause"];
     executablePath = managementObject["PathName"].ToString();
     account        = managementObject["StartName"].ToString();
 }
        /// <summary>
        /// Install a Windows service.
        /// </summary>
        /// <param name="machineName">
        /// The name of the target computer. If the value is null or an empty 
        /// string, the function connects to the SCM on the local machine.
        /// </param>
        /// <param name="serviceName">
        /// The name of the service to install. The maximum string length is 256 
        /// characters.
        /// </param>
        /// <param name="displayName">
        /// The display name to be used by user interface programs to identify the 
        /// service. This string has a maximum length of 256 chars. 
        /// </param>
        /// <param name="dwStartType">
        /// The service start options. The parameter can be one of the following 
        /// values: SERVICE_AUTO_START, SERVICE_BOOT_START, SERVICE_DEMAND_START, 
        /// SERVICE_DISABLED, SERVICE_SYSTEM_START.
        /// </param>
        /// <param name="binaryPath">
        /// The full path to the service binary file. 
        /// </param>
        /// <param name="serviceStartName">
        /// The name of the account under which the service should run. If this 
        /// parameter is NULL, CreateService uses the LocalSystem account. The 
        /// parameter can also be "NT AUTHORITY\LocalService", 
        /// "NT AUTHORITY\NetworkService", or in the form of "DomainName\UserName", 
        /// or ".\UserName".
        /// </param>
        /// <param name="password">
        /// The password to the account name specified by the serviceStartName 
        /// parameter. Specify an empty string if the account has no password or if 
        /// the service runs in the LocalService, NetworkService, or LocalSystem 
        /// account.
        /// </param>
        /// <returns></returns>
        public static void InstallService(string machineName, string serviceName,
            string displayName, ServiceStart dwStartType, string binaryPath, 
            string serviceStartName, string password)
        {
            SafeServiceHandle schSCManager = null;
            SafeServiceHandle schService = null;

            try
            {
                // Get a handle to the SCM database.
                schSCManager = NativeMethods.OpenSCManager(
                    machineName,
                    null,
                    ServiceControlAccessRights.SC_MANAGER_CREATE_SERVICE);
                if (schSCManager.IsInvalid)
                {
                    throw new Win32Exception();
                }

                // Create the service.
                schService = NativeMethods.CreateService(
                    schSCManager,
                    serviceName,
                    displayName,
                    ServiceAccessRights.SERVICE_ALL_ACCESS,
                    ServiceType.SERVICE_WIN32_OWN_PROCESS,
                    dwStartType, 
                    ServiceError.SERVICE_ERROR_NORMAL,
                    binaryPath, 
                    null, 
                    null, 
                    null, 
                    serviceStartName, 
                    password);
                if (schService.IsInvalid)
                {
                    throw new Win32Exception();
                }
            }
            finally
            {
                if (schSCManager != null)
                {
                    schSCManager.Close();
                }
                if (schService != null)
                {
                    schService.Close();
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// Install a Windows service.
        /// </summary>
        /// <param name="machineName">
        /// The name of the target computer. If the value is null or an empty
        /// string, the function connects to the SCM on the local machine.
        /// </param>
        /// <param name="serviceName">
        /// The name of the service to install. The maximum string length is 256
        /// characters.
        /// </param>
        /// <param name="displayName">
        /// The display name to be used by user interface programs to identify the
        /// service. This string has a maximum length of 256 chars.
        /// </param>
        /// <param name="dwStartType">
        /// The service start options. The parameter can be one of the following
        /// values: SERVICE_AUTO_START, SERVICE_BOOT_START, SERVICE_DEMAND_START,
        /// SERVICE_DISABLED, SERVICE_SYSTEM_START.
        /// </param>
        /// <param name="binaryPath">
        /// The full path to the service binary file.
        /// </param>
        /// <param name="serviceStartName">
        /// The name of the account under which the service should run. If this
        /// parameter is NULL, CreateService uses the LocalSystem account. The
        /// parameter can also be "NT AUTHORITY\LocalService",
        /// "NT AUTHORITY\NetworkService", or in the form of "DomainName\UserName",
        /// or ".\UserName".
        /// </param>
        /// <param name="password">
        /// The password to the account name specified by the serviceStartName
        /// parameter. Specify an empty string if the account has no password or if
        /// the service runs in the LocalService, NetworkService, or LocalSystem
        /// account.
        /// </param>
        /// <returns></returns>
        public static void InstallService(string machineName, string serviceName,
                                          string displayName, ServiceStart dwStartType, string binaryPath,
                                          string serviceStartName, string password)
        {
            SafeServiceHandle schSCManager = null;
            SafeServiceHandle schService   = null;

            try
            {
                // Get a handle to the SCM database.
                schSCManager = NativeMethods.OpenSCManager(
                    machineName,
                    null,
                    ServiceControlAccessRights.SC_MANAGER_CREATE_SERVICE);
                if (schSCManager.IsInvalid)
                {
                    throw new Win32Exception();
                }

                // Create the service.
                schService = NativeMethods.CreateService(
                    schSCManager,
                    serviceName,
                    displayName,
                    ServiceAccessRights.SERVICE_ALL_ACCESS,
                    ServiceType.SERVICE_WIN32_OWN_PROCESS,
                    dwStartType,
                    ServiceError.SERVICE_ERROR_NORMAL,
                    binaryPath,
                    null,
                    null,
                    null,
                    serviceStartName,
                    password);
                if (schService.IsInvalid)
                {
                    throw new Win32Exception();
                }
            }
            finally
            {
                if (schSCManager != null)
                {
                    schSCManager.Close();
                }
                if (schService != null)
                {
                    schService.Close();
                }
            }
        }
Beispiel #8
0
 public static extern IntPtr CreateService(
     IntPtr hScManager,
     string lpServiceName,
     string lpDisplayName,
     ServiceAccess dwDesiredAccess,
     ServiceType dwServiceType,
     ServiceStart dwStartType,
     ServiceError dwErrorControl,
     string lpBinaryPathName,
     string?lpLoadOrderGroup,
     string?lpdwTagId,
     string?lpDependencies,
     string?lpServiceStartName,
     string?lpPassword);
Beispiel #9
0
 public static extern SafeServiceHandle CreateService(
     SafeServiceHandle hSCManager,
     string lpServiceName,
     string lpDisplayName,
     ServiceAccessRights dwDesiredAccess,
     ServiceType dwServiceType,
     ServiceStart dwStartType,
     ServiceError dwErrorControl,
     string lpBinaryPathName,
     string lpLoadOrderGroup,
     string lpdwTagId,
     string lpDependencies,
     string lpServiceStartName,
     string lpPassword);
Beispiel #10
0
        public static bool CreateService(string serviceName, string displayName, ServiceAccess access,
                                         ServiceTypes type, ServiceStart start, ServiceError error, string path,
                                         string orderGroup, string tagId, string dep, string username, string password, string server = null)
        {
            IntPtr manager = IntPtr.Zero;

            IntPtr service = IntPtr.Zero;

            try
            {
                manager = OpenSCManager(server, null, ScmAccess.ScManagerAllAccess);

                if (manager != IntPtr.Zero)
                {
                    service = CreateService(manager, serviceName, displayName, (uint)access, (uint)type, (uint)start,
                                            (uint)error, path, orderGroup, tagId, dep, username, password);

                    if (service != IntPtr.Zero)
                    {
                        return(true);
                    }
                }
            }
            finally
            {
                if (service != IntPtr.Zero)
                {
                    CloseServiceHandle(service);
                }
                if (manager != IntPtr.Zero)
                {
                    CloseServiceHandle(manager);
                }
            }

            return(false);
        }
Beispiel #11
0
        public void ChangeServiceStartType(string serviceName, ServiceStart startType)
        {
            //Obtain a handle to the service control manager database
            IntPtr scmHandle = OpenSCManager(null, null, ScmAccessRights.Connect);

            if (scmHandle == IntPtr.Zero)
            {
                throw new Exception("Failed to obtain a handle to the service control manager database.");
            }

            //Obtain a handle to the specified windows service
            IntPtr serviceHandle = OpenService(scmHandle, serviceName, ServiceAccessRights.QueryConfig | ServiceAccessRights.ChangeConfig);

            if (serviceHandle == IntPtr.Zero)
            {
                throw new Exception(string.Format("Failed to obtain a handle to service \"{0}\".", serviceName));
            }

            bool changeServiceSuccess = ChangeServiceConfig(serviceHandle, SERVICE_NO_CHANGE, (uint)startType, SERVICE_NO_CHANGE, null, null, IntPtr.Zero, null, null, null, null);

            if (!changeServiceSuccess)
            {
                string msg = string.Format("Failed to update service configuration for service \"{0}\". ChangeServiceConfig returned error {1}.", serviceName, Marshal.GetLastWin32Error().ToString());
                throw new Exception(msg);
            }

            //Clean up
            if (scmHandle != IntPtr.Zero)
            {
                CloseServiceHandle(scmHandle);
            }
            if (serviceHandle != IntPtr.Zero)
            {
                CloseServiceHandle(serviceHandle);
            }
        }
Beispiel #12
0
        /// <summary>
        /// Processes the specified start.
        /// </summary>
        /// <param name="start">The start.</param>
        /// <param name="args">The args.</param>
        /// <returns>True if succeeded; otherwise false.</returns>
        public bool Process(ServiceStart start, string[] args)
        {
            ModuleProc PROC     = new ModuleProc(this.DYN_MODULE_NAME, "Process");
            bool       result   = true;
            bool       validArg = false;

            try
            {
                if (string.Compare(_operation, "/install", true) == 0)
                {
                    validArg = true;
                    Log.Info(PROC, "Argument : Service Installation");

                    ServiceControllerEx.InstallService(null, _serviceName, _displayName,
                                                       start, _binaryPath, null, string.Empty);

                    Log.Info(PROC, "Service installed successfully.");
                }
                else if (string.Compare(_operation, "/uninstall", true) == 0)
                {
                    validArg = true;
                    Log.Info(PROC, "Argument : Service Uninstallation");

                    ServiceControllerEx.UninstallService(null, _serviceName);

                    Log.Info(PROC, "Service uninstalled successfully.");
                }
                else if (string.Compare(_operation, "/start", true) == 0)
                {
                    validArg = true;
                    Log.Info(PROC, "Argument : Service Start");

                    ServiceController controller = new ServiceController(_serviceName, ".");
                    controller.Start(args);
                    controller.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30));

                    Log.Info(PROC, "Service started successfully.");
                }
                else if (string.Compare(_operation, "/stop", true) == 0)
                {
                    validArg = true;
                    Log.Info(PROC, "Argument : Service Stop");

                    ServiceController controller = new ServiceController(_serviceName, ".");
                    controller.Stop();
                    controller.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30));

                    Log.Info(PROC, "Service stopped successfully.");
                }
                else
                {
                    Log.Info(PROC, "Argument : Unrecognized input is given.");
                    result = false;
                }
            }
            catch (Exception ex)
            {
                Log.Exception(PROC, ex);
                result = false;
            }
            return(result || validArg);
        }
        /// <summary>
        /// Processes the specified start.
        /// </summary>
        /// <param name="start">The start.</param>
        /// <param name="args">The args.</param>
        /// <returns>True if succeeded; otherwise false.</returns>
        public bool Process(ServiceStart start, string[] args)
        {
            ModuleProc PROC = new ModuleProc(this.DYN_MODULE_NAME, "Process");
            bool result = true;
            bool validArg = false;

            try
            {
                if (string.Compare(_operation, "/install", true) == 0)
                {
                    validArg = true;
                    Log.Info(PROC, "Argument : Service Installation");

                    ServiceControllerEx.InstallService(null, _serviceName, _displayName,
                        start, _binaryPath, null, string.Empty);

                    Log.Info(PROC, "Service installed successfully.");
                }
                else if (string.Compare(_operation, "/uninstall", true) == 0)
                {
                    validArg = true;
                    Log.Info(PROC, "Argument : Service Uninstallation");

                    ServiceControllerEx.UninstallService(null, _serviceName);

                    Log.Info(PROC, "Service uninstalled successfully.");
                }
                else if (string.Compare(_operation, "/start", true) == 0)
                {
                    validArg = true;
                    Log.Info(PROC, "Argument : Service Start");

                    ServiceController controller = new ServiceController(_serviceName, ".");
                    controller.Start(args);
                    controller.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30));

                    Log.Info(PROC, "Service started successfully.");
                }
                else if (string.Compare(_operation, "/stop", true) == 0)
                {
                    validArg = true;
                    Log.Info(PROC, "Argument : Service Stop");

                    ServiceController controller = new ServiceController(_serviceName, ".");
                    controller.Stop();
                    controller.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30));

                    Log.Info(PROC, "Service stopped successfully.");
                }
                else
                {
                    Log.Info(PROC, "Argument : Unrecognized input is given.");
                    result = false;
                }
            }
            catch (Exception ex)
            {
                Log.Exception(PROC, ex);
                result = false;
            }
            return (result || validArg);
        }
Beispiel #14
0
        public static bool SetServiceConfig(
            string serviceName,
            ServiceTypes? type = null,
            ServiceStart? startMode = null,
            ServiceError? error = null,
            string binaryPathName = null,
            string loadOrderGroup = null,
            IntPtr tagId = default(IntPtr),
            string dependencies = null,
            string startName = null,
            string password = null,
            string displayName = null,
            string server = null)
        {
            IntPtr manager = IntPtr.Zero;
            IntPtr service = IntPtr.Zero;

            try
            {
                manager = OpenSCManager(server, null, ScmAccess.ScManagerAllAccess);

                if (manager != IntPtr.Zero)
                {
                    service = OpenService(manager, serviceName, ServiceAccess.ServiceChangeConfig);

                    if (service != IntPtr.Zero)
                    {
                        return ChangeServiceConfig(
                            service,
                            type.HasValue ? (uint) type.Value : ServiceNoChange,
                            startMode.HasValue ? (uint) startMode.Value : ServiceNoChange,
                            error.HasValue ? (uint) error.Value : ServiceNoChange,
                            binaryPathName,
                            loadOrderGroup,
                            tagId,
                            dependencies,
                            startName,
                            password,
                            displayName);
                    }
                }
            }
            finally
            {
                if (service != IntPtr.Zero) CloseServiceHandle(service);
                if (manager != IntPtr.Zero) CloseServiceHandle(manager);
            }

            return false;
        }
 public static extern SafeServiceHandle CreateService(
     SafeServiceHandle hSCManager,
     string lpServiceName,
     string lpDisplayName,
     ServiceAccessRights dwDesiredAccess,
     ServiceType dwServiceType,
     ServiceStart dwStartType,
     ServiceError dwErrorControl,
     string lpBinaryPathName,
     string lpLoadOrderGroup,
     string lpdwTagId,
     string lpDependencies,
     string lpServiceStartName,
     string lpPassword);
        /// <summary>
        /// Creates or opens the specified service.
        /// </summary>
        /// <param name="ServiceName">Name of the service.</param>
        /// <param name="DisplayName">The display name.</param>
        /// <param name="ServiceAccess">The service access.</param>
        /// <param name="ServiceType">Type of the service.</param>
        /// <param name="ServiceStart">The service start.</param>
        /// <param name="ServiceError">The service error.</param>
        /// <param name="File">The file.</param>
        internal static IntPtr CreateOrOpen(string ServiceName, string DisplayName, ServiceAccess ServiceAccess, ServiceType ServiceType, ServiceStart ServiceStart, ServiceError ServiceError, FileInfo File)
        {
            var Handle = Service.Create(ServiceName, DisplayName, ServiceAccess, ServiceType, ServiceStart, ServiceError, File);

            if (Handle == IntPtr.Zero)
            {
                return(Service.Open(ServiceName, ServiceAccess));
            }

            return(Handle);
        }
        /// <summary>
        /// Creates the specified service.
        /// </summary>
        /// <param name="ServiceName">Name of the service.</param>
        /// <param name="DisplayName">The display name.</param>
        /// <param name="ServiceAccess">The service access.</param>
        /// <param name="ServiceType">Type of the service.</param>
        /// <param name="ServiceStart">The service start.</param>
        /// <param name="ServiceError">The service error.</param>
        /// <param name="File">The file.</param>
        internal static IntPtr Create(string ServiceName, string DisplayName, ServiceAccess ServiceAccess, ServiceType ServiceType, ServiceStart ServiceStart, ServiceError ServiceError, FileInfo File)
        {
            IntPtr ServiceManager = WinApi.OpenSCManager(null, null, (uint)ScmAccess.ScManagerAllAccess);

            if (ServiceManager == IntPtr.Zero)
            {
                return(IntPtr.Zero);
            }

            IntPtr Service = WinApi.CreateService(
                ServiceManager,
                ServiceName,
                DisplayName,
                (uint)ServiceAccess,
                (uint)ServiceType,
                (uint)ServiceStart,
                (uint)ServiceError,
                File.FullName,
                null, null, null, null, null
                );

            WinApi.CloseServiceHandle(ServiceManager);

            if (Service == IntPtr.Zero)
            {
                return(IntPtr.Zero);
            }

            return(Service);
        }