Exemplo n.º 1
1
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            string serviceFolder = Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location );
            SqlServerTypes.Utilities.LoadNativeAssemblies( serviceFolder );
            System.Diagnostics.Debugger.Launch();
            RockMemoryCache.Clear();

            // set the current directory to the same as the current exe so that we can find the web.connectionstrings.config
            Directory.SetCurrentDirectory( serviceFolder );
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new JobScheduler()
            };

            //// NOTE: To run and debug this service in Visual Studio uncomment out the debug code below
            //// Make sure you have a web.connectionstring.config in your debug/bin directory!
            //JobScheduler debug = new JobScheduler();
            //debug.StartJobScheduler();

            // if you'd rather debug the app running as an actual service do the following:
            // 1. Install the app as a service 'installutil <yourproject>.exe' (installutil is found C:\Windows\Microsoft.NET\Framework64\v4.0.30319\)
            // 2. Add the line System.Diagnostics.Debugger.Launch(); where you'd like to debug
            //
            // Note: to uninstall the service run 'installutil /u <yourproject>.exe'
            //System.Diagnostics.Debugger.Launch();

            ServiceBase.Run( ServicesToRun );
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            AddTraceListeners();

            if (Environment.UserInteractive == false)
            {
                ServiceBase[] ServicesToRun = new ServiceBase[] { new ReportService() };
                ServiceBase.Run(ServicesToRun);
            }
            else
            {
                CreateMethodCache();

                Console.Clear();
                Console.ForegroundColor = ConsoleColor.White;
                Console.WindowWidth = 80;
                Console.WindowHeight = 20;
                Console.BufferWidth = 100;
                Console.BufferHeight = 120;
                Console.Title = "ServiceProvider";

                if (args.Length > 0)
                {
                    RunCommand(args);
                    return;
                }
                StartService();

                MainLoop();
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new TrackerService()
            };

            if (System.Environment.UserInteractive)
            {
                string parameter = string.Concat(args);
                switch (parameter)
                {
                    case "--install":
                        ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                        break;
                    case "--uninstall":
                        ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                        break;
                }
            }
            else
            {
                ServiceBase.Run(ServicesToRun);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// 應用程式的主要進入點。
        /// </summary>
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            if (System.Environment.UserInteractive)
            {
                string parameter = string.Concat(args);
                switch (parameter)
                {
                    case "--install":
                        ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                        break;
                    case "--uninstall":
                        ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                        break;
                }
            }
            else
            {
                ServiceBase[] ServicesToRun = new ServiceBase[]
                {
                    new ALOLService_v2()
                };
                ServiceBase.Run(ServicesToRun);
            }
        }
Exemplo n.º 5
0
 private static void Main(string[] args) {
   // Install as service, see http://stackoverflow.com/a/12703878
   if (Environment.UserInteractive) {
     try {
       string parameter = string.Concat(args);
       switch (parameter) {
         case "--install":
           ManagedInstallerClass.InstallHelper(new[] { Assembly.GetExecutingAssembly().Location });
           break;
         case "--uninstall":
           ManagedInstallerClass.InstallHelper(new[] { "/u", Assembly.GetExecutingAssembly().Location });
           break;
       }
     }
     catch (Exception ex) {
       Console.WriteLine("Error on (un)install of Hive Slave service: " + Environment.NewLine + ex);
     }
   } else {
     ServiceBase[] ServicesToRun;
     ServicesToRun = new ServiceBase[]
     {
       new JanitorService()
     };
     ServiceBase.Run(ServicesToRun);
   }
 }
Exemplo n.º 6
0
 /// <summary>
 /// 应用程序的主入口点。
 /// </summary>
 static void Main()
 {
     int type = ServiceConfigs.ServiceType;
     ServiceBase[] ServicesToRun = null;
     if (type == 1)
     {
         ServicesToRun = new ServiceBase[] 
         { 
             new SyncMessageService() 
         };
     }
     //else if (type == 2)
     //{
     //    ServicesToRun = new ServiceBase[] 
     //    { 
     //        new MQConsumerService() 
     //    };
     //}
     //else
     //{
     //    ServicesToRun = new ServiceBase[] 
     //    { 
     //        new SyncMessageService(),
     //        new MQConsumerService() 
     //    };
     //}
     ServiceBase.Run(ServicesToRun);
 }
