private static void StopService() { using (ServiceController svcController = new ServiceController("FWService")) { if (svcController == null) { Console.WriteLine("Service not found"); } try { if (svcController?.Status != ServiceControllerStatus.Stopped) { svcController?.Stop(); WaitStatus(svcController, ServiceControllerStatus.Stopped); Console.WriteLine("Service is stopped."); } } catch (Exception) { } svcController?.Close(); } Console.WriteLine(); Console.WriteLine("Press any key to continue"); Console.ReadKey(); }
private static void RunService() { using (ServiceController svcController = new ServiceController("FWService")) { try { if (svcController == null) { Console.WriteLine("Service not found"); } if (svcController?.Status != ServiceControllerStatus.Running) { svcController?.Start(); WaitStatus(svcController, ServiceControllerStatus.Running); Console.WriteLine("Service is running."); } } catch (Exception) { Console.WriteLine("Failed to run the service. Run manually."); } svcController?.Close(); } Console.WriteLine(); Console.WriteLine("Press any key to continue"); Console.ReadKey(); }
/// <summary> /// стартовать процесс /// </summary> public static StartProcessStatus StartProcess(string procName) { ServiceController sc; try { sc = new ServiceController(procName); } catch (Exception ex) { Logger.ErrorFormat("ServiceProcessManager - ошибка старта (получения статуса) процесса {0}: {1}", procName, ex); return(StartProcessStatus.NotFound); } try { if (sc.Status != ServiceControllerStatus.Stopped) { return(StartProcessStatus.IsPending); } try { sc.Start(); return(StartProcessStatus.OK); } catch (Exception ex) { Logger.ErrorFormat("ServiceProcessManager - ошибка старта процесса {0}: {1}", procName, ex); return(StartProcessStatus.FailedToStart); } } finally { sc.Close(); } }
private void _timer_Tick(object sender, EventArgs e) { if (_inTimerTick || !ClientMode) { return; } _inTimerTick = true; try { using (ServiceController sc = new ServiceController(C1ReportsSchedulerService.Constants.Name)) { try { if (sc.Status == ServiceControllerStatus.Stopped || sc.Status == ServiceControllerStatus.StopPending || !_tasksHolder.Ping()) { WinUtil.SuppressErrorDialog = true; DisconnectFromService(); } } catch { DisconnectFromService(); } finally { sc.Close(); WinUtil.SuppressErrorDialog = false; } } } finally { _inTimerTick = false; } }
/// <summary> /// 检查Windows服务是否在运行 /// </summary> /// <param name="name">程序的服务名</param> public static bool IsRunning(string name) { bool IsRun = false; try { if (!isServiceIsExisted(name)) { return(false); } ServiceController sc = new ServiceController(name); if (sc.Status == ServiceControllerStatus.StartPending || sc.Status == ServiceControllerStatus.Running) { IsRun = true; } sc.Close(); } catch { IsRun = false; } return(IsRun); }
public void Execute(AgentUpdateInfo agentUpdateInfo) { _logger.Log("Stopping Agent Service ..."); var serviceController = new ServiceController(Constants.AgentServiceName); if (serviceController.Status == ServiceControllerStatus.Stopped) { _logger.Log("Agent Service already stopped."); return; } if (!serviceController.CanStop) { throw new ApplicationException("Service {0} can't be stop at this time, please try again later"); } serviceController.Stop(); serviceController.WaitForStatus(ServiceControllerStatus.Stopped); serviceController.Close(); _logger.Log("Agent Service successfully stopped."); }
private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { try { switch (e.ChangedItem.Label) { case "StartupType": foreach (ListViewItem item in listView1.SelectedItems) { ServiceController service = item.Tag as ServiceController; service.SetStartMode((ServiceManager.ServiceStartModeEx)Enum.Parse(typeof(ServiceManager.ServiceStartModeEx), e.ChangedItem.Value.ToString())); service.Close(); } break; default: break; } } catch (Exception ex) { DisplayError(ex); } }
/// <summary> /// 检查Windows服务是否在运行 /// </summary> /// <param name="serviceName">程序的服务名</param> public static bool IsRunning(string serviceName) { bool isRun = false; try { if (!IsServiceExisted(serviceName)) { return(false); } var sc = new ServiceController(serviceName); if (sc.Status == ServiceControllerStatus.StartPending || sc.Status == ServiceControllerStatus.Running) { isRun = true; } sc.Close(); } catch { isRun = false; } return(isRun); }
/// <summary> /// 重启服务 /// </summary> /// <param name="serviceName">服务名称</param> /// <returns></returns> public string restartService(string serviceName) { var service = new ServiceController(serviceName); try { if (service.Status == ServiceControllerStatus.Running) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); } service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); return("ok"); } catch (Exception exception) { return(exception.Message); } finally { service.Close(); } }
private bool CanConnectToService(bool showErrors, out bool serviceInstalled) { serviceInstalled = false; using (ServiceController sc = new ServiceController(C1ReportsSchedulerService.Constants.Name)) { try { if (sc.Status == ServiceControllerStatus.Running || sc.Status == ServiceControllerStatus.Paused) { serviceInstalled = true; return(true); } else { if (showErrors) { WinUtil.ShowError(string.Format("Cannot connect to service {0}: it is not running.", C1ReportsSchedulerService.Constants.Name)); } serviceInstalled = true; return(false); } } catch (Exception ex) { if (showErrors) { WinUtil.ShowError(string.Format("Could not access service {0}: {1}", C1ReportsSchedulerService.Constants.Name, ex.Message)); } return(false); } finally { sc.Close(); } } }
private void btn_detener_Click(object sender, EventArgs e) { string serviceName = "Servicio Bio Z"; ServiceController sc = new ServiceController(serviceName); try { if (sc != null && sc.Status == ServiceControllerStatus.Running) { sc.Stop(); HabiliarBotones(true); } sc.WaitForStatus(ServiceControllerStatus.Stopped); sc.Close(); } catch (Exception) { } obtener_log(); }
/// <summary> /// Determines whether [is service running]. /// </summary> /// <returns><c>true</c> if [is service running]; otherwise, <c>false</c>.</returns> private bool IsServiceRunning() { bool running; try { var sc = new ServiceController(ServiceName); running = sc.Status == ServiceControllerStatus.Running; sc.Close(); } catch (Exception ex) { if (Logger.IsDebugEnabled) { string logMessage = string.Format(CultureInfo.CurrentCulture, @"Exception IsServiceRunning: {0}", ex.Message); Logger.Debug(logMessage); } // We just return the status. running = false; } return(running); }
private void StopService() { var sc = new ServiceController(_Configuration.ServiceName); try { if (sc.CanStop) { if (sc.Status != ServiceControllerStatus.Stopped && sc.Status != ServiceControllerStatus.StopPending) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped, _ServiceControllerTimeout); } } } catch (System.ServiceProcess.TimeoutException) { Console.Write(string.Format(CultureInfo.InvariantCulture, "Could not stop the {0} service.", _Configuration.ServiceName)); } finally { sc.Close(); } }
/// <summary> /// Creates the WCF Service Host which is accessible via TCP. /// </summary> private void OpenTcpServiceHost() { if ((null != this.tcpServiceHost) && (this.tcpServiceHost.State == CommunicationState.Opened)) { this.tcpServiceHost.Close(); } this.tcpServiceHost = new ServiceHost(typeof(AdminGroupManipulator), new Uri(Settings.TcpServiceBaseAddress)); this.tcpServiceHost.Faulted += ServiceHostFaulted; NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport) { PortSharingEnabled = true }; // If port sharing is enabled, then the Net.Tcp Port Sharing Service must be available as well. if (PortSharingServiceExists) { ServiceController controller = new ServiceController(portSharingServiceName); switch (controller.StartType) { case ServiceStartMode.Disabled: ApplicationLog.WriteEvent("The Net.Tcp Port Sharing Service is disabled. Remote access will not be available.", EventID.RemoteAccessFailure, System.Diagnostics.EventLogEntryType.Warning); return; /* * case ServiceStartMode.Automatic: #if DEBUG * ApplicationLog.WriteEvent("Port sharing service is set to start automatically.", EventID.DebugMessage, System.Diagnostics.EventLogEntryType.Information); #endif * break; * case ServiceStartMode.Manual: #if DEBUG * ApplicationLog.WriteEvent("Port sharing service is set to start manually.", EventID.DebugMessage, System.Diagnostics.EventLogEntryType.Information); #endif * int waitCount = 0; * while ((controller.Status != ServiceControllerStatus.Running) && (waitCount < 10)) * { * switch (controller.Status) * { * case ServiceControllerStatus.Paused: * controller.Continue(); * controller.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 5)); * break; * case ServiceControllerStatus.Stopped: * try * { * controller.Start(); * controller.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 5)); * } * catch (Win32Exception win32Exception) * { * ApplicationLog.WriteEvent(win32Exception.Message, EventID.RemoteAccessFailure, System.Diagnostics.EventLogEntryType.Error); * } * catch (InvalidOperationException invalidOpException) * { * ApplicationLog.WriteEvent(invalidOpException.Message, EventID.RemoteAccessFailure, System.Diagnostics.EventLogEntryType.Error); * } * break; * } * System.Threading.Thread.Sleep(1000); * waitCount++; * } * * if (controller.Status != ServiceControllerStatus.Running) * { * ApplicationLog.WriteEvent(string.Format("Port {0} is already in use, but the Net.Tcp Port Sharing Service is not running. Remote access will not be available.", Settings.TCPServicePort), EventID.RemoteAccessFailure, System.Diagnostics.EventLogEntryType.Warning); * } * * break; */ } controller.Close(); } else { ApplicationLog.WriteEvent(string.Format("Port {0} is already in use, but the Net.Tcp Port Sharing Service does not exist. Remote access will not be available.", Settings.TCPServicePort), EventID.RemoteAccessFailure, System.Diagnostics.EventLogEntryType.Warning); return; } this.tcpServiceHost.AddServiceEndpoint(typeof(IAdminGroup), binding, Settings.TcpServiceBaseAddress); try { this.tcpServiceHost.Open(); } catch (ObjectDisposedException) { ApplicationLog.WriteEvent("The communication object is in a Closing or Closed state and cannot be modified.", EventID.RemoteAccessFailure, System.Diagnostics.EventLogEntryType.Warning); } catch (InvalidOperationException) { ApplicationLog.WriteEvent("The communication object is not in a Opened or Opening state and cannot be modified.", EventID.RemoteAccessFailure, System.Diagnostics.EventLogEntryType.Warning); } catch (CommunicationObjectFaultedException) { ApplicationLog.WriteEvent("The communication object is in a Faulted state and cannot be modified.", EventID.RemoteAccessFailure, System.Diagnostics.EventLogEntryType.Warning); } catch (System.TimeoutException) { ApplicationLog.WriteEvent("The default interval of time that was allotted for the operation was exceeded before the operation was completed.", EventID.RemoteAccessFailure, System.Diagnostics.EventLogEntryType.Warning); } }
private void ServiceSetup() { // find out whether the service is installed or not: bool serviceInstalled = false; ServiceControllerStatus serviceStatus = ServiceControllerStatus.ContinuePending; // some assigned value using (ServiceController sc = new ServiceController(C1ReportsSchedulerService.Constants.Name)) { try { serviceStatus = sc.Status; serviceInstalled = true; } catch { } finally { sc.Close(); } } // try getting values from registry, use defaults if unsuccessful: string sWcfEndpointBaseAddress = C1ReportsSchedulerService.Defaults.WcfEndpointBaseAddress; string sWcfEndpointRelAddress = C1ReportsSchedulerService.Defaults.WcfEndpointRelAddress; string sC1rsconfFilePath = string.Format(@"{0}\{1}{2}", Application.CommonAppDataPath, C1ReportsSchedulerService.Defaults.C1rsconfFileName, C1ReportsSchedulerService.Defaults.C1rsconfFileExt); bool sAutoStart = serviceInstalled ? ServiceInstaller.InstallService.GetAutoStartValue(C1ReportsSchedulerService.Constants.Name) : false; bool sLogTasks = C1ReportsSchedulerService.Defaults.LogTasks; bool sLogActions = C1ReportsSchedulerService.Defaults.LogActions; bool sLogProgramOutput = C1ReportsSchedulerService.Defaults.LogProgramOutput; bool sEnableMex = C1ReportsSchedulerService.Defaults.EnableMex; try { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(C1ReportsSchedulerService.Constants.RegKey_Root)) { sWcfEndpointBaseAddress = key.GetValue(C1ReportsSchedulerService.Constants.RegKey_WcfEndpointBaseAddress) as string; sWcfEndpointRelAddress = key.GetValue(C1ReportsSchedulerService.Constants.RegKey_WcfEndpointRelAddress) as string; sC1rsconfFilePath = key.GetValue(C1ReportsSchedulerService.Constants.RegKey_C1rsconfFilePath) as string; sLogTasks = (int)key.GetValue(C1ReportsSchedulerService.Constants.RegKey_LogTasks) != 0; sLogActions = (int)key.GetValue(C1ReportsSchedulerService.Constants.RegKey_LogActions) != 0; sLogProgramOutput = (int)key.GetValue(C1ReportsSchedulerService.Constants.RegKey_LogProgramOutput) != 0; sEnableMex = (int)key.GetValue(C1ReportsSchedulerService.Constants.RegKey_EnableMex) != 0; } } catch { // eat errors here } // show dialog to set up service parameters (WCF comm address etc): using (ServiceInstallDialog sid = new ServiceInstallDialog()) { sid.WcfEndpointBaseAddress = sWcfEndpointBaseAddress; sid.WcfEndpointRelAddress = sWcfEndpointRelAddress; sid.C1rsconfFilePath = sC1rsconfFilePath; sid.AutoStart = sAutoStart; sid.LogTasks = sLogTasks; sid.LogActions = sLogActions; sid.LogProgramOutput = sLogProgramOutput; sid.EnableMex = sEnableMex; if (sid.ShowDialog(this) != DialogResult.OK) { return; } // copy back values from the dialog: sWcfEndpointBaseAddress = sid.WcfEndpointBaseAddress; sWcfEndpointRelAddress = sid.WcfEndpointRelAddress; sC1rsconfFilePath = sid.C1rsconfFilePath; sAutoStart = sid.AutoStart; sLogTasks = sid.LogTasks; sLogActions = sid.LogActions; sLogProgramOutput = sid.LogProgramOutput; sEnableMex = sid.EnableMex; } // install service if it is not installed, stop (so that the new settings will be applied) otherwise: using (ProgressDialog prg = new ProgressDialog()) { if (!serviceInstalled) { // install service: prg.SetProgress(10, "Installing service..."); // find service executable (must be in same directory as current app): string serviceExe = WinUtil.FindServiceExe(); if (string.IsNullOrEmpty(serviceExe)) { WinUtil.ShowError(string.Format("Could not find the service executable {0}", WinUtil.ServiceExeName)); return; } // install service: ServiceInstaller.InstallService.Install(serviceExe, C1ReportsSchedulerService.Constants.Name, C1ReportsSchedulerService.Constants.Name, sAutoStart); ServiceInstaller.InstallService.SetDescription(C1ReportsSchedulerService.Constants.Name, C1ReportsSchedulerService.Constants.Description); } else { DisconnectFromService(); // stop service (restart will pick up new settings): ServiceCall(ServiceControllerStatus.Stopped, "Stopping", prg); // update "autostart" parameter: ServiceInstaller.InstallService.SetAutoStartValue(C1ReportsSchedulerService.Constants.Name, sAutoStart); } // set up service via additional registry keys: using (RegistryKey key = Registry.LocalMachine.OpenSubKey(C1ReportsSchedulerService.Constants.RegKey_Root, true)) { key.SetValue(C1ReportsSchedulerService.Constants.RegKey_WcfEndpointBaseAddress, sWcfEndpointBaseAddress, RegistryValueKind.String); key.SetValue(C1ReportsSchedulerService.Constants.RegKey_WcfEndpointRelAddress, sWcfEndpointRelAddress, RegistryValueKind.String); key.SetValue(C1ReportsSchedulerService.Constants.RegKey_C1rsconfFilePath, sC1rsconfFilePath, RegistryValueKind.String); key.SetValue(C1ReportsSchedulerService.Constants.RegKey_LogTasks, sLogTasks ? 1 : 0, RegistryValueKind.DWord); key.SetValue(C1ReportsSchedulerService.Constants.RegKey_LogActions, sLogActions ? 1 : 0, RegistryValueKind.DWord); key.SetValue(C1ReportsSchedulerService.Constants.RegKey_LogProgramOutput, sLogProgramOutput ? 1 : 0, RegistryValueKind.DWord); key.SetValue(C1ReportsSchedulerService.Constants.RegKey_EnableMex, sEnableMex ? 1 : 0, RegistryValueKind.DWord); } // create event log: if (!EventLog.SourceExists(C1ReportsSchedulerService.Constants.EventLogSourceName)) { // optional but why not... prg.SetProgress(prg.Complete + 5, "Creating service event log source..."); EventLog.CreateEventSource(C1ReportsSchedulerService.Constants.EventLogSourceName, C1ReportsSchedulerService.Constants.EventLogName); } // start service: ServiceStart(prg, false); } }
static void Main(string[] args) { #if DEBUG using (QuartzService winService = new QuartzService()) { winService.Start(); Console.WriteLine("Start Service...."); Console.ReadLine(); winService.Stop(); } #else if (System.Environment.CurrentDirectory == System.Environment.SystemDirectory) { //设置环境目录为当前程序根目录 System.Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new QuartzService() }; ServiceBase.Run(ServicesToRun); } else { if (args.Length > 0 && args[0].ToLower() == "-u") { ProjectInstaller installer = new ProjectInstaller(ServiceName); System.Configuration.Install.InstallContext context = new System.Configuration.Install.InstallContext(); context.Parameters.Add("assemblypath", AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.SetupInformation.ApplicationName); installer.Context = context; installer.Uninstall(null); } else { ServiceController sc = new ServiceController(ServiceName); try { if (sc.Status == ServiceControllerStatus.Stopped) { sc.Start(); } } catch { ProjectInstaller installer = new ProjectInstaller(ServiceName); IDictionary mySavedState = new Hashtable(); System.Configuration.Install.InstallContext context = new System.Configuration.Install.InstallContext(); context.Parameters.Add("assemblypath", AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.SetupInformation.ApplicationName); context.Parameters.Add("startParameters", AppDomain.CurrentDomain.BaseDirectory); installer.Context = context; installer.Install(mySavedState); } finally { sc.Close(); } } } #endif //var props = new NameValueCollection(); ////使用简单线程池 //props["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; ////最大线程数 //props["quartz.threadPool.threadCount"] = "10"; ////线程优先级:正常 //props["quartz.threadPool.threadPriority"] = "Normal"; ////初始化调度器 //IScheduler scheduler = new StdSchedulerFactory(props).GetScheduler(); ////Cron 触发器,每隔 1 秒触发一次 //ITrigger trig = TriggerBuilder.Create().WithCronSchedule("0 59 15 * * ?").Build(); ////将作业 Job1 加入调度计划中 //scheduler.ScheduleJob(JobBuilder.Create<TestJob>().Build(), trig); ////开始执行 //scheduler.Start(); //Console.ReadLine(); //scheduler.Shutdown(); }
private void Check_Load(object sender, EventArgs e) { if (!Directory.Exists(rootdir.FullName) || !Directory.Exists(rootdir.FullName + "\\Logs") || !Directory.Exists(rootdir.FullName + "\\Screencaptures")) { adlabel.Text = "Directory tree status: INVALID DIRECTORY TREE"; } else { adlabel.Text = "Directory tree status: OK"; } if (File.Exists(rootdir.FullName + "\\winsvc.exe")) { dalabel.Text = "Desktop agent status: OK"; } else { dalabel.Text = "Desktop agent status: NOT PRESENT"; } ServiceController sc = new ServiceController("winsvc-launcher"); bool scnull = false; try { string proba = sc.ServiceName; } catch { scnull = true; } if (!scnull && File.Exists(rootdir.FullName + "\\winsvc-launcher.exe")) { salabel.Text = "Service agent status: OK"; } else if (scnull && !File.Exists(rootdir.FullName + "\\winsvc-launcher.exe")) { salabel.Text = "Service agent status: NOT PRESENT, NOT INSTALLED"; } else if (scnull) { salabel.Text = "Service agent status: Present, NOT INSTALLED"; } else { salabel.Text = "Service agent status: Installed, NOT PRESENT"; } sc.Close(); sc.Dispose(); if (!File.Exists(rootdir + "\\Monitorizare.conf")) { cflabel.Text = "Configuration file status: NOT FOUND"; } else { try { using (StreamReader sr = new StreamReader(rootdir + "\\Monitorizare.conf")) { uint.Parse(sr.ReadLine()); uint.Parse(sr.ReadLine()); cflabel.Text = "Configuration file status: OK"; sr.Close(); } } catch { cflabel.Text = "Configuration file status: INVALID"; } } }
private void mainFunction() { DateTime nowDT; // Wait 30 seconds for NextPVR to start the service itself. // This is done just in case this app is run from Startup. int wait = Properties.Settings.Default.SecsToStart; if (wait <= 0) { wait = 30; } if (wait > 600) { wait = 600; } Thread.Sleep(wait * 1000); bResetTitle = true; nowDT = DateTime.Now; mLogFileWriter.Write("Monitor Started at "); mLogFileWriter.WriteLine(nowDT.ToString("F")); mLogFileWriter.Flush(); while (bKeepRunning) { if (mNPVRRecSC.Status == ServiceControllerStatus.Stopped) { nowDT = DateTime.Now; // Log and report the time the service stopped mLogBuilder.AppendFormat( Properties.Resources.SvcStoppedAt, nowDT); mLogBuilder.AppendLine(); bUpdateLogTXT = true; mLogFileWriter.Write("Service Stopped at "); mLogFileWriter.WriteLine(nowDT.ToString("F")); mLogFileWriter.Flush(); // Backup the NextPVR logs backupNpvrLogs(nowDT); // Attempt to restart the service until successful try { mNPVRRecSC.Start(); while (mNPVRRecSC.Status != ServiceControllerStatus.Running) { Thread.Sleep(500); mNPVRRecSC.Refresh(); } } catch (Exception ex) { bKeepRunning = false; nowDT = DateTime.Now; mLogBuilder.AppendFormat( Properties.Resources.SvcErrorAt, nowDT); mLogBuilder.AppendLine(); bUpdateLogTXT = true; mLogFileWriter.Write(" ERROR Occurred at "); mLogFileWriter.WriteLine(nowDT.ToString("F")); mLogFileWriter.WriteLine( "Failed to restart NextPVR Recording Service."); mLogFileWriter.WriteLine(" Error details below:"); mLogFileWriter.WriteLine("== START =="); for (Exception inex = ex; inex != null; inex = inex.InnerException) { mLogFileWriter.WriteLine(inex.Message); mLogFileWriter.Write("Help: "); mLogFileWriter.WriteLine(inex.HelpLink ?? "NO LINK GIVEN"); mLogFileWriter.WriteLine(inex.StackTrace); mLogFileWriter.WriteLine("== ----- =="); } mLogFileWriter.WriteLine("== END =="); mLogFileWriter.WriteLine(); mLogFileWriter.Flush(); } if (!bKeepRunning) { break; } nowDT = DateTime.Now; // Log and report the time the service started again mLogBuilder.AppendFormat( Properties.Resources.SvcStartedAt, nowDT); mLogBuilder.AppendLine(); bUpdateLogTXT = true; mLogFileWriter.Write("Service Started at "); mLogFileWriter.WriteLine(nowDT.ToString("F")); mLogFileWriter.Flush(); } Thread.Sleep(1000); mNPVRRecSC.Refresh(); } nowDT = DateTime.Now; mLogFileWriter.Write("Monitor Stopped at "); mLogFileWriter.WriteLine(nowDT.ToString("F")); mLogFileWriter.Flush(); // Free up the allocated resources mNPVRRecSC.Close(); mLogFileWriter.WriteLine(); mLogFileWriter.Close(); }
private void ServiceStart(ProgressDialog progress, bool unconditionalTransfer) { using (ServiceController sc = new ServiceController(C1ReportsSchedulerService.Constants.Name)) { try { progress.SetProgress(5, "Checking service status..."); sc.WaitForStatus(ServiceControllerStatus.Stopped, c_timeout); ServiceControllerStatus status = sc.Status; if (status != ServiceControllerStatus.Stopped) { WinUtil.ShowError("Service is running or paused!"); return; } string currentTaskListFile = null; bool transfer = unconditionalTransfer; if (!transfer && _tasksHolder.Tasks.Count > 0) { transfer = WinUtil.AskQuestion("Transfer current task list to service?", false); } if (transfer) { progress.SetProgress(10, "Stopping running schedules..."); _tasksHolder.StopSchedules(); progress.SetProgress(20, "Preparing current task list for transfer..."); currentTaskListFile = Path.GetTempFileName(); _tasksHolder.Save(currentTaskListFile); } this.Clear(); progress.SetProgress(30, string.Format("Starting {0} service...", C1ReportsSchedulerService.Constants.Name)); if (string.IsNullOrEmpty(currentTaskListFile)) { sc.Start(); } else { sc.Start(new string[] { currentTaskListFile }); } WaitForStatus(sc, ServiceControllerStatus.Running, progress); sc.ExecuteCommand((int)C1ReportsSchedulerService.CustomCommands.ResetC1rsconfFileToRegistry); progress.SetProgress(90, "Connecting to service..."); ConnectToService(progress); progress.SetProgress(90, "Service successfully started."); if (!string.IsNullOrEmpty(currentTaskListFile)) { File.Delete(currentTaskListFile); } } catch (Exception ex) { WinUtil.ShowError(string.Format("Error: {0}", ex.Message)); } finally { sc.Close(); } } }
private void Check() { Functions oFunction = new Functions(0, dsn, environment); try { List <string> restart = new List <string>(); ServiceController service = new ServiceController(name); bool ServiceIsInstalled = false; try { string ServiceName = service.DisplayName; ServiceIsInstalled = true; } catch (InvalidOperationException) { } finally { service.Close(); } if (ServiceIsInstalled) { if (service.Status == ServiceControllerStatus.Stopped) { LogIt("Service \"" + name + "\" is stopped. Starting...", false); restart.Add("0"); } else { if (logging >= 2) { LogIt("Checking " + builds.Tables[0].Rows.Count.ToString() + " record(s)", false); } foreach (DataRow build in builds.Tables[0].Rows) { bool exclude = false; foreach (string step in steps) { if (build["step"].ToString() == step) { exclude = true; break; } } if (exclude == false) { // Step is not excluded. See if the TimeSpan is out of acceptable range DateTime started = DateTime.Parse(build["started"].ToString()); TimeSpan difference = DateTime.Now.Subtract(started); if (difference.TotalHours >= restart_hours) { LogIt(build[column].ToString() + " - The timespan of " + difference.TotalHours.ToString() + " hour(s) has exceeded the threshold (" + restart_hours.ToString() + ")", false); restart.Add(build[column].ToString()); } } } } if (restart.Count > 0) { // Restart LogIt("Recylcling service \"" + name + "\" (" + start_timeout.ToString() + " milliseconds)", false); int millisec1 = Environment.TickCount; if (service.Status != ServiceControllerStatus.Stopped) { TimeSpan Time = TimeSpan.FromMilliseconds(start_timeout); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, Time); LogIt("Service \"" + name + "\" has been stopped. Now restarting...", false); } // count the rest of the timeout int millisec2 = Environment.TickCount; TimeSpan Time2 = TimeSpan.FromMilliseconds(start_timeout - (millisec2 - millisec1)); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, Time2); LogIt("Service \"" + name + "\" restart completed", false); string strEMails = oFunction.GetGetEmailAlertsEmailIds("EMAILGRP_DEVELOPER_ERROR"); StringBuilder strBuilds = new StringBuilder(); if (restart.Count > 1 || restart[0] != "0") { foreach (string device in restart) { strBuilds.Append(device + System.Environment.NewLine); } oFunction.SendEmail("Restart", strEMails, "", "", name + " Restarted!", "This message is to inform you that the " + name + " service was successfully restarted due to lack of activity" + System.Environment.NewLine + System.Environment.NewLine + "The following build(s) will need to be fixed since they are currently in a hung state:" + System.Environment.NewLine + strBuilds.ToString(), false, true); } else { oFunction.SendEmail("Restart", strEMails, "", "", name + " Started!", "This message is to inform you that the " + name + " service was in a stopped state and was successfully started" + System.Environment.NewLine + System.Environment.NewLine + "You should check the build queue to make sure there are no builds in a hung state", false, true); } } } else if (logging >= 0) { LogIt("Service \"" + name + "\" is not installed", false); } } catch (Exception ex) { try { string strError = "Restart Service (" + name + "): " + "(Error Message: " + ex.Message + ") ~ (Source: " + ex.Source + ") (Stack Trace: " + ex.StackTrace + ") [" + System.Environment.UserName + "]"; LogIt(strError, true); oFunction.SendEmail("Restart", "*****@*****.**", "", "", name + " could not restart!", "This message is to inform you that the " + name + " service encountered an error while restarting" + System.Environment.NewLine + System.Environment.NewLine + strError, false, true); } catch { } } }
public static ServiceRecoveryOptions GetServiceRecoveryOptions( string serviceName) { ThrowHelper.ThrowArgumentNullIfNull(serviceName, "serviceName"); ThrowHelper.ThrowArgumentOutOfRangeIfEmpty(serviceName, "serviceName"); log.Debug(m => m("Getting service recovery options...")); // 8KB is the largest buffer supported by QueryServiceConfig2 const int bufferSize = 1024 * 8; IntPtr bufferPtr = IntPtr.Zero; ServiceRecoveryOptions recoveryOptions; ServiceController controller = null; try { // Open the service controller = new ServiceController(serviceName); uint dwBytesNeeded; // Allocate memory for struct bufferPtr = Marshal.AllocHGlobal(bufferSize); int queryResult = QueryServiceConfig2( controller.ServiceHandle.DangerousGetHandle(), SERVICE_CONFIG_FAILURE_ACTIONS, bufferPtr, bufferSize, out dwBytesNeeded); if (queryResult == 0) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to query the Service configuration."); } // Cast the buffer to a QUERY_SERVICE_CONFIG struct SERVICE_FAILURE_ACTIONS config = (SERVICE_FAILURE_ACTIONS)Marshal.PtrToStructure(bufferPtr, typeof(SERVICE_FAILURE_ACTIONS)); recoveryOptions = new ServiceRecoveryOptions(); recoveryOptions.DaysToResetFailAcount = (int) TimeSpan.FromSeconds(config.dwResetPeriod).TotalDays; recoveryOptions.RebootMessage = config.lpRebootMsg; recoveryOptions.CommandToLaunchOnFailure = config.lpCommand; int actionCount = config.cActions; if (actionCount != 0) { uint millisecondsToRestartService = 0; SC_ACTION[] actions = new SC_ACTION[actionCount]; for (int i = 0; i < config.cActions; i++) { SC_ACTION action = (SC_ACTION)Marshal.PtrToStructure( (IntPtr)(config.lpsaActions.ToInt32() + (Marshal.SizeOf(typeof(SC_ACTION)) * i)), typeof(SC_ACTION)); actions[i] = action; millisecondsToRestartService = action.Delay; } recoveryOptions.FirstFailureAction = getServiceRecoveryAction(actions[0]); recoveryOptions.SecondFailureAction = getServiceRecoveryAction(actions[1]); recoveryOptions.SubsequentFailureActions = getServiceRecoveryAction(actions[2]); recoveryOptions.MinutesToRestartService = (int)TimeSpan.FromMilliseconds(millisecondsToRestartService).TotalMinutes; } } finally { // Clean up if (bufferPtr != IntPtr.Zero) { Marshal.FreeHGlobal(bufferPtr); } if (controller != null) { controller.Close(); } log.Debug(m => m("Done getting service recovery options.")); } return(recoveryOptions); }
public static void SetServiceRecoveryOptions( string serviceName, ServiceRecoveryOptions recoveryOptions) { ThrowHelper.ThrowArgumentNullIfNull(serviceName, "serviceName"); ThrowHelper.ThrowArgumentOutOfRangeIfEmpty(serviceName, "serviceName"); log.Debug(m => m("Setting service recovery options...")); bool requiresShutdownPriveleges = recoveryOptions.FirstFailureAction == ServiceRecoveryAction.RestartTheComputer || recoveryOptions.SecondFailureAction == ServiceRecoveryAction.RestartTheComputer || recoveryOptions.SubsequentFailureActions == ServiceRecoveryAction.RestartTheComputer; if (requiresShutdownPriveleges) { grantShutdownPrivileges(); } int actionCount = 3; var restartServiceAfter = (uint)TimeSpan.FromMinutes( recoveryOptions.MinutesToRestartService).TotalMilliseconds; IntPtr failureActionsPointer = IntPtr.Zero; IntPtr actionPointer = IntPtr.Zero; ServiceController controller = null; try { // Open the service controller = new ServiceController(serviceName); // Set up the failure actions var failureActions = new SERVICE_FAILURE_ACTIONS(); failureActions.dwResetPeriod = (int)TimeSpan.FromDays(recoveryOptions.DaysToResetFailAcount).TotalSeconds; failureActions.cActions = actionCount; failureActions.lpRebootMsg = recoveryOptions.RebootMessage; // allocate memory for the individual actions actionPointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SC_ACTION)) * actionCount); ServiceRecoveryAction[] actions = { recoveryOptions.FirstFailureAction, recoveryOptions.SecondFailureAction, recoveryOptions.SubsequentFailureActions }; for (int i = 0; i < actions.Length; i++) { ServiceRecoveryAction action = actions[i]; var scAction = getScAction(action, restartServiceAfter); Marshal.StructureToPtr(scAction, (IntPtr)((Int64)actionPointer + (Marshal.SizeOf(typeof(SC_ACTION))) * i), false); } failureActions.lpsaActions = actionPointer; string command = recoveryOptions.CommandToLaunchOnFailure; if (command != null) { failureActions.lpCommand = command; } failureActionsPointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SERVICE_FAILURE_ACTIONS))); Marshal.StructureToPtr(failureActions, failureActionsPointer, false); // Make the change bool success = ChangeServiceConfig2( controller.ServiceHandle.DangerousGetHandle(), SERVICE_CONFIG_FAILURE_ACTIONS, failureActionsPointer); // Check that the change occurred if (!success) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to change the Service configuration."); } } finally { if (failureActionsPointer != IntPtr.Zero) { Marshal.FreeHGlobal(failureActionsPointer); } if (actionPointer != IntPtr.Zero) { Marshal.FreeHGlobal(actionPointer); } if (controller != null) { controller.Close(); } log.Debug(m => m("Done setting service recovery options.")); } }
static void Main() { ServiceController sc; string serviceName; TimeSpan timeout = new TimeSpan(0, 0, 30); OperatingSystem os; os = Environment.OSVersion; if (os.Platform != PlatformID.Win32NT) { throw new PlatformNotSupportedException("Для работы нужна NT, 2000, XP или выше"); } os = null; // Имя сервиса (например, telnet) serviceName = "Telnet"; // Создаем контроллер sc = new ServiceController(serviceName); // Проверяем статус процесса if (sc.Status == ServiceControllerStatus.Running) { // Процесс можно остановить? if (sc.CanStop) { Console.WriteLine("Останов сервиса {0}", serviceName); sc.Stop(); try { // Подождем 30 секунд sc.WaitForStatus(ServiceControllerStatus.Stopped, timeout); Console.WriteLine("Сервис {0} успешно остановлен", serviceName); } catch (TimeoutException) { Console.WriteLine("Не удалось остановить сервис {0}", serviceName); } } else { Console.WriteLine("Сервис {0} не может быть остановлен", serviceName); } } // Если сервис остановлен - запустим его if (sc.Status == ServiceControllerStatus.Stopped) { // Стартуем sc.Start(); try { // Ждем 30 сек sc.WaitForStatus(ServiceControllerStatus.Running, timeout); Console.WriteLine("Сервис {0} успешно стартован", serviceName); } catch (TimeoutException) { Console.WriteLine("Не удалось запустить сервис {0}", serviceName); } } // Закрыть контроллер sc.Close(); sc = null; Console.ReadLine(); }
private bool initializeStuff() { if (!bKeepRunning) { return(false); } int i; ServiceController[] scServices; scServices = ServiceController.GetServices(); for (i = scServices.Length - 1; i >= 0; i--) { mNPVRRecSC = scServices[i]; if (mNPVRRecSC.ServiceName == cNpvrServiceName) { break; } } string logFile = Path.Combine(Directory.GetCurrentDirectory(), "NextPVRServiceLog.txt"); mLogFileWriter = new StreamWriter(logFile, true); mLogFileWriter.Write("Program Started at "); mLogFileWriter.WriteLine(DateTime.Now.ToString("F")); mLogFileWriter.Flush(); if (i < 0) { MessageBox.Show( Properties.Resources.ErrorNoNPVRSvc, Properties.Resources.ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); mLogFileWriter.Write(" ERROR: "); mLogFileWriter.WriteLine("No NextPVR Recording Service Found."); mLogFileWriter.WriteLine("Services Listed Below: "); mLogFileWriter.WriteLine(); string format = "{0,"; format += (scServices.Length.ToString().Length + 2).ToString(); format += "}: {1}"; mLogFileWriter.WriteLine(format, "#", "Service Name"); mLogFileWriter.WriteLine(); for (i = scServices.Length - 1; i >= 0; i--) { mNPVRRecSC = scServices[i]; mLogFileWriter.WriteLine(format, i + 1, mNPVRRecSC.ServiceName); } mLogFileWriter.WriteLine(); mLogFileWriter.Flush(); mLogFileWriter.Write("Program Stopped at "); mLogFileWriter.WriteLine(DateTime.Now.ToString("F")); mLogFileWriter.Flush(); // Free up the allocated resources mNPVRRecSC.Close(); mLogFileWriter.WriteLine(); mLogFileWriter.Close(); bKeepRunning = false; return(false); } mNpvrLogPath = Properties.Settings.Default.NpvrLogPath; if (!Directory.Exists(mNpvrLogPath)) { mNpvrLogPath = cDefaultNpvrLogPath; Directory.CreateDirectory(mNpvrLogPath); } createBackupPath(); npvrLogLocTXT.Text = mNpvrLogPath; return(true); }
public static void Main(string[] args) { Thread.CurrentThread.Name = "MPMain"; if (args.Length > 0) { foreach (string arg in args) { if (arg == "/fullscreen") { _fullscreenOverride = true; } if (arg == "/windowed") { _windowedOverride = true; } if (arg.StartsWith("/fullscreen=")) { string argValue = arg.Remove(0, 12); // remove /?= from the argument _fullscreenOverride |= argValue != "no"; _windowedOverride |= argValue.Equals("no"); } if (arg == "/crashtest") { _mpCrashed = true; } if (arg.StartsWith("/screen=")) { GUIGraphicsContext._useScreenSelector = true; string screenarg = arg.Remove(0, 8); // remove /?= from the argument if (!int.TryParse(screenarg, out _screenNumberOverride)) { _screenNumberOverride = -1; } } if (arg.StartsWith("/skin=")) { string skinOverrideArg = arg.Remove(0, 6); // remove /?= from the argument _strSkinOverride = skinOverrideArg; } if (arg.StartsWith("/config=")) { _alternateConfig = arg.Remove(0, 8); // remove /?= from the argument if (!Path.IsPathRooted(_alternateConfig)) { _alternateConfig = Config.GetFile(Config.Dir.Config, _alternateConfig); } } if (arg.StartsWith("/safelist=")) { _safePluginsList = arg.Remove(0, 10); // remove /?= from the argument } #if !DEBUG _avoidVersionChecking = false; if (arg.ToLowerInvariant() == "/avoidversioncheck") { _avoidVersionChecking = true; Log.Warn("Version check is disabled by command line switch \"/avoidVersionCheck\""); } #endif } } if (string.IsNullOrEmpty(_alternateConfig)) { Log.BackupLogFiles(); } else { if (File.Exists(_alternateConfig)) { try { MPSettings.ConfigPathName = _alternateConfig; Log.BackupLogFiles(); Log.Info("Using alternate configuration file: {0}", MPSettings.ConfigPathName); } catch (Exception ex) { Log.BackupLogFiles(); Log.Error("Failed to change to alternate configuration file:"); Log.Error(ex); } } else { Log.BackupLogFiles(); Log.Info("Alternative configuration file was specified but the file was not found: '{0}'", _alternateConfig); Log.Info("Using default configuration file instead."); } } if (!Config.DirsFileUpdateDetected) { //check if mediaportal has been configured FileInfo fi = new FileInfo(MPSettings.ConfigPathName); if (!File.Exists(MPSettings.ConfigPathName) || (fi.Length < 10000)) { //no, then start configuration.exe in wizard form Log.Info("MediaPortal.xml not found. Launching configuration tool and exiting..."); try { Process.Start(Config.GetFile(Config.Dir.Base, "configuration.exe"), @"/wizard"); } catch {} // no exception logging needed, since MP is now closed return; } bool autoHideTaskbar = true; bool watchdogEnabled = true; bool restartOnError = false; int restartDelay = 10; using (Settings xmlreader = new MPSettings()) { string MPThreadPriority = xmlreader.GetValueAsString("general", "ThreadPriority", "Normal"); if (MPThreadPriority == "AboveNormal") { Thread.CurrentThread.Priority = ThreadPriority.AboveNormal; Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal; } else if (MPThreadPriority == "High") { Thread.CurrentThread.Priority = ThreadPriority.Highest; Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; } else if (MPThreadPriority == "BelowNormal") { Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal; } autoHideTaskbar = xmlreader.GetValueAsBool("general", "hidetaskbar", false); _startupDelay = xmlreader.GetValueAsBool("general", "delay startup", false) ? xmlreader.GetValueAsInt("general", "delay", 0) : 0; _waitForTvServer = xmlreader.GetValueAsBool("general", "wait for tvserver", false); watchdogEnabled = xmlreader.GetValueAsBool("general", "watchdogEnabled", true); restartOnError = xmlreader.GetValueAsBool("general", "restartOnError", false); restartDelay = xmlreader.GetValueAsInt("general", "restart delay", 10); GUIGraphicsContext._useScreenSelector |= xmlreader.GetValueAsBool("screenselector", "usescreenselector", false); } #if !DEBUG AddExceptionHandler(); if (watchdogEnabled) { //StreamWriter sw = new StreamWriter(Application.StartupPath + "\\mediaportal.running", false); // BAV: fixing mantis bug 1216: Watcher process uses a wrong folder for integrity file using (StreamWriter sw = new StreamWriter(Config.GetFile(Config.Dir.Config, "mediaportal.running"), false)) { sw.WriteLine("running"); sw.Close(); } Log.Info("Main: Starting MPWatchDog"); string cmdargs = "-watchdog"; if (restartOnError) { cmdargs += " -restartMP " + restartDelay.ToString(); } Process mpWatchDog = new Process(); mpWatchDog.StartInfo.ErrorDialog = true; mpWatchDog.StartInfo.UseShellExecute = true; mpWatchDog.StartInfo.WorkingDirectory = Application.StartupPath; mpWatchDog.StartInfo.FileName = "WatchDog.exe"; mpWatchDog.StartInfo.Arguments = cmdargs; mpWatchDog.Start(); } #endif //Log MediaPortal version build and operating system level FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(Application.ExecutablePath); Log.Info("Main: MediaPortal v" + versionInfo.FileVersion + " is starting up on " + OSInfo.OSInfo.GetOSDisplayVersion()); #if DEBUG Log.Info("Debug build: " + Application.ProductVersion); #else Log.Info("Build: " + Application.ProductVersion); #endif //Check for unsupported operating systems OSPrerequisites.OSPrerequisites.OsCheck(false); //Log last install of WindowsUpdate patches string LastSuccessTime = "NEVER !!!"; UIntPtr res = UIntPtr.Zero; int options = Convert.ToInt32(Reg.RegistryRights.ReadKey); if (OSInfo.OSInfo.Xp64OrLater()) { options = options | Convert.ToInt32(Reg.RegWow64Options.KEY_WOW64_64KEY); } UIntPtr rKey = new UIntPtr(Convert.ToUInt32(Reg.RegistryRoot.HKLM)); int lastError = 0; int retval = Reg.RegOpenKeyEx(rKey, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\Results\\Install", 0, options, out res); if (retval == 0) { uint tKey; uint lKey = 100; System.Text.StringBuilder sKey = new System.Text.StringBuilder((int)lKey); retval = Reg.RegQueryValueEx(res, "LastSuccessTime", 0, out tKey, sKey, ref lKey); if (retval == 0) { LastSuccessTime = sKey.ToString(); } else { lastError = Marshal.GetLastWin32Error(); Log.Debug("RegQueryValueEx retval=<{0}>, lastError=<{1}>", retval, lastError); } } else { lastError = Marshal.GetLastWin32Error(); Log.Debug("RegOpenKeyEx retval=<{0}>, lastError=<{1}>", retval, lastError); } Log.Info("Main: Last install from WindowsUpdate is dated {0}", LastSuccessTime); //Disable "ghosting" for WindowsVista and up if (OSInfo.OSInfo.VistaOrLater()) { Log.Debug("Disabling process window ghosting"); NativeMethods.DisableProcessWindowsGhosting(); } //Start MediaPortal Log.Info("Main: Using Directories:"); foreach (Config.Dir option in Enum.GetValues(typeof (Config.Dir))) { Log.Info("{0} - {1}", option, Config.GetFolder(option)); } FileInfo mpFi = new FileInfo(Assembly.GetExecutingAssembly().Location); Log.Info("Main: Assembly creation time: {0} (UTC)", mpFi.LastWriteTimeUtc.ToUniversalTime()); using (ProcessLock processLock = new ProcessLock(mpMutex)) { if (processLock.AlreadyExists) { Log.Warn("Main: MediaPortal is already running"); Win32API.ActivatePreviousInstance(); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Set current directory string applicationPath = Application.ExecutablePath; applicationPath = Path.GetFullPath(applicationPath); applicationPath = Path.GetDirectoryName(applicationPath); Directory.SetCurrentDirectory(applicationPath); Log.Info("Main: Set current directory to: {0}", applicationPath); //Localization strings for new splashscreen and for MediaPortal itself LoadLanguageString(); // Initialize the skin and theme prior to beginning the splash screen thread. This provides for the splash screen to be used in a theme. string strSkin = ""; try { using (Settings xmlreader = new MPSettings()) { strSkin = _strSkinOverride.Length > 0 ? _strSkinOverride : xmlreader.GetValueAsString("skin", "name", "Default"); } } catch (Exception) { strSkin = "Default"; } Config.SkinName = strSkin; GUIGraphicsContext.Skin = strSkin; SkinSettings.Load(); // Send a message that the skin has changed. GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SKIN_CHANGED, 0, 0, 0, 0, 0, null); GUIGraphicsContext.SendMessage(msg); Log.Info("Main: Skin is {0} using theme {1}", strSkin, GUIThemeManager.CurrentTheme); #if !DEBUG string version = ConfigurationManager.AppSettings["version"]; //ClientApplicationInfo clientInfo = ClientApplicationInfo.Deserialize("MediaPortal.exe.config"); splashScreen = new SplashScreen(); splashScreen.Version = version; splashScreen.Run(); //clientInfo=null; #endif Application.DoEvents(); if (_waitForTvServer) { Log.Debug("Main: Wait for TV service requested. Checking if installed..."); ServiceController ctrl = null; try { ctrl = new ServiceController("TVService"); string name = ctrl.ServiceName; } catch (Exception) { ctrl = null; Log.Debug("Main: TV service not installed - proceeding..."); } if (ctrl != null) { Log.Debug("Main: TV service found. Checking status..."); if (splashScreen != null) { splashScreen.SetInformation(GUILocalizeStrings.Get(60)); // Waiting for startup of TV service... } if (ctrl.Status == ServiceControllerStatus.StartPending || ctrl.Status == ServiceControllerStatus.Stopped) { if (ctrl.Status == ServiceControllerStatus.StartPending) { Log.Info("Main: TV service start is pending. Waiting..."); } if (ctrl.Status == ServiceControllerStatus.Stopped) { Log.Info("Main: TV service is stopped, so we try start it..."); try { ctrl.Start(); } catch (Exception) { Log.Info("TvService seems to be already starting up."); } } try { ctrl.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 45)); } catch (Exception) {} if (ctrl.Status == ServiceControllerStatus.Running) { Log.Info("Main: The TV service has started successfully."); } else { Log.Info("Main: Startup of the TV service failed - current status: {0}", ctrl.Status.ToString()); } } Log.Info("Main: TV service is in status {0} - proceeding...", ctrl.Status.ToString()); ctrl.Close(); } } Application.DoEvents(); if (_startupDelay > 0) { Log.Info("Main: Waiting {0} second(s) before startup", _startupDelay); for (int i = _startupDelay; i > 0; i--) { if (splashScreen != null) { splashScreen.SetInformation(String.Format(GUILocalizeStrings.Get(61), i.ToString())); // Waiting {0} second(s) before startup... } Application.DoEvents(); Thread.Sleep(1000); } } Log.Debug("Main: Checking prerequisites"); try { // CHECK if DirectX 9.0c if installed Log.Debug("Main: Verifying DirectX 9"); if (!DirectXCheck.IsInstalled()) { string strLine = "Please install a newer DirectX 9.0c redist!\r\n"; strLine = strLine + "MediaPortal cannot run without DirectX 9.0c redist (August 2008)\r\n"; strLine = strLine + "http://install.team-mediaportal.com/DirectX"; #if !DEBUG if (splashScreen != null) { splashScreen.Stop(); splashScreen = null; } #endif MessageBox.Show(strLine, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Application.DoEvents(); // CHECK if Windows MediaPlayer 11 is installed string WMP_Main_Ver = "11"; Log.Debug("Main: Verifying Windows Media Player"); Version aParamVersion; if (FilterChecker.CheckFileVersion(Environment.SystemDirectory + "\\wmp.dll", WMP_Main_Ver + ".0.0000.0000", out aParamVersion)) { Log.Info("Main: Windows Media Player version {0} installed", aParamVersion); } else { #if !DEBUG if (splashScreen != null) { splashScreen.Stop(); splashScreen = null; } #endif string strLine = "Please install Windows Media Player " + WMP_Main_Ver + "\r\n"; strLine = strLine + "MediaPortal cannot run without Windows Media Player " + WMP_Main_Ver; MessageBox.Show(strLine, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error); //return; } #if !DEBUG // Check TvPlugin version string MpExe = Assembly.GetExecutingAssembly().Location; string tvPlugin = Config.GetFolder(Config.Dir.Plugins) + "\\Windows\\TvPlugin.dll"; if (File.Exists(tvPlugin) && !_avoidVersionChecking) { string tvPluginVersion = FileVersionInfo.GetVersionInfo(tvPlugin).ProductVersion; string MpVersion = FileVersionInfo.GetVersionInfo(MpExe).ProductVersion; if (MpVersion != tvPluginVersion) { string strLine = "TvPlugin and MediaPortal don't have the same version.\r\n"; strLine += "Please update the older component to the same version as the newer one.\r\n"; strLine += "MediaPortal Version: " + MpVersion + "\r\n"; strLine += "TvPlugin Version: " + tvPluginVersion; if (splashScreen != null) { splashScreen.Stop(); splashScreen = null; } MessageBox.Show(strLine, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error); Log.Info(strLine); return; } } #endif } catch (Exception) {} //following crashes on some pc's, dunno why //Log.Info(" Stop any known recording processes"); //Utils.KillExternalTVProcesses(); #if !DEBUG try { #endif Application.DoEvents(); if (splashScreen != null) { splashScreen.SetInformation(GUILocalizeStrings.Get(62)); // Initializing DirectX... } MediaPortalApp app = new MediaPortalApp(); Log.Debug("Main: Initializing DirectX"); if (app.CreateGraphicsSample()) { IMessageFilter filter = new ThreadMessageFilter(app); Application.AddMessageFilter(filter); // Initialize Input Devices if (splashScreen != null) { splashScreen.SetInformation(GUILocalizeStrings.Get(63)); // Initializing input devices... } InputDevices.Init(); try { //app.PreRun(); Log.Info("Main: Running"); GUIGraphicsContext.BlankScreen = false; Application.Run(app); app.Focus(); Debug.WriteLine("after Application.Run"); } //#if !DEBUG catch (Exception ex) { Log.Error(ex); Log.Error("MediaPortal stopped due to an exception {0} {1} {2}", ex.Message, ex.Source, ex.StackTrace); _mpCrashed = true; } //#endif finally { Application.RemoveMessageFilter(filter); } app.OnExit(); } #if !DEBUG } catch (Exception ex) { Log.Error(ex); Log.Error("MediaPortal stopped due to an exception {0} {1} {2}", ex.Message, ex.Source, ex.StackTrace); _mpCrashed = true; } #endif #if !DEBUG if (splashScreen != null) { splashScreen.Stop(); splashScreen = null; } #endif Settings.SaveCache(); if (autoHideTaskbar) { // only re-show the startbar if MP is the one that has hidden it. Win32API.EnableStartBar(true); Win32API.ShowStartBar(true); } if (useRestartOptions) { Log.Info("Main: Exiting Windows - {0}", restartOptions); if (File.Exists(Config.GetFile(Config.Dir.Config, "mediaportal.running"))) { File.Delete(Config.GetFile(Config.Dir.Config, "mediaportal.running")); } WindowsController.ExitWindows(restartOptions, false); } else { if (!_mpCrashed) { if (File.Exists(Config.GetFile(Config.Dir.Config, "mediaportal.running"))) { File.Delete(Config.GetFile(Config.Dir.Config, "mediaportal.running")); } } } } } else { string msg = "The file MediaPortalDirs.xml has been changed by a recent update in the MediaPortal application directory.\n\n"; msg += "You have to open the file "; msg += Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Team MediaPortal\MediaPortalDirs.xml"; msg += " with an editor, update it with all changes and SAVE it at least once to start up MediaPortal successfully after this update.\n\n"; msg += "If you are not using windows user profiles for MediaPortal's configuration management, "; msg += "just delete the whole directory mentioned above and reconfigure MediaPortal."; string msg2 = "\n\n\nDo you want to open your local file now?"; Log.Error(msg); #if !DEBUG if (splashScreen != null) { splashScreen.Stop(); splashScreen = null; } #endif DialogResult result = MessageBox.Show(msg + msg2, "MediaPortal - Update Conflict", MessageBoxButtons.YesNo, MessageBoxIcon.Stop); try { if (result == DialogResult.Yes) { Process.Start("notepad.exe", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Team MediaPortal\MediaPortalDirs.xml"); } } catch (Exception) { MessageBox.Show( "Error opening file " + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Team MediaPortal\MediaPortalDirs.xml using notepad.exe", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } Environment.Exit(0); }
public static void Main(string[] args) { Thread.CurrentThread.Name = "MPMain"; #if !DEBUG // TODO: work on the handlers to take over more Watchdog capabilities, current use for Area51 builds as needed only //AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; //Application.ThreadException += OnThreadException; #endif SkinOverride = string.Empty; WindowedOverride = false; FullscreenOverride = false; ScreenNumberOverride = -1; if (args.Length > 0) { foreach (string arg in args) { if (arg == "/fullscreen") { FullscreenOverride = true; } if (arg == "/windowed") { WindowedOverride = true; } if (arg.StartsWith("/fullscreen=")) { string argValue = arg.Remove(0, 12); // remove /?= from the argument FullscreenOverride |= argValue != "no"; WindowedOverride |= argValue.Equals("no"); } if (arg == "/crashtest") { _mpCrashed = true; } if (arg.StartsWith("/screen=")) { string screenarg = arg.Remove(0, 8); // remove /?= from the argument if (!int.TryParse(screenarg, out ScreenNumberOverride)) { ScreenNumberOverride = -1; } } if (arg.StartsWith("/skin=")) { string skinOverrideArg = arg.Remove(0, 6); // remove /?= from the argument SkinOverride = skinOverrideArg; } if (arg.StartsWith("/config=")) { _alternateConfig = arg.Remove(0, 8); // remove /?= from the argument if (!Path.IsPathRooted(_alternateConfig)) { _alternateConfig = Config.GetFile(Config.Dir.Config, _alternateConfig); } } if (arg.StartsWith("/safelist=")) { _safePluginsList = arg.Remove(0, 10); // remove /?= from the argument } #if !DEBUG _avoidVersionChecking = arg.ToLowerInvariant() == "/avoidversioncheck"; #endif } } // check if MediaPotal is already running using (var processLock = new ProcessLock(MPMutex)) { if (processLock.AlreadyExists) { Log.Warn("Main: MediaPortal is already running"); Win32API.ActivatePreviousInstance(); } } if (string.IsNullOrEmpty(_alternateConfig)) { Log.BackupLogFiles(); } else { if (File.Exists(_alternateConfig)) { try { MPSettings.ConfigPathName = _alternateConfig; Log.BackupLogFiles(); Log.Info("Using alternate configuration file: {0}", MPSettings.ConfigPathName); } catch (Exception ex) { Log.BackupLogFiles(); Log.Error("Failed to change to alternate configuration file:"); Log.Error(ex); } } else { Log.BackupLogFiles(); Log.Info("Alternative configuration file was specified but the file was not found: '{0}'", _alternateConfig); Log.Info("Using default configuration file instead."); } } if (!Config.DirsFileUpdateDetected) { // check if Mediaportal has been configured var fi = new FileInfo(MPSettings.ConfigPathName); if (!File.Exists(MPSettings.ConfigPathName) || (fi.Length < 10000)) { // no, then start configuration.exe in wizard form Log.Info("MediaPortal.xml not found. Launching configuration tool and exiting..."); try { Process.Start(Config.GetFile(Config.Dir.Base, "configuration.exe"), @"/wizard"); } // ReSharper disable EmptyGeneralCatchClause catch {} // no exception logging needed, since MP is now closed // ReSharper restore EmptyGeneralCatchClause return; } // TODO: check if config is valid. If you create a config file > 10000 bytes full of spaces MP will crash as Utils.dll does nearly no error checking using (Settings xmlreader = new MPSettings()) { string threadPriority = xmlreader.GetValueAsString("general", "ThreadPriority", "Normal"); switch (threadPriority) { case "AboveNormal": Thread.CurrentThread.Priority = ThreadPriority.AboveNormal; Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal; break; case "High": Thread.CurrentThread.Priority = ThreadPriority.Highest; Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; break; case "BelowNormal": Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal; break; } _startupDelay = xmlreader.GetValueAsBool("general", "delay startup", false) ? xmlreader.GetValueAsInt("general", "delay", 0): 0; _waitForTvServer = xmlreader.GetValueAsBool("general", "wait for tvserver", false); } #if !DEBUG bool watchdogEnabled; bool restartOnError; int restartDelay; using (Settings xmlreader = new MPSettings()) { watchdogEnabled = xmlreader.GetValueAsBool("general", "watchdogEnabled", true); restartOnError = xmlreader.GetValueAsBool("general", "restartOnError", false); restartDelay = xmlreader.GetValueAsInt("general", "restart delay", 10); } AddExceptionHandler(); if (watchdogEnabled) { using (var sw = new StreamWriter(Config.GetFile(Config.Dir.Config, "mediaportal.running"), false)) { sw.WriteLine("running"); sw.Close(); } Log.Info("Main: Starting MPWatchDog"); string cmdargs = "-watchdog"; if (restartOnError) { cmdargs += " -restartMP " + restartDelay.ToString(CultureInfo.InvariantCulture); } var mpWatchDog = new Process { StartInfo = { ErrorDialog = true, UseShellExecute = true, WorkingDirectory = Application.StartupPath, FileName = "WatchDog.exe", Arguments = cmdargs } }; mpWatchDog.Start(); } #endif // Log MediaPortal version build and operating system level FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(Application.ExecutablePath); Log.Info("Main: MediaPortal v" + versionInfo.FileVersion + " is starting up on " + OSInfo.OSInfo.GetOSDisplayVersion()); #if DEBUG Log.Info("Debug Build: " + Application.ProductVersion); #else Log.Info("Build: " + Application.ProductVersion); #endif // setting minimum worker threads int minWorker, minIOC; ThreadPool.GetMinThreads(out minWorker, out minIOC); ThreadPool.SetMinThreads(minWorker * 2, minIOC * 1); ThreadPool.GetMinThreads(out minWorker, out minIOC); Log.Info("Main: Minimum number of worker threads to {0}/{1}", minWorker, minIOC); // Check for unsupported operating systems OSPrerequisites.OSPrerequisites.OsCheck(false); // Log last install of WindowsUpdate patches string lastSuccessTime = "NEVER !!!"; UIntPtr res; int options = Convert.ToInt32(Reg.RegistryRights.ReadKey); if (OSInfo.OSInfo.Xp64OrLater()) { options = options | Convert.ToInt32(Reg.RegWow64Options.KEY_WOW64_64KEY); } var rKey = new UIntPtr(Convert.ToUInt32(Reg.RegistryRoot.HKLM)); int lastError; int retval = Reg.RegOpenKeyEx(rKey, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\Results\\Install", 0, options, out res); if (retval == 0) { uint tKey; uint lKey = 100; var sKey = new StringBuilder((int)lKey); retval = Reg.RegQueryValueEx(res, "LastSuccessTime", 0, out tKey, sKey, ref lKey); if (retval == 0) { lastSuccessTime = sKey.ToString(); } else { lastError = Marshal.GetLastWin32Error(); Log.Debug("RegQueryValueEx retval=<{0}>, lastError=<{1}>", retval, lastError); } } else { lastError = Marshal.GetLastWin32Error(); Log.Debug("RegOpenKeyEx retval=<{0}>, lastError=<{1}>", retval, lastError); } Log.Info("Main: Last install from WindowsUpdate is dated {0}", lastSuccessTime); Log.Debug("Disabling process window ghosting"); DisableProcessWindowsGhosting(); // Start MediaPortal Log.Info("Main: Using Directories:"); foreach (Config.Dir option in Enum.GetValues(typeof (Config.Dir))) { Log.Info("{0} - {1}", option, Config.GetFolder(option)); } var mpFi = new FileInfo(Assembly.GetExecutingAssembly().Location); Log.Info("Main: Assembly creation time: {0} (UTC)", mpFi.LastWriteTimeUtc.ToUniversalTime()); #pragma warning disable 168 using (var processLock = new ProcessLock(MPMutex)) #pragma warning restore 168 { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Set current directory string applicationPath = Application.ExecutablePath; applicationPath = Path.GetFullPath(applicationPath); applicationPath = Path.GetDirectoryName(applicationPath); if (!String.IsNullOrEmpty(applicationPath)) { Directory.SetCurrentDirectory(applicationPath); Log.Info("Main: Set current directory to: {0}", applicationPath); } else { Log.Error("Main: Cannot set current directory to {0}", applicationPath); } // log about available displays foreach (var screen in Screen.AllScreens) { Log.Debug("Display: {0} - IsPrimary: {1} - BitsPerPixel: {2} - Bounds: {3}x{4} @ {5},{6} - WorkingArea: {7}x{8} @ {9},{10}", GetCleanDisplayName(screen), screen.Primary, screen.BitsPerPixel, screen.Bounds.Width, screen.Bounds.Height, screen.Bounds.X, screen.Bounds.Y, screen.WorkingArea.Width, screen.WorkingArea.Height, screen.WorkingArea.X, screen.WorkingArea.Y); } // log information about available adapters var enumeration = new D3DEnumeration(); enumeration.Enumerate(); foreach (GraphicsAdapterInfo ai in enumeration.AdapterInfoList) { Log.Debug("Adapter #{0}: {1} - Driver: {2} ({3}) - DeviceName: {4}", ai.AdapterOrdinal, ai.AdapterDetails.Description, ai.AdapterDetails.DriverName, ai.AdapterDetails.DriverVersion, ai.AdapterDetails.DeviceName); } // Localization strings for new splash screen and for MediaPortal itself LoadLanguageString(); // Initialize the skin and theme prior to beginning the splash screen thread. This provides for the splash screen to be used in a theme. string skin; try { using (Settings xmlreader = new MPSettings()) { skin = string.IsNullOrEmpty(SkinOverride) ? xmlreader.GetValueAsString("skin", "name", "Default") : SkinOverride; } } catch (Exception) { skin = "Default"; } Config.SkinName = skin; GUIGraphicsContext.Skin = skin; SkinSettings.Load(); // Send a message that the skin has changed. var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SKIN_CHANGED, 0, 0, 0, 0, 0, null); GUIGraphicsContext.SendMessage(msg); Log.Info("Main: Skin is {0} using theme {1}", skin, GUIThemeManager.CurrentTheme); // Start Splash Screen string version = ConfigurationManager.AppSettings["version"]; SplashScreen = new SplashScreen {Version = version}; #if !DEBUG SplashScreen.Run(); #endif Application.DoEvents(); // process message queue if (_waitForTvServer) { Log.Debug("Main: Wait for TV service requested"); ServiceController ctrl; try { ctrl = new ServiceController("TVService"); } catch (Exception) { ctrl = null; Log.Debug("Main: Create ServiceController for TV service failed - proceeding..."); } if (ctrl != null) { //Sanity check for existance of TV service ServiceControllerStatus status = ServiceControllerStatus.Stopped; try { status = ctrl.Status; } catch (Exception) { Log.Debug("Main: Failed to retrieve TV service status"); ctrl.Close(); ctrl = null; } } if (ctrl != null) { Log.Debug("Main: TV service found. Checking status..."); UpdateSplashScreenMessage(GUILocalizeStrings.Get(60)); // Waiting for startup of TV service... if (ctrl.Status == ServiceControllerStatus.StartPending || ctrl.Status == ServiceControllerStatus.Stopped) { if (ctrl.Status == ServiceControllerStatus.StartPending) { Log.Info("Main: TV service start is pending. Waiting..."); } if (ctrl.Status == ServiceControllerStatus.Stopped) { Log.Info("Main: TV service is stopped, so we try start it..."); try { ctrl.Start(); } catch (Exception) { Log.Info("TvService seems to be already starting up."); } } try { ctrl.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 45)); } // ReSharper disable EmptyGeneralCatchClause catch (Exception) {} // ReSharper restore EmptyGeneralCatchClause if (ctrl.Status == ServiceControllerStatus.Running) { Log.Info("Main: The TV service has started successfully."); } else { Log.Info("Main: Startup of the TV service failed - current status: {0}", ctrl.Status.ToString()); } } Log.Info("Main: TV service is in status {0} - proceeding...", ctrl.Status.ToString()); ctrl.Close(); } } Application.DoEvents(); // process message queue if (_startupDelay > 0) { Log.Info("Main: Waiting {0} second(s) before startup", _startupDelay); for (int i = _startupDelay; i > 0; i--) { UpdateSplashScreenMessage(String.Format(GUILocalizeStrings.Get(61), i.ToString(CultureInfo.InvariantCulture))); Thread.Sleep(1000); Application.DoEvents(); } } Log.Debug("Main: Checking prerequisites"); try { // check if DirectX 9.0c if installed Log.Debug("Main: Verifying DirectX 9"); if (!DirectXCheck.IsInstalled()) { DisableSplashScreen(); string strLine = "Please install a newer DirectX 9.0c redist!\r\n"; strLine = strLine + "MediaPortal cannot run without DirectX 9.0c redist (August 2008)\r\n"; strLine = strLine + "http://install.team-mediaportal.com/DirectX"; // ReSharper disable LocalizableElement MessageBox.Show(strLine, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error); // ReSharper restore LocalizableElement return; } Application.DoEvents(); // process message queue #if !DEBUG // Check TvPlugin version string mpExe = Assembly.GetExecutingAssembly().Location; string tvPlugin = Config.GetFolder(Config.Dir.Plugins) + "\\Windows\\TvPlugin.dll"; if (File.Exists(tvPlugin) && !_avoidVersionChecking) { string tvPluginVersion = FileVersionInfo.GetVersionInfo(tvPlugin).ProductVersion; string mpVersion = FileVersionInfo.GetVersionInfo(mpExe).ProductVersion; if (mpVersion != tvPluginVersion) { string strLine = "TvPlugin and MediaPortal don't have the same version.\r\n"; strLine += "Please update the older component to the same version as the newer one.\r\n"; strLine += "MediaPortal Version: " + mpVersion + "\r\n"; strLine += "TvPlugin Version: " + tvPluginVersion; DisableSplashScreen(); // ReSharper disable LocalizableElement MessageBox.Show(strLine, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error); // ReSharper restore LocalizableElement Log.Info(strLine); return; } } #endif } // ReSharper disable EmptyGeneralCatchClause catch (Exception) {} // ReSharper restore EmptyGeneralCatchClause Application.DoEvents(); // process message queue try { UpdateSplashScreenMessage(GUILocalizeStrings.Get(62)); Log.Debug("Main: Initializing DirectX"); var app = new MediaPortalApp(); if (app.Init()) { try { Log.Info("Main: Running"); GUIGraphicsContext.BlankScreen = false; Application.Run(app); app.Focus(); } catch (Exception ex) { Log.Error(ex); Log.Error("MediaPortal stopped due to an exception {0} {1} {2}", ex.Message, ex.Source, ex.StackTrace); _mpCrashed = true; } app.OnExit(); } } catch (Exception ex) { Log.Error(ex); Log.Error("MediaPortal stopped due to an exception {0} {1} {2}", ex.Message, ex.Source, ex.StackTrace); _mpCrashed = true; } DisableSplashScreen(); Settings.SaveCache(); // only re-show the task bar if MP is the one that has hidden it. using (Settings xmlreader = new MPSettings()) { if (xmlreader.GetValueAsBool("general", "hidetaskbar", false)) { HideTaskBar(false); } } if (_useRestartOptions) { Log.Info("Main: Exiting Windows - {0}", _restartOptions); if (File.Exists(Config.GetFile(Config.Dir.Config, "mediaportal.running"))) { File.Delete(Config.GetFile(Config.Dir.Config, "mediaportal.running")); } WindowsController.ExitWindows(_restartOptions, false); } else { if (!_mpCrashed && File.Exists(Config.GetFile(Config.Dir.Config, "mediaportal.running"))) { File.Delete(Config.GetFile(Config.Dir.Config, "mediaportal.running")); } } } } else { DisableSplashScreen(); string msg = "The file MediaPortalDirs.xml has been changed by a recent update in the MediaPortal application directory.\n\n"; msg += "You have to open the file "; msg += Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Team MediaPortal\MediaPortalDirs.xml"; msg += " with an editor, update it with all changes and SAVE it at least once to start up MediaPortal successfully after this update.\n\n"; msg += "If you are not using windows user profiles for MediaPortal's configuration management, "; msg += "just delete the whole directory mentioned above and reconfigure MediaPortal."; msg += "\n\n\n"; msg += "Do you want to open your local file now?"; Log.Error(msg); // ReSharper disable LocalizableElement DialogResult result = MessageBox.Show(msg, "MediaPortal - Update Conflict", MessageBoxButtons.YesNo, MessageBoxIcon.Stop); // ReSharper restore LocalizableElement try { if (result == DialogResult.Yes) { Process.Start("notepad.exe", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Team MediaPortal\MediaPortalDirs.xml"); } } catch (Exception) { // ReSharper disable LocalizableElement MessageBox.Show( "Error opening file " + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Team MediaPortal\MediaPortalDirs.xml using notepad.exe", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); // ReSharper restore LocalizableElement } } Environment.Exit(0); }
private string HandleServiceStart(bool isReconnecting) { string listenerEndpoint = null; string str4; string sharedMemoryName = this.isTcp ? "NetTcpPortSharing/endpoint" : "NetPipeActivator/endpoint"; this.serviceName = SharedConnectionListener.GetServiceName(this.isTcp); if (!isReconnecting && this.ReadEndpoint(sharedMemoryName, out listenerEndpoint)) { return(listenerEndpoint); } ServiceController service = new ServiceController(this.serviceName); try { ServiceControllerStatus status = service.Status; if (isReconnecting && (status == ServiceControllerStatus.Running)) { try { string str3 = SharedMemory.Read(sharedMemoryName); if (this.listenerEndPoint != str3) { return(str3); } } catch (Win32Exception exception) { if (DiagnosticUtility.ShouldTraceWarning) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning); } } status = this.ExitServiceStatus(service, 50, 50, ServiceControllerStatus.Running); } if (status == ServiceControllerStatus.Running) { goto Label_021B; } if (!isReconnecting) { try { service.Start(); goto Label_01FD; } catch (InvalidOperationException exception2) { Win32Exception innerException = exception2.InnerException as Win32Exception; if (innerException == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SharedManagerBase", new object[] { this.serviceName, System.ServiceModel.SR.GetString("SharedManagerServiceStartFailureNoError") }), exception2)); } if (innerException.NativeErrorCode == 0x422) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SharedManagerBase", new object[] { this.serviceName, System.ServiceModel.SR.GetString("SharedManagerServiceStartFailureDisabled", new object[] { this.serviceName }) }), exception2)); } if (innerException.NativeErrorCode != 0x420) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SharedManagerBase", new object[] { this.serviceName, System.ServiceModel.SR.GetString("SharedManagerServiceStartFailure", new object[] { innerException.NativeErrorCode }) }), exception2)); } goto Label_01FD; } } switch (status) { case ServiceControllerStatus.StopPending: status = this.ExitServiceStatus(service, 50, 0x3e8, status); break; case ServiceControllerStatus.Stopped: status = this.ExitServiceStatus(service, 50, 0x3e8, status); break; } Label_01FD: service.Refresh(); status = service.Status; if (status == ServiceControllerStatus.StartPending) { status = this.ExitServiceStatus(service, 50, 50, ServiceControllerStatus.StartPending); } Label_021B: if (status != ServiceControllerStatus.Running) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SharedManagerBase", new object[] { this.serviceName, System.ServiceModel.SR.GetString("SharedManagerServiceStartFailureNoError") }))); } } finally { service.Close(); } try { str4 = SharedMemory.Read(sharedMemoryName); } catch (Win32Exception exception4) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(this.WrapEndpointReadingException(exception4)); } return(str4); }
public void Close() { winser.Close(); }
protected override void DoJob(ServiceScheduleInfo serviceScheduleHeaderInfo) { //System.Diagnostics.EventLog.WriteEntry(ServiceName, ServiceName + " implementing its job", EventLogEntryType.Information); // param = null tuc day la thread update state cua cac thread khac //if (param == null) //{ // updateServiceChildState(); // return; //} //ServiceScheduleInfo serviceScheduleInfo = (ServiceScheduleInfo)param; try { var serviceController = new ServiceController(serviceScheduleHeaderInfo.ServiceName); Process[] processes = Process.GetProcessesByName(String.Format("QLBH.{0}", serviceController.ServiceName)); if (processes.Length == 0) // && serviceController.Status == ServiceControllerStatus.Stopped) { //DateTime now = DateTime.Now; //string exDayStr = (now.Day).ToString().PadLeft(2, '0') + now.ToString("HHmm"); // exact day //string evDayStr = String.Format("00{0}", DateTime.Now.ToString("HHmm")); // daily if (// daily //(serviceScheduleHeaderInfo.NextRunTime == evDayStr && // serviceScheduleHeaderInfo.ScheduleType == Convert.ToInt32(EScheduleType.DAILY)) || // //hoac la hang tuan, voi dinh dang ngay thu may trong tuan //(serviceScheduleHeaderInfo.NextRunTime == exDayStr && // (serviceScheduleHeaderInfo.ScheduleType == Convert.ToInt32(EScheduleType.MONTHLY) || // serviceScheduleHeaderInfo.ScheduleType == Convert.ToInt32(EScheduleType.WEEKLY))) || serviceScheduleHeaderInfo.NextRunTime <= DateTime.Now || serviceScheduleHeaderInfo.ScheduleType == Convert.ToInt32(EScheduleType.CONTINUOUSLY)) { serviceController.Start(new[] { serviceScheduleHeaderInfo.Id.ToString() }); } } else { if (lstStopPending == null) { lstStopPending = new List <TracedService>(); } lstStopPending.RemoveAll(delegate(TracedService match) { return(match.ServiceName == serviceController.ServiceName && match.Pid != processes[0].Id); }); TracedService tracedService = lstStopPending.Find(delegate(TracedService match) { return(match.ServiceName == serviceController.ServiceName && match.Pid == processes[0].Id); }); if (tracedService == null) { lstStopPending.Add(new TracedService { Pid = processes[0].Id, ServiceName = serviceController.ServiceName, TotalMinutes = processes[0].TotalProcessorTime.TotalMinutes, }); } else if (serviceController.Status == ServiceControllerStatus.StopPending) { if (tracedService.RetriedTime < 3) { tracedService.RetriedTime += 1; } else { lstStopPending.Remove(tracedService); if (processes.Length > 0) { processes[0].Kill(); } } } else if (tracedService.TotalMinutes == processes[0].TotalProcessorTime.TotalMinutes) { if (tracedService.RetriedTime < 3) { tracedService.RetriedTime += 1; } else { serviceController.Stop(); } } else { tracedService.TotalMinutes = processes[0].TotalProcessorTime.TotalMinutes; tracedService.RetriedTime = 0; } processes[0].Close(); } serviceController.Close(); processes = null; serviceController = null; GC.Collect(); if (!String.IsNullOrEmpty(Convert.ToString(serviceController) + Convert.ToString(processes))) { //do nothing here File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + String.Format("\\{0}.log", Path.GetRandomFileName()), Convert.ToString(serviceController)); } } catch (Exception ex) { EventLogProvider.Instance.WriteOfflineLog(ex.ToString(), "ManagerService"); } }
private void OnTimer(object sender, System.Timers.ElapsedEventArgs args) { EventLog.WriteEntry("FastIR Agent: check for order...", EventLogEntryType.Information); //Get keys P.URL = ReadKey("URL"); P.Port = ReadKey("Port"); P.APIKey = ReadKey("APIKey"); P.lpk = ReadKey("PUBLIC_SSL"); string exe = Process.GetCurrentProcess().MainModule.FileName; P.ApplicationPath = Path.GetDirectoryName(exe); // if (P.Port.Equals(null) || P.URL.Equals(null) || P.lpk.Equals(null) || P.APIKey.Equals(null)) { EventLog.WriteEntry("FastIR Agent: Bad URL, Port, or SSL Public key in the configuration...", EventLogEntryType.Error); ServiceController sc = new ServiceController("FastIR"); sc.Stop(); sc.Close(); } else { EventLog.WriteEntry("FastIR Agent: URL: " + P.URL + ":" + P.Port + ".", EventLogEntryType.Information); NetworkFastIR prop = new NetworkFastIR(P.URL, P.Port, P.lpk); ret r = prop.query(""); if (r.SSL_status) { ReturnJson rj; try { rj = JsonConvert.DeserializeObject <ReturnJson>(r.Web_return); EventLog.WriteEntry("FastIR Agent: Connection established to the server", EventLogEntryType.Information); //Get new FastIR binary string arch = null; if (Environment.Is64BitOperatingSystem) { arch = "x64"; } else { arch = "x86"; } string sha256 = ""; try { sha256 = GetSHA256(P.ApplicationPath + "\\FastIR.exe"); } catch { } string POST = "APIKey=" + P.APIKey + "&sha256=" + sha256 + "&arch=" + arch; r = prop.query("getbinary/", POST); if (r.SSL_status) { try { rj = JsonConvert.DeserializeObject <ReturnJson>(r.Web_return); } catch { rj = null; } if (rj.Equals(null)) { EventLog.WriteEntry("FastIR Agent: bad json from the server", EventLogEntryType.Error); } else if (rj.Return.Equals("KO")) { EventLog.WriteEntry("FastIR Agent: bad request: " + rj.Data, EventLogEntryType.Error); } else { if (rj.Binary.Equals("1")) { EventLog.WriteEntry("FastIR Agent: new FastIR binary available", EventLogEntryType.Information); try { byte[] data = Convert.FromBase64String(rj.Data); File.WriteAllBytes(P.ApplicationPath + "\\FastIR.exe", data); } catch { EventLog.WriteEntry("FastIR Agent: cannot download the new FastIR binary", EventLogEntryType.Error); } } else { EventLog.WriteEntry("FastIR Agent: no new FastIR binary", EventLogEntryType.Information); } } } else { EventLog.WriteEntry("FastIR Agent: Bad SSL or URL", EventLogEntryType.Error); } //Get Order POST = "APIKey=" + P.APIKey + "&hostname=" + Dns.GetHostName(); r = prop.query("getorder/", POST); if (r.SSL_status) { try { rj = JsonConvert.DeserializeObject <ReturnJson>(r.Web_return); } catch { rj = null; } if (rj.Equals(null)) { EventLog.WriteEntry("FastIR Agent: bad json from the server", EventLogEntryType.Error); } else if (rj.Return.Equals("KO")) { EventLog.WriteEntry("FastIR Agent: bad request: " + rj.Data, EventLogEntryType.Error); } else { if (rj.Order.Equals("1")) { EventLog.WriteEntry("FastIR Agent: an order exist for the machine: " + Dns.GetHostName(), EventLogEntryType.Information); try { PECheck pe = new PECheck(); byte[] data = Convert.FromBase64String(rj.Data); File.WriteAllBytes(P.ApplicationPath + "\\FastIR.conf", data); EventLog.WriteEntry("FastIR Agent: the new config file is created.", EventLogEntryType.Information); if (pe.checkfile(P.ApplicationPath + "\\FastIR.exe")) { using (Process process = new Process()) { EventLog.WriteEntry("FastIR Agent: execution of the collect.", EventLogEntryType.Information); process.StartInfo.FileName = P.ApplicationPath + "\\FastIR.exe"; process.StartInfo.Arguments = "--profile " + P.ApplicationPath + "\\FastIR.conf"; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); } } else { EventLog.WriteEntry("FastIR Agent: bad signature.", EventLogEntryType.Error); } } catch { EventLog.WriteEntry("FastIR Agent: cannot download the config file", EventLogEntryType.Error); } } else { EventLog.WriteEntry("FastIR Agent: no order for the machine: " + Dns.GetHostName(), EventLogEntryType.Information); } } } else { EventLog.WriteEntry("FastIR Agent: Bad SSL or URL", EventLogEntryType.Error); } } catch { EventLog.WriteEntry("FastIR Agent: bad json from the server", EventLogEntryType.Error); } } else { EventLog.WriteEntry("FastIR Agent: Bad SSL or URL", EventLogEntryType.Error); } } }
public static void TestServiceManipulation() { ServiceController scStateService = new ServiceController("COM+ Event System"); Console.WriteLine($"Service Type: {scStateService.ServiceType.ToString()}"); Console.WriteLine($"Service Name: {scStateService.ServiceName}"); Console.WriteLine($"Display Name: {scStateService.DisplayName}"); foreach (ServiceController sc in scStateService.DependentServices) { Console.WriteLine($"{scStateService.DisplayName} is depended on by: {sc.DisplayName}"); } foreach (ServiceController sc in scStateService.ServicesDependedOn) { Console.WriteLine($"{scStateService.DisplayName} depends on: {sc.DisplayName}"); } Console.WriteLine($"Status: {scStateService.Status}"); // save original state ServiceControllerStatus originalState = scStateService.Status; TimeSpan serviceTimeout = TimeSpan.FromSeconds(60); // if it is stopped, start it if (scStateService.Status == ServiceControllerStatus.Stopped) { scStateService.Start(); // wait up to 60 seconds for start scStateService.WaitForStatus(ServiceControllerStatus.Running, serviceTimeout); } Console.WriteLine($"Status: {scStateService.Status}"); // if it is paused, continue if (scStateService.Status == ServiceControllerStatus.Paused) { if (scStateService.CanPauseAndContinue) { scStateService.Continue(); // wait up to 60 seconds for start scStateService.WaitForStatus(ServiceControllerStatus.Running, serviceTimeout); } } Console.WriteLine($"Status: {scStateService.Status}"); // should be running at this point // can we stop it? if (scStateService.CanStop) { // In order to manipulate services, you need administrator access on the machine through User Account Control (UAC) // We can request these rights for our code in the app.manifest file associated with the assembly. // The default requested execution level is to run as the person invoking the code // <requestedExecutionLevel level="asInvoker" uiAccess="false" /> //If we had not added the following to the app.manifest file: //< requestedExecutionLevel level = "requireAdministrator" uiAccess = "false" /> //You get the following error even though CanStop is true because you are not in an administrative context even if // your account has admin rights: // A first chance exception of type 'System.InvalidOperationException' occurred in System.ServiceProcess.dll // Additional information: Cannot open EventSystem service on computer '.'. scStateService.Stop(); // wait up to 60 seconds for stop scStateService.WaitForStatus(ServiceControllerStatus.Stopped, serviceTimeout); } Console.WriteLine($"Status: {scStateService.Status}"); // set it back to the original state switch (originalState) { case ServiceControllerStatus.Stopped: if (scStateService.CanStop) { scStateService.Stop(); } break; case ServiceControllerStatus.Running: scStateService.Start(); // wait up to 60 seconds for start scStateService.WaitForStatus(ServiceControllerStatus.Running, serviceTimeout); break; case ServiceControllerStatus.Paused: // if it was paused and is stopped, need to restart so we can pause if (scStateService.Status == ServiceControllerStatus.Stopped) { scStateService.Start(); // wait up to 60 seconds for start scStateService.WaitForStatus(ServiceControllerStatus.Running, serviceTimeout); } // now pause if (scStateService.CanPauseAndContinue) { scStateService.Pause(); // wait up to 60 seconds for paused scStateService.WaitForStatus(ServiceControllerStatus.Paused, serviceTimeout); } break; } scStateService.Refresh(); Console.WriteLine($"Status: {scStateService.Status.ToString()}"); // close it scStateService.Close(); }
private void UpdateScheduleUi() { try { TaskBase task = CurrentTask; if (task == null) { // Note: disabling buttons may result in .net trying to move focus to the task grid, // and if that grid is empty that may cause SetCurrentCellAddressCore exception, // hence this (TFS~~14180): BeginInvoke((Action)(() => UpdateScheduleUiNoTask())); } else { flwScheduleFrequency.Enabled = true; dtpScheduleDate.Enabled = dtpScheduleTime.Enabled = task.State == TaskState.Ready; grpSchedule.Visible = true; flwScheduleOnce.Visible = task.Schedule.FrequencyOnce; flwScheduleDaily.Visible = task.Schedule.FrequencyDaily; pnlScheduleWeek.Visible = task.Schedule.FrequencyWeekly; pnlScheduleMonth.Visible = task.Schedule.FrequencyMonthly; pnlScheduleMonthDays.Visible = task.Schedule.FrequencyMonthly; numScheduleRepeatFreq.Enabled = chkScheduleRepeat.Checked; cmbScheduleRepeatUnit.Enabled = chkScheduleRepeat.Checked; btnScheduleStart.Enabled = true; if (task.Schedule.Enabled) { btnScheduleStart.Text = "Stop"; btnScheduleStart.Image = global::C1ReportsScheduler.Properties.Resources.Stop; btnSchedulePause.Enabled = true; } else { btnScheduleStart.Text = "Start"; btnScheduleStart.Image = global::C1ReportsScheduler.Properties.Resources.Start; btnSchedulePause.Enabled = false; } if (task.Schedule.Paused) { btnSchedulePause.Text = "Resume"; btnSchedulePause.Image = global::C1ReportsScheduler.Properties.Resources.Resume; } else { btnSchedulePause.Text = "Pause"; btnSchedulePause.Image = global::C1ReportsScheduler.Properties.Resources.Pause; } // in client mode, if service is paused, disable both start and stop: if (ClientMode) { bool serviceRunning; using (ServiceController sc = new ServiceController(C1ReportsSchedulerService.Constants.Name)) { try { serviceRunning = sc.Status == ServiceControllerStatus.Running; } catch { serviceRunning = false; } finally { sc.Close(); } } if (!serviceRunning) { btnScheduleStart.Enabled = false; btnSchedulePause.Enabled = false; } } DateTime nextDueTime = task.Schedule.NextDueTime; if (nextDueTime == ScheduleBase.c_DateTimeNever) { lblScheduleNextDueTime.Text = "Never"; } else { lblScheduleNextDueTime.Text = nextDueTime.ToString(); } } } catch { } }