예제 #1
0
        public bool StartHost(int port, bool local = false)
        {
            //UninstallService();
            if (!local)
            {
                File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ServiceParams.txt"),
                                  new JavaScriptSerializer().Serialize(new ServiceInstallParams {
                    Port = port
                }));
                return(WindowsServiceInstaller.Install(false, new string[0]));
            }

            var host = new ServiceHost(typeof(ServiceManager));

            host.AddServiceEndpoint(typeof(IServiceManager), new NetTcpBinding("Default"), "net.tcp://localhost:" + port + "/ServiceManager");
            try
            {
                host.Open();
            }
            catch
            {
                return(false);
            }
            _serviceHost = host;
            return(true);
        }
예제 #2
0
        public Task <int> TryExecute(string[] arguments)
        {
            var state       = _PersistentInstallState.Load();
            var serviceName = (string)state[StateConstants.InstalledServiceName].NotNull();
            var installer   = new WindowsServiceInstaller(new UninstallConfiguration(serviceName))
            {
                Context = _InstallContextProvider.GetContext()
            };

            try
            {
                installer.Uninstall(state);
            }
            catch
            {
                try
                {
                    installer.Rollback(state);
                }
                catch
                {
                    // Do nothing here
                }

                _PersistentInstallState.Delete();

                throw;
            }

            return(Task.FromResult(0));
        }
예제 #3
0
 public static void Main(string[] args)
 {
     if (args.Contains("-i", StringComparer.InvariantCultureIgnoreCase))
     {
         WindowsServiceInstaller.RuntimeInstall <ServiceImplementation>();
     }
     else if (args.Contains("-u", StringComparer.InvariantCultureIgnoreCase))
     {
         WindowsServiceInstaller.RuntimeUnInstall <ServiceImplementation>();
     }
     else
     {
         using (var implementation = new ServiceImplementation())
         {
             if (Environment.UserInteractive)
             {
                 ConsoleHarness.Run(args, implementation);
             }
             else
             {
                 ServiceBase.Run(new WindowsServiceHarness(implementation));
             }
         }
     }
 }
        public Task <int> TryExecute(string[] arguments)
        {
            var installer = new WindowsServiceInstaller(_Configuration)
            {
                Context = _InstallContextProvider.GetContext()
            };

            var state = new Hashtable {
                [StateConstants.InstalledServiceName] = _Configuration.ServiceName
            };

            try
            {
                installer.Install(state);
                installer.Commit(state);

                _PersistentInstallState.Save(state);
            }
            catch
            {
                try
                {
                    installer.Rollback(state);
                }
                catch
                {
                    // Do nothing here
                }

                throw;
            }

            return(Task.FromResult(0));
        }
예제 #5
0
        public static void Main()
        {
#if DEBUG
            ServiceLocator.Start();

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();

            return;
#endif

            var serviceOptions = GetServiceOptions();

            var installer = new WindowsServiceInstaller();
            if (installer.IsServiceExists(serviceOptions.ServiceName))
            {
                Console.WriteLine($"Service '{serviceOptions.ServiceName}' already installed. Stop and remove it.");

                installer.Stop(serviceOptions.ServiceName);
                installer.Uninstall(serviceOptions);
            }

            Console.WriteLine($"Install and start '{serviceOptions.ServiceName}' service");

            installer.Install(serviceOptions);
            installer.Start(serviceOptions.ServiceName);

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }
        public void Can_Install_And_Uninstall_Service_Test()
        {
            var serviceName = "EmptyTestService";
            var installer = new WindowsServiceInstaller();

            var installResult = installer.Install(serviceName);

            Assert.IsTrue(installResult, $"cant install windows service: {serviceName}");

            var uninstallResult = installer.Uninstall(serviceName);

            Assert.IsTrue(uninstallResult, $"can't uninstall existing service: {serviceName}");
        }
예제 #7
0
 private void btnUn_Click(object sender, EventArgs e)
 {
     WindowsServiceInstaller srv = new WindowsServiceInstaller();
     if (txtName.Text != "")
     {
         if (srv.UnInstallService(txtName.Text))
             lblResult.Text = "OK";
         else
             lblResult.Text = "Fail";
     }
     else
         lblResult.Text = "Null";
 }
