Ejemplo n.º 1
0
 /// <summary>
 /// 安装服务
 /// </summary>
 /// <param name="serviceName">服务名</param>
 /// <param name="displayName">友好名称</param>
 /// <param name="description">服务描述</param>
 /// <param name="binaryFilePath">映像文件路径,可带参数</param>
 /// <param name="startType">启动类型</param>
 /// <param name="account">启动账户</param>
 /// <param name="dependencies">依赖服务</param>
 public static void Install(string serviceName, string displayName, string description, string binaryFilePath, ServiceStartType startType, ServiceAccount account = ServiceAccount.LocalSystem, string[] dependencies = null)
 {
     IntPtr scm = OpenSCManager();
     IntPtr service = IntPtr.Zero;
     try
     {
         service = Win32Class.CreateService(scm, serviceName, displayName, Win32Class.SERVICE_ALL_ACCESS, Win32Class.SERVICE_WIN32_OWN_PROCESS, startType, Win32Class.SERVICE_ERROR_NORMAL, binaryFilePath, null, IntPtr.Zero, ProcessDependencies(dependencies), GetServiceAccountName(account), null);
         if (service == IntPtr.Zero)
         {
             if (Marshal.GetLastWin32Error() == 0x431)//ERROR_SERVICE_EXISTS
             { throw new ApplicationException("服务已存在!"); }
             throw new ApplicationException("服务安装失败!");
         }
         //设置服务描述
         Win32Class.SERVICE_DESCRIPTION sd = new Win32Class.SERVICE_DESCRIPTION();
         try
         {
             sd.description = Marshal.StringToHGlobalUni(description);
             Win32Class.ChangeServiceConfig2(service, 1, ref sd);
         }
         finally
         {
             Marshal.FreeHGlobal(sd.description); //释放
         }
     }
     finally
     {
         if (service != IntPtr.Zero)
         {
             Win32Class.CloseServiceHandle(service);
         }
         Win32Class.CloseServiceHandle(scm);
     }
 }
Ejemplo n.º 2
0
        public ServiceBase()
        {
            this.CanPauseAndContinue = IsOverriden((Action)OnPause) && IsOverriden((Action)OnContinue);
            this.CanStop = IsOverriden((Action)OnStop);
            this.CanShutdown = IsOverriden((Action)OnShutdown);
            this.CanHandlePowerEvent = IsOverriden((Func<PowerBroadcastStatus, bool>)OnPowerEvent);
            this.CanHandleSessionChangeEvent = IsOverriden((Action<SessionChangeDescription>)OnSessionChange);
            this.StartType = ServiceStartType.AutoStart;
            this.Dependencies = null;

            if (IsOverriden((Action)OnPreShutdown))
            {
                FieldInfo acceptedCommandsFieldInfo = typeof(System.ServiceProcess.ServiceBase).GetField("acceptedCommands", BindingFlags.Instance | BindingFlags.NonPublic);
                if (acceptedCommandsFieldInfo != null)
                {
                    int value = (int)acceptedCommandsFieldInfo.GetValue(this);
                    acceptedCommandsFieldInfo.SetValue(this, value | SERVICE_ACCEPT_PRESHUTDOWN);
                }
            }
        }
Ejemplo n.º 3
0
 public ServiceHandle CreateService(string name, string displayName,
                                    ServiceType type, ServiceStartType startType, string binaryPath)
 {
     return(this.CreateService(name, displayName, type, startType,
                               ServiceErrorControl.Ignore, binaryPath, null, null, null));
 }
Ejemplo n.º 4
0
 public static extern SafeServiceHandle CreateService(SafeServiceHandle hSCManager,
                                                      string lpServiceName, string lpDisplayName, SERVICE_ACCESS dwDesiredAccess,
                                                      SERVICE_TYPE dwServiceType, ServiceStartType dwStartType, SERVICE_ERROR dwErrorControl,
                                                      string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId,
                                                      char[] lpDependencies, string lpServiceStartName, string lpPassword);
