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

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

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

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

                    IDictionary state = new Hashtable();

                    try
                    {
                        installer.Install(state);
                        installer.Commit(state);
                    }
                    catch (Exception ex)
                    {
                        installer.Rollback(state);
                        throw new Exception("Failed to install the service.", ex);
                    }
                }
            }
        }
예제 #2
0
        //Cria um serviço novo e registra o mesmo no caminho System\Current\Services
        public static void CreateService(string executablePath, string serviceName, string serviceDescription, string DisplayServiceName)
        {
            string retorno = VerifyInstanceTotal(@"SYSTEM\CurrentControlSet\services\" + serviceName, "DisplayName");

            if (retorno == "")
            {
                ServiceProcessInstaller ProcesServiceInstaller = new ServiceProcessInstaller();
                ProcesServiceInstaller.Account = ServiceAccount.User;

                ServiceInstaller servico = new ServiceInstaller();
                InstallContext   Context = new System.Configuration.Install.InstallContext();
                String           path    = String.Format("/assemblypath={0}", executablePath);
                String[]         cmdline = { path };

                Context             = new System.Configuration.Install.InstallContext("", cmdline);
                servico.Context     = Context;
                servico.DisplayName = DisplayServiceName;
                servico.Description = serviceDescription;
                servico.ServiceName = serviceName;
                servico.StartType   = ServiceStartMode.Automatic;
                servico.Parent      = ProcesServiceInstaller;

                System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();

                ServiceController serviceExists = new ServiceController(serviceName);

                servico.Install(state);
            }
        }
        public void ItPersistsArgumentsInFile(
            string containerDirectory, string machineIp, string syslogHostIp, string syslogPort, string machineName)
        {
            var context = new InstallContext();
            context.Parameters.Add("CONTAINER_DIRECTORY", containerDirectory);
            context.Parameters.Add("MACHINE_IP", machineIp);
            context.Parameters.Add("SYSLOG_HOST_IP", syslogHostIp);
            context.Parameters.Add("SYSLOG_PORT", syslogPort);
            context.Parameters.Add("MACHINE_NAME", machineName);
            configurationManager.Context = context;
            configurationManager.OnBeforeInstall(null);

            var acl = Directory.GetAccessControl(tempDirectory.ToString());
            var accessRules = acl.GetAccessRules(true, true, typeof(SecurityIdentifier));
            Assert.Equal(accessRules.Count, 1);
            var rule = (FileSystemAccessRule)accessRules[0];
            Assert.Equal(rule.AccessControlType, AccessControlType.Allow);
            Assert.Equal(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), rule.IdentityReference);
            Assert.Equal(rule.FileSystemRights, FileSystemRights.FullControl);

            var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var parametersPath = Path.Combine(tempDirectory.ToString(), "parameters.json");
            var jsonString = File.ReadAllText(parametersPath);
            var hash = javaScriptSerializer.Deserialize<Dictionary<string, string>>(jsonString);
            Assert.Equal(hash["CONTAINER_DIRECTORY"], containerDirectory);
            Assert.Equal(hash["MACHINE_IP"], machineIp);
            Assert.Equal(hash["SYSLOG_HOST_IP"], syslogHostIp);
            Assert.Equal(hash["SYSLOG_PORT"], syslogPort);
            Assert.Equal(hash["MACHINE_NAME"], machineName);
        }
예제 #4
0
        public virtual void Install(string serviceName)
        {
            Logger.Info("Installing service '{0}'", serviceName);


            var installer = new ServiceProcessInstaller
                                {
                                    Account = ServiceAccount.LocalSystem
                                };

            var serviceInstaller = new ServiceInstaller();


            String[] cmdline = { @"/assemblypath=" + Process.GetCurrentProcess().MainModule.FileName };

            var context = new InstallContext("service_install.log", cmdline);
            serviceInstaller.Context = context;
            serviceInstaller.DisplayName = serviceName;
            serviceInstaller.ServiceName = serviceName;
            serviceInstaller.Description = "NzbDrone Application Server";
            serviceInstaller.StartType = ServiceStartMode.Automatic;
            serviceInstaller.ServicesDependedOn = new[] { "EventLog", "Tcpip" };

            serviceInstaller.Parent = installer;

            serviceInstaller.Install(new ListDictionary());

            Logger.Info("Service Has installed successfully.");
        }
예제 #5
0
 static void Main(string[] args)
 {
     string opt = null;
     if (args.Length >= 1)
     {
         opt = args[0].ToLower();
     }
     if (opt == "/install" || opt == "/uninstall")
     {
         TransactedInstaller ti = new TransactedInstaller();
         MonitorInstaller mi = new MonitorInstaller("OPC_FILE_WATCHER");
         ti.Installers.Add(mi);
         string path = String.Format("/assemblypath={0}", Assembly.GetExecutingAssembly().Location);
         string[] cmdline = { path };
         InstallContext ctx = new InstallContext("", cmdline);
         ti.Context = ctx;
         if (opt == "/install")
         {
             Console.WriteLine("Installing");
             ti.Install(new Hashtable());
         }
         else if (opt == "/uninstall")
         {
             Console.WriteLine("Uninstalling");
                 try { ti.Uninstall(null); } catch (InstallException ie) { Console.WriteLine(ie.ToString()); }
         }
     }
     else
     {
         ServiceBase[] services;
         services = new ServiceBase[] { new OPCDataParser() }; ServiceBase.Run(services);
     }
 }
예제 #6
0
 public FrmConfig(System.Configuration.Install.InstallContext context, InstallController ctrl)
 {
     formContext = context;
     this.ctrl   = ctrl;
     InitializeComponent();
     this.CenterToScreen();
 }
예제 #7
0
        private void PrintStartText(string activity)
        {
            if (this.UseNewContext)
            {
                InstallContext context = this.CreateAssemblyContext();
                if (base.Context != null)
                {
                    base.Context.LogMessage(System.Configuration.Install.Res.GetString("InstallLogContent", new object[] { this.Path }));
                    base.Context.LogMessage(System.Configuration.Install.Res.GetString("InstallFileLocation", new object[] { context.Parameters["logfile"] }));
                }
                base.Context = context;
            }
            base.Context.LogMessage(string.Format(CultureInfo.InvariantCulture, activity, new object[] { this.Path }));
            base.Context.LogMessage(System.Configuration.Install.Res.GetString("InstallLogParameters"));
            if (base.Context.Parameters.Count == 0)
            {
                base.Context.LogMessage("   " + System.Configuration.Install.Res.GetString("InstallLogNone"));
            }
            IDictionaryEnumerator enumerator = (IDictionaryEnumerator)base.Context.Parameters.GetEnumerator();

            while (enumerator.MoveNext())
            {
                string key  = (string)enumerator.Key;
                string str2 = (string)enumerator.Value;
                if (key.Equals("password", StringComparison.InvariantCultureIgnoreCase))
                {
                    str2 = "********";
                }
                base.Context.LogMessage("   " + key + " = " + str2);
            }
        }
        private void PrintStartText(string activity)
        {
            if (UseNewContext)
            {
                InstallContext newContext = CreateAssemblyContext();
                // give a warning in the main log file that we're switching over to the assembly-specific file
                if (Context != null)
                {
                    Context.LogMessage(Res.GetString(Res.InstallLogContent, Path));
                    Context.LogMessage(Res.GetString(Res.InstallFileLocation, newContext.Parameters["logfile"]));
                }
                Context = newContext;
            }

            // print out some info on the install
            Context.LogMessage(string.Format(activity, Path));
            Context.LogMessage(Res.GetString(Res.InstallLogParameters));
            if (Context.Parameters.Count == 0)
            {
                Context.LogMessage("   " + Res.GetString(Res.InstallLogNone));
            }
            IDictionaryEnumerator en = (IDictionaryEnumerator)Context.Parameters.GetEnumerator();

            while (en.MoveNext())
            {
                Context.LogMessage("   " + (string)en.Key + " = " + (string)en.Value);
            }
        }
        private InstallContext CreateAssemblyContext()
        {
            InstallContext context = new InstallContext(System.IO.Path.ChangeExtension(Path, ".InstallLog"), CommandLine);

            context.Parameters["assemblypath"] = Path;
            return(context);
        }