예제 #8
0
        static void Main(string[] args)
        {
            Tracer.Initialize(@"C:\WeatherCenter\Logs", "WeatherService", Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture), Environment.UserInteractive);

            if (args.Contains("-install", StringComparer.InvariantCultureIgnoreCase))
            {
                Tracer.WriteLine("Starting install...");

                try
                {
                    WindowsServiceInstaller.RuntimeInstall <ServiceImplementation>();
                }
                catch (Exception exception)
                {
                    Tracer.WriteException("Service install", exception);
                }

                Tracer.WriteLine("Install complete");
            }
            else if (args.Contains("-uninstall", StringComparer.InvariantCultureIgnoreCase))
            {
                Tracer.WriteLine("Starting uninstall...");

                try
                {
                    WindowsServiceInstaller.RuntimeUnInstall <ServiceImplementation>();
                }
                catch (Exception exception)
                {
                    Tracer.WriteException("Service uninstall", exception);
                }

                Tracer.WriteLine("Uninstall complete");
            }
            else
            {
                Tracer.WriteLine("Starting service");

                var implementation = new ServiceImplementation();

                if (Environment.UserInteractive)
                {
                    ConsoleHarness.Run(args, implementation);
                }
                else
                {
                    ServiceBase.Run(new WindowsServiceHarness(implementation));
                }
            }
        }
예제 #9
0
        private static bool IsSetupRequested(StreamWatchOptions options)
        {
            if (options.Install)
            {
                WindowsServiceInstaller.RuntimeInstall <StreamWatchWindowsService>();
            }
            else if (options.Uninstall)
            {
                WindowsServiceInstaller.RuntimeUnInstall <StreamWatchWindowsService>();
            }
            else
            {
                return(false);
            }

            return(true);
        }
예제 #10
0
        // The main entry point for the windows service application.
        static void Main(string[] args)
        {
            try
            {
                // If install was a command line flag, then run the installer at runtime.
                if (args.Contains("-install", StringComparer.InvariantCultureIgnoreCase))
                {
                    WindowsServiceInstaller.RuntimeInstall <ServiceImplementation>();
                }

                // If uninstall was a command line flag, run uninstaller at runtime.
                else if (args.Contains("-uninstall", StringComparer.InvariantCultureIgnoreCase))
                {
                    WindowsServiceInstaller.RuntimeUnInstall <ServiceImplementation>();
                }

                // Otherwise, fire up the service as either console or windows service based on UserInteractive property.
                else
                {
                    var implementation = new ServiceImplementation();

                    // If started from console, file explorer, etc, run as console app.
                    if (Environment.UserInteractive)
                    {
                        ConsoleHarness.Run(args, implementation);
                    }

                    // Otherwise run as a windows service
                    else
                    {
                        ServiceBase.Run(new WindowsServiceHarness(implementation));
                    }
                }
            }
            catch (Exception ex)
            {
                // Write to console
                ConsoleHarness.WriteToConsole(ConsoleColor.Red, "An exception occurred in Main(): {0}", ex);

                // Write to log
                Logger.Instance.Log(true, pEx: ex);
            }
        }
        public void ExecuteTest()
        {
            ProgramConfig config;
            TraceLogger   logger = new TraceLogger(new MockUpTraceEventProvider());

            Assert.IsFalse(ServiceController.GetServices().Any(p => p.ServiceName == "ServiceFabricUpdateService"));

            config = new ProgramConfig(ExecutionModes.Install, null);
            WindowsServiceInstaller.Execute(config, logger);
            while (!ServiceController.GetServices().Any(p => p.ServiceName == "ServiceFabricUpdateService"))
            {
                Thread.Sleep(3000);
            }

            TestUtility.UninstallService("ServiceFabricUpdateService");
            while (ServiceController.GetServices().Any(p => p.ServiceName == "ServiceFabricUpdateService"))
            {
                Thread.Sleep(3000);
            }
        }
예제 #12
0
        public bool UninstallService()
        {
            //if(IsWindowsServiceRunning)
            try
            {
                return(WindowsServiceInstaller.Install(true, new string[0]));
            }
            catch
            {
                return(false);
            }

            //if(_serviceHost != null)
            //{
            //    _serviceHost.Close();
            //    _serviceHost = null;
            //    return true;
            //}
            //return false;
        }
예제 #13
0
파일: Runtime.cs 프로젝트: danryd/Tarro
 private static void ManageInstallation(string[] args)
 {
     if (args[0] == "-?")
     {
         PrintUsage();
     }
     var name = args[1];
     var installer = new WindowsServiceInstaller(name, ServiceAccount.NetworkService);
     if (args[0] == "install")
     {
         installer.Install(new Hashtable());
     }
     else if (args[0] == "uninstall")
     {
         installer.Uninstall(new Hashtable());
     }
     else
     {
         PrintUsage();
     }
 }
예제 #14
0
        public void InstallWith(WindowsServiceInstaller installer)
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            using (var ti = new TransactedInstaller())
            {
                ti.Installers.Add(installer);

                var assembly = Assembly.GetEntryAssembly();
                if (assembly == null)
                {
                    throw new NullReferenceException("assembly");
                }

                var path = string.Format("/assemblypath={0}", assembly.Location);
                string[] commandLine = {path};

                var context = new InstallContext(null, commandLine);
                ti.Context = context;
                ti.Install(new Hashtable());
            }
        }