Exemplo n.º 7
0
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] { new WMSWCFService() };
            ServiceBase.Run(ServicesToRun);

        }
Exemplo n.º 8
0
        static void Main()
        {
            if (!Environment.UserInteractive)
            {
                // Startup as service.
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new Service1()
                };
                ServiceBase.Run(ServicesToRun);
            }
            else
            {
                // Startup as application
                try
                {
                    var options = System.Configuration.ConfigurationManager.GetSection("CrawlerOptions") as CrawlerOptions;
                    logger.Info("Config is {0}", options);
                    var crawler = new Crawler(options);
                    crawler.Start();
                }
                catch (Exception ex)
                {
                    logger.Fatal(ex);
                }

            }


        }
Exemplo n.º 9
0
    	/// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
			var commandLine = new CommandLine(args);

			if (commandLine.RunAsService)
			{
				var ServicesToRun = new ServiceBase[] { new ShredHostService() };
				ServiceBase.Run(ServicesToRun);
			}
			else if (!String.IsNullOrEmpty(commandLine.PreviousExeConfigurationFilename))
			{
				var groups = SettingsGroupDescriptor.ListInstalledLocalSettingsGroups();
				groups.Add(new SettingsGroupDescriptor(typeof (ShredSettingsMigrator).Assembly.GetType("ClearCanvas.Server.ShredHost.ShredHostServiceSettings")));
				foreach (var group in groups)
					SettingsMigrator.MigrateSharedSettings(group, commandLine.PreviousExeConfigurationFilename);

				ShredSettingsMigrator.MigrateAll(commandLine.PreviousExeConfigurationFilename);
			}
			else
			{
				ShredHostService.InternalStart();
				Console.WriteLine("Press <Enter> to terminate the ShredHost.");
				Console.WriteLine();
				Console.ReadLine();
				ShredHostService.InternalStop();
			}
        }
Exemplo n.º 10
0
 private static void Main()
 {
     try
     {
         AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
     #if DEBUG
     var s = new Service1();
     new Error().Add("moo");
     s.OnDebug();
     System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
     #else
         ServiceBase[] ServicesToRun;
         ServicesToRun = new ServiceBase[]
     {
         new Service1()
     };
         ServiceBase.Run(ServicesToRun);
     #endif
     }
     catch (Exception e)
     {
         var message =
         e.Message + Environment.NewLine + e.Source + Environment.NewLine + e.StackTrace
         + Environment.NewLine + e.InnerException;
         new Error().Add(message);
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            #if (!DEBUG)
              ServiceBase[] ServicesToRun;
              ServicesToRun = new ServiceBase[]
                        {
                          new TimerService()
                        };
              ServiceBase.Run(ServicesToRun);

              #else
              //// Debug code: this allows the process to run as a non-service.

              //// It will kick off the service start point, but never kill it.

              //// Shut down the debugger to exit

              TimerService service = new TimerService();
              service.StartService(false, false, true);

              //// Put a breakpoint on the following line to always catch
              //// your service when it has finished its work
              System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

              #endif
        }
Exemplo n.º 12
0
        public void Run()
        {
            _log.Debug("[Topshelf] Starting up as a windows service application");
            var servicesToRun = new ServiceBase[] {this};

            Run(servicesToRun);
        }
Exemplo n.º 13
0
        /// <summary>
        ///     The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            //#if DEBUG
            //            //If the mode is in debugging
            //            //create a new service instance
            //            var myService = new MonitoringUnit();
            //            //call the start method - this will start the Timer.
            //            myService.Start();
            //            //Set the Thread to sleep
            //            Thread.Sleep(1000000000);
            //            Console.Read();
            //#else
            //var servicesToRun = new ServiceBase[]
            //{
            //    new MonitoringUnit()
            //};
            //ServiceBase.Run(servicesToRun);
            //#endif

            var servicesToRun = new ServiceBase[]
            {
                new MonitoringUnit()
            };
            ServiceBase.Run(servicesToRun);
        }