예제 #10
0
        //Cria um serviço novo e registra o mesmo no caminho System\Current\Services
        public static void CreateService(string executablePath, string serviceName, string serviceDescription, string displayServiceName)
        {
            ServiceProcessInstaller ProcesServiceInstaller = new ServiceProcessInstaller();

            ProcesServiceInstaller.Account = ServiceAccount.User;

            ServiceInstaller service = new ServiceInstaller();
            InstallContext   Context = new System.Configuration.Install.InstallContext();
            String           path    = String.Format("/assemblypath={0}", executablePath);

            String[] cmdline = { path };

            Context             = new System.Configuration.Install.InstallContext("", cmdline);
            service.Context     = Context;
            service.DisplayName = displayServiceName;
            service.Description = serviceDescription;
            service.ServiceName = serviceName;
            service.StartType   = ServiceStartMode.Automatic;
            service.Parent      = ProcesServiceInstaller;

            System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();

            ServiceController serviceExists = new ServiceController(serviceName);

            service.Install(state);
        }
        public CustomInstaller(Service service)
        {
            _service = service;
            Installers.Add(GetServiceInstaller());
            Installers.Add(GetServiceProcessInstaller());
            var baseDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
            Context = new InstallContext(
                null,
                new[]
                    {
                        "/LogToConsole=true",
                        "/InstallStateDir=" + Path.Combine(baseDir, "service-install.state"),
                        "/LogFile=" + Path.Combine(baseDir, "service-install.log")
                    });

            foreach (string key in Context.Parameters.Keys)
            {
                Writer.WriteLine("{0}={1}", key, Context.Parameters[key]);
            }

            if (_service.StartMode == ServiceStartMode.Automatic)
            {
                Committed += (sender, args) => new ServiceController(service.ServiceName).Start();
            }
        }
예제 #12
0
        public void RunPrecompiler()
        {
            var appBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            var targetFile = Path.Combine(appBase, "RunPrecompiler.dll");
            File.Delete(targetFile);

            var parent = new ParentInstaller();
            var precompile = new PrecompileInstaller();

            precompile.TargetAssemblyFile = targetFile;
            precompile.ViewPath = "MonoRail.Tests.Views";
            precompile.DescribeBatch += ((sender, e) => e.Batch.For<StubController>().Include("*").Include("_*"));

            var context = new InstallContext();
            var state = new Hashtable();

            parent.Installers.Add(precompile);
            parent.Install(state);
            parent.Commit(state);

            Assert.That(File.Exists(targetFile), "File exists");

            var result = Assembly.LoadFrom(targetFile);
            Assert.AreEqual(3, result.GetTypes().Count());
        }
        public void ItPersistsArgumentsInFile(
            string containerDirectory, string machineIp, string syslogHostIp, string syslogPort, string machineName)
        {
            using(var tempDirectory = new TempDirectory())
            {
                var configurationManager = new ConfigurationManagerTest();
                var context = new InstallContext();
                context.Parameters.Add("CONTAINER_DIRECTORY", containerDirectory);
                context.Parameters.Add("MACHINE_IP", machineIp);
                context.Parameters.Add("SYSLOG_HOST_IP", syslogHostIp);
                context.Parameters.Add("SYSLOG_PORT", syslogPort);
                context.Parameters.Add("assemblypath", tempDirectory.ToString());
                context.Parameters.Add("MACHINE_NAME", machineName);
                configurationManager.Context = context;
                configurationManager.OnBeforeInstall(null);

                var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                var jsonString = File.ReadAllText(Path.Combine(tempDirectory.ToString(), @"..\parameters.json"));
                var hash = javaScriptSerializer.Deserialize<Dictionary<string, string>>(jsonString);
                Assert.Equal(hash["CONTAINER_DIRECTORY"], containerDirectory);
                Assert.Equal(hash["MACHINE_IP"], machineIp);
                Assert.Equal(hash["SYSLOG_HOST_IP"], syslogHostIp);
                Assert.Equal(hash["SYSLOG_PORT"], syslogPort);
                Assert.Equal(hash["MACHINE_NAME"], machineName);
            }
        }
예제 #14
0
 public FrmConfig(System.Configuration.Install.InstallContext context, InstallController ctrl)
 {
     formContext = context;
     this.ctrl = ctrl;
     InitializeComponent();
     this.CenterToScreen();
 }
예제 #15
0
 public InstallContext(string logFilePath, string[] commandLine)
 {
     this.parameters = InstallContext.ParseCommandLine(commandLine);
     if (this.Parameters["logfile"] == null && logFilePath != null)
     {
         this.Parameters["logfile"] = logFilePath;
     }
 }
예제 #16
0
        public override void Install(IDictionary stateSaver)
        {
            string strAssPath = "/assemblypath=\"{0}\" \"" + this.Context.Parameters["path"]+"\"";

            Context = new InstallContext("", new string[] { String.Format(strAssPath, System.Reflection.Assembly.GetExecutingAssembly().Location) });

            base.Install(stateSaver);
        }
예제 #17
0
 public void DeleteService(string i_ServiceName)
 {
     ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
     InstallContext Context = new InstallContext(AppDomain.CurrentDomain.BaseDirectory + "\\uninstalllog.log", null);
     ServiceInstallerObj.Context = Context;
     ServiceInstallerObj.ServiceName = i_ServiceName;
     ServiceInstallerObj.Uninstall(null);
 }
예제 #18
0
 /// <summary>
 /// UnInstalls the Windows service with the given "installer" object.
 /// </summary>
 /// <param name="pi"></param>
 /// <param name="pathToService"></param>
 public static void uninstallService(Installer pi, string pathToService)
 {
     TransactedInstaller ti = new TransactedInstaller ();
     ti.Installers.Add (pi);
     string[] cmdline = {pathToService};
     InstallContext ctx = new InstallContext ("Uninstall.log", cmdline );
     ti.Context = ctx;
     ti.Uninstall ( null );
 }
예제 #19
0
 public InstallContext(string logFilePath, string[] commandLine)
 {
     Parameters = InstallContext.ParseCommandLine(commandLine);
     if (Parameters["logfile"] != null || logFilePath == null)
     {
         return;
     }
     Parameters["logfile"] = logFilePath;
 }
예제 #20
0
        public FrmDbInstall(System.Configuration.Install.InstallContext context, InstallController ctrl)
        {
            Logger.info("FrmDbInstall");

            formContext = context;
            this.ctrl   = ctrl;
            InitializeComponent();
            this.CenterToScreen();
        }