Ejemplo n.º 5
0
 public static extern bool ChangeServiceConfig(
     SafeServiceHandle hService,
     ServiceType dwServiceType,
     ServiceStartType dwStartType,
     ServiceErrorControl dwErrorControl,
     string lpBinaryPathName,
     string lpLoadOrderGroup,
     int lpdwTagId,
     string lpDependencies,
     string lpServiceStartName,
     string lpPassword,
     string lpDisplayName);
        public NativeService CreateService(string name, string displayname, string cmdline, ServiceRights rights, ServiceStartType starttype = ServiceStartType.AutoStart)
        {
            if (!(this.IsInvalid || this.IsClosed))
            {
                NativeService service = CreateService(this, name, displayname, rights, ServiceType.OwnProcess, starttype, ServiceErrorControl.Normal, cmdline, null, IntPtr.Zero, null, null, null);

                if (service.IsClosed || service.IsInvalid)
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                return service;
            }
            else
            {
                throw new ObjectDisposedException("NativeServiceManager");
            }
        }
Ejemplo n.º 7
0
        public ServiceHandle CreateService(string serviceName, string displayName, string binaryPath, ServiceType serviceType, ServiceStartType startupType, ErrorSeverity errorSeverity, Win32ServiceCredentials credentials)
        {
            var service = NativeInterop.CreateServiceW(this, serviceName, displayName, ServiceControlAccessRights.All, serviceType, startupType, errorSeverity,
                                                       binaryPath, null,
                                                       IntPtr.Zero, null, credentials.UserName, credentials.Password);

            service.NativeInterop = NativeInterop;

            if (service.IsInvalid)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            return(service);
        }
Ejemplo n.º 8
0
Archivo: Win32.cs Proyecto: hakib1/sys
 public static extern IntPtr CreateService(IntPtr hSCManager, string lpServiceName, string lpDisplayName, ServiceAccessRights dwDesiredAccess, ServiceType dwServiceType, ServiceStartType dwStartType, ServiceError dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lp, string lpPassword);
Ejemplo n.º 9
0
 ///<summary>Describes a new Win32 service.</summary>
 /// <param name="Name">The name of the service used in the service database.</param>
 /// <param name="DisplayName">The name of the service that will be displayed in the services snap-in.</param>
 /// <param name="Description">The description of the service that will be displayed in the service snap-in.</param>
 /// <param name="ServiceType">Indicates the type of service you will be running. By default this is "Default."</param>
 /// <param name="ServiceStartType">Service start options. By default this is "AutoStart."</param>
 public ServiceAttribute(string Name, string DisplayName, string Description, ServiceType ServiceType, ServiceStartType ServiceStartType)
 {
     this.name             = Name;
     this.displayName      = DisplayName;
     this.description      = Description;
     this.run              = true;
     this.servType         = ServiceType;
     this.servAccessType   = ServiceAccessType.AllAccess;
     this.servStartType    = ServiceStartType;
     this.servErrorControl = ServiceErrorControl.Normal;
     this.servControls     = ServiceControls.Default;
     this.logName          = "Services";
 }
Ejemplo n.º 10
0
 public static extern bool ChangeServiceConfig(IntPtr hService, ServiceTypes nServiceType, ServiceStartType nStartType, ServiceErrorControlType nErrorControl,
                                               [Optional] string lpBinaryPathName, [Optional] string lpLoadOrderGroup, [Optional] IntPtr lpdwTagId, [In, Optional] char[] lpDependencies,
                                               [Optional] string lpServiceStartName, [Optional] string lpPassword, [Optional] string lpDisplayName);
Ejemplo n.º 11
0
        /// <summary>
        /// Installs the service.
        /// </summary>
        /// <param name="DisplayName">Service display name.</param>
        /// <param name="Description">Service description.</param>
        /// <param name="StartType">How the service should be started.</param>
        /// <param name="StartImmediately">If the service should be started immediately.</param>
        /// <param name="FailureActions">Service failure actions.</param>
        /// <param name="Credentials">Credentials to use when running service.</param>
        /// <returns>
        /// Return code:
        ///
        /// 0: Installed, not started.
        /// 1: Installed, started.
        /// 2: Updated, not started.
        /// 3: Updated, started.
        /// </returns>
        /// <exception cref="Exception">If service could not be installed.</exception>
        public int Install(string DisplayName, string Description, ServiceStartType StartType, bool StartImmediately,
                           ServiceFailureActions FailureActions, Win32ServiceCredentials Credentials)
        {
            string Path = Assembly.GetExecutingAssembly().Location.Replace(".dll", ".exe");

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

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

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

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

                                if (FailureActions != null)
                                {
                                    svc.SetFailureActions(FailureActions);
                                    svc.SetFailureActionFlag(true);
                                }
                                else
                                {
                                    svc.SetFailureActionFlag(false);
                                }

                                if (StartImmediately)
                                {
                                    svc.Start();
                                    return(1);
                                }
                                else
                                {
                                    return(0);
                                }
                            }
                        }
                        else
                        {
                            throw errorException;
                        }
                    }
                }