Exemplo n.º 14
0
 /// <summary>
 /// The main entry point for the application.
 /// </summary>
 static void Main(string[] args)
 {
     if (args.Length == 0)
     {
         ServiceBase[] ServicesToRun;
         ServicesToRun = new ServiceBase[]
         {
             new SetItUpService()
         };
         ServiceBase.Run(ServicesToRun);
     }
     else if (args.Length == 1)
     {
         if (args[0] == "install")
         {
             InstallService();
             StartService();
         }
         if (args[0] == "uninstall")
         {
             StopService();
             UninstallService();
         }
     }
 }
Exemplo n.º 15
0
        public HostService(ServiceBase[] services)
        {
            this.Services = services;
            InitializeComponent();

            OnStartMethod = typeof(ServiceBase).GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Instance);
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            #if Service
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new HttpService()
            };
            ServiceBase.Run(ServicesToRun);
            #else

            Console.BufferWidth = 120;
            Console.BufferHeight = 1024;

            StaticServerStuff.args = args;
            StaticServerStuff.Init();

            while (true)
            {
                Console.Write("\r" + StaticServerStuff.promt);
                try
                {
                    StaticServerStuff.ProcessCommand(Console.ReadLine());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            #endif
        }
Exemplo n.º 17
0
		static void Main(string[] args)
		{
			try
			{
				// service that contains a single engine which automatically discovers ISchedulerTask implementations
				var service = new SingleSchedulerEngineExecutionService<AllHostTasksSchedulerEngine>("MyTaskSchedulerService");

				// to manually control included ISchedulerTasks, create your own engine by inheriting from SchedulerEngine.
				// to have more engines running concurrently, create your own scheduler engine executor by inheriting from SchedulerEngineExecutionServiceBase

				//runnning the service as any other windows service:
				if (Environment.UserInteractive)
				{
					Console.WriteLine("Starting ExampleService in command-line mode ..");
					Console.WriteLine("Press CTRL-C to terminate ..");

					service.Start();
					Console.ReadLine();
					service.Stop();
				}
				else
				{
					var ServicesToRun = new ServiceBase[] { service };
					ServiceBase.Run(ServicesToRun);
				}
			}
			catch (Exception exception)
			{
				Debugger.Break();
				throw;
			}
		}
Exemplo n.º 18
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            String[] myargs = Environment.GetCommandLineArgs();
            if (myargs.Length > 1)
            {
                String arg = myargs[1].ToLower();
                if ((arg == "-install") || (arg == "-i"))
                {
                    String[] args = new String[1];
                    args[0] = Assembly.GetExecutingAssembly().Location;
                    ExecuteInstallUtil(args);
                }
                if ((arg == "-uninstall") || (arg == "-u"))
                {
                    String[] args = new String[2];
                    args[0] = Assembly.GetExecutingAssembly().Location;
                    args[1] = "-u";
                    ExecuteInstallUtil(args);
                }
                return;
            }

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new AnvizService()
            };
            ServiceBase.Run(ServicesToRun);
        }
Exemplo n.º 19
0
 /// <summary>
 /// The main entry point for the application.
 /// </summary>
 static void Main()
 {
     if (Type.GetType("Mono.Runtime") != null // mono-service2 sucks; run as foreground process instead
     #if DEBUG
         || Debugger.IsAttached
     #endif
         )
     {
         try
         {
             var svc = new FooSyncService();
             var args = Environment.GetCommandLineArgs();
             svc.Start(args.Where((arg, index) => index > 0).ToArray());
         }
         catch (Exception ex)
         {
             Console.WriteLine("Unhandled {0}: {1}", ex.GetType().Name, ex.Message);
     Console.WriteLine(ex.StackTrace);
         }
     }
     else
     {
         ServiceBase[] ServicesToRun;
         ServicesToRun = new ServiceBase[]
         {
             new FooSyncService()
         };
         ServiceBase.Run(ServicesToRun);
     }
 }