예제 #21
0
 /// <summary>
 /// Installs the Windows service with the given "installer" object.
 /// </summary>
 /// <param name="installer">The installer.</param>
 /// <param name="pathToService">The path to service.</param>
 public static void InstallService(Installer installer, string pathToService)
 {
     TransactedInstaller ti = new TransactedInstaller();
     ti.Installers.Add(installer);
     string[] cmdline = { pathToService };
     InstallContext ctx = new InstallContext("Install.log", cmdline);
     ti.Context = ctx;
     ti.Install(new Hashtable());
 }
예제 #22
0
        public FrmDbInstall(System.Configuration.Install.InstallContext context, InstallController ctrl)
        {
            Logger.info("FrmDbInstall");

            formContext = context;
            this.ctrl = ctrl;
            InitializeComponent();
            this.CenterToScreen();
        }
예제 #23
0
      public void StartForeground(string[] args)
      {
         if (args.Length > 0)
         {
            switch (args[0])
            {
               case "/install":
               case "-install":
               case "--install":
                  {
                     var directory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Barcodes");
                     if (args.Length > 1)
                     {
                        directory = Path.GetFullPath(args[1]);
                     }
                     if (!Directory.Exists(directory))
                        throw new ArgumentException(String.Format("The barcode directory {0} doesn't exists.", directory));
                     
                     var transactedInstaller = new TransactedInstaller();
                     var serviceInstaller = new ServiceInstaller();
                     transactedInstaller.Installers.Add(serviceInstaller);
                     var ctx = new InstallContext();
                     ctx.Parameters["assemblypath"] = String.Format("{0} \"{1}\"", Assembly.GetExecutingAssembly().Location, directory);
                     transactedInstaller.Context = ctx;
                     transactedInstaller.Install(new Hashtable());

                     Console.WriteLine("The service is installed. Barcode images have to be placed into the directory {0}.", directory);
                  }
                  return;
               case "/uninstall":
               case "-uninstall":
               case "--uninstall":
                  {
                     var transactedInstaller = new TransactedInstaller();
                     var serviceInstaller = new ServiceInstaller();
                     transactedInstaller.Installers.Add(serviceInstaller);
                     var ctx = new InstallContext();
                     ctx.Parameters["assemblypath"] = String.Format("{0}", Assembly.GetExecutingAssembly().Location);
                     transactedInstaller.Context = ctx;
                     transactedInstaller.Uninstall(null);

                     Console.WriteLine("The service is uninstalled.");
                  }
                  return;
               default:
                  if (args[0][0] != '/' &&
                      args[0][0] != '-')
                     throw new ArgumentException(String.Format("The argument {0} isn't supported.", args[0]));
                  break;
            }
         }

         OnStart(args);

         Console.ReadLine();
      }
예제 #24
0
		private TransactedInstaller InitializeInstaller(Dictionary<string, string> parameters)
		{
			SetupParameters(parameters);
			var ti = new TransactedInstaller();
			var ai = new AssemblyInstaller(Path.Combine(_sourcePath, _serviceExecutable), _parameters);
			ti.Installers.Add(ai);
			var ic = new InstallContext("Install.log", _parameters);
			ti.Context = ic;
			return ti;
		}
        /// <summary>
        /// setup the Babalu perfmon counters
        /// </summary>
        /// <param name="context"></param>
        public static void SetupPerfmonCounters(InstallContext context)
        {
            context.LogMessage("Perfmon Babalu counters installer begins");
            #if !DEBUG
            if (PerformanceCounterCategory.Exists(BabaluCounterDescriptions.CounterCategory))
                PerformanceCounterCategory.Delete(BabaluCounterDescriptions.CounterCategory);
            #endif
            BabaluCounterDescriptions.InstallCounters();

            context.LogMessage("Perfmon Babalu counters installer ends");
        }
예제 #26
0
        private InstallContext CreateAssemblyContext()
        {
            InstallContext context = new InstallContext(System.IO.Path.ChangeExtension(this.Path, ".InstallLog"), this.CommandLine);

            if (base.Context != null)
            {
                context.Parameters["logtoconsole"] = base.Context.Parameters["logtoconsole"];
            }
            context.Parameters["assemblypath"] = this.Path;
            return(context);
        }
예제 #27
0
        private InstallContext CreateAssemblyContext()
        {
            var installContext = new InstallContext(System.IO.Path.ChangeExtension(Path, ".InstallLog"), CommandLine);

            if (Context != null)
            {
                installContext.Parameters["logtoconsole"] = Context.Parameters["logtoconsole"];
            }
            installContext.Parameters["assemblypath"] = Path;
            return(installContext);
        }
예제 #28
0
        // Perform the installation process, saving the previous
        // state in the "stateSaver" object.
        public override void Install(IDictionary stateSaver)
        {
            // Make sure that we have a context.
            if (Context == null)
            {
                Context = new InstallContext("con", new String [0]);
            }

            // Log the start of the transaction.
            Context.LogLine(S._("Installer_BeginInstallTransaction"));
            try
            {
                // Run the installation process.
                try
                {
                    Context.LogLine(S._("Installer_BeginInstall"));
                    base.Install(stateSaver);
                }
                catch (SystemException)
                {
                    // Roll back the transaction.
                    Context.LogLine(S._("Installer_BeginRollback"));
                    try
                    {
                        Rollback(stateSaver);
                    }
                    catch (SystemException)
                    {
                        // Ignore errors during rollback.
                    }
                    Context.LogLine(S._("Installer_EndRollback"));

                    // Notify the caller about the rollback.
                    throw new InvalidOperationException
                              (S._("Installer_RollbackPerformed"));
                }

                // Commit the transaction.
                Context.LogLine(S._("Installer_BeginCommit"));
                try
                {
                    Commit(stateSaver);
                }
                finally
                {
                    Context.LogLine(S._("Installer_EndCommit"));
                }
            }
            finally
            {
                Context.LogLine(S._("Installer_EndInstallTransaction"));
            }
        }
    // Perform the installation process, saving the previous
    // state in the "stateSaver" object.
    public override void Install(IDictionary stateSaver)
			{
				// Make sure that we have a context.
				if(Context == null)
				{
					Context = new InstallContext("con", new String [0]);
				}

				// Log the start of the transaction.
				Context.LogLine(S._("Installer_BeginInstallTransaction"));
				try
				{
					// Run the installation process.
					try
					{
						Context.LogLine(S._("Installer_BeginInstall"));
						base.Install(stateSaver);
					}
					catch(SystemException)
					{
						// Roll back the transaction.
						Context.LogLine(S._("Installer_BeginRollback"));
						try
						{
							Rollback(stateSaver);
						}
						catch(SystemException)
						{
							// Ignore errors during rollback.
						}
						Context.LogLine(S._("Installer_EndRollback"));
	
						// Notify the caller about the rollback.
						throw new InvalidOperationException
							(S._("Installer_RollbackPerformed"));
					}
	
					// Commit the transaction.
					Context.LogLine(S._("Installer_BeginCommit"));
					try
					{
						Commit(stateSaver);
					}
					finally
					{
						Context.LogLine(S._("Installer_EndCommit"));
					}
				}
				finally
				{
					Context.LogLine(S._("Installer_EndInstallTransaction"));
				}
			}