Ejemplo n.º 12
0
        /// <summary>
        /// 安装服务
        /// </summary>
        /// <param name="serviceName">服务名</param>
        /// <param name="displayName">友好名称</param>
        /// <param name="binaryFilePath">映像文件路径,可带参数</param>
        /// <param name="description">服务描述</param>
        /// <param name="startType">启动类型</param>
        /// <param name="account">启动账户</param>
        /// <param name="dependencies">依赖服务</param>
        public static void Install(string serviceName, string displayName, string binaryFilePath, string description, ServiceStartType startType, ServiceAccount account = ServiceAccount.LocalSystem, string[] dependencies = null)
        {
            IntPtr scm = OpenSCManager();

            IntPtr service = IntPtr.Zero;

            try
            {
                service = Win32Class.CreateService(scm, serviceName, displayName, Win32Class.SERVICE_ALL_ACCESS, Win32Class.SERVICE_WIN32_OWN_PROCESS, startType, Win32Class.SERVICE_ERROR_NORMAL, binaryFilePath, null, IntPtr.Zero, ProcessDependencies(dependencies), GetServiceAccountName(account), null);

                if (service == IntPtr.Zero)
                {
                    if (Marshal.GetLastWin32Error() == 0x431)//ERROR_SERVICE_EXISTS
                    {
                        throw new ApplicationException("服务已存在!");
                    }

                    throw new ApplicationException("服务安装失败!");
                }

                //设置服务描述
                Win32Class.SERVICE_DESCRIPTION sd = new Win32Class.SERVICE_DESCRIPTION();
                try
                {
                    sd.description = Marshal.StringToHGlobalUni(description);
                    Win32Class.ChangeServiceConfig2(service, 1, ref sd);
                }
                finally
                {
                    Marshal.FreeHGlobal(sd.description); //释放
                }
            }
            finally
            {
                if (service != IntPtr.Zero)
                {
                    Win32Class.CloseServiceHandle(service);
                }
                Win32Class.CloseServiceHandle(scm);
            }
        }