Exemplo n.º 20
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        public static void Main(string[] args)
        {
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

            if (args.Length > 0)
            {
                // Parse the command line args
                var install = ParseCommandLine(args);
                if (install == true)
                {
                    InstallationManager.Install(args);
                }
                else if (install == false)
                {
                    InstallationManager.Uninstall(args);
                }
                else
                {
            Trace.Listeners.Add(new ConsoleTraceListener());
            Trace.WriteLine("Debugging press return to exit...");
            var svc = new SyslogSharpService();
            svc.Debug();
            Console.ReadLine();
            Trace.WriteLine("Finished.");

            //					Console.WriteLine("Invalid command line args -i for install or -u for uninstall");
                }
            }
            else
            {
                var servicesToRun = new ServiceBase[] { new SyslogSharpService() };

                ServiceBase.Run(servicesToRun);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                NLog.Config.SimpleConfigurator.ConfigureForConsoleLogging(NLog.LogLevel.Debug);
                if (args[0] == "-debug")
                {
                    Debug(args);
                }
                else if (args[0] == "-testTask")
                {
                    if (args.Length < 2) throw new Exception("Task file name missing");
                    TestTask(args[1]);
                }
                else if (args[0] == "-testJob")
                {
                    if (args.Length < 2) throw new Exception("Job ID missing");
                    TestJob(args[1]);
                }
                else
                {
                    Console.WriteLine("Invalid arguments specified.");
                    Console.WriteLine("Possible options: \n-debug\n-testTask [task json file]\n-testJob [jobId]");
                }
                return;
            }

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };
            ServiceBase.Run(ServicesToRun);
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            EnsureBuildNumberIsPutIntoSummaryFile();

            Dictionary<string,string> arguments = StringUtilities.ParseCommandLine(args);
            // If there is a -Service switch then start as a service otherwise start as a regular application
            if (arguments.ContainsKey("-Service"))
            {
                int maximumNumberOfCores = -1;
                if (arguments.ContainsKey("-MaximumNumberOfCores"))
                    maximumNumberOfCores = Convert.ToInt32(arguments["-MaximumNumberOfCores"]);

                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new RunnerService(maximumNumberOfCores)
                };
                ServiceBase.Run(ServicesToRun);
            }
            else
            {
                if (!RunJobFromCommandLine(args))
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new MainForm(args));
                }
            }
        }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                // Install service
                if (args[0].Trim().ToLower() == "/i")
                { 
                    ManagedInstallerClass.InstallHelper(new string[] { "/i", Assembly.GetExecutingAssembly().Location });
                    return;
                }

                // Uninstall service                 
                if (args[0].Trim().ToLower() == "/u")
                { 
                    ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                    return;
                }
            }

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new ServiceOne(),
                new ServiceTwo() 
            };
            ServiceBase.Run(ServicesToRun);
        }
Exemplo n.º 24
0
        //
        // http://coding.abel.nu/2012/05/debugging-a-windows-service-project/
        static void RunInteractive(ServiceBase[] servicesToRun)
        {
            Console.WriteLine("Services running in interactive mode.");
            Console.WriteLine();

            MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart",
                BindingFlags.Instance | BindingFlags.NonPublic);
            foreach (ServiceBase service in servicesToRun)
            {
                Console.Write("Starting {0}...", service.ServiceName);
                onStartMethod.Invoke(service, new object[] { new string[] { } });
                Console.Write("Started");
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine(
                "Press any key to stop the services and end the process...");
            Console.ReadKey();
            Console.WriteLine();

            MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop",
                BindingFlags.Instance | BindingFlags.NonPublic);
            foreach (ServiceBase service in servicesToRun)
            {
                Console.Write("Stopping {0}...", service.ServiceName);
                onStopMethod.Invoke(service, null);
                Console.WriteLine("Stopped");
            }

            Console.WriteLine("All services stopped.");
            // Keep the console alive for a second to allow the user to see the message.
            Thread.Sleep(1000);
        }