예제 #15
0
        private static void Main(string[] args)
        {
            try
            {
                // install or uninstall windows service
                if (args.Contains("-install", StringComparer.InvariantCultureIgnoreCase))
                {
                    WindowsServiceInstaller.RuntimeInstall <WebDAVService>();
                }
                else if (args.Contains("-uninstall", StringComparer.InvariantCultureIgnoreCase))
                {
                    WindowsServiceInstaller.RuntimeUnInstall <WebDAVService>();
                }

                // otherwise, fire up the service as either console or windows service based on UserInteractive property.
                // if started from console, file explorer, etc, run as console app.
                // otherwise run as a windows service
                else
                {
                    var implementation = new WebDAVService();
                    if (Environment.UserInteractive)
                    {
                        ConsoleHarness.Run(args, implementation);
                    }
                    else
                    {
                        Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
                        ServiceBase.Run(new WindowsServiceHarness(implementation));
                    }
                }
            }

            catch (Exception ex)
            {
                ConsoleHarness.WriteToConsole(ConsoleColor.Red, "An exception occurred in Main(): {0}", ex);
            }
        }
예제 #16
0
        private static void Main(string[] args)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings["LDAP_SETTING"].Value = ActiveDirectory.RootPath;
                ConsoleHarness.WriteToConsole(ConsoleColor.Yellow, "Application is linked to the Domain: " + config.AppSettings.Settings["LDAP_SETTING"].Value);

                if (config.ConnectionStrings.ConnectionStrings["OnlineFilesEntities"] == null || config.ConnectionStrings.ConnectionStrings["OnlineFilesEntities"].ConnectionString == "")
                {
                    ConsoleHarness.WriteToConsole(ConsoleColor.Red, "Connection String (OnlineFilesEntities) is not set in the WebConfig.");
                    ConsoleHarness.WriteToConsole(ConsoleColor.Red, "Hit Any Key to Exit");
                    Console.ReadKey();
                    return;
                }

                config.Save(ConfigurationSaveMode.Full);

                using (var context = new OnlineFilesEntities())
                {
                    bool hadError = false;
                    if (!context.CatalogCollections.Any())
                    {
                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, "No Online Catalog Collections Created.");
                        ConsoleHarness.WriteToConsole(ConsoleColor.Yellow, "Please create an entry in the 'CatalogCollection' and 'Catalog' tables.");
                        ConsoleHarness.WriteToConsole(ConsoleColor.Yellow, @"insert into [CatalogCollection] ([Name]) values ('Default Catalog Collection');");
                        hadError = true;
                    }
                    if (!context.Catalogs.Any())
                    {
                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, @"Missing a default catalog in the database.");
                        ConsoleHarness.WriteToConsole(ConsoleColor.Yellow, @"
insert into [Catalog] ([fk_CatalogCollectionId], [Name], [Offline], [Server], [DatabaseName], [UserName], [Password], [fk_CatalogStatusId])
select 
		pk_CatalogCollectionID					[fk_CatalogCollectionId],
		'Default Catalog'						[Name],
		0										[Offline],
		'Name of SQL Server'					[Server],
		'Name of the Database for the Catalog'	[DatabaseName],
		'Username to connect as'				[UserName],
		'Password to use'						[Password],
		1										[fk_CatalogStatusId]
from
	CatalogCollection;"    );
                        hadError = true;
                    }
                    if (hadError)
                    {
                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, "Hit Any Key to Exit");
                        Console.ReadKey();
                        return;
                    }

                    if (!context.Folders.Any(d => d.pk_FolderId == new Guid()))
                    {
                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, @"The Root Folder does not exist!");

                        ConsoleHarness.WriteToConsole(ConsoleColor.Yellow, @"
insert into [Folder]
(pk_FolderId, fk_ParentFolderId, Name, CreateDt, fk_CatalogCollectionId, Win32FileAttribute, isDeleted, DeletedDt, DeletedBy, Owner, CreatedBy)
select top 1
	'00000000-0000-0000-0000-000000000000',
	null,
	'Root',
	getdate(),
	pk_CatalogCollectionID,
	16,
	0,
	null,
	null,
	'00000000-0000-0000-0000-000000000000',
	'00000000-0000-0000-0000-000000000000'
from 
	[CatalogCollection];"    );

                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, "Hit Any Key to Exit");
                        Console.ReadKey();
                        return;
                    }
                    if (!context.SecurityObjects.Any() && !args.Contains("-SyncADS", StringComparer.CurrentCultureIgnoreCase))
                    {
                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, @"Active Directory has not been Syncronized.");
                        ConsoleHarness.WriteToConsole(ConsoleColor.Yellow, @"Run the program with option '-SyncADS'.");
                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, "Hit Any Key to Exit");
                        Console.ReadKey();
                        return;
                    }
                }

                // if install was a command line flag, then run the installer at runtime.
                if (args.Contains(" - install", StringComparer.InvariantCultureIgnoreCase))
                {
                    WindowsServiceInstaller.RuntimeInstall <ServiceImplementation>();
                }

                // if uninstall was a command line flag, run uninstaller at runtime.
                else if (args.Contains("-uninstall", StringComparer.InvariantCultureIgnoreCase))
                {
                    WindowsServiceInstaller.RuntimeUnInstall <ServiceImplementation>();
                }

                // otherwise, fire up the service as either console or windows service based on UserInteractive property.
                else
                {
                    if (args.Contains("-SyncADS", StringComparer.CurrentCultureIgnoreCase))
                    {
                        ActiveDirectory.Syncrhonize();
                    }

                    var implementation = new ServiceImplementation();

                    // if started from console, file explorer, etc, run as console app.
                    if (Environment.UserInteractive)
                    {
                        ConsoleHarness.Run(args, implementation);
                    }

                    // otherwise run as a windows service
                    else
                    {
                        Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
                        ServiceBase.Run(new WindowsServiceHarness(implementation));
                    }
                }
            }

            catch (Exception ex)
            {
                ConsoleHarness.WriteToConsole(ConsoleColor.Red, "An exception occurred in Main(): {0}", ex);
                ConsoleHarness.WriteToConsole(ConsoleColor.Red, "Hit Any Key to Exit");
                Console.ReadKey();
            }
        }