예제 #30
0
        public bool DeployService()
        {
            try
            {
                Installer installer = new Installer();


                ServiceProcessInstaller processInstaller = new ServiceProcessInstaller();
                EventLogInstaller       customEventLogInstaller;

                processInstaller.Account = _settings.ServiceAccount;

                if (processInstaller.Account == ServiceAccount.User)
                {
                    processInstaller.Username = _settings.ServiceAccountUserName;
                    processInstaller.Password = _settings.ServiceAccountPassword;
                }

                ServiceInstaller serviceInstaller = new ServiceInstaller();
                InstallContext   Context          = new System.Configuration.Install.InstallContext();
                String           path             = String.Format("/assemblypath={0}", _settings.ServiceExecutalePath);//String.Format("/assemblypath={0}", @"<<path of executable of window service>>");
                String[]         cmdline          = { path };

                Context = new System.Configuration.Install.InstallContext("", cmdline);
                serviceInstaller.Context     = Context;
                serviceInstaller.DisplayName = _settings.ServiceName;
                serviceInstaller.ServiceName = _settings.ServiceName;
                serviceInstaller.Description = _settings.ServiceDescription;
                serviceInstaller.StartType   = _settings.ServiceStartMode;

                //usama
                serviceInstaller.Parent = processInstaller;

                // Create an instance of 'EventLogInstaller'.
                customEventLogInstaller = new EventLogInstaller();
                // Set the 'Source' of the event log, to be created.
                customEventLogInstaller.Source = "customTayaLog";
                // Set the 'Event Log' that the source is created in.
                customEventLogInstaller.Log = "TayaApplication";
                // Add myEventLogInstaller to 'InstallerCollection'.

                //serviceInstaller.Installers.Add(customEventLogInstaller);
                System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();
                serviceInstaller.Install(state);

                return(true);
            }
            catch (Exception ex)
            {
                LogHelper.LogException(ex, "ServiceUtility.DeployService", LogType.Watcher);
                return(false);
            }
        }
	public void SetUp ()
	{
		string logFile = "./InstallContextTestLog.txt";
		string[] param = new string[] {
		    "/Option1=value1", 
		    "-Option2=value2",
		    "-Option3",
		    "Option4",
		    "/Option5=True",
		    "/Option6=no"
		};
		ic = new InstallContext (logFile, param);
	}
        public void ItPersistsArgumentsInFile(
            string consulDomain, string consulIps, Uri cfEtcdCluster, string loggregatorSharedSecret,
            string redundancyZone, string stack, string machineIp)
        {
            var context = new InstallContext();
            var consulEncryptFile = Path.Combine(sourceDirectory.ToString(), "encrypt_key");
            File.WriteAllText(consulEncryptFile, "content");

            context.Parameters.Add("CONSUL_DOMAIN", consulDomain);
            context.Parameters.Add("CONSUL_IPS", consulIps);
            context.Parameters.Add("CF_ETCD_CLUSTER", cfEtcdCluster.ToString());
            context.Parameters.Add("LOGGREGATOR_SHARED_SECRET", loggregatorSharedSecret);
            context.Parameters.Add("REDUNDANCY_ZONE", redundancyZone);
            context.Parameters.Add("STACK", stack);
            context.Parameters.Add("MACHINE_IP", machineIp);
            context.Parameters.Add("CONSUL_ENCRYPT_FILE", consulEncryptFile);
            context.Parameters.Add("REP_REQUIRE_TLS", false.ToString());
            configurationManager.Context = context;
            configurationManager.OnBeforeInstall(null);

            DirectorySecurity directoryAcl = Directory.GetAccessControl(tempDirectory.ToString());
            AuthorizationRuleCollection accessRules = directoryAcl.GetAccessRules(true, true,
                typeof (SecurityIdentifier));
            Assert.Equal(accessRules.Count, 1);
            var rule = (FileSystemAccessRule) accessRules[0];
            Assert.Equal(rule.AccessControlType, AccessControlType.Allow);
            Assert.Equal(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), rule.IdentityReference);
            Assert.Equal(rule.FileSystemRights, FileSystemRights.FullControl);

            FileSecurity fileAcl = File.GetAccessControl(Path.Combine(tempDirectory.ToString(), "encrypt_key"));
            accessRules = fileAcl.GetAccessRules(true, true, typeof (SecurityIdentifier));
            Assert.Equal(accessRules.Count, 1);
            rule = (FileSystemAccessRule) accessRules[0];
            Assert.Equal(rule.AccessControlType, AccessControlType.Allow);
            Assert.Equal(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), rule.IdentityReference);
            Assert.Equal(rule.FileSystemRights, FileSystemRights.FullControl);

            var javaScriptSerializer = new JavaScriptSerializer();
            string parametersPath = Path.Combine(tempDirectory.ToString(), "parameters.json");
            string jsonString = File.ReadAllText(parametersPath);
            var hash = javaScriptSerializer.Deserialize<Dictionary<string, string>>(jsonString);
            Assert.Equal(hash["CONSUL_DOMAIN"], consulDomain);
            Assert.Equal(hash["CONSUL_IPS"], consulIps);
            Assert.Equal(hash["CF_ETCD_CLUSTER"], cfEtcdCluster.ToString());
            Assert.Equal(hash["LOGGREGATOR_SHARED_SECRET"], loggregatorSharedSecret);
            Assert.Equal(hash["REDUNDANCY_ZONE"], redundancyZone);
            Assert.Equal(hash["STACK"], stack);
            Assert.Equal(hash["MACHINE_IP"], machineIp);
            Assert.Equal(hash["CONSUL_ENCRYPT_FILE"], Path.Combine(tempDirectory.ToString(), "encrypt_key"));
            Assert.Equal(hash["REP_REQUIRE_TLS"], false.ToString());
        }
예제 #33
0
        static void Main( string[] args )
        {
            InstallContext context = new InstallContext();

            context.Parameters["assemblypath"] = typeof( ProjectInstaller ).Assembly.CodeBase.Substring( 8 ).Replace( '/', '\\' );
            context.Parameters["Mode"] = "1";

            using (ProjectInstaller installer = new ProjectInstaller { AutoTestMode = true, Context = context })
            {
                Dictionary<string, string> items = new Dictionary<string, string>();

                installer.Install( items );
            }
        }
 /// <summary>Performs the installation.</summary>
 /// <param name="savedState">An <see cref="T:System.Collections.IDictionary" /> in which this method saves information needed to perform a commit, rollback, or uninstall operation. </param>
 /// <exception cref="T:System.ArgumentException">The <paramref name="savedState" /> parameter is null. </exception>
 /// <exception cref="T:System.Exception">The installation failed, and is being rolled back. </exception>
 public override void Install(IDictionary savedState)
 {
     if (Context == null)
     {
         Context = new InstallContext();
     }
     Context.LogMessage(Environment.NewLine + Res.GetString("InstallInfoTransacted"));
     try
     {
         var flag = true;
         try
         {
             Context.LogMessage(Environment.NewLine + Res.GetString("InstallInfoBeginInstall"));
             base.Install(savedState);
         }
         catch (Exception ex)
         {
             flag = false;
             Context.LogMessage(Environment.NewLine + Res.GetString("InstallInfoException"));
             LogException(ex, Context);
             Context.LogMessage(Environment.NewLine + Res.GetString("InstallInfoBeginRollback"));
             try
             {
                 Rollback(savedState);
             }
             catch (Exception)
             {
             }
             Context.LogMessage(Environment.NewLine + Res.GetString("InstallInfoRollbackDone"));
             throw new InvalidOperationException(Res.GetString("InstallRollback"), ex);
         }
         if (flag)
         {
             Context.LogMessage(Environment.NewLine + Res.GetString("InstallInfoBeginCommit"));
             try
             {
                 Commit(savedState);
             }
             finally
             {
                 Context.LogMessage(Environment.NewLine + Res.GetString("InstallInfoCommitDone"));
             }
         }
     }
     finally
     {
         Context.LogMessage(Environment.NewLine + Res.GetString("InstallInfoTransactedDone"));
     }
 }