Ejemplo n.º 13
0
        public static int Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                Log.Error("Unhandled exception caught.", new KeyValuePair <string, object>("IsTerminating", e.IsTerminating));

                if (e.ExceptionObject is Exception ex)
                {
                    Log.Critical(ex);
                }
                else if (e.ExceptionObject != null)
                {
                    Log.Critical(e.ExceptionObject.ToString());
                }
                else
                {
                    Log.Critical("Unexpected null exception thrown.");
                }
            };

            AppDomain.CurrentDomain.DomainUnload += (sender, e) =>
            {
                Log.Informational("Unloading domain.");
            };

            AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
            {
                Log.Informational("Exiting process.");
                Log.Terminate();
            };

            try
            {
                string                  ServiceName = "IoT Gateway Service";
                string                  DisplayName = ServiceName;
                string                  Description = "Windows Service hosting the Waher IoT Gateway.";
                string                  Arg;
                ServiceStartType        StartType   = ServiceStartType.Disabled;
                Win32ServiceCredentials Credentials = Win32ServiceCredentials.LocalService;
                bool Install = false;
                bool Uninstall = false;
                bool Immediate = false;
                bool AsConsole = false;
                bool Error = false;
                bool Help = false;
                int  i, c = args.Length;

                Log.RegisterExceptionToUnnest(typeof(System.Runtime.InteropServices.ExternalException));
                Log.RegisterExceptionToUnnest(typeof(System.Security.Authentication.AuthenticationException));

                Log.Register(new Waher.Events.WindowsEventLog.WindowsEventLog("IoTGateway"));
                Log.Informational("Program started.");

                for (i = 0; i < c; i++)
                {
                    Arg = args[i];

                    switch (Arg.ToLower())
                    {
                    case "-?":
                        Help = true;
                        break;

                    case "-install":
                        Install = true;
                        break;

                    case "-uninstall":
                        Uninstall = true;
                        break;

                    case "-immediate":
                        Immediate = true;
                        break;

                    case "-console":
                        AsConsole = true;
                        break;

                    case "-displayname":
                        i++;
                        if (i >= c)
                        {
                            Error = true;
                            break;
                        }

                        DisplayName = args[i];
                        break;

                    case "-description":
                        i++;
                        if (i >= c)
                        {
                            Error = true;
                            break;
                        }

                        Description = args[i];
                        break;

                    case "-start":
                        i++;
                        if (i >= c)
                        {
                            Error = true;
                            break;
                        }

                        if (!Enum.TryParse <ServiceStartType>(args[i], out StartType))
                        {
                            Error = true;
                            break;
                        }
                        break;

                    case "-localsystem":
                        Credentials = Win32ServiceCredentials.LocalSystem;
                        break;

                    case "-localservice":
                        Credentials = Win32ServiceCredentials.LocalService;
                        break;

                    case "-networkservice":
                        Credentials = Win32ServiceCredentials.NetworkService;
                        break;

                    default:
                        Error = true;
                        break;
                    }
                }

                if (Error || Help)
                {
                    Log.Informational("Displaying help.");

                    Console.Out.WriteLine("IoT Gateway Windows Service Application.");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Command line switches:");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("-?                   Brings this help.");
                    Console.Out.WriteLine("-install             Installs service in operating system");
                    Console.Out.WriteLine("-uninstall           Uninstalls service from operating system.");
                    Console.Out.WriteLine("-displayname Name    Sets the display name of the service. Default is \"IoT ");
                    Console.Out.WriteLine("                     Gateway Service\".");
                    Console.Out.WriteLine("-description Desc    Sets the textual description of the service. Default is ");
                    Console.Out.WriteLine("                     \"Windows Service hosting the Waher IoT Gateway.\".");
                    Console.Out.WriteLine("-start Mode          Sets the default starting mode of the service. Default is ");
                    Console.Out.WriteLine("                     Disabled. Available options are StartOnBoot, ");
                    Console.Out.WriteLine("                     StartOnSystemStart, AutoStart, StartOnDemand and Disabled.");
                    Console.Out.WriteLine("-immediate           If the service should be started immediately.");
                    Console.Out.WriteLine("-console             Run the service as a console application.");
                    Console.Out.WriteLine("-localsystem         Installed service will run using the Local System account.");
                    Console.Out.WriteLine("-localservice        Installed service will run using the Local Service account");
                    Console.Out.WriteLine("                     (default).");
                    Console.Out.WriteLine("-networkservice      Installed service will run using the Network Service");
                    Console.Out.WriteLine("                     account.");

                    return(-1);
                }

                if (Install && Uninstall)
                {
                    Log.Error("Conflicting arguments.");
                    Console.Out.Write("Conflicting arguments.");
                    return(-1);
                }

                if (Install)
                {
                    Log.Informational("Installing service.");
                    InstallService(ServiceName, DisplayName, Description, StartType, Immediate, Credentials);
                }
                else if (Uninstall)
                {
                    Log.Informational("Uninstalling service.");
                    UninstallService(ServiceName);
                }
                else if (AsConsole)
                {
                    Log.Informational("Running as console application.");
                    RunAsConsole();
                }
                else
                {
                    Log.Informational("Running as service application.");
                    RunAsService(ServiceName);
                }

                return(0);
            }
            catch (Exception ex)
            {
                Log.Critical(ex);
                Console.Out.WriteLine(ex.Message);
                return(-1);
            }
        }
Ejemplo n.º 14
0
 /// <summary>
 /// ���÷��������ʽ
 /// </summary>
 /// <param name="_type">����</param>
 /// <param name="serviceName">������</param>
 public static void SetRunType(ServiceStartType _type, string serviceName)
 {
     RegistryKey k = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\" + serviceName + "\\", true);
     k.SetValue("Start", Convert.ToInt32(_type), RegistryValueKind.DWord);
     k.Close();
 }
Ejemplo n.º 15
0
        private static void InstallService(string ServiceName, string DisplayName, string Description, ServiceStartType StartType, bool Immediate,
                                           ServiceFailureActions FailureActions, Win32ServiceCredentials Credentials)
        {
            ServiceHost host = new ServiceHost(ServiceName);
            int         i;

            switch (i = host.Install(DisplayName, Description, StartType, Immediate, FailureActions, Credentials))
            {
            case 0:
                Console.Out.WriteLine("Service successfully installed. Service start is pending.");
                break;

            case 1:
                Console.Out.WriteLine("Service successfully installed and started.");
                break;

            case 2:
                Console.Out.WriteLine("Service registration successfully updated. Service start is pending.");
                break;

            case 3:
                Console.Out.WriteLine("Service registration successfully updated. Service started.");
                break;

            default:
                throw new Exception("Unexpected installation result: " + i.ToString());
            }
        }
