/// <summary> /// Install a windows service at runtime. /// </summary> /// <param name="windowsServiceSetup">Instance of WindowsServiceSetup.</param> public static void RuntimeInstall(WindowsServiceSetup windowsServiceSetup) { TransactedInstaller transactedInstaller = null; try { transactedInstaller = new TransactedInstaller(); transactedInstaller.Installers.Add(new WindowsServiceInstaller(windowsServiceSetup)); transactedInstaller.Context = new InstallContext(null, new[] { string.Format("/assemblypath=\"{0}\"", windowsServiceSetup.ServiceAssemblyPath) }); transactedInstaller.Install(new Hashtable()); } catch (Exception e) { InternalLogger.Log(e); } finally { if (transactedInstaller != null) { transactedInstaller.Dispose(); transactedInstaller = null; } } }
// The main entry point for the process static void Main(string[] args) { string opt = null; // check for arguments if (args.Length > 0) { opt = args[0]; if (opt != null && opt.ToLower() == "/install") { ParamsWin mForm = new ParamsWin(); if (mForm.ShowDialog() == DialogResult.Cancel) { return; } TransactedInstaller ti = new TransactedInstaller(); ProjectInstaller pi = new ProjectInstaller(); ti.Installers.Add(pi); String path = String.Format("/assemblypath={0}", Assembly.GetExecutingAssembly().Location); String[] cmdline = { path }; InstallContext ctx = new InstallContext("", cmdline); ti.Context = ctx; try { ServiceController mService = new ServiceController("OneAssistance"); if (mService.DisplayName != string.Empty) { if (mService.CanStop) { mService.Stop(); mService.WaitForStatus(ServiceControllerStatus.Stopped); } ti.Uninstall(null); } } catch (System.Exception) { } ti.Install(new Hashtable()); } else if (opt != null && opt.ToLower() == "/update") { try { ServiceController mService = new ServiceController("OneAssistance"); string n = mService.DisplayName; } catch (System.Exception e) { MessageBox.Show(e.Message, "OneAssistanceSrvc /update", MessageBoxButtons.OK); return; } ParamsWin mForm = new ParamsWin(); if (mForm.ShowDialog() == DialogResult.OK) { MessageBox.Show("Service params successfully updated!", "OneAssistance Service", MessageBoxButtons.OK); } } else if (opt != null && opt.ToLower() == "/uninstall") { TransactedInstaller ti = new TransactedInstaller(); ProjectInstaller mi = new ProjectInstaller(); ti.Installers.Add(mi); String path = String.Format("/assemblypath={0}", Assembly.GetExecutingAssembly().Location); String[] cmdline = { path }; InstallContext ctx = new InstallContext("", cmdline); ti.Context = ctx; try { ti.Uninstall(null); } catch (System.Exception) { } RegValues lRegValues = new RegValues(); lRegValues.clearRegValues(); } else if (opt != null && opt.ToLower() == "/version") { MessageBox.Show("Version: 1.0.0", "OneAssistance Service", MessageBoxButtons.OK); } } if (opt == null) // e.g. ,nothing on the command line { #if (!DEBUG) System.ServiceProcess.ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new DoCheckUp() }; ServiceBase.Run(ServicesToRun); #else // debug code: allows the process to run as a non-service // will kick off the service start point, but never kill it // shut down the debugger to exit DoIntegration service = new DoIntegration(); service.OnStart(null); Thread.Sleep(Timeout.Infinite); #endif } }
private void install() { var exePath = GetExePath(); try { if (_containNotInstall) //安装 { if (ShowConfirm("如果您之前执行过安装操作,请先使用原程序卸载服务再使用本程序执行安装操作!")) { using (TransactedInstaller transactedInstaller = new TransactedInstaller()) { var installLog = new Hashtable(); AssemblyInstaller assemblyInstaller = new AssemblyInstaller(exePath, null); transactedInstaller.Installers.Add(assemblyInstaller); transactedInstaller.Install(installLog); } //修改ImagePath foreach (var service in GetServicesFromMef()) { if (service is WindowsServiceBase) { ServiceHelper.ChangeExePath(service.ServiceName, $"\"{exePath}\" -Daemon {service.ServiceName}"); //添加启动参数 ((WindowsServiceUIViewModel)_serviceUIs[service.ServiceName]).ApplyCommand.Execute(); //设置启动模式 } } updateInstallButton(); logInfo("安装所有Windows服务成功"); } } else //卸载 { if (ShowConfirm("确定要卸载本控制台中的所有Windows服务吗?")) { using (TransactedInstaller transactedInstaller = new TransactedInstaller()) { AssemblyInstaller assemblyInstaller = new AssemblyInstaller(exePath, null); transactedInstaller.Installers.Add(assemblyInstaller); transactedInstaller.Uninstall(null); } updateInstallButton(); logInfo("卸载所有Windows服务成功"); } } } catch (Exception ex) { logError("操作失败:" + ex.Message, ex); if (ShowConfirm($"操作失败【{ex.Message}】,是否以管理员权限重启本程序以执行操作?")) { //退出 _niMain.ContextMenu.MenuItems[0].PerformClick(); //创建启动对象 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.UseShellExecute = true; startInfo.WorkingDirectory = Environment.CurrentDirectory; startInfo.FileName = exePath; //设置启动动作,确保以管理员身份运行 startInfo.Verb = "runas"; try { System.Diagnostics.Process.Start(startInfo); } catch { } } } }
static void Main(string[] pArgs) { AppDomain.CurrentDomain.UnhandledException += onUnhandledException; EventLog.WriteEntry("Application", "Application level Exception handler installed...", EventLogEntryType.Information, 1); var _assemblyName = Assembly.GetEntryAssembly().GetName().Name; var _location = Assembly.GetEntryAssembly().Location; var _replicationService = new ReplicationService(_assemblyName, _location); if (pArgs.Length == 0) { // no arguments, just run ServiceBase.Run(new ServiceBase[] { _replicationService }); return; } string _opt = pArgs[0]; try { if (_opt.ToLower() == "/install" || _opt.ToLower() == "/uninstall") { if (pArgs.Length != 2) { Console.WriteLine("Usage: appname /install (or /uninstall) version"); return; } //-- Create installers var _ti = new TransactedInstaller(); var _cmdLine = new[] { string.Format("/assemblypath={0}", Assembly.GetExecutingAssembly().Location) }; _ti.Context = new InstallContext(string.Empty, _cmdLine); _ti.Installers.Add(new ReplicationServiceInstaller(pArgs[1])); if (_opt.ToLower() == "/install") { _ti.Install(new Hashtable()); } else if (_opt.ToLower() == "/uninstall") { _ti.Uninstall(null); } } else if (_opt.ToLower() == "/console") { _replicationService.Start(null); Console.WriteLine("\r\nStarted... Press ENTER to stop."); Console.ReadLine(); Console.WriteLine("Stopping..."); _replicationService.Stop(); } else { Console.WriteLine("Error, Valid Arguments are: /console, /install or /uninstall. Press any ENTER to finish..."); } } catch (Exception _ex) { Console.WriteLine("Timok.Rbr, Exception in [" + _opt + "] mode: " + _ex); } }
internal static void installService() { ServiceInstaller serviceInstaller = null; ServiceProcessInstaller serviceProcessInstaller = null; Installer projectInstaller = null; TransactedInstaller transactedInstaller = null; try { serviceInstaller = new ServiceInstaller(); serviceInstaller.ServiceName = "OpenVPNManager"; serviceInstaller.StartType = ServiceStartMode.Automatic; serviceProcessInstaller = new ServiceProcessInstaller(); serviceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem; serviceProcessInstaller.Password = null; serviceProcessInstaller.Username = null; projectInstaller = new Installer(); projectInstaller.Installers.Add(serviceInstaller); projectInstaller.Installers.Add(serviceProcessInstaller); transactedInstaller = new TransactedInstaller(); transactedInstaller.Installers.Add(projectInstaller); transactedInstaller.Context = new InstallContext(); transactedInstaller.Context.Parameters["assemblypath"] = Assembly.GetExecutingAssembly().Location + "\" \"/EXECUTESERVICE"; transactedInstaller.Install(new Hashtable()); } catch (InvalidOperationException e) { if (e.InnerException != null && e.InnerException is Win32Exception)// Probably: "Service already exists." { MessageBox.Show("Error: " + e.InnerException.Message); } else if (e.InnerException != null && e.InnerException is InvalidOperationException && e.InnerException.InnerException != null && e.InnerException.InnerException is Win32Exception)// Probably: "Permission denied" { String MSG_ServiceInstallPermissionErrorAdvice = Program.res.GetString("MSG_ServiceInstallPermissionErrorAdvice"); MessageBox.Show("Error: " + e.InnerException.InnerException.Message + "\r\n\r\n" + MSG_ServiceInstallPermissionErrorAdvice); } else { throw; } } finally { if (serviceInstaller != null) { serviceInstaller.Dispose(); } if (serviceProcessInstaller != null) { serviceProcessInstaller.Dispose(); } if (projectInstaller != null) { projectInstaller.Dispose(); } if (transactedInstaller != null) { transactedInstaller.Dispose(); } } }
/// <summary> /// 应用程序的主入口点。 /// </summary> static void Main(string[] args) { //ServiceBase[] ServicesToRun; //ServicesToRun = new ServiceBase[] //{ // new Service1() //}; //ServiceBase.Run(ServicesToRun); #region 务直接运行 if (args.Length == 0) { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new DemoService() }; ServiceBase.Run(ServicesToRun); } #endregion #region 调试启动 else if (args[0].ToLower() == "/d" || args[0].ToLower() == "-d") { DemoMain.Start(); while (true) { System.Threading.Thread.Sleep(1000); } } #endregion #region 安装服务 else if (args[0].ToLower() == "/i" || args[0].ToLower() == "-i") { try { string[] cmdline = { }; string serviceFileName = System.Reflection.Assembly.GetExecutingAssembly().Location; TransactedInstaller transactedInstaller = new TransactedInstaller(); AssemblyInstaller assemblyInstaller = new AssemblyInstaller(serviceFileName, cmdline); transactedInstaller.Installers.Add(assemblyInstaller); transactedInstaller.Install(new System.Collections.Hashtable()); } catch (Exception ex) { string msg = ex.Message; } } #endregion #region 除服务 else if (args[0].ToLower() == "/u" || args[0].ToLower() == "-u") { try { string[] cmdline = { }; string serviceFileName = System.Reflection.Assembly.GetExecutingAssembly().Location; TransactedInstaller transactedInstaller = new TransactedInstaller(); AssemblyInstaller assemblyInstaller = new AssemblyInstaller(serviceFileName, cmdline); transactedInstaller.Installers.Add(assemblyInstaller); transactedInstaller.Uninstall(null); } catch (Exception ex) { string msg = ex.Message; } } #endregion }
/// <summary> /// The main entry point for the process /// options: /// - Install /// 1. /install /// 2. /i /// - Uninstall /// 1. /uninstall /// 2. /u /// </summary> /// <param name="args">The args. A <see cref="T:System.String[]"/> Object.</param> public static void Main(string[] args) { #region Access Log #if TRACE { COM.Handler.LogHandler.Tracking("Access Method: " + typeof(Indexus).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;"); } #endif #endregion Access Log string optionalArgs = string.Empty; if (args.Length > 0) { optionalArgs = args[0]; } #region args Handling if (!string.IsNullOrEmpty(optionalArgs)) { if ("/?".Equals(optionalArgs.ToLower())) { Console.WriteLine("Help Menu"); Console.ReadLine(); return; } else if ("/local".Equals(optionalArgs.ToLower())) { Console.Title = "Shared Cache - Server"; Console.BackgroundColor = ConsoleColor.DarkBlue; Console.ForegroundColor = ConsoleColor.White; // running as cmd appliacation Indexus SrvIndexus = new Indexus(); SrvIndexus.StartService(); Console.ReadLine(); SrvIndexus.StopService(); return; } else if (@"/verbose".Equals(optionalArgs.ToLower())) { // Console.SetOut(this); // Console.SetIn(Console.Out); // Console.ReadLine(); return; } TransactedInstaller ti = new TransactedInstaller(); IndexusInstaller ii = new IndexusInstaller(); ti.Installers.Add(ii); string path = string.Format("/assemblypath={0}", System.Reflection.Assembly.GetExecutingAssembly().Location); string[] cmd = { path }; InstallContext context = new InstallContext(string.Empty, cmd); ti.Context = context; if ("/install".Equals(optionalArgs.ToLower()) || "/i".Equals(optionalArgs.ToLower())) { ti.Install(new Hashtable()); } else if ("/uninstall".Equals(optionalArgs.ToLower()) || "/u".Equals(optionalArgs.ToLower())) { ti.Uninstall(null); } else { StringBuilder sb = new StringBuilder(); sb.Append(@"Your provided Argument is not available." + Environment.NewLine); sb.Append(@"Use one of the following once:" + Environment.NewLine); sb.AppendFormat(@"To Install the service '{0}': '/install' or '/i'" + Environment.NewLine, @"IndeXus.Net"); sb.AppendFormat(@"To Un-Install the service'{0}': '/uninstall' or '/u'" + Environment.NewLine, @"IndeXus.Net"); Console.WriteLine(sb.ToString()); } } else { // nothing received as input argument ServiceBase[] servicesToRun; servicesToRun = new ServiceBase[] { new Indexus() }; ServiceBase.Run(servicesToRun); } #endregion args Handling }
private void DoSetup() { try { //停止服务 ServiceController sc; bool isInstalled = false; try { ServiceController[] services = ServiceController.GetServices(); sc = services.FirstOrDefault(s => s.ServiceName == SERVICE_NAME); if (sc != null) { //如果服务已经安装,则停止服务 isInstalled = true; if (sc.Status != ServiceControllerStatus.Stopped) { AppendMessage(string.Format("Stopping service...")); sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 60)); } KillProcess(PROCESS_NAME); } } catch (Exception ex) { AppendMessage(string.Format("Stop service failed.\t{0}", ex.Message)); } //判断数据文件是否存在 var rsUMPData = App.GetResourceStream(new Uri("/UMPClientPackageSetup;component/Resources/UMPClientData.zip", UriKind.RelativeOrAbsolute)); if (rsUMPData == null) { AppendMessage(string.Format("UMPClientData not exist.")); return; } var stream = rsUMPData.Stream; if (stream == null) { AppendMessage(string.Format("UMPClientData not exist.")); return; } //拷贝证书及设置文件到UMPClient目录 string strUserClientDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "UMP.Client"); if (!Directory.Exists(strUserClientDir)) { AppendMessage(string.Format("UserClientDir not exist.\t{0}", strUserClientDir)); return; } string strClientDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "UMP\\UMPClient"); if (!Directory.Exists(strClientDir)) { Directory.CreateDirectory(strClientDir); } try { DirectoryInfo dirInfo = new DirectoryInfo(strUserClientDir); FileInfo[] files = dirInfo.GetFiles(); for (int i = 0; i < files.Length; i++) { FileInfo file = files[i]; if (file.Name.ToLower() == "ump.setted.xml" || file.Extension.ToLower() == ".pfx") { string strTarget = Path.Combine(strClientDir, file.Name); try { File.Copy(file.FullName, strTarget, true); AppendMessage(string.Format("Copy file end.\t{0}\t{1}", file.FullName, strTarget)); } catch (Exception ex) { AppendMessage(string.Format("Copy file fail.\t{0}", ex.Message)); } } } AppendMessage(string.Format("Copy file end")); } catch (Exception ex) { AppendMessage(string.Format("Copy files fail.\t{0}", ex.Message)); return; } string strClientPackage = Path.Combine(strClientDir, "UMPClientPackage"); if (!Directory.Exists(strClientPackage)) { Directory.CreateDirectory(strClientPackage); } //解压文件 AppendMessage(string.Format("Extracting files...")); using (var zipStream = new ZipInputStream(stream)) { ZipEntry theEntry; while ((theEntry = zipStream.GetNextEntry()) != null) { string dirName = strClientPackage; string pathToZip = theEntry.Name; if (!string.IsNullOrEmpty(pathToZip)) { dirName = Path.GetDirectoryName(Path.Combine(dirName, pathToZip)); } DateTime datetime = theEntry.DateTime; if (string.IsNullOrEmpty(dirName)) { continue; } string fileName = Path.GetFileName(pathToZip); Directory.CreateDirectory(dirName); if (!string.IsNullOrEmpty(fileName)) { string filePath = Path.Combine(dirName, fileName); AppendMessage(string.Format("Extracting file {0}", fileName)); using (FileStream streamWriter = File.Create(filePath)) { int size; byte[] data = new byte[2048]; while (true) { size = zipStream.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); //还原文件的修改时间 FileInfo fileInfo = new FileInfo(filePath); fileInfo.LastWriteTime = datetime; } } } } AppendMessage(string.Format("Extract files end.")); //如果服务未安装,先安装服务 if (!isInstalled) { string strServiceFile = Path.Combine(strClientPackage, "UMPClientPackage.exe"); if (!File.Exists(strServiceFile)) { AppendMessage(string.Format("UMPClientPackage.exe not exist.\t{0}", strServiceFile)); return; } string[] options = { }; try { AppendMessage(string.Format("Installing service...")); TransactedInstaller transacted = new TransactedInstaller(); AssemblyInstaller installer = new AssemblyInstaller(strServiceFile, options); transacted.Installers.Add(installer); transacted.Install(new Hashtable()); isInstalled = true; AppendMessage(string.Format("Service installed")); } catch (Exception ex) { AppendMessage(string.Format("InstallService fail.\t{0}", ex.Message)); } } //启动服务 if (!isInstalled) { AppendMessage(string.Format("Service not installed.")); return; } try { AppendMessage(string.Format("Starting service...")); sc = new ServiceController(SERVICE_NAME); sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 60)); AppendMessage(string.Format("Service started.")); } catch (Exception ex) { AppendMessage(string.Format("StartService fail.\t{0}", ex.Message)); return; } AppendMessage(string.Format("Setup end")); Thread.Sleep(1000); mIsSetuped = true; } catch (Exception ex) { AppendMessage(ex.Message); } }
public static int Main(string[] a) { Arguments args = new Arguments(a); if (!string.IsNullOrEmpty(args["?"]) || !string.IsNullOrEmpty(args["help"])) { Usage(); return(0); } //if(a.Length == 0) //{ // Application.EnableVisualStyles(); // Application.SetCompatibleTextRenderingDefault(false); // Application.Run(new MainForm()); // return 0; //} if (!string.IsNullOrEmpty(args[Constants.PARAM_CPU])) { if (float.TryParse(args[Constants.PARAM_CPU], out ServiceInfo.CpuUsageLimit)) { if (ServiceInfo.CpuUsageLimit < 5 || ServiceInfo.CpuUsageLimit > 90) { Console.Write("The CPU uages limit should be between 5 and 90"); return(-1); } } } #region Service installation bool install = !string.IsNullOrEmpty(args[Constants.PARAM_INSTALL]), uninstall = !string.IsNullOrEmpty(args[Constants.PARAM_UNINSTALL]); if (install || uninstall) { if (string.IsNullOrEmpty(args[Constants.PARAM_NAME])) { Console.WriteLine("Service Name is not supplied to install/uninstall the windows Service"); return(-1); } ServiceInfo.ServiceName = args[Constants.PARAM_NAME]; if (install && string.IsNullOrEmpty(args[Constants.PARAM_PATH])) { Console.WriteLine("Path was not supplied to install the windows Service"); return(-1); } ServiceInfo.Directory = args[Constants.PARAM_PATH]; if (install && string.IsNullOrEmpty(args[Constants.PARAM_APPCONFIG])) { Console.WriteLine("Application config path was not supplied"); return(-1); } ServiceInfo.ConfigFilePath = args[Constants.PARAM_APPCONFIG]; TransactedInstaller installer = new TransactedInstaller(); Assembly asm = Assembly.GetExecutingAssembly(); installer.Context = new InstallContext("WinSvc.log", a); AssemblyInstaller assemInstaller = new AssemblyInstaller(Assembly.GetExecutingAssembly(), a); Hashtable hash = new Hashtable(); ServiceProcessInstaller spi; ServiceInstaller si; installer.Installers.Add(assemInstaller); //Supress the output of the installation if (string.IsNullOrEmpty(args[Constants.PARAM_SUPRESS])) { Console.SetOut(TextWriter.Null); } try { if (install) { string assemblyPath; if (ServiceInfo.CpuUsageLimit > 0) { assemblyPath = string.Format("\"{0}\" -s -p=\"{1}\" -c=\"{2}\" -n=\"{3}\" -cpu=\"{4}\" ", asm.Location, Path.GetFullPath(ServiceInfo.Directory), Path.GetFullPath(ServiceInfo.ConfigFilePath), ServiceInfo.ServiceName, ServiceInfo.CpuUsageLimit); } else { assemblyPath = string.Format("\"{0}\" -s -p=\"{1}\" -c=\"{2}\" -n=\"{3}\" ", asm.Location, Path.GetFullPath(ServiceInfo.Directory), Path.GetFullPath(ServiceInfo.ConfigFilePath), ServiceInfo.ServiceName); } string account = args[Constants.PARAM_SERVICEACCOUNT]; if (string.IsNullOrEmpty(account)) { ServiceInfo.Account = ServiceAccount.NetworkService; } else { ServiceInfo.User = args[Constants.PARAM_USER]; switch (account.ToLower()) { case "networkservice": ServiceInfo.Account = ServiceAccount.NetworkService; break; case "localsystem": ServiceInfo.Account = ServiceAccount.LocalSystem; break; case "localservice": ServiceInfo.Account = ServiceAccount.LocalService; break; case "user": ServiceInfo.Account = ServiceAccount.User; if (string.IsNullOrEmpty(ServiceInfo.User)) { ServiceInfo.User = Thread.CurrentPrincipal.Identity.Name; } break; default: Console.WriteLine(); Console.WriteLine("Invalid account for the service."); Console.WriteLine("Account can be either of LocalSystem/LocalService" + "/NetworkService/User"); return(-1); } } string startType = args[Constants.PARAM_START_TYPE]; if (string.IsNullOrEmpty(startType)) { ServiceInfo.StartType = ServiceStartMode.Automatic; } else { switch (startType.ToLower()) { case "automatic": ServiceInfo.StartType = ServiceStartMode.Automatic; break; case "manual": ServiceInfo.StartType = ServiceStartMode.Manual; break; case "disable": ServiceInfo.StartType = ServiceStartMode.Disabled; break; default: Console.WriteLine(); Console.WriteLine("Invalid Service start mode"); Console.WriteLine("Service start mode can be either of Automatic/Manual/Disabled"); return(-1); } } assemInstaller.BeforeInstall += delegate(object sender, InstallEventArgs e) { spi = (ServiceProcessInstaller)assemInstaller.Installers[0] .Installers[0]; si = (ServiceInstaller)assemInstaller.Installers[0].Installers[1]; spi.Account = ServiceInfo.Account; spi.Username = ServiceInfo.User; si.Description = string.Format("{0} is a .NET Shell Windows Service " + "to run any service implemented using " + "XecMe.Core.IService", ServiceInfo.ServiceName); si.DisplayName = ServiceInfo.ServiceName; si.ServiceName = ServiceInfo.ServiceName; si.StartType = ServiceInfo.StartType; }; installer.Install(hash); //Registry Path HKEY_LOCAL_MACHINE-> SYSTEM-> CONTROLSET*-> SERVICES -><NAME OF SERVICE> Registry.SetValue(string.Format(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\{0}\", ServiceInfo.ServiceName), "ImagePath", assemblyPath, RegistryValueKind.String); if (ServiceInfo.CpuUsageLimit > 0) { //This is required to support the Process name for the PerformanceCounters //Registry Path HKEY_LOCAL_MACHINE-> SYSTEM-> CONTROLSET*-> SERVICES-> PerfProc-> Performance Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance", "ProcessNameFormat", 2, RegistryValueKind.DWord); } EventLog.WriteEntry(ServiceInfo.ServiceName, "Service installed successfully.", EventLogEntryType.Information); } else { installer.Uninstall(null); EventLog.WriteEntry(ServiceInfo.ServiceName, "Service uninstalled successfully.", EventLogEntryType.Information); } } catch (Exception e) { EventLog.WriteEntry(ServiceInfo.ServiceName, string.Concat("Error while installing/uninstalling ", ServiceInfo.ServiceName, e), EventLogEntryType.Error); } return(0); } #endregion Service installation ServiceInfo.Directory = args[Constants.PARAM_PATH]; if (string.IsNullOrEmpty(ServiceInfo.Directory) || !Directory.Exists(ServiceInfo.Directory)) { Console.WriteLine("Path was not supplied or does not exist for executing windows Service"); return(-1); } ServiceInfo.ConfigFilePath = args[Constants.PARAM_APPCONFIG]; if (string.IsNullOrEmpty(ServiceInfo.ConfigFilePath) || !File.Exists(ServiceInfo.ConfigFilePath)) { Console.WriteLine("Config path was not supplied or does not exist for executing windows Service"); return(-1); } if (string.IsNullOrEmpty(args[Constants.PARAM_NAME])) { Console.WriteLine("Batch/Service Name was not supplied"); return(-1); } ServiceInfo.ServiceName = args[Constants.PARAM_NAME]; if (!string.IsNullOrEmpty(args[Constants.PARAM_TIMEOUT])) { int.TryParse(args[Constants.PARAM_TIMEOUT], out ServiceInfo.Timeout); } if (ServiceInfo.CpuUsageLimit >= 5 && ServiceInfo.CpuUsageLimit <= 90) { CpuUsageLimiter.Limit = ServiceInfo.CpuUsageLimit; CpuUsageLimiter.Start(); } if (string.IsNullOrEmpty(args[Constants.PARAM_SERVICE])) { RunBatchProcess(a); return(0); } else { RunAsService(); return(0); } }
private void DoInstall(string serviceName, string displayName, string description) { _logger.LogInformation("Install: Preparing"); var isMissingParam = false; if (string.IsNullOrWhiteSpace(serviceName)) { _logger.LogWarning("Missing parameter : [/serviceName <value>]"); isMissingParam = true; } if (string.IsNullOrWhiteSpace(displayName)) { _logger.LogWarning("Missing parameter : [/displayName <value>]"); isMissingParam = true; } if (string.IsNullOrWhiteSpace(description)) { _logger.LogWarning("Missing parameter : [/description <value>]"); isMissingParam = true; } if (isMissingParam) { _logger.LogError("Install : Aborting due to missing parameters"); return; } var exeName = Process.GetCurrentProcess().MainModule.FileName; _logger.LogInformation($"Install: Parameters [serviceName:{serviceName}] [displayName:{displayName}] [description:{description}] [path:{exeName}]"); var installer = new TransactedInstaller(); var pi = new ServiceInstaller(displayName, serviceName, description); installer.Installers.Add(pi); var path = $"/assemblypath={exeName}"; var context = new InstallContext("install.log", new[] { path }); context.LogMessage("Using path " + path); installer.Context = context; var state = new Hashtable(); try { installer.Install(state); } catch (Exception e) { _logger.LogExceptionEx(e, e.Message, ("serviceName", serviceName)); } _logger.LogInformation("Install : Done"); }
static void Main(String[] args) { try { if (args.Length == 0) { //no args, just run the service ServiceBase.Run(new SvrBase()); } else { //we're installing or uninstalling ArrayList options = new ArrayList(); Boolean toConsole = false; Boolean toUnInstall = false; Boolean toInstall = false; Boolean toPrintHelp = false; TransactedInstaller myTransactedInstaller = new TransactedInstaller(); String myOption; AssemblyInstaller myAssemblyInstaller; InstallContext myInstallContext; try { for (int i = 0; i < args.Length; i++) { String argument = args[i].Trim(); // Process the arguments. if (argument.StartsWith("/") || argument.StartsWith("-")) { myOption = argument.Substring(1); //if they want to run in console mode, pass in the /c if (String.Compare(myOption, "c", true) == 0) { toConsole = true; break; } //check for instance name if (myOption.StartsWith("n=") && myOption.Trim().Length > 2) { options.Add(myOption); continue; } // Determine whether the option is to 'install' an assembly. if ((String.Compare(myOption, "i", true) == 0) || (String.Compare(myOption, "install", true) == 0)) { toInstall = true; options.Add(myOption); continue; } // Determine whether the option is to 'uninstall' an assembly. if ((String.Compare(myOption, "u", true) == 0) || (String.Compare(myOption, "uninstall", true) == 0)) { toUnInstall = true; options.Add(myOption); continue; } // Determine whether the option is for printing help information. if ((String.Compare(myOption, "?", true) == 0) || (String.Compare(myOption, "help", true) == 0)) { toPrintHelp = true; break; } // Add the option encountered to the list of all options encountered for the current assembly. // if instance=val or i=val was included in the cmdline, it'll go through in this } } //**************************************************************************** //**************************************************************************** //**************************************************************************** //**************************************************************************** //**************************************************************************** //**************************************************************************** //**************************************************************************** //**************************************************************************** //**************************************************************************** //**************************************************************************** //GO CONSOLE MODE BABY!!! - call the 2 methods defined at the top if (toConsole) { ConsoleModeStart(); Console.WriteLine("Press enter key to quit"); Console.ReadLine(); ConsoleModeStop(); Console.WriteLine("Application Terminated"); return; } // IF THE above statement is true, the rest of this will never happen // If user requested help or didn't provide any assemblies to install then print help message. if (toPrintHelp) { PrintHelpMessage(); return; } // Create an instance of 'AssemblyInstaller' that installs the given assembly. String[] parameters = (String[])options.ToArray(typeof(string)); myAssemblyInstaller = new AssemblyInstaller(_executableName, parameters); // Add the instance of 'AssemblyInstaller' to the 'TransactedInstaller'. myTransactedInstaller.Installers.Add(myAssemblyInstaller); // Create an instance of 'InstallContext' with the options specified. myInstallContext = new InstallContext("Install.log", parameters); myTransactedInstaller.Context = myInstallContext; // Install or Uninstall an assembly depending on the option provided. if ((toInstall && toUnInstall)) { Console.WriteLine(" CANNOT DO BOTH INSTALL AND UNINSTALL."); } else { if (toInstall) { myTransactedInstaller.Install(new Hashtable()); } if (toUnInstall) { myTransactedInstaller.Uninstall(null); } } } catch (Exception e) { Log.WriteLine(" Exception raised : {0}", e.Message); } } } catch (Exception e) { Log.WriteLine(" Exception raised : {0}", e.Message); } }
static void Main(string[] args) { // Interop.CoInitializeSecurity(IntPtr.Zero, -1, null, IntPtr.Zero, Interop.RPC_C_AUTHN_LEVEL_NONE, Interop.RPC_C_IMP_LEVEL_IDENTIFY, IntPtr.Zero, Interop.EOAC_NONE, IntPtr.Zero); long hres; try { hres = Interop.CoInitializeSecurity(IntPtr.Zero, -1, IntPtr.Zero, IntPtr.Zero, (uint)RpcAuthnLevel.None, (uint)RpcImpLevel.Identify, IntPtr.Zero, (uint)EoAuthnCap.None, IntPtr.Zero); } catch (COMException e) { Logger.LogMessage("CoInitializeSecurity Execption: " + e.Message, Logger.FATAL); } bool restartLogAppend = false; string opt = null; int dwResetPeriod = 60 * 60; // Debugger.Break(); try { ProjectInstaller.sServiceName = ConfigurationManager.AppSettings["ServiceName"]; ProjectInstaller.dwResetPeriod = Convert.ToInt32(ConfigurationManager.AppSettings["ResetPeriod"]); ProjectInstaller.sServiceUser = ConfigurationManager.AppSettings["ServiceUser"]; ProjectInstaller.sServicePassword = ConfigurationManager.AppSettings["ServicePassword"]; restartLogAppend = Convert.ToBoolean(ConfigurationManager.AppSettings["RestartLogAppend"]); } catch (Exception) { dwResetPeriod = 60 * 60; } Logger.RestartLog(restartLogAppend); string version = Misc.VersionNumber(); Logger.LogMessage("MTConnect 4 OPC Agent OPC Version 2.0 - Release " + version, Logger.FATAL); if (args.Length > 0) { // check for arguments opt = args[0]; ProjectInstaller.dwResetPeriod = dwResetPeriod; try { if (opt != null && opt.ToLower() == "/install") { TransactedInstaller ti = new TransactedInstaller(); ProjectInstaller pi = new ProjectInstaller(); ti.Installers.Add(pi); String path = String.Format("/assemblypath={0}", 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(); ProjectInstaller mi = new ProjectInstaller(); ti.Installers.Add(mi); String path = String.Format("/assemblypath={0}", Assembly.GetExecutingAssembly().Location); String[] cmdline = { path }; InstallContext ctx = new InstallContext("", cmdline); ti.Context = ctx; ti.Uninstall(null); } } catch (Exception e) { Logger.LogMessage(e.Message, Logger.FATAL); } } if (opt == null) // e.g. ,nothing on the command line { #if (!DEBUG) ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); #else // debug code: allows the process to run as a non-service // will kick off the service start point, but never kill it // shut down the debugger to exit Service1 service = new Service1(); service.OnStart(null); Thread.Sleep(Timeout.Infinite); #endif } }
private void bInstall_Click(object sender, EventArgs e) { try { if (containNotInstall) //安装 { if (ShowConfirm("如果您之前执行过安装操作,请先使用原程序卸载服务再使用本程序执行安装操作!")) { using (TransactedInstaller transactedInstaller = new TransactedInstaller()) { var installLog = new Hashtable(); AssemblyInstaller assemblyInstaller = new AssemblyInstaller(Application.ExecutablePath, null); transactedInstaller.Installers.Add(assemblyInstaller); transactedInstaller.Install(installLog); } //修改ImagePath foreach (var service in GetServicesFromMef()) { if (service is WindowsServiceBase) { bool delayedAutoStart; ServiceInfo serviceInfo = ServiceHelper.QueryServiceConfig(service.ServiceName, out delayedAutoStart); ServiceHelper.ChangeExePath(service.ServiceName, $"{serviceInfo.binaryPathName} -Daemon {service.ServiceName}"); } } updateInstallButton(); logInfo("安装所有Windows服务成功"); } } else //卸载 { if (ShowConfirm("确定要卸载本控制台中的所有Windows服务吗?")) { using (TransactedInstaller transactedInstaller = new TransactedInstaller()) { AssemblyInstaller assemblyInstaller = new AssemblyInstaller(Application.ExecutablePath, null); transactedInstaller.Installers.Add(assemblyInstaller); transactedInstaller.Uninstall(null); } updateInstallButton(); logInfo("卸载所有Windows服务成功"); } } } catch (Exception ex) { logError("操作失败:" + ex.Message, ex); if (ShowConfirm($"操作失败【{ex.Message}】,是否以管理员权限重启本程序以执行操作?")) { //退出 tsmiExit.PerformClick(); //创建启动对象 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.UseShellExecute = true; startInfo.WorkingDirectory = Environment.CurrentDirectory; startInfo.FileName = Application.ExecutablePath; //设置启动动作,确保以管理员身份运行 startInfo.Verb = "runas"; try { System.Diagnostics.Process.Start(startInfo); } catch { } } } }
private static void InstallService() { using (TransactedInstaller transactedInstaller = CreateTransactedInstaller()) transactedInstaller.Install(new Hashtable()); }
/// <summary> /// Installs the service(s) in the specified assembly. /// </summary> /// <param name="path"> /// A string containing the path to the service assembly. /// </param> /// <param name="startMode"> /// An enumeration that describes how and when this service is started. /// </param> /// <param name="account"> /// An enumeration that describes the type of account under which the service will run. /// </param> /// <param name="credentials"> /// The user credentials of the account under which the service will run. /// </param> /// <param name="parameters"> /// A dictionary of parameters passed to the service's installer. /// </param> public static void InstallService(string path, ServiceStartMode startMode, ServiceAccount account, NetworkCredential credentials, StringDictionary parameters) { if (string.IsNullOrEmpty(path)) { throw new ArgumentException("The specified path parameter is invalid."); } string filename = Path.GetFileNameWithoutExtension(path); try { // Initialize the service installer Assembly serviceAssembly = Assembly.LoadFrom(path); var serviceInstaller = new AssemblyInstaller(serviceAssembly, null); var commandLine = new ArrayList { string.Format("StartMode={0}", startMode.ToString("g")) }; // Set the service start mode // Set the service account switch (account) { case ServiceAccount.LocalService: case ServiceAccount.NetworkService: case ServiceAccount.LocalSystem: { commandLine.Add(string.Format("Account={0}", account.ToString("g"))); break; } case ServiceAccount.User: { commandLine.Add(string.Format("Account={0}", CredentialHelper.GetFullyQualifiedName(credentials))); commandLine.Add(string.Format("Password={0}", credentials.Password)); break; } } // Set any parameters if (parameters != null) { foreach (string key in parameters.Keys) { commandLine.Add(string.Format("{0}={1}", key, parameters[key])); } } // Initialize the service installer serviceInstaller.CommandLine = ( string[] )commandLine.ToArray(typeof(string)); // Initialize the base installer var transactedInstaller = new TransactedInstaller( ); transactedInstaller.Installers.Add(serviceInstaller); transactedInstaller.Context = new InstallContext(string.Format("{0}.log", filename), ( string[] )commandLine.ToArray(typeof(string))); // Install the service var savedState = new Hashtable( ); transactedInstaller.Install(savedState); } catch (Exception exception) { throw new Exception("Unable to install the specified service.", exception); } }
private static void Main(string[] args) { if (ProcessHelper.IsProcessAlreadyRunning()) { return; } Thread.CurrentThread.Name = "Main Thread"; IrssLog.Open("IR Server.log"); try { if (args.Length == 0) { IRServer = new IRServer(); if (IRServer.DoStart()) { SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(OnPowerModeChanged); ReceiverWindow receiverWindow = new ReceiverWindow(Shared.ServerWindowName); Application.Run(); SystemEvents.PowerModeChanged -= new PowerModeChangedEventHandler(OnPowerModeChanged); receiverWindow.DestroyHandle(); receiverWindow = null; IRServer.DoStop(); } } else { foreach (string parameter in args) { switch (parameter.ToUpperInvariant().Replace("-", "/")) { case "/INSTALL": IrssLog.Info("Installing IR Server ..."); using (TransactedInstaller transactedInstaller = new TransactedInstaller()) { using (IRServerInstaller IRServerInstaller = new IRServerInstaller()) { transactedInstaller.Installers.Add(IRServerInstaller); string path = "/assemblypath=" + Assembly.GetExecutingAssembly().Location; string[] cmdline = { path }; InstallContext installContext = new InstallContext(String.Empty, cmdline); transactedInstaller.Context = installContext; transactedInstaller.Install(new Hashtable()); } } break; case "/UNINSTALL": IrssLog.Info("Uninstalling IR Server ..."); using (TransactedInstaller transactedInstaller = new TransactedInstaller()) { using (IRServerInstaller IRServerInstaller = new IRServerInstaller()) { transactedInstaller.Installers.Add(IRServerInstaller); string path = "/assemblypath=" + Assembly.GetExecutingAssembly().Location; string[] cmdline = { path }; InstallContext installContext = new InstallContext(String.Empty, cmdline); transactedInstaller.Context = installContext; transactedInstaller.Uninstall(null); } } break; case "/START": IrssLog.Info("Starting IR Server ..."); using (ServiceController serviceController = new ServiceController(Shared.ServerName)) if (serviceController.Status == ServiceControllerStatus.Stopped) { serviceController.Start(); } break; case "/STOP": IrssLog.Info("Stopping IR Server ..."); using (ServiceController serviceController = new ServiceController(Shared.ServerName)) if (serviceController.Status == ServiceControllerStatus.Running) { serviceController.Stop(); } break; case "/RESTART": IrssLog.Info("Restarting IR Server ..."); using (ServiceController serviceController = new ServiceController(Shared.ServerName)) { if (serviceController.Status == ServiceControllerStatus.Running) { serviceController.Stop(); } serviceController.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30)); if (serviceController.Status == ServiceControllerStatus.Stopped) { serviceController.Start(); } } break; case "/SERVICE": { IRServer IRServer = new IRServer(); ServiceBase.Run(IRServer); } break; default: throw new InvalidOperationException(String.Format("Unknown command line parameter \"{0}\"", parameter)); } } IrssLog.Info("Done."); } } catch (Exception ex) { IrssLog.Error(ex); } finally { IrssLog.Close(); } }
public static void Install(string[] args) { bool flag = false; bool flag2 = false; TransactedInstaller installerWithHelp = new TransactedInstaller(); bool flag3 = false; try { ArrayList list = new ArrayList(); for (int i = 0; i < args.Length; i++) { if (args[i].StartsWith("/", StringComparison.Ordinal) || args[i].StartsWith("-", StringComparison.Ordinal)) { string strA = args[i].Substring(1); if ((string.Compare(strA, "u", StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare(strA, "uninstall", StringComparison.OrdinalIgnoreCase) == 0)) { flag = true; } else if ((string.Compare(strA, "?", StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare(strA, "help", StringComparison.OrdinalIgnoreCase) == 0)) { flag3 = true; } else if (string.Compare(strA, "AssemblyName", StringComparison.OrdinalIgnoreCase) == 0) { flag2 = true; } else { list.Add(args[i]); } } else { string name = args[i]; ServiceName = name; Assembly assembly = Assembly.GetExecutingAssembly(); AssemblyInstaller installer2 = new AssemblyInstaller(assembly, (string[])list.ToArray(typeof(string))); installerWithHelp.Installers.Add(installer2); } } if (flag3 || (installerWithHelp.Installers.Count == 0)) { flag3 = true; installerWithHelp.Installers.Add(new AssemblyInstaller()); throw new InvalidOperationException("GetHelp(installerWithHelp)"); } installerWithHelp.Context = new InstallContext("InstallUtil.InstallLog", (string[])list.ToArray(typeof(string))); } catch (Exception exception2) { if (flag3) { throw exception2; } throw new InvalidOperationException("InstallInitializeException"); } try { string str2 = installerWithHelp.Context.Parameters["installtype"]; if ((str2 != null) && (string.Compare(str2, "notransaction", StringComparison.OrdinalIgnoreCase) == 0)) { string str3 = installerWithHelp.Context.Parameters["action"]; if ((str3 != null) && (string.Compare(str3, "rollback", StringComparison.OrdinalIgnoreCase) == 0)) { installerWithHelp.Context.LogMessage("InstallRollbackNtRun"); for (int j = 0; j < installerWithHelp.Installers.Count; j++) { installerWithHelp.Installers[j].Rollback(null); } } else if ((str3 != null) && (string.Compare(str3, "commit", StringComparison.OrdinalIgnoreCase) == 0)) { installerWithHelp.Context.LogMessage("InstallCommitNtRun"); for (int k = 0; k < installerWithHelp.Installers.Count; k++) { installerWithHelp.Installers[k].Commit(null); } } else if ((str3 != null) && (string.Compare(str3, "uninstall", StringComparison.OrdinalIgnoreCase) == 0)) { installerWithHelp.Context.LogMessage("InstallUninstallNtRun"); for (int m = 0; m < installerWithHelp.Installers.Count; m++) { installerWithHelp.Installers[m].Uninstall(null); } } else { installerWithHelp.Context.LogMessage("InstallInstallNtRun"); for (int n = 0; n < installerWithHelp.Installers.Count; n++) { installerWithHelp.Installers[n].Install(null); } } } else if (!flag) { IDictionary stateSaver = new Hashtable(); installerWithHelp.Install(stateSaver); } else { installerWithHelp.Uninstall(null); } } catch (Exception exception3) { throw exception3; } }
//static string GetAssemblyPath() //{ // //return Assembly.GetExecutingAssembly().Location; // return Assembly.GetEntryAssembly().Location; //} #endregion #region service install //see: https://msdn.microsoft.com/zh-cn/library/system.configuration.install.installcontext%28v=vs.80%29.aspx static void ServiceInstall(string serviceName, bool install) { //config var username = ConfigurationManager.AppSettings["ServiceUsername"]; var password = ConfigurationManager.AppSettings["ServicePassword"]; var ServiceDepended = ConfigurationManager.AppSettings["ServiceDepended"]; var description = ConfigurationManager.AppSettings["ServiceDescription"]; //account ServiceAccount account = ServiceAccount.LocalSystem; if (!string.IsNullOrEmpty(username)) { switch (username) { case "LocalService": account = System.ServiceProcess.ServiceAccount.LocalService; break; case "LocalSystem": account = System.ServiceProcess.ServiceAccount.LocalSystem; break; case "NetworkService": account = System.ServiceProcess.ServiceAccount.NetworkService; break; default: account = System.ServiceProcess.ServiceAccount.User; break; } } //account TransactedInstaller ti = new TransactedInstaller(); if (account == ServiceAccount.User) { ti.Installers.Add(new ServiceProcessInstaller { Account = ServiceAccount.User , Username = username , Password = password }); } else { ti.Installers.Add(new ServiceProcessInstaller { Account = account }); } //service config ti.Installers.Add(new ServiceInstaller { ServiceName = serviceName, DisplayName = serviceName, Description = string.IsNullOrEmpty(description) ? "" : description, ServicesDependedOn = string.IsNullOrEmpty(ServiceDepended) ? new string[0] : ServiceDepended.Split(';'), StartType = ServiceStartMode.Automatic }); //context ti.Context = new InstallContext(); ti.Context.Parameters["assemblypath"] = Assembly.GetEntryAssembly().Location; //"\"" + Assembly.GetEntryAssembly().Location + "\" /service"; //ti.Context.Parameters["assemblypath"] = "\""+ Assembly.GetEntryAssembly().Location + "\"";// /ServiceName=" + serviceName; //ti.Context.Parameters["CommandLine"] = "/ServiceName=" + serviceName; if (install) { var installState = new Hashtable(); // Call the 'Install' method. ti.Install(installState); } else { // Call the 'UnInstall' method. ti.Uninstall(null); } }
public static void Main(String[] args) { ArrayList options = new ArrayList(); String myOption; bool toUnInstall = false; bool toPrintHelp = false; TransactedInstaller myTransactedInstaller = new TransactedInstaller(); AssemblyInstaller myAssemblyInstaller; InstallContext myInstallContext; try { for (int i = 0; i < args.Length; i++) { // Process the arguments. if (args[i].StartsWith("/") || args[i].StartsWith("-")) { myOption = args[i].Substring(1); // Determine whether the option is to 'uninstall' a assembly. if (String.Compare(myOption, "u", true) == 0 || String.Compare(myOption, "uninstall", true) == 0) { toUnInstall = true; continue; } // Determine whether the option is for printing help information. if (String.Compare(myOption, "?", true) == 0 || String.Compare(myOption, "help", true) == 0) { toPrintHelp = true; continue; } // Add the option encountered to the list of all options // encountered for the current assembly. options.Add(myOption); } else { // Determine whether the assembly file exists. if (!File.Exists(args[i])) { // If assembly file doesn't exist then print error. Console.WriteLine(" Error : {0} - Assembly file doesn't exist.", args[i]); return; } // <Snippet2> // Create an instance of 'AssemblyInstaller' that installs the given assembly. myAssemblyInstaller = new AssemblyInstaller(args[i], (string[])options.ToArray(typeof(string))); // Add the instance of 'AssemblyInstaller' to the 'TransactedInstaller'. myTransactedInstaller.Installers.Add(myAssemblyInstaller); // </Snippet2> } } // If user requested help or didn't provide any assemblies to install // then print help message. if (toPrintHelp || myTransactedInstaller.Installers.Count == 0) { PrintHelpMessage(); return; } // Create an instance of 'InstallContext' with the options specified. myInstallContext = new InstallContext("Install.log", (string[])options.ToArray(typeof(string))); myTransactedInstaller.Context = myInstallContext; // Install or Uninstall an assembly depending on the option provided. if (!toUnInstall) { myTransactedInstaller.Install(new Hashtable()); } else { myTransactedInstaller.Uninstall(null); } } catch (Exception e) { Console.WriteLine(" Exception raised : {0}", e.Message); } }
private static void Main(String[] CommandLineArgs) { //Komandozeilenargumente eingegeben??? if (CommandLineArgs.Length > 0) { if (CommandLineArgs[0] == "/install") { //Service hinzufügen TransactedInstaller serviceInstaller; Hashtable stateSaver; InstallContext installContext; ProjectInstaller mi; serviceInstaller = new TransactedInstaller(); stateSaver = new Hashtable(); mi = new ProjectInstaller(); serviceInstaller.Installers.Add(mi); string prgPfad = "\"" + Assembly.GetExecutingAssembly().Location + "\" " + "/service"; installContext = new InstallContext("ServiceInstall.log", null); installContext.Parameters.Add("assemblyPath", prgPfad); serviceInstaller.Context = installContext; try { serviceInstaller.Install(stateSaver); } catch (Exception ex) { MessageBox.Show("Fehler bein installieren des Service: " + ex.ToString()); } } //serviceInstaller.Commit(stateSaver) else if (CommandLineArgs[0] == "/uninstall") { //Service löschen... TransactedInstaller serviceInstaller; Hashtable stateSaver; InstallContext installContext; ProjectInstaller mi; serviceInstaller = new TransactedInstaller(); stateSaver = new Hashtable(); mi = new ProjectInstaller(); serviceInstaller.Installers.Add(mi); string prgPfad = "\"" + Assembly.GetExecutingAssembly().Location + "\" \"" + "/service\""; installContext = new InstallContext("ServiceInstall.log", null); installContext.Parameters.Add("assemblyPath", prgPfad); serviceInstaller.Context = installContext; try { serviceInstaller.Uninstall(null); } catch (Exception ex) { MessageBox.Show("Fehler bein deinstallieren des Service: " + ex.ToString()); } } else if (CommandLineArgs[0] == "/service") { Service service = new Service(); ServiceBase.Run(new ServiceBase[] { service }); } } //Keine Komandozeilenargumente.... else { { Application.Run(new ServiceConfig()); } } }
public static void Main() { try { // <Snippet1> // <Snippet2> // <Snippet3> TransactedInstaller myTransactedInstaller = new TransactedInstaller(); AssemblyInstaller myAssemblyInstaller1; AssemblyInstaller myAssemblyInstaller2; InstallContext myInstallContext; // Create a instance of 'AssemblyInstaller' that installs 'MyAssembly1.exe'. myAssemblyInstaller1 = new AssemblyInstaller("MyAssembly1.exe", null); // Add the instance of 'AssemblyInstaller' to the 'TransactedInstaller'. myTransactedInstaller.Installers.Insert(0, myAssemblyInstaller1); // Create a instance of 'AssemblyInstaller' that installs 'MyAssembly2.exe'. myAssemblyInstaller2 = new AssemblyInstaller("MyAssembly2.exe", null); // Add the instance of 'AssemblyInstaller' to the 'TransactedInstaller'. myTransactedInstaller.Installers.Insert(1, myAssemblyInstaller2); // Remove the 'myAssemblyInstaller2' from the 'Installers' collection. if (myTransactedInstaller.Installers.Contains(myAssemblyInstaller2)) { Console.WriteLine("\nInstaller at index : {0} is being removed", myTransactedInstaller.Installers.IndexOf(myAssemblyInstaller2)); myTransactedInstaller.Installers.Remove(myAssemblyInstaller2); } // </Snippet3> // </Snippet2> // </Snippet1> //Print the installers to be installed. InstallerCollection myInstallers = myTransactedInstaller.Installers; Console.WriteLine("\nPrinting all installers to be installed\n"); for (int i = 0; i < myInstallers.Count; i++) { if ((myInstallers[i].GetType()).Equals(typeof(AssemblyInstaller))) { Console.WriteLine("{0} {1}", i + 1, ((AssemblyInstaller)myInstallers[i]).Path); } } // Create a instance of 'InstallContext' with log file named 'Install.log'. myInstallContext = new InstallContext("Install.log", null); myTransactedInstaller.Context = myInstallContext; // Install an assembly. myTransactedInstaller.Install(new Hashtable()); } catch (Exception e) { Console.WriteLine("Exception raised : {0}", e.Message); } }
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(); }
/// <summary> /// The main entry point for the application. /// </summary> private static void Main(string[] args) { // Init Common logger -> this will enable TVPlugin to write in the Mediaportal.log file var loggerName = Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]); var dataPath = Log.GetPathName(); var loggerPath = Path.Combine(dataPath, "log"); #if DEBUG if (loggerName != null) { loggerName = loggerName.Replace(".vshost", ""); } #endif CommonLogger.Instance = new CommonLog4NetLogger(loggerName, dataPath, loggerPath); NameValueCollection appSettings = ConfigurationManager.AppSettings; appSettings.Set("GentleConfigFile", String.Format(@"{0}\gentle.config", PathManager.GetDataPath)); string opt = null; if (args.Length >= 1) { opt = args[0]; } if (opt != null && opt.ToUpperInvariant() == "/INSTALL") { TransactedInstaller ti = new TransactedInstaller(); ProjectInstaller mi = new ProjectInstaller(); 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.Install(new Hashtable()); return; } if (opt != null && opt.ToUpperInvariant() == "/UNINSTALL") { TransactedInstaller ti = new TransactedInstaller(); ProjectInstaller mi = new ProjectInstaller(); 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); return; } // When using /DEBUG switch (in visual studio) the TvService is not run as a service // Make sure the real TvService is disabled before debugging with /DEBUG if (opt != null && opt.ToUpperInvariant() == "/DEBUG") { Service1 s = new Service1(); s.DoStart(new string[] { "/DEBUG" }); do { Thread.Sleep(100); } while (true); } // More than one user Service may run within the same process. To add // another service to this process, change the following line to // create a second service object. For example, // // ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()}; // ServiceBase[] ServicesToRun = new ServiceBase[] { new Service1() }; ServicesToRun[0].CanShutdown = true; // Allow OnShutdown() ServiceBase.Run(ServicesToRun); }
public void Install() { transactedInstaller.Install(new Hashtable()); }
private static void Main(string[] args) { // Set up the crash dump handler. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(unhandledException); cultureInfo = new System.Globalization.CultureInfo("en-GB"); settingsManager = new SettingsManager(); cloudFlareAPI = new CloudFlareAPI(); if (args.Length > 0) { if (args[0] == "/service") { runService(); return; } if (args[0] == "/install") { if (!isAdmin) { AttachConsole(-1 /*ATTACH_PARENT_PROCESS*/ ); Console.WriteLine("Need to be running from an elevated (Administrator) command prompt."); FreeConsole(); return; } Console.WriteLine("The Service version is unstable!"); //Warning. TransactedInstaller ti = new TransactedInstaller(); ti.Installers.Add(new ServiceInstaller()); ti.Context = new InstallContext("", null); ti.Context.Parameters["assemblypath"] = "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\" /service"; ti.Install(new System.Collections.Hashtable()); ti.Dispose(); return; } if (args[0] == "/uninstall") { if (!isAdmin) { AttachConsole(-1 /*ATTACH_PARENT_PROCESS*/ ); Console.WriteLine("Need to be running from an elevated (Administrator) command prompt."); FreeConsole(); return; } TransactedInstaller ti = new TransactedInstaller(); ti.Installers.Add(new ServiceInstaller()); ti.Context = new System.Configuration.Install.InstallContext("", null); ti.Context.Parameters["assemblypath"] = "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\" /service"; ti.Uninstall(null); ti.Dispose(); return; } } runGUI(); return; }//end Main()
public void LaunchIt() { Hashtable install_state = new Hashtable(); Installer uninstaller = null; try { string pid_str = Process.GetCurrentProcess().Id.ToString(); string service_name = "SYSTEMCommandPrompt_" + pid_str; string event_name = "Global\\" + service_name; TransactedInstaller master_installer = new TransactedInstaller(); ServiceInstaller svcinst = new ServiceInstaller(); // don't set svcinst.Parent svcinst.Description = "Temporary service, should be safe to delete."; svcinst.DisplayName = "Temporary service (should be safe to delete)"; svcinst.ServiceName = service_name; svcinst.StartType = ServiceStartMode.Manual; ServiceProcessInstaller spi = new ServiceProcessInstaller(); // don't set spi.Parent spi.Account = ServiceAccount.LocalSystem; master_installer.Installers.AddRange(new Installer[] { spi, svcinst }); master_installer.Context = new InstallContext(); master_installer.Context.Parameters["assemblypath"] = string.Format("\"{0}\" -service {1} {2}", typeof(Form1).Assembly.Location, service_name, pid_str); LogMessage("Creating service: {0} running as {1}", service_name, spi.Account); master_installer.Install(install_state); uninstaller = master_installer; using (EventWaitHandle ready_signal = new EventWaitHandle(false, EventResetMode.AutoReset, event_name)) { using (ServiceController sc = new ServiceController(service_name)) { LogMessage("Starting service"); sc.Start(); } LogMessage("Waiting for service to acknowledge..."); ready_signal.WaitOne(120000); } } finally { if (uninstaller != null) { LogMessage("Deleting service..."); uninstaller.Uninstall(install_state); } } }
static int install_uninstall(bool uninstall) { try { TransactedInstaller ti = new TransactedInstaller(); if (uninstall == false) { ArrayList cmdline = new ArrayList(); Console.WriteLine(Assembly.GetExecutingAssembly().Location); cmdline.Add("/LogToConsole=false"); cmdline.Add("/ShowCallStack"); cmdline.Add(Assembly.GetExecutingAssembly().Location); string[] str = cmdline.ToArray(typeof(string)) as string[]; foreach (string s in str) { Console.WriteLine(s); } InstallContext ctx = new InstallContext("install.log", cmdline.ToArray(typeof(string)) as string[]); ti.Installers.Add(new SampleInstallerClass()); ti.Context = ctx; ti.Install(new Hashtable()); RegistryKey k = Registry.LocalMachine.OpenSubKey(SVC_SERVICE_KEY, true); k.SetValue("Description", "Sample service"); k.CreateSubKey("Parameters"); // add any configuration parameters in to this sub-key to read back OnStart() k.Close(); Console.WriteLine("Installation successful, starting service '{0}'...", SVC_APP_NAME); // attempt to start the service /* * ServiceController service = new ServiceController( SVC_APP_NAME ); * TimeSpan timeout = TimeSpan.FromMilliseconds(15000); * service.Start(); * service.WaitForStatus( ServiceControllerStatus.Running, timeout ); */ return(0); } else { ServiceController service = new ServiceController(SVC_APP_NAME); TimeSpan timeout = TimeSpan.FromMilliseconds(15000); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); ArrayList cmdline = new ArrayList(); cmdline.Add("/u"); cmdline.Add(Assembly.GetExecutingAssembly().Location); InstallContext ctx = new InstallContext("install.log", cmdline.ToArray(typeof(string)) as string[]); ti.Installers.Add(new SampleInstallerClass()); ti.Context = ctx; ti.Uninstall(null); RegistryKey key = Registry.CurrentUser.OpenSubKey(SVC_SERVICE_PKEY, true); key.DeleteSubKeyTree(SVC_APP_NAME); key.Close(); return(0); } } catch (Exception e) { Console.WriteLine(e.InnerException.Message + e.StackTrace); return(1); } }
static void Main(String[] CommandLineArgs) { //Komandozeilenargumente eingegeben??? if (CommandLineArgs.Length > 0) { if (CommandLineArgs[0] == "/install") { //Service hinzufügen TransactedInstaller serviceInstaller; Hashtable stateSaver; InstallContext installContext; ProjectInstaller mi; serviceInstaller = new TransactedInstaller(); stateSaver = new Hashtable(); mi = new ProjectInstaller(); serviceInstaller.Installers.Add(mi); string prgPfad = "\"" + Assembly.GetExecutingAssembly().Location + "\" " + "/service"; installContext = new InstallContext("ServiceInstall.log", null); installContext.Parameters.Add("assemblyPath", prgPfad); foreach (string myStr in CommandLineArgs) { if (myStr == "/postgres") { mi.postgres = true; } else if (myStr == "/mysql") { mi.mysql = true; } else if (myStr == "/mssql") { mi.mssql = true; } } serviceInstaller.Context = installContext; try { serviceInstaller.Install(stateSaver); } catch (Exception ex) { MessageBox.Show("Fehler bein installieren des Service: " + ex.ToString()); } } //serviceInstaller.Commit(stateSaver) else if (CommandLineArgs[0] == "/uninstall") { //Service löschen... TransactedInstaller serviceInstaller; Hashtable stateSaver; InstallContext installContext; ProjectInstaller mi; serviceInstaller = new TransactedInstaller(); stateSaver = new Hashtable(); mi = new ProjectInstaller(); serviceInstaller.Installers.Add(mi); string prgPfad = "\"" + Assembly.GetExecutingAssembly().Location + "\" \"" + "/service\""; installContext = new InstallContext("ServiceInstall.log", null); installContext.Parameters.Add("assemblyPath", prgPfad); serviceInstaller.Context = installContext; try { serviceInstaller.Uninstall(null); } catch (Exception ex) { MessageBox.Show("Fehler bein deinstallieren des Service: " + ex.ToString()); } } else if (CommandLineArgs[0] == "/service") { ProtokollerDatenbankService myProt = new ProtokollerDatenbankService(); ServiceBase.Run(new ServiceBase[] { myProt }); } } //Keine Komandozeilenargumente.... else { //Zuerst versuchen den Service zu starten.... //ProtkollerDatenbank myProt = new ProtkollerDatenbank(); //ServiceBase.Run(new ServiceBase[] {myProt}); //Wenn starten nicht möglich war, dann war es doppelklick auf die Datei //daher Config anzeigen.... //if (myProt.ServiceRunning == false) { Application.Run(new ServiceConfig()); } } }