예제 #35
0
        /// <include file='doc\TransactedInstaller.uex' path='docs/doc[@for="TransactedInstaller.Uninstall"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public override void Uninstall(IDictionary savedState)
        {
            if (Context == null)
            {
                Context = new InstallContext();
            }

            Context.LogMessage(Environment.NewLine + Environment.NewLine + Res.GetString(Res.InstallInfoBeginUninstall));
            try {
                base.Uninstall(savedState);
            }
            finally {
                Context.LogMessage(Environment.NewLine + Res.GetString(Res.InstallInfoUninstallDone));
            }
        }
예제 #36
0
        public virtual void UnInstall(string serviceName)
        {
            Logger.Info("Uninstalling {0} service", serviceName);

            Stop(serviceName);
            
            var serviceInstaller = new ServiceInstaller();

            var context = new InstallContext("service_uninstall.log", null);
            serviceInstaller.Context = context;
            serviceInstaller.ServiceName = serviceName;
            serviceInstaller.Uninstall(null);

            Logger.Info("{0} successfully uninstalled", serviceName);
        }
        /// <include file='doc\TransactedInstaller.uex' path='docs/doc[@for="TransactedInstaller.Uninstall"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public override void Uninstall(IDictionary savedState)
        {
            if (Context == null)
            {
                Context = new InstallContext("con", new string[0]);
            }

            Context.LogMessage("\r\n\r\n" + Res.GetString(Res.InstallInfoBeginUninstall));
            try {
                base.Uninstall(savedState);
            }
            finally {
                Context.LogMessage("\r\n" + Res.GetString(Res.InstallInfoUninstallDone));
            }
        }
예제 #38
0
        private static bool InstallService(string serviceName, string displayName)
        {

            bool success = false;
            try
            {

                string exeFullPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                string workingPath = System.IO.Path.GetDirectoryName(exeFullPath);
                string logPath = System.IO.Path.Combine(workingPath, "Install.log");
                ServiceStartMode startmode = ServiceStartMode.Automatic;
                ServiceAccount account = ServiceAccount.LocalService;
                string username = "";
                string password = "";

                startmode = ServiceStartMode.Automatic;
                account = ServiceAccount.LocalSystem;

                Hashtable savedState = new Hashtable();
                ProjectInstaller myProjectInstaller = new ProjectInstaller();
                InstallContext myInstallContext = new InstallContext(logPath, new string[] { });
                myProjectInstaller.Context = myInstallContext;
                myProjectInstaller.ServiceName = serviceName;
                myProjectInstaller.DisplayName = displayName;
                //myProjectInstaller.Description = "Self Install Service test";
                myProjectInstaller.StartType = startmode;
                myProjectInstaller.Account = account;
                if (account == ServiceAccount.User)
                {

                    myProjectInstaller.ServiceUsername = username;
                    myProjectInstaller.ServicePassword = password;

                }
                myProjectInstaller.Context.Parameters["AssemblyPath"] = exeFullPath;

                myProjectInstaller.Install(savedState);                
                ServiceUtility.StopStartServices(serviceName, ServiceControllerStatus.StartPending);
                success = true;

            }
            catch (Exception ex)
            {

            }
            return success;
        }
예제 #39
0
        public void ExecuteInternal(HostArguments args)
        {
            var serviceInstaller = new ServiceInstaller
            {
                ServiceName = args.ServiceName,
                Description = args.Description,
                DisplayName = args.DisplayName,
            };
            SetStartMode(serviceInstaller, args.StartMode);

            var serviceProcessInstaller = new ServiceProcessInstaller
            {
                Username = args.Username,
                Password = args.Password,
                Account = args.ServiceAccount,
            };
            var installers = new Installer[]
            {
                serviceInstaller,
                serviceProcessInstaller
            };

            var arguments = String.Empty;

            if (!String.IsNullOrEmpty(args.Url))
            {
                arguments += string.Format(" --url=\"{0}\"", args.Url);
            }

            using (var hostInstaller = new HostInstaller(args, arguments, installers))
            using (var transactedInstaller = new TransactedInstaller())
            {
                transactedInstaller.Installers.Add(hostInstaller);

                var assembly = Assembly.GetEntryAssembly();

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

                var context = new InstallContext(null, commandLine);
                transactedInstaller.Context = context;

                Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

                action(transactedInstaller);
            }
        }
예제 #40
0
        public static void Uninstall(string[] args)
        {
            string name = args.Length == 2 ? args[1] : DEFAULT_NAME;
            try {

                TransactedInstaller ti = new TransactedInstaller();
                WindowsServiceProjectInstaller mi = WindowsServiceProjectInstaller.Create(name);
                ti.Installers.Add(mi);
                string path = string.Format("/assemblypath={0}", System.Reflection.Assembly.GetExecutingAssembly().Location);
                string[] cmdline = { path };
                InstallContext ctx = new InstallContext("", cmdline);
                ti.Context = ctx;
                ti.Uninstall(null);
            }
                //Swallow exception when we're trying to uninstall non-existent service
            catch { }
        }
예제 #41
0
        private void InstallService()
        {
            try
            {
                ServiceProcessInstaller ProcesServiceInstaller = new ServiceProcessInstaller();
                ServiceInstaller        ServiceInstallerObj    = new ServiceInstaller();
                InstallContext          Context = new System.Configuration.Install.InstallContext();
                string ServiceExePath           = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
                                                               ((DataRowView)(lstServices.SelectedItem)).Row["ServiceName"].ToString() + ".exe");

                if (File.Exists(ServiceExePath))
                {
                    File.Delete(ServiceExePath);
                }


                File.Copy(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
                                       "ServiceLoader.exe"),
                          Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
                                       ((DataRowView)(lstServices.SelectedItem)).Row["ServiceName"].ToString() + ".exe"));

                String path = String.Format("/assemblypath={0}", ServiceExePath);
                if (!File.Exists(ServiceExePath))
                {
                    MessageBox.Show(((DataRowView)(lstServices.SelectedItem)).Row["ServiceName"].ToString() + ".exe does not exists in " + ServiceExePath, "Service Controller", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                String[] cmdline = { path };
                Context = new System.Configuration.Install.InstallContext(Environment.CurrentDirectory + cInstallFileName, cmdline);
                ServiceInstallerObj.Context     = Context;
                ServiceInstallerObj.DisplayName = ((DataRowView)(lstServices.SelectedItem)).Row["ServiceDisplayName"].ToString();
                ServiceInstallerObj.Description = ((DataRowView)(lstServices.SelectedItem)).Row["ServiceDescription"].ToString();;
                ServiceInstallerObj.ServiceName = ((DataRowView)(lstServices.SelectedItem)).Row["ServiceName"].ToString();
                ServiceInstallerObj.StartType   = ServiceStartMode.Automatic;
                ServiceInstallerObj.Parent      = ProcesServiceInstaller;

                System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();
                ServiceInstallerObj.Install(state);
                WriteLogFromInstallLog();
            }
            catch (Exception ex)
            {
                txtLog.Text = ex.StackTrace;
            }
        }
 private void UnInstallService()
 {
     try
     {
         ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
         File.Delete(Environment.CurrentDirectory + cInstallFileName);
         InstallContext Context = new System.Configuration.Install.InstallContext(Environment.CurrentDirectory + cInstallFileName, null);
         ServiceInstallerObj.Context     = Context;
         ServiceInstallerObj.ServiceName = ((DataRowView)(lstServices.SelectedItem)).Row["ServiceName"].ToString();
         ServiceInstallerObj.Uninstall(null);
         WriteLogFromInstallLog();
     }
     catch (Exception ex)
     {
         txtLog.Text = ex.StackTrace;
     }
 }