Ejemplo n.º 16
0
        public static int Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                if (e.IsTerminating)
                {
                    string FileName = Path.Combine(Gateway.AppDataFolder, "UnhandledException.txt");
                    Networking.Sniffers.XmlFileSniffer.MakeUnique(ref FileName);

                    using (StreamWriter w = File.CreateText(FileName))
                    {
                        w.Write("Type: ");

                        if (e.ExceptionObject != null)
                        {
                            w.WriteLine(e.ExceptionObject.GetType().FullName);
                        }
                        else
                        {
                            w.WriteLine("null");
                        }

                        w.Write("Time: ");
                        w.WriteLine(DateTime.Now.ToString());

                        w.WriteLine();
                        if (e.ExceptionObject is Exception ex)
                        {
                            while (ex != null)
                            {
                                w.WriteLine(ex.Message);
                                w.WriteLine();
                                w.WriteLine(ex.StackTrace);
                                w.WriteLine();

                                ex = ex.InnerException;
                            }
                        }
                        else
                        {
                            if (e.ExceptionObject != null)
                            {
                                w.WriteLine(e.ExceptionObject.ToString());
                            }

                            w.WriteLine();
                            w.WriteLine(Environment.StackTrace);
                        }

                        w.Flush();
                    }
                }

                if (e.ExceptionObject is Exception ex2)
                {
                    Log.Critical(ex2);
                }
                else if (e.ExceptionObject != null)
                {
                    Log.Critical(e.ExceptionObject.ToString());
                }
                else
                {
                    Log.Critical("Unexpected null exception thrown.");
                }
            };

            AppDomain.CurrentDomain.DomainUnload += (sender, e) =>
            {
                Log.Informational("Unloading domain.");
            };

            AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
            {
                Log.Informational("Exiting process.");
                Log.Terminate();
            };

            try
            {
                string                  ServiceName = "IoT Gateway Service";
                string                  DisplayName = ServiceName;
                string                  Description = "Windows Service hosting the Waher IoT Gateway.";
                string                  Arg;
                ServiceStartType        StartType   = ServiceStartType.Disabled;
                Win32ServiceCredentials Credentials = Win32ServiceCredentials.LocalService;
                bool Install = false;
                bool Uninstall = false;
                bool Immediate = false;
                bool AsConsole = false;
                bool Error = false;
                bool Help = false;
                int  i, c = args.Length;

                Log.RegisterExceptionToUnnest(typeof(System.Runtime.InteropServices.ExternalException));
                Log.RegisterExceptionToUnnest(typeof(System.Security.Authentication.AuthenticationException));

                Log.Register(new Waher.Events.WindowsEventLog.WindowsEventLog("IoTGateway"));
                Log.Informational("Program started.");

                for (i = 0; i < c; i++)
                {
                    Arg = args[i];

                    switch (Arg.ToLower())
                    {
                    case "-?":
                        Help = true;
                        break;

                    case "-install":
                        Install = true;
                        break;

                    case "-uninstall":
                        Uninstall = true;
                        break;

                    case "-immediate":
                        Immediate = true;
                        break;

                    case "-console":
                        AsConsole = true;
                        break;

                    case "-displayname":
                        i++;
                        if (i >= c)
                        {
                            Error = true;
                            break;
                        }

                        DisplayName = args[i];
                        break;

                    case "-description":
                        i++;
                        if (i >= c)
                        {
                            Error = true;
                            break;
                        }

                        Description = args[i];
                        break;

                    case "-start":
                        i++;
                        if (i >= c)
                        {
                            Error = true;
                            break;
                        }

                        if (!Enum.TryParse <ServiceStartType>(args[i], out StartType))
                        {
                            Error = true;
                            break;
                        }
                        break;

                    case "-localsystem":
                        Credentials = Win32ServiceCredentials.LocalSystem;
                        break;

                    case "-localservice":
                        Credentials = Win32ServiceCredentials.LocalService;
                        break;

                    case "-networkservice":
                        Credentials = Win32ServiceCredentials.NetworkService;
                        break;

                    case "-instance":
                        i++;
                        if (i >= c)
                        {
                            Error = true;
                            break;
                        }

                        instanceName = args[i];
                        break;

                    default:
                        Error = true;
                        break;
                    }
                }

                if (Error || Help)
                {
                    Log.Informational("Displaying help.");

                    Console.Out.WriteLine("IoT Gateway Windows Service Application.");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Command line switches:");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("-?                   Brings this help.");
                    Console.Out.WriteLine("-install             Installs service in operating system");
                    Console.Out.WriteLine("-uninstall           Uninstalls service from operating system.");
                    Console.Out.WriteLine("-displayname Name    Sets the display name of the service. Default is \"IoT ");
                    Console.Out.WriteLine("                     Gateway Service\".");
                    Console.Out.WriteLine("-description Desc    Sets the textual description of the service. Default is ");
                    Console.Out.WriteLine("                     \"Windows Service hosting the Waher IoT Gateway.\".");
                    Console.Out.WriteLine("-start Mode          Sets the default starting mode of the service. Default is ");
                    Console.Out.WriteLine("                     Disabled. Available options are StartOnBoot, ");
                    Console.Out.WriteLine("                     StartOnSystemStart, AutoStart, StartOnDemand and Disabled.");
                    Console.Out.WriteLine("-immediate           If the service should be started immediately.");
                    Console.Out.WriteLine("-console             Run the service as a console application.");
                    Console.Out.WriteLine("-localsystem         Installed service will run using the Local System account.");
                    Console.Out.WriteLine("-localservice        Installed service will run using the Local Service account");
                    Console.Out.WriteLine("                     (default).");
                    Console.Out.WriteLine("-networkservice      Installed service will run using the Network Service");
                    Console.Out.WriteLine("                     account.");
                    Console.Out.WriteLine("-instance INSTANCE   Name of instance. Default is the empty string. Parallel");
                    Console.Out.WriteLine("                     instances of the IoT Gateway can execute, provided they");
                    Console.Out.WriteLine("                     are given separate instance names.");

                    return(-1);
                }

                if (Install && Uninstall)
                {
                    Log.Error("Conflicting arguments.");
                    Console.Out.Write("Conflicting arguments.");
                    return(-1);
                }

                if (Install)
                {
                    Log.Informational("Installing service.");

                    InstallService(ServiceName, DisplayName, Description, StartType, Immediate,
                                   new ServiceFailureActions(TimeSpan.FromDays(1), null, null, new ScAction[]
                    {
                        new ScAction()
                        {
                            Type = ScActionType.ScActionRestart, Delay = TimeSpan.FromMinutes(1)
                        },
                        new ScAction()
                        {
                            Type = ScActionType.ScActionRestart, Delay = TimeSpan.FromMinutes(1)
                        },
                        new ScAction()
                        {
                            Type = ScActionType.ScActionRestart, Delay = TimeSpan.FromMinutes(1)
                        }
                    }), Credentials);

                    return(0);
                }
                else if (Uninstall)
                {
                    Log.Informational("Uninstalling service.");
                    UninstallService(ServiceName);

                    return(0);
                }
                else
                {
                    if (AsConsole)
                    {
                        Log.Informational("Running as console application.");
                        RunAsConsole();
                    }
                    else
                    {
                        Log.Informational("Running as service application.");
                        RunAsService(ServiceName);
                    }

                    return(1);                          // Allows the service to be restarted.
                }
            }
            catch (Exception ex)
            {
                Log.Critical(ex);
                Console.Out.WriteLine(ex.Message);
                return(1);
            }
        }