Exemplo n.º 25
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            // resolve debug mode
            bool runAsService = !args.Contains("-debug");
            SiLADemoProviderService service = new SiLADemoProviderService();
            if (runAsService)
            {
                ServiceBase[] servicesToRun;
                servicesToRun = new ServiceBase[] 
			{ 
				service
			};

                ServiceBase.Run(servicesToRun);
            }
            else
            {
                // start service for debugging
                service.Start();

                Console.WriteLine("- Running: Hit any key to abort -");
                Console.ReadKey();

                // stop
                service.Stop();
            }        
        
        }
Exemplo n.º 26
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new Service1() 
            };
            ServiceBase.Run(ServicesToRun);


//            var service = new Service1();
//#if DEBUG
//            service.Start(args);

//            Console.WriteLine("Service started, press any key to kill");
//            Console.ReadKey();

//            service.Stop();
//#else
//                        ServiceBase.Run(new ServiceBase[] { service });
//#endif



        }
Exemplo n.º 27
0
 static void Main(String[] args) {
     bool service = false;
     Queue<String> vars = new Queue<string>();
     foreach (String v in args) vars.Enqueue(v);
     while (vars.Count != 0) {
         String a = vars.Dequeue();
         if (a.StartsWith("@")) {
             foreach (String v in CLUt.Parse(File.ReadAllText(a.Substring(1), Encoding.Default))) vars.Enqueue(v);
             continue;
         }
         if (a.StartsWith("/s=")) {
             als.Add(a.Substring(3));
         }
         if (a == "/service") {
             service = true;
         }
     }
     if (service) {
         ServiceBase[] ServicesToRun = new ServiceBase[] { new Program() };
         ServiceBase.Run(ServicesToRun);
     }
     else {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new Form1(als));
     }
 }
Exemplo n.º 28
0
        static void Main()
        {
#if DEBUG
            try
            {
                ServiceStartup.Run();
                Console.WriteLine("Press <CTRL>+C to stop.");
                SetConsoleCtrlHandler(ConsoleCtrlCheck, true);
                Thread.Sleep(Timeout.Infinite);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: {0}: {1}", ex.GetType().Name, ex.Message);
                throw;
            }
            finally
            {
                ServiceStartup.Stop();
            }
#else
            var appHost = ServiceStartup.GetAppHostListner();

            var servicesToRun = new ServiceBase[] 
            { 
                new WinService(appHost, ServiceStartup.ListeningOn) 
            };
            ServiceBase.Run(servicesToRun);
#endif

        }
Exemplo n.º 29
0
 /// <summary>
 /// The main entry point for the application.
 /// </summary>
 static void Main(string[] args)
 {
     if (args != null && args.Length == 1 && args[0].Length > 1 && ((int)args[0][0] == 45 || (int)args[0][0] == 47))
     {
         switch (args[0].Substring(1).ToLower())
         {
             case "install":
             case "i":
                 ServiceInstaller.InstallMe();
                 break;
             case "uninstall":
             case "u":
                 ServiceInstaller.UninstallMe();
                 break;
             case "start":
                 ServiceInstaller.StartMe("EIA Model Service");
                 break;
             case "stop":
                 ServiceInstaller.StopMe("EIA Model Service");
                 break;
         }
     }
     else
     {
         ServiceBase[] ServicesToRun;
         ServicesToRun = new ServiceBase[]
     {
         new ParserService()
     };
         ServiceBase.Run(ServicesToRun);
     }
 }