예제 #43
0
        // A transacted install will either completely succeed or fail and leave the
        // machine in its initial state. The Install method is called on each of the
        // installers. If they all succeed, then the Commit method is called on each
        // of them. If any of the Install methods fails, then that installer's Rollback
        // method is called, as are the Rollback methods on all the installers whose
        // Install methods ran before the failure.
        /// <include file='doc\TransactedInstaller.uex' path='docs/doc[@for="TransactedInstaller.Install"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public override void Install(IDictionary savedState)
        {
            if (Context == null)
            {
                Context = new InstallContext();
            }

            Context.LogMessage(Environment.NewLine + Res.GetString(Res.InstallInfoTransacted));
            try {
                bool success = true;
                try {
                    Context.LogMessage(Environment.NewLine + Res.GetString(Res.InstallInfoBeginInstall));
                    base.Install(savedState);
                }
                catch (Exception e) {
                    success = false;
                    Context.LogMessage(Environment.NewLine + Res.GetString(Res.InstallInfoException));
                    Installer.LogException(e, Context);

                    Context.LogMessage(Environment.NewLine + Res.GetString(Res.InstallInfoBeginRollback));
                    try {
                        Rollback(savedState);
                    }
                    catch (Exception) {
                    }
                    Context.LogMessage(Environment.NewLine + Res.GetString(Res.InstallInfoRollbackDone));

                    // make sure the failure goes all the way to the top.
                    throw new InvalidOperationException(Res.GetString(Res.InstallRollback), e);
                }
                if (success)
                {
                    Context.LogMessage(Environment.NewLine + Res.GetString(Res.InstallInfoBeginCommit));
                    try {
                        Commit(savedState);
                    }
                    finally {
                        Context.LogMessage(Environment.NewLine + Res.GetString(Res.InstallInfoCommitDone));
                    }
                }
            }
            finally {
                Context.LogMessage(Environment.NewLine + Res.GetString(Res.InstallInfoTransactedDone));
            }
        }
예제 #44
0
 public static void Install(string[] args)
 {
     string name = args.Length == 2 ? args[1] : DEFAULT_NAME;
     try {
         TransactedInstaller ti = new TransactedInstaller();
         WindowsServiceProjectInstaller pi = WindowsServiceProjectInstaller.Create(name);
         ti.Installers.Add(pi);
         string path = string.Format("/assemblypath={0}",
             System.Reflection.Assembly.GetExecutingAssembly().Location);
         string[] cmdline = { path };
         InstallContext ctx = new InstallContext("", cmdline);
         ti.Context = ctx;
         ti.Install(new Hashtable());
     } catch (Exception ex) {
         Console.WriteLine("ERROR: {0}", ex.Message);
         Environment.Exit(1);
     }
 }
예제 #45
0
        private static TransactedInstaller CreateTransactedInstaller(ServiceBeschreibung name, string logFilePath) {
            var serviceProcessInstaller = new ServiceProcessInstaller {
                Account = ServiceAccount.LocalSystem
            };

            var transactedInstaller = new TransactedInstaller();
            transactedInstaller.Installers.Add(serviceProcessInstaller);
            var path = string.Format("/assemblypath={0}", Assembly.GetEntryAssembly().Location);
            var installContext = new InstallContext(logFilePath, new[] {path});
            transactedInstaller.Context = installContext;

            var serviceInstaller = new ServiceInstaller {
                ServiceName = name.Name,
                DisplayName = name.DisplayName,
                Description = name.Description
            };
            transactedInstaller.Installers.Add(serviceInstaller);
            return transactedInstaller;
        }
예제 #46
0
 private static Installer CreateInstaller(string serviceName)
 {
     var installer = new TransactedInstaller();
     installer.Installers.Add(new ServiceInstaller
     {
         ServiceName = serviceName,
         DisplayName = serviceName,
         StartType = ServiceStartMode.Manual
     });
     installer.Installers.Add(new ServiceProcessInstaller
     {
         Account = ServiceAccount.LocalSystem
     });
     var installContext = new InstallContext(
         serviceName + ".install.log", null);
     installContext.Parameters["assemblypath"] =
         Assembly.GetEntryAssembly().Location;
     installer.Context = installContext;
     return installer;
 }
예제 #47
0
파일: Program.cs 프로젝트: Evolveum/openicf
 private static void DoInstall(IDictionary<string, string> options)
 {
     if (options.ContainsKey(OPT_SERVICE_NAME))
     {
         ProjectInstaller.ServiceName = options[OPT_SERVICE_NAME];
     }
     TransactedInstaller ti = new TransactedInstaller();
     string[] cmdline =
     {
         Assembly.GetExecutingAssembly ().Location
     };
     AssemblyInstaller ai = new AssemblyInstaller(
         cmdline[0],
         new string[0]);
     ti.Installers.Add(ai);
     InstallContext ctx = new InstallContext("install.log",
                                              cmdline);
     ti.Context = ctx;
     ti.Install(new System.Collections.Hashtable());
 }
예제 #48
0
파일: Service.cs 프로젝트: dannylloyd/Monty
        static void Main(string[] args)
        {
            string opt=null;
            if(args.Length >0 )
            {
                opt=args[0];
            }

            if(opt!=null && opt.ToLower()=="/install")
            {
                TransactedInstaller ti= new TransactedInstaller();
                MyInstaller pi = new MyInstaller();
                ti.Installers.Add(pi);
                String path=String.Format("/assemblypath={0}",
                    System.Reflection.Assembly.GetExecutingAssembly().Location);
                String[] cmdline={path};
                InstallContext ctx = new InstallContext("",cmdline);
                ti.Context =ctx;
                ti.Install(new Hashtable());
            }
            else if (opt !=null && opt.ToLower()=="/uninstall")
            {
                TransactedInstaller ti=new TransactedInstaller();
                MyInstaller mi=new MyInstaller();
                ti.Installers.Add(mi);
                String path = String.Format("/assemblypath={0}",
                    System.Reflection.Assembly.GetExecutingAssembly().Location);
                String[] cmdline={path};
                InstallContext ctx = new InstallContext("",cmdline);
                ti.Context=ctx;
                ti.Uninstall(null);

            }

            if(opt==null)  // e.g. ,nothing on the command line
            {
                System.ServiceProcess.ServiceBase[] ServicesToRun;
                ServicesToRun = new System.ServiceProcess.ServiceBase[] { new SiteMonitor() };
                System.ServiceProcess.ServiceBase.Run(ServicesToRun);
            }
        }
예제 #49
0
        internal static void LogException(Exception e, InstallContext context)
        {
            bool flag = true;

            for (; e != null; e = e.InnerException)
            {
                if (flag)
                {
                    context.LogMessage(e.GetType().FullName + ": " + e.Message);
                    flag = false;
                }
                else
                {
                    context.LogMessage(Res.GetString("InstallLogInner", (object)e.GetType().FullName, (object)e.Message));
                }
                if (context.IsParameterTrue("showcallstack"))
                {
                    context.LogMessage(e.StackTrace);
                }
            }
        }