Ejemplo n.º 17
0
 public static extern IntPtr CreateService(IntPtr hScm, string serviceName, string displayName, ServiceAccessMask desiredAccess,
                                           ServiceType serviceType, ServiceStartType startType, ServiceErrorControl errorControl,
                                           string imagePath, string loadOrderGroup, IntPtr tag,
                                           string dependencies = null, string serviceStartName = null, string password = null);
Ejemplo n.º 18
0
        public virtual void ChangeConfig(string displayName, string binaryPath, ServiceType serviceType, ServiceStartType startupType, ErrorSeverity errorSeverity, Win32ServiceCredentials credentials)
        {
            bool success = Win32.ChangeServiceConfigW(this, serviceType, startupType, errorSeverity, binaryPath, null, IntPtr.Zero, null, credentials.UserName, credentials.Password, displayName);

            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
        }
Ejemplo n.º 19
0
        public NativeService CreateService(string name, string displayname, string cmdline, ServiceRights rights, ServiceStartType starttype = ServiceStartType.AutoStart)
        {
            if (!(this.IsInvalid || this.IsClosed))
            {
                NativeService service = CreateService(this, name, displayname, rights, ServiceType.OwnProcess, starttype, ServiceErrorControl.Normal, cmdline, null, IntPtr.Zero, null, null, null);

                if (service.IsClosed || service.IsInvalid)
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                return(service);
            }
            else
            {
                throw new ObjectDisposedException("NativeServiceManager");
            }
        }