예제 #17
0
        private void performOperation(
            IConfiguration configuration,
            CommandLineArguments commandLineArguments,
            string assemblyPath,
            Predicate <ServiceInfo> exclusionFilter,
            Converter <ServiceInfo, string> exclusionMessageConverter,
            string cancelMessage,
            Converter <string, string> preOperationMessageConverter,
            Action <WindowsServiceInstaller> operationAction,
            Converter <string, string> postOperationMessageConverter,
            Action <IEnumerable <ServiceInfo> > postOperationAction)
        {
            ThrowHelper.ThrowArgumentNullIfNull(configuration, "configuration");
            ThrowHelper.ThrowArgumentNullIfNull(commandLineArguments, "commandLineArguments");
            ThrowHelper.ThrowArgumentNullIfNull(assemblyPath, "assemblyPath");
            ThrowHelper.ThrowArgumentNullIfNull(exclusionFilter, "exclusionFilter");
            ThrowHelper.ThrowArgumentNullIfNull(exclusionMessageConverter, "exclusionMessageConverter");
            ThrowHelper.ThrowArgumentNullIfNull(cancelMessage, "cancelMessage");
            ThrowHelper.ThrowArgumentNullIfNull(preOperationMessageConverter, "preOperationMessageConverter");
            ThrowHelper.ThrowArgumentNullIfNull(operationAction, "operationAction");
            ThrowHelper.ThrowArgumentNullIfNull(postOperationMessageConverter, "postOperationMessageConverter");
            ThrowHelper.ThrowArgumentNullIfNull(postOperationAction, "postOperationAction");

            log.Debug(m => m("Executing installer command '{0}'...", operationAction));

            var services =
                getServicesToPerformActionOn(configuration,
                                             exclusionFilter,
                                             exclusionMessageConverter);

            if (services.Count == 0)
            {
                log.Info(cancelMessage);
                Console.WriteLine(cancelMessage);
                return;
            }

            checkServicesInContainer(services);

            try
            {
                string displayNames =
                    string.Join("','",
                                Array.ConvertAll(services.ToArray(),
                                                 s => s.DisplayName));
                string preOperationMessage = preOperationMessageConverter(displayNames);
                log.Info(preOperationMessage);
                Console.WriteLine(preOperationMessage);
                using (var installer = new WindowsServiceInstaller(
                           services,
                           commandLineArguments,
                           assemblyPath))
                {
                    operationAction(installer);
                }
                string postOperationMessage = postOperationMessageConverter(displayNames);
                log.Info(postOperationMessage);
                Console.WriteLine(postOperationMessage);

                postOperationAction(services);
            }
            catch (Exception e)
            {
                log.Error(e);
            }
            log.Debug(m => m("Done executing installer command '{0}'...", operationAction));
        }
예제 #18
0
 public void UninstallWith(WindowsServiceInstaller windowsServiceInstaller)
 {
     windowsServiceInstaller.Uninstall(new Hashtable());
 }