예제 #50
0
        // Uninstall and return to a previously saved state.
        public override void Uninstall(IDictionary savedState)
        {
            // Make sure that we have a context.
            if (Context == null)
            {
                Context = new InstallContext("con", new String [0]);
            }

            // Log the start of the transaction.
            Context.LogLine(S._("Installer_BeginUninstallTransaction"));
            try
            {
                // Run the uninstallation process.
                base.Uninstall(savedState);
            }
            finally
            {
                Context.LogLine
                    (S._("Installer_EndUninstallTransaction"));
            }
        }
예제 #51
0
 // Initialize this object if necessary.
 private void Initialize()
 {
     if (info == null)
     {
         if (Context == null)
         {
             Context = new InstallContext(null, commandLine);
         }
         if (assembly != null)
         {
             info           = new AssemblyInfo();
             info.assembly  = assembly;
             info.installer = this;
             LoadInstallers(info);
         }
         else
         {
             LoadInstallerAssembly(assemblyPath, Context);
         }
     }
 }
        public static Installer CreateInstaller(string displayName, string serviceName, string description, string dependedon, string configFile)
        {
            var installer = new TransactedInstaller();

            var install = new ServiceInstaller(){
                DisplayName = displayName,
                ServiceName = serviceName,
                StartType = ServiceStartMode.Automatic,
                Description = description
            };

            installer.Installers.Add(install);

            installer.Installers.Add(new ServiceProcessInstaller
            {
                Account = ServiceAccount.LocalSystem
            });

            var installContext = new InstallContext(serviceName + ".install.log", null);

            string starterFullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CStarterD.exe");

            if (!string.IsNullOrEmpty(configFile))
            {
                installContext.Parameters["assemblypath"] = "\"" + starterFullPath + "\"" + " -c=" + configFile;
            }
            else
            {
                installContext.Parameters["assemblypath"] = "\"" + starterFullPath + "\"";
            }

            if(!string.IsNullOrEmpty(dependedon))
            {
                install.ServicesDependedOn = dependedon.Split(new char[] { ',' });
            }

            installer.Context = installContext;

            return installer;
        }
예제 #53
0
        /// <include file='doc\Installer.uex' path='docs/doc[@for="Installer.LogException"]/*' />
        /// <devdoc>
        /// Writes exception information for the given inner exception and any
        /// inner exceptions it may have to the given context object.
        /// </devdoc>
        internal static void LogException(Exception e, InstallContext context)
        {
            bool toplevel = true;

            while (e != null)
            {
                if (toplevel)
                {
                    context.LogMessage(e.GetType().FullName + ": " + e.Message);
                    toplevel = false;
                }
                else
                {
                    context.LogMessage(Res.GetString(Res.InstallLogInner, e.GetType().FullName, e.Message));
                }
                if (context.IsParameterTrue("showcallstack"))
                {
                    context.LogMessage(e.StackTrace);
                }
                e = e.InnerException;
            }
        }
        private void PrintStartText(string activity)
        {
            if (UseNewContext)
            {
                InstallContext newContext = CreateAssemblyContext();
                // give a warning in the main log file that we're switching over to the assembly-specific file
                if (Context != null)
                {
                    Context.LogMessage(Res.GetString(Res.InstallLogContent, Path));
                    Context.LogMessage(Res.GetString(Res.InstallFileLocation, newContext.Parameters["logfile"]));
                }
                Context = newContext;
            }

            // print out some info on the install
            Context.LogMessage(string.Format(System.Globalization.CultureInfo.InvariantCulture, activity, Path));
            Context.LogMessage(Res.GetString(Res.InstallLogParameters));
            if (Context.Parameters.Count == 0)
            {
                Context.LogMessage("   " + Res.GetString(Res.InstallLogNone));
            }
            IDictionaryEnumerator en = (IDictionaryEnumerator)Context.Parameters.GetEnumerator();

            while (en.MoveNext())
            {
                string key   = (string)en.Key;
                string value = (string)en.Value;

                // hide password parameters
                if (key.Equals("password", StringComparison.InvariantCultureIgnoreCase))
                {
                    value = "********";
                }

                Context.LogMessage("   " + key + " = " + value);
            }
        }
예제 #55
0
        } // end initialize method

        // add persistences
        public void addPersistence(string command, string commandArg, string theName)
        {
            Console.WriteLine("");
            Console.WriteLine("[*] INFO: Adding service persistence");
            Console.WriteLine("[*] INFO: Command: " + command);
            Console.WriteLine("[*] INFO: Command Args: " + commandArg);
            Console.WriteLine("[*] INFO: Service Name: " + theName);
            Console.WriteLine("");

            bool serviceExists = lib.Utils.ServiceExists(theName);

            // if service doesn't exist, then add it
            if (!serviceExists)
            {
                try
                {
                    ServiceProcessInstaller ProcessServiceInstaller = new ServiceProcessInstaller();
                    ProcessServiceInstaller.Account = ServiceAccount.User;

                    ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
                    InstallContext   Context             = new System.Configuration.Install.InstallContext();
                    String           path    = String.Format("/assemblypath={0}", command + " " + commandArg);
                    string[]         cmdline = { path };

                    Context = new InstallContext("", cmdline);

                    ServiceInstallerObj.DisplayName = theName;
                    ServiceInstallerObj.ServiceName = theName;
                    ServiceInstallerObj.Description = theName;
                    ServiceInstallerObj.StartType   = ServiceStartMode.Automatic;
                    ServiceInstallerObj.Parent      = ProcessServiceInstaller;
                    ServiceInstallerObj.Context     = Context;

                    System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();
                    ServiceInstallerObj.Install(state);
                }

                catch (Exception ex)
                {
                    Console.WriteLine("[-] ERROR: Admin privileges are needed to add a service. Please run as an admin user in high integrity.");
                    return;
                }

                // make sure service did get installed
                serviceExists = lib.Utils.ServiceExists(theName);
                if (serviceExists)
                {
                    Console.WriteLine("");
                    Console.WriteLine("[+] SUCCESS: Service persistence added");
                }
                else
                {
                    Console.WriteLine("");
                    Console.WriteLine("[-] ERROR: Service not added successfully");
                }
            } // end if service doesn't exist


            // if service does exist, display message
            else
            {
                Console.WriteLine("");
                Console.WriteLine("[-] ERROR: Service with that name already exists");
                return;
            }
        } // end add persistence