Ejemplo n.º 20
0
 public static extern SafeServiceHandle CreateService(SafeServiceHandle hSCManager, string lpServiceName, string lpDisplayName, ServiceAccess dwDesiredAccess, ServiceType dwServiceType, ServiceStartType dwStartType, ServiceErrorControl dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);
Ejemplo n.º 21
0
 bool INativeInterop.ChangeServiceConfigW(ServiceHandle service, ServiceType serviceType, ServiceStartType startType, ErrorSeverity errorSeverity, string binaryPath, string loadOrderGroup, IntPtr outUIntTagId, string dependencies, string serviceUserName, string servicePassword, string displayName)
 {
     return(ChangeServiceConfigW(service, serviceType, startType, errorSeverity, binaryPath, loadOrderGroup, outUIntTagId, dependencies, serviceUserName, servicePassword, displayName));
 }
Ejemplo n.º 22
0
 public static extern IntPtr CreateService(IntPtr hSCManager, string lpSvcName, string lpDisplayName, ServiceControlManagerType dwDesiredAccess, ServiceType dwServiceType, ServiceStartType dwStartType, ServiceErrorControl dwErrorControl, string lpPathName, string lpLoadOrderGroup, int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);
Ejemplo n.º 23
0
 ServiceHandle INativeInterop.CreateServiceW(ServiceControlManager serviceControlManager, string serviceName, string displayName,
                                             ServiceControlAccessRights desiredControlAccess, ServiceType serviceType, ServiceStartType startType, ErrorSeverity errorSeverity,
                                             string binaryPath,
                                             string loadOrderGroup, IntPtr outUIntTagId, string dependencies, string serviceUserName, string servicePassword)
 {
     return(CreateServiceW(serviceControlManager, serviceName, displayName, desiredControlAccess, serviceType, startType, errorSeverity,
                           binaryPath, loadOrderGroup, outUIntTagId, dependencies, serviceUserName, servicePassword));
 }
Ejemplo n.º 24
0
 protected static extern NativeService CreateService(
     NativeServiceManager hSCManager,
     string lpServiceName,
     string lpDisplayName,
     ServiceRights dwDesiredAccess,
     ServiceType dwServiceType,
     ServiceStartType dwStartType,
     ServiceErrorControl dwErrorControl,
     string lpBinaryPathName,
     string lpLoadOrderGroup,
     IntPtr lpdwTagId,
     string lpDependencies,
     string lpServiceStartName,
     string lpPassword
 );
        public ServiceHandle CreateService(string name, string displayName, ServiceType type, ServiceStartType startType, ServiceErrorControl errorControl, string binaryPath, string group, string accountName, string password)
        {
            IntPtr service = Win32.CreateService(
                this,
                name,
                displayName,
                ServiceAccess.All,
                type,
                startType,
                errorControl,
                binaryPath,
                group,
                IntPtr.Zero,
                IntPtr.Zero,
                accountName,
                password
                );

            if (service == IntPtr.Zero)
            {
                Win32.Throw();
            }

            return(new ServiceHandle(service, true));
        }
Ejemplo n.º 26
0
 public static extern SafeServiceHandle CreateService(SafeServiceHandle hSCManager, string lpServiceName, string lpDisplayName, ServiceAccess dwDesiredAccess, ServiceType dwServiceType, ServiceStartType dwStartType, ServiceErrorControl dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);
Ejemplo n.º 27
0
 public SetServiceTask(string serviceName, ServiceStartType startType, bool stopNow = false)
 {
     _serviceName = serviceName;
     _startType   = startType;
     _stopNow     = stopNow;
 }