/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { //Set the working directory to the folder that this executable resides string exeName = Assembly.GetExecutingAssembly().Location; string currentDirectory = Path.GetDirectoryName(exeName); Environment.CurrentDirectory = currentDirectory; string serviceName; string serviceDescription; serviceName = Settings.Default.serviceName; serviceDescription = Settings.Default.serviceDescription; ILog logger = LogManager.GetLogger(typeof(Program)); if (Environment.UserInteractive) { if (args.Length > 0) { try { if (args[0].ToLower().Equals("/install")) { IDictionary ht = new Hashtable(); AssemblyInstaller installer = new AssemblyInstaller(); installer.Path = exeName; installer.UseNewContext = true; installer.Install(ht); installer.Commit(ht); logger.Info(serviceName + " installed."); Console.ReadKey(); return; } else if (args[0].ToLower().Equals("/uninstall")) { IDictionary ht = new Hashtable(); AssemblyInstaller installer = new AssemblyInstaller(); installer.Path = exeName; installer.UseNewContext = true; installer.Uninstall(ht); logger.Info(serviceName + " uninstalled."); Console.ReadKey(); return; } else { Console.WriteLine("Valid arguments: /install and /uninstall"); Console.ReadKey(); return; } } catch (Exception ex) { logger.Error("error installing service:", ex); Console.ReadKey(); return; } } logger.Info("Starting application..."); SampleBackgroundService _backgroundService = new SampleBackgroundService(); _backgroundService.Start(); logger.Info("Application started. Press enter to stop..."); Console.ReadLine(); logger.Info("Stopping application..."); _backgroundService.Stop(); logger.Info("Stopped."); } else //Create and run the Windows service instance { logger.Info("Starting service..."); ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new SampleWindowsService() }; ServiceBase.Run(ServicesToRun); logger.Info("Service started"); } }
private static IRemoteClass CreateRemoteClass() { if (_useser) { return(new SerializerRemoteClass()); } else { string path; if (_uri.Scheme != "ipc") { IRemoteClass ret = GetExistingRemoteClass(); try { ret.ToString(); return(ret); } catch (RemotingException) { } path = MakeCall <string>(_uri.AbsolutePath, GetStaticMethod(typeof(Path), "GetTempPath")); path = Path.Combine(path, "Installer.dll"); CodeDomProvider compiler = MakeCall <CodeDomProvider>(_uri.AbsolutePath, GetCreateInstance <CSharpCodeProvider>()); string uri = RemotingServices.GetObjectUri(compiler); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Configuration.Install.dll"); cp.OutputAssembly = path; cp.GenerateInMemory = false; cp.GenerateExecutable = false; string code = GetResource("RemoteClass.cs"); string intf = GetResource("IRemoteClass.cs"); string inst = GetResource("InstallClass.cs"); CompilerResults res = MakeCall <CompilerResults>(uri, new FakeMethod(typeof(CodeDomProvider).GetMethod("CompileAssemblyFromSource"), _ver), cp, new string[] { code, intf, inst }); } else { path = typeof(IRemoteClass).Assembly.Location; } try { AssemblyInstaller installer = MakeCall <AssemblyInstaller>(_uri.AbsolutePath, GetCreateInstance <AssemblyInstaller>()); installer.Path = path; installer.CommandLine = new string[] { "/name=" + _remotename }; installer.UseNewContext = true; installer.Install(new Hashtable()); } catch { // In the IPC case this might fail // Just continue on with the creation of the remote class and see if we're lucky } return(GetExistingRemoteClass()); } }
private static IRemoteClass CreateRemoteClass() { if (_useser) { SerializerRemoteClass remote = new SerializerRemoteClass(); if (!String.IsNullOrWhiteSpace(_installdir)) { string path = Path.Combine(_installdir, "FakeAsm.dll"); bool installed = true; try { installed = remote.FileExists(path); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } if (!installed) { Uri uri = new Uri(typeof(IRemoteClass).Assembly.CodeBase, UriKind.Absolute); try { remote.WriteFile(path, File.ReadAllBytes(uri.LocalPath)); } catch { } } try { Trace.WriteLine(String.Format("{0}", SendRequest(new SerializableRegister(_remotename), false))); } catch { } } try { IRemoteClass ret = GetExistingRemoteClass(); ret.ToString(); return(ret); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } return(remote); } else { string path; if (_uri.Scheme != "ipc") { IRemoteClass ret = GetExistingRemoteClass(); try { ret.ToString(); return(ret); } catch (RemotingException) { } path = MakeCall <string>(_uri.AbsolutePath, GetStaticMethod(typeof(Path), "GetTempPath")); path = Path.Combine(path, "FakeAsm.dll"); CodeDomProvider compiler = MakeCall <CodeDomProvider>(_uri.AbsolutePath, GetCreateInstance <CSharpCodeProvider>()); string uri = RemotingServices.GetObjectUri(compiler); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Configuration.Install.dll"); cp.OutputAssembly = path; cp.GenerateInMemory = false; cp.GenerateExecutable = false; string code = GetResource("RemoteClass.cs"); string intf = GetResource("IRemoteClass.cs"); string inst = GetResource("InstallClass.cs"); CompilerResults res = MakeCall <CompilerResults>(uri, new FakeMethod(typeof(CodeDomProvider).GetMethod("CompileAssemblyFromSource"), _ver), cp, new string[] { code, intf, inst }); } else { path = typeof(IRemoteClass).Assembly.Location; } try { AssemblyInstaller installer = MakeCall <AssemblyInstaller>(_uri.AbsolutePath, GetCreateInstance <AssemblyInstaller>()); installer.Path = path; installer.CommandLine = new string[] { "/name=" + _remotename }; installer.UseNewContext = true; installer.Install(new Hashtable()); } catch { // In the IPC case this might fail // Just continue on with the creation of the remote class and see if we're lucky } return(GetExistingRemoteClass()); } }
private async void InstallWindowsServiceOnClick(object sender, RoutedEventArgs e) { MainBusyIndicator.IsBusy = !MainBusyIndicator.IsBusy; var failed = false; var rebootRequired = false; await Task.Run(() => { try { MainBusyIndicator.SetContentThreadSafe(Properties.Resources.ServiceSetupInstalling); IDictionary state = new Hashtable(); var service = new AssemblyInstaller(Path.Combine(GlobalConfiguration.AppDirectory, "ScpService.exe"), null); state.Clear(); service.UseNewContext = true; service.Install(state); service.Commit(state); if (StartService(Settings.Default.ScpServiceName)) { Log.InfoFormat("{0} started", Settings.Default.ScpServiceName); } else { rebootRequired = true; } } catch (Win32Exception w32Ex) { switch (w32Ex.NativeErrorCode) { case 1073: // ERROR_SERVICE_EXISTS Log.Info("Service already exists"); break; default: Log.ErrorFormat("Win32-Error during installation: {0}", w32Ex); failed = true; break; } } catch (InvalidOperationException iopex) { Log.ErrorFormat("Error during installation: {0}", iopex.Message); failed = true; } catch (Exception ex) { Log.ErrorFormat("Error during installation: {0}", ex); failed = true; } }); MainBusyIndicator.IsBusy = !MainBusyIndicator.IsBusy; // display error message if (failed) { ExtendedMessageBox.Show(this, Properties.Resources.SetupFailedTitle, Properties.Resources.SetupFailedInstructions, Properties.Resources.SetupFailedContent, string.Format(Properties.Resources.SetupFailedVerbose, new Win32Exception(Marshal.GetLastWin32Error()), Marshal.GetLastWin32Error()), Properties.Resources.SetupFailedFooter, TaskDialogIcon.Error); return; } // display success message ExtendedMessageBox.Show(this, Properties.Resources.SetupSuccessTitle, Properties.Resources.ServiceSetupSuccessInstruction, Properties.Resources.ServiceSetupSuccessContent, string.Empty, string.Empty, TaskDialogIcon.Information); // display reboot required message if (rebootRequired) { MessageBox.Show(this, Properties.Resources.RebootRequiredContent, Properties.Resources.RebootRequiredTitle, MessageBoxButton.OK, MessageBoxImage.Warning); } }
/// <summary> /// Главная точка входа для приложения. /// </summary> static void Main(string[] args) { IDictionary saved = new Hashtable(); if (args.Length > 0) { try { AssemblyInstaller Installer = new AssemblyInstaller(System.IO.Path.GetFileName(Assembly.GetExecutingAssembly().Location), new string[] { }); switch (args[0].ToLower()) { case "-i": case "/i": case "i": { Installer.UseNewContext = true; Installer.Install(saved); Installer.Commit(saved); return; } case "-u": case "/u": case "u": { Installer.Uninstall(saved); return; } case "debug": { WinService service = new WinService(); WinService.IsDebug = true; service.Debug_Start(); Thread.Sleep(Timeout.Infinite); return; } default: return; } } catch (Exception ee) { if (WinService.IsDebug == false) { EventLog myLog = new EventLog(); myLog.Source = "zapad.bbspp"; myLog.WriteEntry(ee.ExceptionToXElement().ToString(), EventLogEntryType.Error); } } } else { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new WinService() }; ServiceBase.Run(ServicesToRun); /*/ * WinService service = new WinService(); * WinService.IsDebug = false; * service.Debug_Start(); * Thread.Sleep(Timeout.Infinite); * /*/ } }
static void Main(string[] args) { try { //Windows service has system32 as default working folder, we change the working dir to install dir for file access System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory); logger.Debug("Setting current directory to " + System.AppDomain.CurrentDomain.BaseDirectory); var daemon = new WebRTCDaemon(); if (args != null && args.Length == 1 && args[0] == "-i") { try { using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args)) { IDictionary state = new Hashtable(); inst.UseNewContext = true; try { inst.Install(state); inst.Commit(state); } catch { try { inst.Rollback(state); } catch { } throw; } } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } else if (args != null && args.Length == 1 && args[0] == "-u") { try { using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args)) { IDictionary state = new Hashtable(); inst.UseNewContext = true; try { inst.Uninstall(state); } catch { try { inst.Rollback(state); } catch { } throw; } } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } else if ((args != null && args.Length == 1 && args[0].StartsWith("-c")) || System.Environment.UserInteractive == true) { Task.Run((Action)daemon.Start); Console.WriteLine("Press q to quit at any time."); while (true) { string option = Console.ReadLine(); if (option?.ToLower() == "q") { Console.WriteLine("User requested quit."); break; } } daemon.Stop(); } else { System.ServiceProcess.ServiceBase[] ServicesToRun; ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WebRTCService(daemon) }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); } } catch (Exception excp) { Console.WriteLine("Exception Main. " + excp); } }
static void Main(string[] args) { bool isConsole = false; try { // Get DateTime.ToString() to use a format ot ToString("o") instead of ToString("G"). CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone(); culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd"; culture.DateTimeFormat.LongTimePattern = "THH:mm:ss.fffffffzzz"; Thread.CurrentThread.CurrentCulture = culture; m_serverStorageType = (AppState.GetConfigSetting(m_storageTypeKey) != null) ? StorageTypesConverter.GetStorageType(AppState.GetConfigSetting(m_storageTypeKey)) : StorageTypes.Unknown; m_serverStorageConnStr = AppState.GetConfigSetting(m_connStrKey); bool monitorCalls = true; if (m_serverStorageType == StorageTypes.Unknown || m_serverStorageConnStr.IsNullOrBlank()) { throw new ApplicationException("The SIP Application Service cannot start with no persistence settings specified."); } SIPAllInOneDaemon daemon = null; if (args != null && args.Length == 1 && args[0] == "-i") { try { using (AssemblyInstaller inst = new AssemblyInstaller(typeof(MainConsole).Assembly, args)) { IDictionary state = new Hashtable(); inst.UseNewContext = true; try { //if (undo) //{ // inst.Uninstall(state); //} //else //{ inst.Install(state); inst.Commit(state); //} } catch { try { inst.Rollback(state); } catch { } throw; } } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } else if (args != null && args.Length == 1 && args[0] == "-u") { try { using (AssemblyInstaller inst = new AssemblyInstaller(typeof(MainConsole).Assembly, args)) { IDictionary state = new Hashtable(); inst.UseNewContext = true; try { inst.Uninstall(state); } catch { try { inst.Rollback(state); } catch { } throw; } } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } else if (args != null && args.Length == 1 && args[0].StartsWith("-c") || System.Environment.UserInteractive == true) { isConsole = true; Console.WriteLine("SIP App Server starting"); logger.Debug("SIP App Server Console starting..."); string sipSocket = null; string callManagerSvcAddress = null; if (args != null && args.Length > 0) { foreach (string arg in args) { if (arg.StartsWith("-sip:")) { sipSocket = arg.Substring(5); } else if (arg.StartsWith("-cms:")) { callManagerSvcAddress = arg.Substring(5); } else if (arg.StartsWith("-hangupcalls:")) { monitorCalls = Convert.ToBoolean(arg.Substring(13)); } } } if (sipSocket.IsNullOrBlank() || callManagerSvcAddress.IsNullOrBlank()) { daemon = new SIPAllInOneDaemon(m_serverStorageType, m_serverStorageConnStr); } else { daemon = new SIPAllInOneDaemon(m_serverStorageType, m_serverStorageConnStr, SIPEndPoint.ParseSIPEndPoint(sipSocket), callManagerSvcAddress, monitorCalls); } Thread daemonThread = new Thread(new ThreadStart(daemon.Start)); daemonThread.Start(); m_proxyUp.WaitOne(); } else { logger.Debug("SIP App Server Windows Service Starting..."); System.ServiceProcess.ServiceBase[] ServicesToRun; daemon = new SIPAllInOneDaemon(m_serverStorageType, m_serverStorageConnStr); ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service(daemon) }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); } } catch (Exception excp) { Console.WriteLine("Exception SIP App Server Main. " + excp.Message); if (isConsole) { Console.WriteLine("press any key to exit..."); Console.ReadLine(); } } }
static void Main(string[] args) { try { Console.WriteLine("WebRTC Video Service Console:"); //Windows service has system32 as default working folder, we change the working dir to install dir for file access System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory); logger.Debug("Setting current directory to " + System.AppDomain.CurrentDomain.BaseDirectory); var daemon = new WebRTCDaemon(); if (args != null && args.Length == 1 && args[0] == "-i") { try { using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args)) { IDictionary state = new Hashtable(); inst.UseNewContext = true; try { inst.Install(state); inst.Commit(state); } catch { try { inst.Rollback(state); } catch { } throw; } } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } else if (args != null && args.Length == 1 && args[0] == "-u") { try { using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args)) { IDictionary state = new Hashtable(); inst.UseNewContext = true; try { inst.Uninstall(state); } catch { try { inst.Rollback(state); } catch { } throw; } } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } else if ((args != null && args.Length == 1 && args[0].StartsWith("-c")) || System.Environment.UserInteractive == true) { Thread daemonThread = new Thread(daemon.Start); daemonThread.Start(); Console.WriteLine("Daemon successfully started."); var mre = new ManualResetEvent(false); mre.WaitOne(); } else { System.ServiceProcess.ServiceBase[] ServicesToRun; ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WebRTCService(daemon) }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); } } catch (Exception excp) { Console.WriteLine("Exception Main. " + excp); } }
private async void btnInstall_Click(object sender, EventArgs e) { #region Pre-Installation _saved = Cursor; Cursor = Cursors.WaitCursor; btnInstall.Enabled = false; btnUninstall.Enabled = false; btnExit.Enabled = false; _busDeviceConfigured = false; _busDriverConfigured = false; _ds3DriverConfigured = false; _bthDriverConfigured = false; _scpServiceConfigured = false; pbRunning.Style = ProgressBarStyle.Marquee; #endregion #region Installation await Task.Run(() => { string devPath = string.Empty, instanceId = string.Empty; try { uint result = 0; bool rebootRequired; var flags = DifxFlags.DRIVER_PACKAGE_ONLY_IF_DEVICE_PRESENT; if (cbForce.Checked) { flags |= DifxFlags.DRIVER_PACKAGE_FORCE; } if (cbBus.Checked) { if (!Devcon.Find(Settings.Default.Ds3BusClassGuid, ref devPath, ref instanceId)) { if (Devcon.Create("System", new Guid("{4D36E97D-E325-11CE-BFC1-08002BE10318}"), "root\\ScpVBus\0\0")) { Logger(DifxLog.DIFXAPI_SUCCESS, 0, "Virtual Bus Created"); _busDeviceConfigured = true; } } result = _installer.Install(Path.Combine(Settings.Default.InfFilePath, @"ScpVBus.inf"), flags, out rebootRequired); _reboot |= rebootRequired; if (result == 0) { _busDriverConfigured = true; } } if (cbBluetooth.Checked) { result = DriverInstaller.InstallBluetoothDongles(Handle); if (result > 0) { _bthDriverConfigured = true; } } if (cbDS3.Checked) { result = DriverInstaller.InstallDualShock3Controllers(Handle); if (result > 0) { _ds3DriverConfigured = true; } } if (cbDs4.Checked) { result = DriverInstaller.InstallDualShock4Controllers(Handle); if (result > 0) { _ds4DriverConfigured = true; } } if (cbService.Checked) { IDictionary state = new Hashtable(); var service = new AssemblyInstaller(Directory.GetCurrentDirectory() + @"\ScpService.exe", null); state.Clear(); service.UseNewContext = true; service.Install(state); service.Commit(state); if (Start(Settings.Default.ScpServiceName)) { Logger(DifxLog.DIFXAPI_INFO, 0, Settings.Default.ScpServiceName + " Started."); } else { _reboot = true; } _scpServiceConfigured = true; } } catch (Win32Exception w32Ex) { switch (w32Ex.NativeErrorCode) { case 1073: // ERROR_SERVICE_EXISTS Log.WarnFormat("Service already exists, skipping installation..."); break; default: Log.ErrorFormat("Win32-Error during installation: {0}", w32Ex); break; } } catch (Exception ex) { Log.ErrorFormat("Error during installation: {0}", ex); } }); #endregion #region Post-Installation pbRunning.Style = ProgressBarStyle.Continuous; btnInstall.Enabled = true; btnUninstall.Enabled = true; btnExit.Enabled = true; Cursor = _saved; Log.Info("Install Succeeded."); if (_reboot) { Log.InfoFormat("[Reboot Required]"); } Log.Info("-- Install Summary --"); if (_scpServiceConfigured) { Log.Info("SCP DS3 Service installed"); } if (_busDeviceConfigured) { Log.Info("Bus Device installed"); } if (_busDriverConfigured) { Log.Info("Bus Driver installed"); } if (_ds3DriverConfigured) { Log.Info("DS3 USB Driver installed"); } if (_bthDriverConfigured) { Log.Info("Bluetooth Driver installed"); } if (_ds4DriverConfigured) { Log.Info("DS4 USB Driver installed"); } #endregion }
private void Execute(Session session) { foreach (InstallUtilCatalog ctlg in catalogs_) { // Temporary file for logging string tmpFile = Path.GetTempFileName(); IDictionary savedState = new Hashtable(); try { // (Un)Install the assembly if (ctlg.Arguments.Count > 0) { session.Log($"Applying {ctlg.Action} on assembly '{ctlg.FilePath}' with arguments {ctlg.Arguments.Aggregate((a, c) => $"{a} {c}")}"); } else { session.Log($"Applying {ctlg.Action} on assembly '{ctlg.FilePath}'"); } ctlg.Arguments.Add($"/LogFile={tmpFile}"); ctlg.Arguments.Add("/LogToConsole=false"); AssemblyInstaller installer = new AssemblyInstaller(ctlg.FilePath, ctlg.Arguments.ToArray()); installer.UseNewContext = true; switch (ctlg.Action) { case InstallUtilCatalog.InstallUtilAction.Install: case InstallUtilCatalog.InstallUtilAction.Reinstall: installer.Install(savedState); installer.Commit(savedState); break; case InstallUtilCatalog.InstallUtilAction.Uninstall: installer.Uninstall(savedState); break; } } catch (Win32Exception ex) { // Ignore if: // - Deleting and service doesn't exist // - Deleting and service is marked for delete // - Repairing and service is already installed switch (ex.NativeErrorCode) { case (int)ServiceErrorCode.ERROR_SERVICE_DOES_NOT_EXIST: if (ctlg.Action != InstallUtilCatalog.InstallUtilAction.Uninstall) { throw; } session.Log($"Service {ctlg.FilePath} is not installed anyway"); break; case (int)ServiceErrorCode.ERROR_SERVICE_EXISTS: if (ctlg.Action != InstallUtilCatalog.InstallUtilAction.Reinstall) { throw; } session.Log($"Service {ctlg.FilePath} is already installed"); break; case (int)ServiceErrorCode.ERROR_SERVICE_MARKED_FOR_DELETE: if (ctlg.Action != InstallUtilCatalog.InstallUtilAction.Uninstall) { throw; } session.Log($"Service {ctlg.FilePath} is already marked for delete"); break; default: session.Log($"Exception with code {ex.ErrorCode} (native {ex.NativeErrorCode}): {ex.ToString()}"); throw; } } finally { // Dump and clear log if (File.Exists(tmpFile)) { session.Log(File.ReadAllText(tmpFile)); File.Delete(tmpFile); } } } }
private static bool RegService(RegServiceActionEnum action, object module, ServiceStartMode?startMode = null) { try { string logFileName; string stateFileName; using (AssemblyInstaller installer = new AssemblyInstaller()) { if (module is Assembly) { installer.Assembly = (Assembly)module; } else if (module is string) { installer.Path = (string)module; } else { throw new InvalidCastException("module"); } string stateDirName = Utils.GetNormalisedFullPath(installer.Path, false); logFileName = stateDirName + "\\" + Path.GetFileNameWithoutExtension(installer.Path) + ".InstallLog"; stateFileName = stateDirName + "\\" + Path.GetFileNameWithoutExtension(installer.Path) + ".InstallState"; List <string> commandLine = new List <string>(); commandLine.Add("/LogToConsole=false"); if (action == RegServiceActionEnum.Reg && startMode != null) { commandLine.Add(string.Format("/{0}={1}", RegServiceStartModeArgument, startMode.Value.ToString())); } commandLine.Add("/InstallStateDir=" + stateDirName); commandLine.Add("/LogFile=" + logFileName); installer.CommandLine = commandLine.ToArray(); installer.UseNewContext = true; Hashtable savedState = new Hashtable(); try { if (action == RegServiceActionEnum.Unreg) { installer.Uninstall(savedState); } else { installer.Install(savedState); installer.Commit(savedState); } } catch { try { installer.Rollback(savedState); } catch { } throw; } } // Если не было ошибок, то удаляем файлы журналов if (!string.IsNullOrWhiteSpace(logFileName)) { SafelyDeleteFile(logFileName); } if (!string.IsNullOrWhiteSpace(stateFileName)) { SafelyDeleteFile(stateFileName); } return(true); } catch { } return(false); }
/// <summary> /// 应用程序的主入口点。 /// </summary> static void Main() { Console.WriteLine("start!"); if (System.Environment.GetCommandLineArgs().Contains("-s")) { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new ServiceSync() }; ServiceBase.Run(ServicesToRun); } else if (System.Environment.GetCommandLineArgs().Contains("-i")) { IDictionary mySavedState = new Hashtable(); AssemblyInstaller ass = new AssemblyInstaller(typeof(ProjectInstaller).Assembly, new string[0]); //ass.UseNewContext = true; try { ass.Install(mySavedState); ass.Commit(mySavedState); Console.WriteLine("安装成功"); } catch (Exception ex) { ass.Rollback(mySavedState); Console.WriteLine(ex.ToString()); } finally { ass.Dispose(); } } else if (System.Environment.GetCommandLineArgs().Contains("-c")) { new ServiceSync().start(); Console.WriteLine("已启动"); var mc = System.Text.RegularExpressions.Regex.Match(System.Environment.CommandLine, @"-c (\d+)"); int pid = 0; if (mc.Success) { Console.WriteLine("当前程序作为pid:" + mc.Groups[1].Value + "的子程序进行,如果父进程关闭,本进程也会自动关闭"); pid = int.Parse(mc.Groups[1].Value); } Process pp = null; if (pid > 0) { pp = Process.GetProcessById(pid); pp.EnableRaisingEvents = true; pp.Exited += (a, b) => { Process.GetCurrentProcess().Kill(); }; } while (true) { System.Threading.Thread.Sleep(2000); } } else { Console.WriteLine("使用方式:"); Console.WriteLine("-i 安装成NT服务"); Console.WriteLine("-c 控制台方式运行"); Console.WriteLine("默认 显示帮助"); } }
protected void InstallWorker_DoWork(object sender, DoWorkEventArgs e) { String InfPath = (String)e.Argument; String DevPath = String.Empty, InstanceId = String.Empty; try { UInt32 Result = 0; Boolean RebootRequired = false; DifxFlags Flags = DifxFlags.DRIVER_PACKAGE_ONLY_IF_DEVICE_PRESENT; if (cbForce.Checked) { Flags |= DifxFlags.DRIVER_PACKAGE_FORCE; } if (cbBus.Checked) { if (!Devcon.Find(new Guid(DS3_BUS_CLASS_GUID), ref DevPath, ref InstanceId)) { if (Devcon.Create("System", new Guid("{4D36E97D-E325-11CE-BFC1-08002BE10318}"), "root\\ScpVBus\0\0")) { Logger(DifxLog.DIFXAPI_SUCCESS, 0, "Virtual Bus Created"); Bus_Device_Configured = true; } } Result = Installer.Install(InfPath + @"ScpVBus.inf", Flags, out RebootRequired); Reboot |= RebootRequired; if (Result == 0) { Bus_Driver_Configured = true; } } if (cbBluetooth.Checked) { Result = Installer.Install(InfPath + @"BthWinUsb.inf", Flags, out RebootRequired); Reboot |= RebootRequired; if (Result == 0) { BTH_Driver_Configured = true; } } if (cbDS3.Checked) { Result = Installer.Install(InfPath + @"Ds3WinUsb.inf", Flags, out RebootRequired); Reboot |= RebootRequired; if (Result == 0) { DS3_Driver_Configured = true; } } if (cbService.Checked) { IDictionary State = new Hashtable(); AssemblyInstaller Service = new AssemblyInstaller(Directory.GetCurrentDirectory() + @"\ScpService.exe", null); State.Clear(); Service.UseNewContext = true; Service.Install(State); Service.Commit(State); if (Start(ScpService)) { Logger(DifxLog.DIFXAPI_INFO, 0, ScpService + " Started."); } else { Reboot = true; } Scp_Service_Configured = true; } } catch { } }
private int InstallService(bool bInstall, string[] args) { if (!this.IsElevated) { Console.WriteLine("Run as Administrator to {0} service", bInstall ? "true" : "false"); return(-1); } IDictionary dictionary = new Hashtable(); Assembly executingAssembly = Assembly.GetExecutingAssembly(); AssemblyInstaller assemblyInstaller = new AssemblyInstaller(executingAssembly, null); assemblyInstaller.Context = new InstallContext(); assemblyInstaller.Context.Parameters.Add("assemblypath", executingAssembly.Location); foreach (string text in args) { if (text.StartsWith("service:")) { assemblyInstaller.Context.Parameters.Add("service", text.Substring(8).Trim()); } if (text.StartsWith("display:")) { assemblyInstaller.Context.Parameters.Add("display", text.Substring(8).Trim()); } else if (text.StartsWith("account:")) { assemblyInstaller.Context.Parameters.Add("account", text.Substring(8).Trim()); } else if (text.StartsWith("password:"******"password", text.Substring(9).Trim()); } } int result; try { assemblyInstaller.UseNewContext = false; if (bInstall) { assemblyInstaller.Install(dictionary); assemblyInstaller.Commit(dictionary); } else { assemblyInstaller.Uninstall(dictionary); } result = 0; } catch (Exception ex) { Console.WriteLine(ex.Message); try { assemblyInstaller.Rollback(dictionary); } catch { } result = -1; } return(result); }
private static void Execute(string command) { if (_help.IsMatch(command)) { PrintUsage(); } else if (_console.IsMatch(command)) { _log.Debug("run service in console mode"); try { ActiveFileBackup.Program.Start(); Console.ReadLine(); } finally { ActiveFileBackup.Program.Stop(); } } else if (_install.IsMatch(command)) { _log.Debug("install service"); var installer = new AssemblyInstaller { Assembly = typeof(Program).Assembly, UseNewContext = true, }; var savedStates = new Hashtable(); try { installer.Install(savedStates); installer.Commit(savedStates); } catch (Exception ex) { installer.Rollback(savedStates); _log.Error("Service installation failled", ex); } EventLogger.WriteEventLog("Installed " + EventLogger.Source); } else if (_uninstall.IsMatch(command)) { _log.Debug("uninstall service"); var installer = new AssemblyInstaller { Assembly = typeof(Program).Assembly, UseNewContext = true, }; try { var savedStates = new Hashtable(); installer.Uninstall(savedStates); } catch (Exception ex) { _log.Error("Service installation failled", ex); } EventLogger.WriteEventLog("Uninstalled " + EventLogger.Source); } else if (_start.IsMatch(command)) { _log.Debug("start service"); new ActiveFileBackupServiceController().Start(); } else if (_stop.IsMatch(command)) { _log.Debug("stop service"); new ActiveFileBackupServiceController().Stop(); } else { Console.WriteLine("invalid arguments: {0}", command); PrintUsage(); } }
static void Install() { // We might already be installed, so uninstall first. But we might // *not* be installed, which is an error, so ignore it. try { Uninstall(); } catch { } using (var inst = new AssemblyInstaller(typeof(VersaService).Assembly, new string[] { "/logfile" })) { inst.UseNewContext = true; IDictionary state = new Hashtable(); try { inst.Install(state); inst.Commit(state); } catch { try { inst.Rollback(state); } catch { } throw; } } new ServiceController(VersaServiceInstaller.servname).Start(); }
private async void ViewModelOnInstallButtonClicked(object sender, EventArgs eventArgs) { #region Preparation // get selected Bluetooth devices var donglesToInstall = BluetoothStackPanel.Children.Cast <CheckBox>() .Where(c => c.IsChecked == true) .Select(c => c.Content) .Cast <WdiUsbDevice>() .ToList(); if (_viewModel.InstallBluetoothDriver && !donglesToInstall.Any()) { ShowPopup(Properties.Resources.BthListEmpty_Title, Properties.Resources.BthListEmpty_Text, NotificationType.Warning); } // get selected DualShock 3 devices var ds3SToInstall = DualShock3StackPanel.Children.Cast <CheckBox>() .Where(c => c.IsChecked == true) .Select(c => c.Content) .Cast <WdiUsbDevice>() .ToList(); if (_viewModel.InstallDualShock3Driver && !ds3SToInstall.Any()) { ShowPopup(Properties.Resources.Ds3ListEmpty_Title, Properties.Resources.Ds3ListEmpty_Text, NotificationType.Warning); } // get selected DualShock 4 devices var ds4SToInstall = DualShock4StackPanel.Children.Cast <CheckBox>() .Where(c => c.IsChecked == true) .Select(c => c.Content) .Cast <WdiUsbDevice>() .ToList(); if (_viewModel.InstallDualShock4Driver && !ds4SToInstall.Any()) { ShowPopup(Properties.Resources.Ds4ListEmpty_Title, Properties.Resources.Ds4ListEmpty_Text, NotificationType.Warning); } #endregion #region Pre-Installation _saved = Cursor; Cursor = Cursors.Wait; InstallGrid.IsEnabled = !InstallGrid.IsEnabled; MainProgressBar.IsIndeterminate = !MainProgressBar.IsIndeterminate; #endregion #region Driver Installation await Task.Run(() => { string devPath = string.Empty, instanceId = string.Empty; var forceInstall = _viewModel.ForceDriverInstallation; try { uint result = 0; var flags = DifxFlags.DRIVER_PACKAGE_ONLY_IF_DEVICE_PRESENT; if (forceInstall) { flags |= DifxFlags.DRIVER_PACKAGE_FORCE; } var rebootRequired = false; var busInfPath = Path.Combine(GlobalConfiguration.AppDirectory, "System", "ScpVBus.inf"); Log.DebugFormat("ScpVBus.inf path: {0}", busInfPath); // check for existance of Scp VBus if (!Devcon.Find(Settings.Default.VirtualBusClassGuid, ref devPath, ref instanceId)) { // if not detected, install Inf-file in Windows Driver Store if (Devcon.Install(busInfPath, ref rebootRequired)) { Log.Info("Virtual Bus Driver pre-installed in Windows Driver Store successfully"); if (Devcon.Create("System", new Guid("{4D36E97D-E325-11CE-BFC1-08002BE10318}"), "root\\ScpVBus\0\0")) { Logger(DifxLog.DIFXAPI_SUCCESS, 0, "Virtual Bus Created"); _busDeviceConfigured = true; } else { Log.Fatal("Virtual Bus Device creation failed"); return; } } else { Log.FatalFormat("Virtual Bus Driver pre-installation failed with Win32 error {0}", (uint)Marshal.GetLastWin32Error()); return; } } // install Virtual Bus driver result = _installer.Install(busInfPath, flags, out rebootRequired); _reboot |= rebootRequired; if (result == 0) { _busDriverConfigured = true; } // install Xbox 360 driver if requested (Vista/7 only) if (_viewModel.IsXbox360DriverNeeded && _viewModel.InstallXbox360Driver) { string driverPath = string.Empty, os = OsInfoHelper.OsInfo; switch (OsInfoHelper.OsParse(os)) { case OsType.Vista: driverPath = Path.Combine(GlobalConfiguration.AppDirectory, @"Xbox360\driver\vista_xp\xusb21.inf"); break; case OsType.Win7: driverPath = Path.Combine(GlobalConfiguration.AppDirectory, @"Xbox360\driver\win7\xusb21.inf"); break; default: Log.WarnFormat("Microsoft Xbox 360 controller driver installation for unknown OS requested, won't install driver"); break; } if (driverPath != string.Empty) { Log.DebugFormat("{0} detected, {1} driver selected", os, driverPath); Log.InfoFormat("Installing Microsoft Xbox 360 controller driver in Windows Driver Store"); if (Devcon.Install(driverPath, ref rebootRequired)) { Log.Info("Successfully installed Microsoft Xbox 360 controller driver"); } else { Log.ErrorFormat("Couldn't install Microsoft Xbox 360 controller drivers [{0}]", driverPath); } } } if (_viewModel.InstallBluetoothDriver) { result = DriverInstaller.InstallBluetoothDongles(donglesToInstall, force: forceInstall); if (result > 0) { _bthDriverConfigured = true; } } if (_viewModel.InstallDualShock3Driver) { result = DriverInstaller.InstallDualShock3Controllers(ds3SToInstall, force: forceInstall); if (result > 0) { _ds3DriverConfigured = true; } } if (_viewModel.InstallDualShock4Driver) { result = DriverInstaller.InstallDualShock4Controllers(ds4SToInstall, force: forceInstall); if (result > 0) { _ds4DriverConfigured = true; } } if (_viewModel.InstallWindowsService) { IDictionary state = new Hashtable(); var service = new AssemblyInstaller(Path.Combine(GlobalConfiguration.AppDirectory, "ScpService.exe"), null); state.Clear(); service.UseNewContext = true; service.Install(state); service.Commit(state); if (StartService(Settings.Default.ScpServiceName)) { Logger(DifxLog.DIFXAPI_INFO, 0, Settings.Default.ScpServiceName + " Started."); } else { _reboot = true; } _scpServiceConfigured = true; } } catch (Win32Exception w32Ex) { switch (w32Ex.NativeErrorCode) { case 1073: // ERROR_SERVICE_EXISTS Log.Info("Service already exists, attempting to restart..."); StopService(Settings.Default.ScpServiceName); Log.Info("Service stopped successfully"); StartService(Settings.Default.ScpServiceName); Log.Info("Service started successfully"); break; default: Log.ErrorFormat("Win32-Error during installation: {0}", w32Ex); break; } } catch (InvalidOperationException iopex) { Log.ErrorFormat("Error during installation: {0}", iopex.Message); } catch (Exception ex) { Log.ErrorFormat("Error during installation: {0}", ex); } }); #endregion #region Post-Installation MainProgressBar.IsIndeterminate = !MainProgressBar.IsIndeterminate; InstallGrid.IsEnabled = !InstallGrid.IsEnabled; Cursor = _saved; if (_reboot) { Log.InfoFormat("[Reboot Required]"); } if (_scpServiceConfigured) { Log.Info("SCP DSx Service installed"); } if (_busDeviceConfigured) { Log.Info("Bus Device installed"); } if (_busDriverConfigured) { Log.Info("Bus Driver installed"); } if (_ds3DriverConfigured) { Log.Info("DualShock 3 USB Driver installed"); } if (_bthDriverConfigured) { Log.Info("Bluetooth Driver installed"); } if (_ds4DriverConfigured) { Log.Info("DualShock 4 USB Driver installed"); } #endregion }
private async void ViewModelOnInstallButtonClicked(object sender, EventArgs eventArgs) { #region Pre-Installation _saved = Cursor; Cursor = Cursors.Wait; InstallGrid.IsEnabled = !InstallGrid.IsEnabled; #endregion #region Driver Installation await Task.Run(() => { try { if (_viewModel.InstallWindowsService) { IDictionary state = new Hashtable(); var service = new AssemblyInstaller(Path.Combine(GlobalConfiguration.AppDirectory, "ScpService.exe"), null); state.Clear(); service.UseNewContext = true; service.Install(state); service.Commit(state); if (StartService(Settings.Default.ScpServiceName)) { Log.InfoFormat("{0} started", Settings.Default.ScpServiceName); } else { _reboot = true; } _scpServiceConfigured = true; } } catch (Win32Exception w32Ex) { switch (w32Ex.NativeErrorCode) { case 1073: // ERROR_SERVICE_EXISTS Log.Info("Service already exists, attempting to restart..."); StopService(Settings.Default.ScpServiceName); Log.Info("Service stopped successfully"); StartService(Settings.Default.ScpServiceName); Log.Info("Service started successfully"); break; default: Log.ErrorFormat("Win32-Error during installation: {0}", w32Ex); break; } } catch (InvalidOperationException iopex) { Log.ErrorFormat("Error during installation: {0}", iopex.Message); } catch (Exception ex) { Log.ErrorFormat("Error during installation: {0}", ex); } }); #endregion #region Post-Installation InstallGrid.IsEnabled = !InstallGrid.IsEnabled; Cursor = _saved; if (_reboot) { Log.InfoFormat("[Reboot Required]"); } if (_scpServiceConfigured) { Log.Info("SCP DSx Service installed"); } if (_busDeviceConfigured) { Log.Info("Bus Device installed"); } if (_busDriverConfigured) { Log.Info("Bus Driver installed"); } if (_ds3DriverConfigured) { Log.Info("DualShock 3 USB Driver installed"); } if (_bthDriverConfigured) { Log.Info("Bluetooth Driver installed"); } if (_ds4DriverConfigured) { Log.Info("DualShock 4 USB Driver installed"); } #endregion }