예제 #56
0
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>


        static void Main(string[] args)
        {
            if (System.Environment.UserInteractive)
            {
                string parameter = string.Concat(args);
                System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();
                ServiceController SCONTROL = new ServiceController();
                SCONTROL.ServiceName = "appController";
                switch (parameter)
                {
                // http://stackoverflow.com/questions/255056/install-a-net-windows-service-without-installutil-exe
                case "--install":
                    //ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                    ServiceProcessInstaller processInstaller = new ServiceProcessInstaller();
                    processInstaller.Account = ServiceAccount.LocalSystem;

                    System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext();
                    string processPath = Process.GetCurrentProcess().MainModule.FileName;
                    if (processPath != null && processPath.Length > 0)
                    {
                        System.IO.FileInfo fi = new System.IO.FileInfo(processPath);

                        String   path    = String.Format("/assemblypath={0}", fi.FullName);
                        String[] cmdline = { path };
                        Context = new System.Configuration.Install.InstallContext("", cmdline);
                    }


                    SINST.Context = Context;
                    //SINST.DisplayName = String.Format("{0} - {1}", "appController", InstanceID);
                    //SINST.Description = String.Format("{0} - {1}", "appController", InstanceID);
                    //SINST.ServiceName = String.Format("{0}_{1}", "appController", InstanceID);

                    SINST.ServiceName = "appController";
                    SINST.StartType   = ServiceStartMode.Automatic;
                    SINST.Parent      = processInstaller;

                    SINST.ServicesDependedOn = null;
                    System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();
                    SINST.Install(state);

                    //// http://www.dotnet247.com/247reference/msgs/43/219565.aspx
                    //using (RegistryKey oKey = Registry.LocalMachine.OpenSubKey(String.Format(@"SYSTEM\CurrentControlSet\Services\{0}_{1}", "", InstanceID), true))
                    //{
                    //    try
                    //    {
                    //        Object sValue = oKey.GetValue("ImagePath");
                    //        oKey.SetValue("ImagePath", sValue);
                    //    }
                    //    catch (Exception Ex)
                    //    {
                    //        MessageBox.Show(Ex.Message);
                    //    }
                    //}
                    break;

                case "--uninstall":
                    //ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                    //http://www.theblacksparrow.com/


                    SINST.Context = new System.Configuration.Install.InstallContext(
                        Environment.GetEnvironmentVariable("temp") + "\\install.log",
                        null);
                    //SINST.ServiceName = String.Format("{0}_{1}", ServiceName, InstanceID);
                    SINST.ServiceName = "appController";
                    SINST.Uninstall(null);
                    break;

                case "--start":
                    if (SCONTROL.Status == ServiceControllerStatus.Stopped)
                    {
                        SCONTROL.Start();
                    }
                    break;

                case "--stop":
                    if (SCONTROL.Status == ServiceControllerStatus.Running)
                    {
                        SCONTROL.Stop();
                    }
                    break;
                }
            }
            else
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new MyService()
                };
                ServiceBase.Run(ServicesToRun);
            }
        }
예제 #57
0
        // Run the installation process.
        private int Install()
        {
            // Scan the command-line options in groups.
            int    posn = 0;
            int    start;
            String arg;
            bool   both;

            uninstall = false;
            if (args.Length == 0)
            {
                Usage();
                return(1);
            }
            while (posn < args.Length)
            {
                // Extract the next group of options.
                start = posn;
                while (posn < args.Length)
                {
                    arg = args[posn];
                    if (arg.Length == 0)
                    {
                        break;
                    }
                    if (arg[0] == '-')
                    {
                        // Option that starts with "-".
                        ++posn;
                        if (arg.Length == 2 && arg[1] == '-')
                        {
                            // We use "--" to terminate the option
                            // list just prior to a filename that
                            // starts with "-" or "/".
                            break;
                        }
                    }
                    else if (arg[0] == '/')
                    {
                        // Compatibility option that starts with "/".
                        ++posn;
                    }
                    else if (arg[0] == '=')
                    {
                        // May be specifying a value for a previous option.
                        ++posn;
                    }
                    else if (posn > start && args[posn - 1].EndsWith("="))
                    {
                        // Specifying a value for a previous option name.
                        ++posn;
                    }
                    else
                    {
                        // This is a filename.
                        break;
                    }
                }

                // Parse the command line options that we just received.
                optionDict = InstallContext.ParseCommandLine
                                 (args, start, posn - start, out options);

                // Extract the filename.
                if (posn < args.Length)
                {
                    filename = args[posn++];
                }
                else
                {
                    filename = null;
                }

                // Create an install context for this option group.
                context = new InstallContext(optionDict);

                // Check for the "uninstall" and "install" flags.
                both = false;
                if (context.IsParameterTrue("uninstall") ||
                    context.IsParameterTrue("u"))
                {
                    uninstall = true;
                    both      = true;
                }
                if (context.IsParameterTrue("install") ||
                    context.IsParameterTrue("i"))
                {
                    if (both)
                    {
                                                #if !CONFIG_SMALL_CONSOLE
                        Console.Error.WriteLine
                            ("{0}: cannot specify both `--install' and " +
                            "`--uninstall'", program);
                                                #else
                        Console.WriteLine
                            ("{0}: cannot specify both `--install' and " +
                            "`--uninstall'", program);
                                                #endif
                        return(1);
                    }
                    uninstall = false;
                }

                // Check for the version flag.
                if (context.IsParameterTrue("version") ||
                    context.IsParameterTrue("v"))
                {
                    Version();
                    return(0);
                }

                // Check for the help flag.
                if (context.IsParameterTrue("help") ||
                    context.IsParameterTrue("h") ||
                    context.IsParameterTrue("?"))
                {
                    if (filename == null)
                    {
                        Usage();
                    }
                    else
                    {
                        PrintHelpFor(filename);
                    }
                    continue;
                }

                // If we don't have a filename, then print the usage.
                if (filename == null)
                {
                    Usage();
                    return(1);
                }

                // Run the installation/uninstallation process.
                if (uninstall)
                {
                    RunUninstall(filename);
                }
                else
                {
                    RunInstall(filename);
                }
            }
            return(0);
        }
예제 #58
0
        // Load an assembly by name and get the information object for it.
        internal static AssemblyInfo LoadInstallerAssembly
            (String filename, InstallContext logContext)
        {
            String       fullName;
            AssemblyInfo info;

            AssemblyInfo[] newAssemblies;
            int            index;

            lock (typeof(AssemblyInstaller))
            {
                try
                {
                    // See if we have a cached information block,
                    // from when we loaded the assembly previously.
                    fullName = IO.Path.GetFullPath(filename);
                    if (assemblies != null)
                    {
                        for (index = 0; index < assemblies.Length; ++index)
                        {
                            info = assemblies[index];
                            if (info.filename == fullName)
                            {
                                if (info.loadException == null)
                                {
                                    return(info);
                                }
                                throw info.loadException;
                            }
                        }
                        newAssemblies = new AssemblyInfo
                                        [assemblies.Length + 1];
                        Array.Copy(assemblies, 0, newAssemblies, 0,
                                   assemblies.Length);
                        info = new AssemblyInfo();
                        newAssemblies[assemblies.Length] = info;
                        assemblies = newAssemblies;
                    }
                    else
                    {
                        info       = new AssemblyInfo();
                        assemblies = new AssemblyInfo [] { info };
                    }

                    // Try to load the assembly into memory.
                    info.filename = fullName;
                    try
                    {
                        info.assembly = Assembly.LoadFrom(fullName);
                    }
                    catch (SystemException e)
                    {
                        info.loadException = e;
                        throw;
                    }

                    // Wrap the assembly in an installer.
                    info.installer = new AssemblyInstaller();
                    info.installer.assemblyPath = filename;
                    info.installer.info         = info;

                    // Search for all public installer types.
                    LoadInstallers(info);

                    // The assembly is ready to go.
                    return(info);
                }
                catch (SystemException e)
                {
                    if (logContext != null)
                    {
                        if (logContext.IsParameterTrue("ShowCallStack"))
                        {
                            logContext.LogLine
                                ("LoadAssembly: " + e.ToString());
                        }
                        else
                        {
                            logContext.LogLine
                                ("LoadAssembly: " + e.Message);
                        }
                    }
                    throw new InvalidOperationException
                              (String.Format
                                  (S._("Installer_CouldNotLoadAssembly"),
                                  filename), e);
                }
            }
        }
 public CommonForm(System.Configuration.Install.InstallContext context)
 {
     formContext = context;
     InitializeComponent();
     this.CenterToScreen();
 }