Exemplo n.º 30
0
 /// <summary>
 /// Der Haupteinstiegspunkt für die Anwendung.
 /// </summary>
 static void Main(string[] args)
 {
    if (!Environment.UserInteractive)
    {
       var ServicesToRun = new ServiceBase[]
                                        {
                                           new BarcodeScannerService()
                                        };
       ServiceBase.Run(ServicesToRun);
    }
    else
    {
       try
       {
          EnableConsole();
          var service = new BarcodeScannerService();
          service.StartForeground(args);
       }
       catch (Exception exc)
       {
          Console.WriteLine(exc.Message);
          var innerExc = exc.InnerException;
          while (innerExc != null)
          {
             Console.WriteLine(innerExc.Message);
             innerExc = innerExc.InnerException;
          }
       }
    }
 }
Exemplo n.º 31
0
 public Task Run()
 {
     System.ServiceProcess.ServiceBase[] ServicesToRun = new System.ServiceProcess.ServiceBase[] { this };
     System.ServiceProcess.ServiceBase.Run(ServicesToRun);
     return(Task.CompletedTask);
 }
Exemplo n.º 32
0
 /// <include file='doc\ServiceBase.uex' path='docs/doc[@for="ServiceBase.Run1"]/*' />
 /// <devdoc>
 ///    <para>Provides the main
 ///       entry point for an executable that contains a single
 ///       service. Loads the service into memory so it can be
 ///       started.</para>
 /// </devdoc>
 public static void Run(ServiceBase service)
 {
     Run(new ServiceBase[] { service });
 }
 // The main entry point for the process
 static void Main()
 {
     System.ServiceProcess.ServiceBase[] ServicesToRun;
     ServicesToRun = new System.ServiceProcess.ServiceBase[] { new IntegrationServer() };
     System.ServiceProcess.ServiceBase.Run(ServicesToRun);
 }
Exemplo n.º 34
0
        /// <devdoc>
        ///    <para>Provides the main entry point for an executable that
        ///       contains multiple associated services. Loads the specified services into memory so they can be
        ///       started.</para>
        /// </devdoc>
        public static unsafe void Run(ServiceBase[] services)
        {
            if (services == null || services.Length == 0)
            {
                throw new ArgumentException(SR.NoServices);
            }

            IntPtr entriesPointer = Marshal.AllocHGlobal(checked ((services.Length + 1) * sizeof(SERVICE_TABLE_ENTRY)));
            Span <SERVICE_TABLE_ENTRY> entries = new Span <SERVICE_TABLE_ENTRY>((void *)entriesPointer, services.Length + 1);

            entries.Clear();
            try
            {
                bool multipleServices = services.Length > 1;

                // The members of the last entry in the table must have NULL values to designate the end of the table.
                // Leave the last element in the entries span to be zeroed out.
                for (int index = 0; index < services.Length; ++index)
                {
                    ServiceBase service = services[index];
                    service.Initialize(multipleServices);
                    // This method allocates on unmanaged heap; Make sure that the contents are freed after use.
                    entries[index] = service.GetEntry();
                }

                // While the service is running, this function will never return. It will return when the service
                // is stopped.
                // After it returns, SCM might terminate the process at any time
                // (so subsequent code is not guaranteed to run).
                bool res = StartServiceCtrlDispatcher(entriesPointer);

                foreach (ServiceBase service in services)
                {
                    if (service._startFailedException != null)
                    {
                        // Propagate exceptions throw during OnStart.
                        // Note that this same exception is also thrown from ServiceMainCallback
                        // (so SCM can see it as well).
                        service._startFailedException.Throw();
                    }
                }

                string errorMessage = "";

                if (!res)
                {
                    errorMessage = new Win32Exception().Message;
                    Console.WriteLine(SR.CantStartFromCommandLine);
                }

                foreach (ServiceBase service in services)
                {
                    service.Dispose();
                    if (!res)
                    {
                        service.WriteLogEntry(SR.Format(SR.StartFailed, errorMessage), true);
                    }
                }
            }
            finally
            {
                // Free the pointer to the name of the service on the unmanaged heap.
                for (int i = 0; i < entries.Length; i++)
                {
                    Marshal.FreeHGlobal(entries[i].name);
                }

                // Free the unmanaged array containing the entries.
                Marshal.FreeHGlobal(entriesPointer);
            }
        }