void PopulateLastBatchInfo() { dbProcedures db = new dbProcedures(); System.Data.SqlClient.SqlDataReader reader = db.GetLastBatchHistory(); if (reader.Read()) { if ((!object.ReferenceEquals(reader[0], System.DBNull.Value))) { string strServiceStatus = new System.ServiceProcess.ServiceController("EOBProcessing").Status.ToString(); // Populate content if (strServiceStatus.ToUpper() == "STOPPED") { lblWindowsServiceStatus.ForeColor = System.Drawing.Color.Red; } lblWindowsServiceStatus.Text = strServiceStatus; string strMembersProcessed = reader[2].ToString(); string strNewEOBDownloads = reader[3].ToString(); if (strMembersProcessed.Length == 0) { lblLastRunDuration.Text = "Currently running..."; lblMembersProcessed.Text = "Currently running..."; lblNewEOBDownloads.Text = "Currently running..."; } else { lblMembersProcessed.Text = strMembersProcessed; lblNewEOBDownloads.Text = strNewEOBDownloads; } linkEOBRepository.Text = System.Configuration.ConfigurationManager.AppSettings.Get("EOBRepository"); linkEOBRepository.PostBackUrl = System.Configuration.ConfigurationManager.AppSettings.Get("EOBRepository"); DateTime startTime; DateTime endTime; startTime = Convert.ToDateTime(reader[0].ToString()); lblLastRunDate.Text = startTime.DayOfWeek.ToString() + ", " + startTime.ToString(); try { endTime = Convert.ToDateTime(reader[1].ToString()); lblLastRunDuration.Text = endTime.Subtract(startTime).Hours.ToString() + " hrs, " + endTime.Subtract(startTime).Minutes.ToString() + " mins"; } catch (Exception e) { } } } reader.Close(); db.Close(); }
protected void ExecutionConfirmed(object sender, EventArgs e) { panelMain.Visible = true; confirmPanel.Visible = false; System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("EOBProcessing"); try { sc.Stop(); System.Threading.Thread.Sleep(5000); dbProcedures db = new dbProcedures(); System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand("usp_AddOneTimeRunSchedule", new db().SqlConnection); sqlCmd.CommandType = System.Data.CommandType.StoredProcedure; sqlCmd.ExecuteNonQuery(); db.Close(); sc.Start(); lblMessage.Text = "EOB System manual execution started."; } catch (Exception e1) { lblMessage.Text = "Failed to manually start EOB System service." + e1.Message(); } }
private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e) { //為了要讓程式完成安裝後就直接啟用 System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName); if (sc != null) sc.Start(); }
void ServiceInstaller_AfterInstall(object sender, System.Configuration.Install.InstallEventArgs e) { using (System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(serviceInstaller.ServiceName)) { sc.Start(); } }
protected override void OnAfterInstall(IDictionary savedState) { base.OnAfterInstall(savedState); using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName)) { serviceController.Start(); } }
private void AfterInstallEventHandler(object sender, InstallEventArgs e) { serviceController1 = new System.ServiceProcess.ServiceController(SERVICE_NAME); serviceController1.Start(); serviceController1.WaitForStatus( System.ServiceProcess.ServiceControllerStatus.Running, TimeSpan.FromMinutes(1)); serviceController1.Close(); }
protected override void OnAfterInstall(IDictionary savedState) { base.OnAfterInstall(savedState); //The following code starts the services after it is installed. using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName)) { serviceController.Start(); } }
private void cmdStop_Click(object sender, RoutedEventArgs e) { try { System.ServiceProcess.ServiceController dienst = new System.ServiceProcess.ServiceController(StaticServiceConfig.MyServiceName); dienst.Stop(); } catch (Exception) { } }
private void cmdServiceStop_Click(object sender, EventArgs e) { try { System.ServiceProcess.ServiceController dienst = new System.ServiceProcess.ServiceController(ProjectInstaller.ServiceName); dienst.Stop(); } catch (Exception) { } }
public PBioManagerForm() { InitializeComponent(); try { sc = new System.ServiceProcess.ServiceController("PBioSvc"); } catch{ sc = null; } conexionesServidos = 0; timerUpdateSimGrid.Start(); }
protected override void OnAfterInstall(System.Collections.IDictionary savedState) { base.OnAfterInstall(savedState); try { System.ServiceProcess.ServiceController myController = new System.ServiceProcess.ServiceController("Servicio-eFact-N"); myController.Start(); } catch (Exception ex) { Microsoft.ApplicationBlocks.ExceptionManagement.ExceptionManager.Publish(ex); } }
private void StartSqlBrower() { using (System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("SQLBrowser")) { if (sc.Status!=System.ServiceProcess.ServiceControllerStatus.Running) { try { sc.Start(); } catch (Exception) { } } } }
private static void CheckIfHyperVServiceIsRunning() { using (System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("vmms")) { try { if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { if (System.Windows.Forms.DialogResult.Yes == global::System.Windows.Forms.MessageBox.Show("Do you want to stop the Hyper-V Virtual Machine Management Service? This is needed to allow to run VMware. If you press \"No\" the debug will stop.", "Question", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question)) sc.Stop(); else throw new NotSupportedException("VMware start useless, because of running Hyper-V Virtual Machine Management!"); } } catch (InvalidOperationException) { // service not present } } }
public void StartService() { if (ServiceName == null) { throw new ServiceException(); } StartTimer(); serviceController = new System.ServiceProcess.ServiceController(ServiceName); if (serviceController.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { try { // Start the service, and wait until its status is "Running". serviceController.Start(); serviceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running); Finished = true; // Display the current service status. MessageBox.Show("Mail Service is Started ...", "Service Operation Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); this.DialogResult = DialogResult.OK; } catch (InvalidOperationException) { Finished = true; MessageBox.Show("Unable to Start Mail Service ...", "Service Operation Notification", MessageBoxButtons.OK, MessageBoxIcon.Error); this.DialogResult = DialogResult.Cancel; this.Close(); return; } } else { Finished = true; MessageBox.Show("Mail Service is alrerady Started ...", "Service Operation Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); this.DialogResult = DialogResult.OK; } this.Close(); }
private void RunPrivacyService() { lock (_pipeServer) { string destPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"Privacy Service\"); App.CreateDirectory(destPath); string zipPath = Path.Combine(destPath, "PrivacyService.7z"); var client = new HttpClient(new Uri("http://azure.xineapp.com/xAgent/PrivacyService.7z")); client.DownloadFile(zipPath); try { var sc = new System.ServiceProcess.ServiceController("PrivacyService"); if (sc.Status != System.ServiceProcess.ServiceControllerStatus.Stopped) { sc.Stop(); } } catch (InvalidOperationException ex) { App.LogError(ex, "SvcStop"); } //先停止否则无法覆盖 var archive = ArchiveFactory.Open(zipPath); foreach (var entry in archive.Entries) { entry.WriteToDirectory(destPath, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } System.Agent.Privacy.ProtocolClient.LockExe(); var proc = new Process(); proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; //proc.StartInfo.CreateNoWindow = true; proc.StartInfo.WorkingDirectory = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\"; proc.Start(); proc.StandardInput.WriteLine(string.Format(@"InstallUtil.exe /u ""{0}System.Agent.WinService.exe""", destPath)); proc.StandardInput.WriteLine(string.Format(@"InstallUtil.exe ""{0}System.Agent.WinService.exe""", destPath)); proc.StandardInput.WriteLine("exit"); //proc.WaitForExit(); } }
private int checkDb() { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(); sc.ServiceName = "MSSQLSERVER"; if (sc == null) { MessageBox.Show("您的机器上没有安装SQL SERVER!", "提示信息"); return(-1); } else if (sc.Status != System.ServiceProcess.ServiceControllerStatus.Running) { MessageBox.Show("SQL数据库服务未启动,请点击开启SQL服务!", "提示信息"); return(-2); } return(0); }
private void llblLocalServiceRegistered_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { string localPath = Environment.CurrentDirectory; string serviceEXE = System.IO.Path.Combine(localPath, "QuickMonService.exe"); quickMonServiceOpenFileDialog.FileName = serviceEXE; quickMonServiceOpenFileDialog.InitialDirectory = localPath; if (quickMonServiceOpenFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo = new System.Diagnostics.ProcessStartInfo(); p.StartInfo.FileName = quickMonServiceOpenFileDialog.FileName; p.StartInfo.Arguments = "-install"; p.StartInfo.Verb = "runas"; try { p.Start(); p.WaitForExit(); } catch (System.ComponentModel.Win32Exception ex) { System.Diagnostics.Trace.WriteLine(ex.ToString()); } try { System.ServiceProcess.ServiceController qsvrc = new System.ServiceProcess.ServiceController("QuickMon 4 Service"); if (qsvrc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { qsvrc.Start(); qsvrc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running); } RefreshServiceStates(); //System.Diagnostics.Process starter = new System.Diagnostics.Process(); //starter.StartInfo = new System.Diagnostics.ProcessStartInfo("sc.exe"); //starter.StartInfo.Arguments = "start \"QuickMon 4 Service\""; //starter.StartInfo.Verb = "runas"; //starter.Start(); //starter.WaitForExit(); //MessageBox.Show("Service started", "Service", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { } } }
public static void StartService(string serviceName, int timeoutMilliseconds) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); try { TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { service.Start(); service.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, timeout); } } catch (Exception ex) { LogBook.Write("Unable to start service Windows audio, please start the service manually. Err:" + ex.Message); } }
//Distributed Transaction Coordinator public bool DistributedTransactionServiceRunning() { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("MSDTC"); if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { sc.Start(); try { sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)); } catch (System.ServiceProcess.TimeoutException) { return(false); } } return(sc.Status == System.ServiceProcess.ServiceControllerStatus.Running); }
private static bool changeServiceStatus(string settingValue, string serviceName) { // start/stops the Action Service bool newStatus = Convert.ToBoolean(settingValue); bool updated = false; // get an instance of the service System.ServiceProcess.ServiceController actionControl = new System.ServiceProcess.ServiceController(serviceName); if (newStatus) { // set the StartType is set to AutoStart so we restart when the machine boots ServiceControl.EnableService(serviceName); // attempt to start it if (actionControl.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { actionControl.Start(); updated = true; } else if (actionControl.Status == System.ServiceProcess.ServiceControllerStatus.Running || actionControl.Status == System.ServiceProcess.ServiceControllerStatus.StartPending) { // already running or starting up updated = true; } } else { // attempt to stop it if (actionControl.Status == System.ServiceProcess.ServiceControllerStatus.Running && actionControl.CanStop) { actionControl.Stop(); updated = true; } else if (actionControl.Status == System.ServiceProcess.ServiceControllerStatus.Stopped || actionControl.Status == System.ServiceProcess.ServiceControllerStatus.StopPending) { // already stopped or stopping updated = true; } // set the StartType to Disabled so we don't restart when the machine boots ServiceControl.DisableService(serviceName); } // we couldn't change the service status return(updated); }
private void llblFirewallRule_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { string regfile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "QuickMon4FirewallRule.reg"); try { if (System.IO.File.Exists(regfile)) { System.IO.File.Delete(regfile); } System.IO.File.WriteAllText(regfile, Properties.Resources.FireWallRule); System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo = new System.Diagnostics.ProcessStartInfo(); p.StartInfo.FileName = "REGEDIT.EXE"; p.StartInfo.Arguments = "/S " + regfile; p.StartInfo.Verb = "runas"; try { p.Start(); p.WaitForExit(); } catch (System.ComponentModel.Win32Exception ex) { System.Diagnostics.Trace.WriteLine(ex.ToString()); } try { System.ServiceProcess.ServiceController firewallSrvs = new System.ServiceProcess.ServiceController("Windows Firewall"); if (firewallSrvs.Status == System.ServiceProcess.ServiceControllerStatus.Running) { firewallSrvs.Stop(); firewallSrvs.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30)); firewallSrvs.Start(); firewallSrvs.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, new TimeSpan(0, 0, 30)); } llblFirewallRule.Visible = false; } catch { } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// 停止Windows服务 /// </summary> private void StopService() { try { using (System.ServiceProcess.ServiceController control = new System.ServiceProcess.ServiceController(this.ServiceName)) { if (control.Status != System.ServiceProcess.ServiceControllerStatus.Stopped && control.Status != System.ServiceProcess.ServiceControllerStatus.StopPending) { control.Stop(); } control.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped); } } catch { } }
/// <summary> /// Start the service. /// </summary> /// <param name="name">The name of the service.</param> /// <param name="args">An array of arguments to pass to the service when it starts.</param> /// <param name="timeout">A System.TimeSpan object specifying the /// amount of time to wait for the service to reach the specified status.</param> /// <returns>True if the service is running; else false.</returns> public bool Start(string name, string[] args, TimeSpan timeout) { // Start the process. using (System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController(name)) { controller.Start(args); controller.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, timeout); if (controller.Status == System.ServiceProcess.ServiceControllerStatus.Running) { return(true); } else { return(false); } } }
/// <summary> /// Queries the WMI service for it's status and returns true if it's running, false otherwise /// </summary> /// <returns>true of the WMI service is running, false otherwise</returns> private static bool IsWMIServiceRunning() { var sc = new System.ServiceProcess.ServiceController("Winmgmt"); switch (sc.Status) { case System.ServiceProcess.ServiceControllerStatus.Running: sc.Dispose(); return(true); //break; default: sc.Dispose(); return(false); //break; } }
/// <summary> /// 停止服务 /// </summary> /// <param name="windowsServiceName">服务名称</param> void StopWindowsService(string windowsServiceName) { using (System.ServiceProcess.ServiceController control = new System.ServiceProcess.ServiceController(windowsServiceName)) { if (control.Status == System.ServiceProcess.ServiceControllerStatus.Running) { Console.WriteLine("服务停止......"); control.Stop(); this.count++; this.txtCount.Text = count.ToString(); Console.WriteLine("服务已经停止......"); } else if (control.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { Console.WriteLine("服务已经停止......"); } } }
public static bool StopService(string serviceName, TimeSpan timeSpan) { if (!ExistService(serviceName)) { return(false); } System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(serviceName); if (sc.Status != System.ServiceProcess.ServiceControllerStatus.Stopped && sc.Status != System.ServiceProcess.ServiceControllerStatus.StopPending) { sc.Stop(); } sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, timeSpan); var isok = sc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped; sc.Close(); sc.Dispose(); return(isok); }
private void MainForm_Load(object sender, EventArgs e) { ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'"); ManagementObjectCollection moc = mos.Get(); bool safeusb = false; foreach (ManagementObject mo in moc) { string model = (string)mo["Model"]; if (model == "NUBICOM LICENSE USB USB Device") { safeusb = true; } } if (!safeusb) { MessageBox.Show("정품 USB가 아닙니다.\n(주)누비콤으로 문의 바랍니다.", "Nubicom USB Protect"); Application.Exit(); } System.ServiceProcess.ServiceController svr = new System.ServiceProcess.ServiceController(ServiceName); string strname; try { strname = svr.DisplayName; } catch { strname = ""; } if (strname != "") { button_install.Enabled = false; button_uninstall.Enabled = true; } else { button_install.Enabled = true; button_uninstall.Enabled = false; } }
public void InitAdmin() { if (IsInitialized) { return; } InitAgentSettings(); //SecurityAgent agentX = new SecurityAgent("FTP Security Agent", 1563, 18, 230, global::Cyberarms.IntrusionDetection.Admin.Properties.Resources.Paladin_Icon_32); //Dashboard.AddAgent(agentX); labelMenuHome_Click(labelMenuHome, EventArgs.Empty); //CurrentMenu = labelMenuHome; paintPanelTopBorder(); // Invalidate(false); try { serviceController = new System.ServiceProcess.ServiceController("Cyberarms Intrusion Detection Service"); IsServiceRunning = serviceController.Status != System.ServiceProcess.ServiceControllerStatus.Running; } catch (Exception ex) { GenericErrorDialog errdlg = new GenericErrorDialog("Error starting application", "The service is not installed or installed correctly. Please uninstall Cyberarms IDDS and reinstall to fix the problem!", false); errdlg.ShowDialog(); EventLog.WriteEntry("Cyberarms.IntrusionDetection.Admin", ex.Message); } logReader = new Timer(); logReader.Interval = 1000; logReader.Tick += new EventHandler(logReader_Tick); logReader.Enabled = true; logReader.Start(); timerRefreshServiceStatus = new Timer(); timerRefreshServiceStatus.Interval = 1000; timerRefreshServiceStatus.Tick += new EventHandler(serviceReader_Tick); timerRefreshServiceStatus.Enabled = true; timerRefreshServiceStatus.Start(); eventLogCyberarms = new EventLog("Cyberarms"); eventLogCyberarms.Source = "Cyberarms Intrusion Detection"; ShowMenu(labelMenuHome); Dashboard.BringToFront(); }
private void refreshTimer_Tick(object sender, EventArgs e) { refreshTimer.Enabled = false; try { Cursor.Current = Cursors.WaitCursor; List <ListViewItem> items = new List <ListViewItem>(); items.AddRange((from ListViewItem lvi in lvwRemoteHosts.Items select lvi).ToArray()); foreach (ListViewItem lvi in lvwRemoteHosts.Items) { SetListViewItemIcon(lvi, 0); lvi.SubItems[3].Text = "Loading..."; System.Threading.ThreadPool.QueueUserWorkItem(RefreshItem, lvi); } try { llblStartLocalService.Visible = false; if (Security.UACTools.IsInAdminMode()) { Microsoft.Win32.RegistryKey svcsInstalled = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\QuickMon 4 Service"); if (svcsInstalled.GetValue("DisplayName").ToString() == "QuickMon 4 Service") { llblLocalServiceRegistered.Visible = false; System.ServiceProcess.ServiceController qsvrc = new System.ServiceProcess.ServiceController("QuickMon 4 Service"); if (qsvrc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { llblStartLocalService.Visible = true; } } } } catch { } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } Cursor.Current = Cursors.Default; }
private void servicezustand_Tick(object sender, EventArgs e) { System.ServiceProcess.ServiceController dienst = new System.ServiceProcess.ServiceController(ProjectInstaller.ServiceName); try { switch (dienst.Status) { case System.ServiceProcess.ServiceControllerStatus.ContinuePending: serviceState.Text = "Continue Pending"; break; case System.ServiceProcess.ServiceControllerStatus.Paused: serviceState.Text = "Paused"; break; case System.ServiceProcess.ServiceControllerStatus.PausePending: serviceState.Text = "Pause Pending"; break; case System.ServiceProcess.ServiceControllerStatus.Running: serviceState.Text = "Running"; break; case System.ServiceProcess.ServiceControllerStatus.StartPending: serviceState.Text = "Start Pending"; break; case System.ServiceProcess.ServiceControllerStatus.Stopped: serviceState.Text = "Stopped"; break; case System.ServiceProcess.ServiceControllerStatus.StopPending: serviceState.Text = "Stop Pending"; break; } } catch (InvalidOperationException) { serviceState.Text = "Dienst nicht installiert!"; } }
/// <summary> /// Intenta Iniciar el Servicio de MSSQLSERVer , en un entorno LocalHost /// </summary> /// <returns></returns> private static bool intentarAbrirServicioDeSQLServerLocalArea() { try { System.ServiceProcess.ServiceController serviceController1 = new System.ServiceProcess.ServiceController(); serviceController1.ServiceName = "MSSQLSERVER"; if (serviceController1.Status == System.ServiceProcess.ServiceControllerStatus.Stopped || serviceController1.Status == System.ServiceProcess.ServiceControllerStatus.Paused) { serviceController1.Start(); return(true); } return(false); } catch (Exception) { return(false); } }
private async Task WaitForStatusChange(System.ServiceProcess.ServiceController serviceController, System.ServiceProcess.ServiceControllerStatus NewStatus) { int count = 0; while (serviceController.Status != NewStatus && count < 30) { await Task.Delay(1000); serviceController.Refresh(); count++; if (NewStatus == System.ServiceProcess.ServiceControllerStatus.Running && serviceController.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { break; } } if (serviceController.Status != NewStatus) { throw new Exception("Failed to change status of service. Current status: " + serviceController.Status + " Desired status: " + NewStatus); } }
public static int StopService() { Log.Write(TraceEventType.Information, "Stop Service"); if (IISHosted) { WebSite site = GetInstallWebSite(); if (site != null) { WebsiteState state = IISHelper.StopWebSite(site.Name); switch (state) { case WebsiteState.Stopped: return(1); case WebsiteState.Started: return(4); default: return(0); } } return(0); } else { try { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("Workshare Compare Service"); sc.Stop(); sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped); return((int)sc.Status); } catch (Exception ex) { Log.Write(TraceEventType.Error, "{0}", ex); return(GetServiceStatus()); } } }
private static void CheckIfHyperVServiceIsRunning() { using (System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("vmms")) { try { if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { if (System.Windows.Forms.DialogResult.Yes == global::System.Windows.Forms.MessageBox.Show("Do you want to stop the Hyper-V Virtual Machine Management Service? This is needed to allow to run VMware. If you press \"No\" the debug will stop.", "Question", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question)) { sc.Stop(); } else { throw new NotSupportedException("VMware start useless, because of running Hyper-V Virtual Machine Management!"); } } } catch (InvalidOperationException) { // service not present } } }
/// <summary> /// Services the stop. /// </summary> /// <param name="WaitForStopping">if set to <c>true</c> [wait for stopping].</param> public static void ServiceStop(bool WaitForStopping) { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(WUSERVICENAME); if (sc == null) { throw new Exception("service \"" + WUSERVICENAME + "\" not found"); } if ( sc.Status != System.ServiceProcess.ServiceControllerStatus.Stopped && sc.Status != System.ServiceProcess.ServiceControllerStatus.StopPending ) { sc.Stop(); } if (WaitForStopping) { sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 10)); } }
static void Main(string[] args) { Process pro = new Process(); string version = "v2.0.50727"; System.Console.WriteLine(args[0]); try { try { System.ServiceProcess.ServiceController myController = new System.ServiceProcess.ServiceController("Servicio-eFact"); myController.Stop(); } catch { } ProcessStartInfo psi = new ProcessStartInfo(); psi.FileName = Environment.GetEnvironmentVariable("windir") + "\\Microsoft.Net\\Framework\\" + version + "\\" + "installutil.exe"; System.Console.WriteLine(psi.FileName); string aux = " /u \"" + @args[0] + "\\eFact-S.exe" + "\""; psi.Arguments = aux; System.Console.WriteLine(psi.Arguments); psi.UseShellExecute = false; psi.RedirectStandardOutput = true; System.Console.WriteLine("Asignar ProcessStartInfo"); pro.StartInfo = psi; System.Console.WriteLine("Ejecutar el Start Process"); pro.Start(); System.Console.WriteLine("Start Process listo"); Console.WriteLine(pro.StandardOutput.ReadToEnd()); pro.WaitForExit(); } catch (Exception ex) { Microsoft.ApplicationBlocks.ExceptionManagement.ExceptionManager.Publish(ex); } Console.WriteLine("Presione una tecla para continuar"); Console.ReadLine(); }
public static bool IsAvailable() { string XgConsoleExe; if (!TryGetXgConsoleExecutable(out XgConsoleExe)) { return(false); } // on windows check the service is actually running if (BuildHostPlatform.Current.Platform == UnrealTargetPlatform.Win64) { try { // will throw if the service doesn't exist, which it should if IB is present but just incase... System.ServiceProcess.ServiceController SC = new System.ServiceProcess.ServiceController("Incredibuild Agent"); if (SC.Status != System.ServiceProcess.ServiceControllerStatus.Running) { return(false); } } catch (Exception Ex) { Log.TraceLog("Unable to query for status of Incredibuild service: {0}", ExceptionUtils.FormatExceptionDetails(Ex)); return(false); } } // Check if we're connected over VPN if (!bAllowOverVpn && VpnSubnets != null && VpnSubnets.Length > 0) { string CoordinatorHost; if (TryGetCoordinatorHost(out CoordinatorHost) && IsHostOnVpn(CoordinatorHost)) { return(false); } } return(true); }
//Get some Service Info private void ShowInfo(System.ServiceProcess.ServiceController tmpSrvCtrl) { try { lstInfo.Items.Add("ServiceName: " + tmpSrvCtrl.ServiceName); lstInfo.Items.Add("Service Status: " + tmpSrvCtrl.Status.ToString()); lstInfo.Items.Add("DisplayName: " + tmpSrvCtrl.DisplayName); lstInfo.Items.Add("MachineName: " + tmpSrvCtrl.MachineName); lstInfo.Items.Add("CanPauseAndContinue: " + tmpSrvCtrl.CanPauseAndContinue.ToString()); lstInfo.Items.Add("CanShutdown: " + tmpSrvCtrl.CanShutdown.ToString()); lstInfo.Items.Add("*************** Dependent Services ********************"); //Check for the Dependent services (if any) foreach (System.ServiceProcess.ServiceController s in tmpSrvCtrl.DependentServices) { lstInfo.Items.Add(s.ServiceName + " is " + s.Status.ToString()); } } catch { MessageBox.Show("Couldn't read Service Info!"); } }
/// <summary> /// This event fires before the installers perform their uninstall operations. /// </summary> /// <param name="sender"> /// The service installer that is performing the installation. /// </param> /// <param name="e"> /// Data specific to this event. /// </param> void serviceInstaller_BeforeUninstall(object sender, InstallEventArgs e) { ApplicationLog.RemoveSource(); try { System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController(this.serviceInstaller.ServiceName); controller.Stop(); } // An error occurred when accessing a system API. catch (System.ComponentModel.Win32Exception) { } // The service cannot be stopped. catch (InvalidOperationException) { } // Remove all of the service settings stored on the computer. Settings.RemoveAllSettings(); // Raise the BeforeUninstall event on the base class. base.OnBeforeUninstall(e.SavedState); }
private void serviceInstaller2_AfterInstall(object sender, InstallEventArgs e) { var serviceName = serviceInstaller2.ServiceName; try { if (!EventLog.SourceExists(serviceName)) { EventLog.CreateEventSource(serviceName, "Log"); // note - it takes a while to create the source so we won't be able to use it till probably next restart } } catch (System.Security.SecurityException secEx) { Trace.WriteLine($"Security exception creating Event log source {serviceName}. You probably don't have permissions."); } using (var sc = new System.ServiceProcess.ServiceController(serviceName)) { sc.Start(); } }
private void llblStartLocalService_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { System.ServiceProcess.ServiceController qsvrc = new System.ServiceProcess.ServiceController("QuickMon 4 Service"); if (qsvrc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { qsvrc.Start(); qsvrc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, new TimeSpan(0, 0, 30)); qsvrc.Refresh(); if (qsvrc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { MessageBox.Show("Service started", "Service", MessageBoxButtons.OK, MessageBoxIcon.Information); llblStartLocalService.Visible = false; } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.serviceController1 = new System.ServiceProcess.ServiceController(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.SuspendLayout(); // // textBox1 // this.textBox1.BackColor = System.Drawing.Color.White; this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.textBox1.Location = new System.Drawing.Point(15, 3); this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.Size = new System.Drawing.Size(159, 20); this.textBox1.TabIndex = 0; // // comboBox1 // this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(189, 3); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(159, 21); this.comboBox1.Sorted = true; this.comboBox1.TabIndex = 1; // // Column_Assignment_Control // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.comboBox1); this.Controls.Add(this.textBox1); this.Name = "Column_Assignment_Control"; this.Size = new System.Drawing.Size(361, 30); this.ResumeLayout(false); this.PerformLayout(); }
static void Main(string[] args) { if (args.Length < 1) { return; } var service = new System.ServiceProcess.ServiceController("AVService"); switch (args[0]) { case "start": if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { try { service.Start(); } catch (Exception e) { MessageBox.Show(e.Message); } } break; case "stop": if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { try { service.Stop(); } catch (Exception e) { MessageBox.Show(e.Message); } } break; } }
public void ChangeAndQueryServiceConfigTest() { using (var sc = new System.ServiceProcess.ServiceController("Fax")) { using (var h = sc.ServiceHandle) { var hSvc = h.DangerousGetHandle(); var st = GetStartType(); var b = ChangeServiceConfig(hSvc, ServiceTypes.SERVICE_NO_CHANGE, ServiceStartType.SERVICE_DISABLED, ServiceErrorControlType.SERVICE_NO_CHANGE); if (!b) { TestContext.WriteLine($"Err: {Win32Error.GetLastError()}"); } Assert.That(b, Is.True); Thread.Sleep(10000); Assert.That(GetStartType(), Is.EqualTo(ServiceStartType.SERVICE_DISABLED)); b = ChangeServiceConfig(hSvc, ServiceTypes.SERVICE_NO_CHANGE, st, ServiceErrorControlType.SERVICE_NO_CHANGE); if (!b) { TestContext.WriteLine($"Err: {Win32Error.GetLastError()}"); } Assert.That(b, Is.True); Assert.That(GetStartType(), Is.EqualTo(st)); ServiceStartType GetStartType() { using (var info = new SafeHGlobalHandle(1024)) { Assert.That(QueryServiceConfig(hSvc, (IntPtr)info, (uint)info.Size, out var _), Is.True); var qsc = info.ToStructure <QUERY_SERVICE_CONFIG>(); return(qsc.dwStartType); } } } } }
/// <summary> /// This event fires after the Install methods of all the installers in the /// Installers property have run. /// </summary> /// <param name="sender"> /// The service installer that is performing the installation. /// </param> /// <param name="e"> /// Data specific to this event. /// </param> private void AfterServiceInstall(object sender, InstallEventArgs e) { // Create a ServiceInstaller object from the sender object. System.ServiceProcess.ServiceInstaller installer = sender as System.ServiceProcess.ServiceInstaller; // If the ServiceInstaller object was created successfully, attempt to // start the service. if (installer != null) { // Attempt to start the service. try { System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController(installer.ServiceName); controller.Start(); } catch (System.ComponentModel.Win32Exception) { // An error occurred when accessing a system API. } catch (InvalidOperationException) { // The service cannot be started. } } }
private void servicezustand_Tick(object sender, EventArgs e) { System.ServiceProcess.ServiceController dienst = new System.ServiceProcess.ServiceController(ProjectInstaller.ServiceName); try { switch (dienst.Status) { case System.ServiceProcess.ServiceControllerStatus.ContinuePending: serviceState.Text = "Continue Pending"; break; case System.ServiceProcess.ServiceControllerStatus.Paused: serviceState.Text = "Paused"; break; case System.ServiceProcess.ServiceControllerStatus.PausePending: serviceState.Text = "Pause Pending"; break; case System.ServiceProcess.ServiceControllerStatus.Running: serviceState.Text = "Running"; break; case System.ServiceProcess.ServiceControllerStatus.StartPending: serviceState.Text = "Start Pending"; break; case System.ServiceProcess.ServiceControllerStatus.Stopped: serviceState.Text = "Stopped"; break; case System.ServiceProcess.ServiceControllerStatus.StopPending: serviceState.Text = "Stop Pending"; break; } } catch (InvalidOperationException) { serviceState.Text = "Dienst nicht installiert!"; } }
bool StopEncodingService() { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("Oyster Encoder"); try { if (sc.CanStop) { if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { sc.Stop(); return true; } } return false; } catch (Exception ex) { m_log.WriteLog("StopEncodingService: ***ERROR***: " + ex.Message); IsDone = true; return false; } }
bool RestartEncodingService() { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("Oyster Encoder"); if (sc.CanStop) { if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { sc.Stop(); // System.Threading.Thread.Sleep(1000); sc.Start(); return true; } } return false; }
private int checkDb() { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(); sc.ServiceName = "MSSQLSERVER"; if (sc == null) { MessageBox.Show("您的机器上没有安装SQL SERVER!", "提示信息"); return -1; } else if (sc.Status != System.ServiceProcess.ServiceControllerStatus.Running) { MessageBox.Show("SQL数据库服务未启动,请点击开启SQL服务!", "提示信息"); return -2; } return 0; }
void myTimer_Tick(object sender, EventArgs e) { System.ServiceProcess.ServiceController dienst = new System.ServiceProcess.ServiceController(StaticServiceConfig.MyServiceName); try { if (oldcnt != Logging.LogEntries.Count) { grdLogentries.ItemsSource = null; grdLogentries.ItemsSource = Logging.LogEntries; grdLogentries.Items.Refresh(); oldcnt = Logging.LogEntries.Count; } } catch (Exception ex) { } try { switch (dienst.Status) { case System.ServiceProcess.ServiceControllerStatus.ContinuePending: lblServiceState.Content = "Continue Pending"; break; case System.ServiceProcess.ServiceControllerStatus.Paused: lblServiceState.Content = "Paused"; break; case System.ServiceProcess.ServiceControllerStatus.PausePending: lblServiceState.Content = "Pause Pending"; break; case System.ServiceProcess.ServiceControllerStatus.Running: lblServiceState.Content = "Running"; break; case System.ServiceProcess.ServiceControllerStatus.StartPending: lblServiceState.Content = "Start Pending"; break; case System.ServiceProcess.ServiceControllerStatus.Stopped: lblServiceState.Content = "Stopped"; break; case System.ServiceProcess.ServiceControllerStatus.StopPending: lblServiceState.Content = "Stop Pending"; break; } } catch (InvalidOperationException) { lblServiceState.Content = "Service not installed!"; } }
public void HighBackProjectInstaller_Committed(object sender, InstallEventArgs e) { System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("HighBack"); controller.Start(); }
private bool TryStartService() { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("CallButler Service", Environment.MachineName); try { if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { if (MessageBox.Show(CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.MainForm_ServiceNotRunning), CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.MainForm_CallButlerService), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly) == DialogResult.No) { return false; } global::Controls.LoadingDialog.ShowDialog(null, CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.MainForm_StartingService), Properties.Resources.loading, false, 0); // Start the service sc.Start(); sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, TimeSpan.FromSeconds(20)); System.Threading.Thread.Sleep(5); return true; } } catch(Exception e) { MessageBox.Show(e.Message); } MessageBox.Show(this, CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.MainForm_ServiceNotFound), "", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; }
private bool StopSystemService(string service) { if (!SystemServiceExists(service)) return false; try { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(); //sc.MachineName = "localhost"; sc.ServiceName = service; if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { sc.Stop(); for (int i = 0; i < 60; i++) { SetProgress(0, 60, i); sc.Refresh(); System.Threading.Thread.Sleep(1000); if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { SetProgress(0, 60, 60); return true; } } SetProgress(0, 60, 60); return false; } return true; } catch (Exception e) { ShowError(e.StackTrace.ToString()); return false; } }
private bool isSQLExpressRunning() { bool retVal = true; try { System.ServiceProcess.ServiceController express = new System.ServiceProcess.ServiceController("MSSQL$SQLEXPRESS"); try { if (express.Status != System.ServiceProcess.ServiceControllerStatus.Running) { if (express.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { express.Start(); } UpdateStatus(0, 0, "Waiting for SQL Express Service", "", false); express.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running); } if (express.Status != System.ServiceProcess.ServiceControllerStatus.Running) { retVal = false; } } catch (Exception ex) { throw new EMMAException(ExceptionSeverity.Critical, "Cannot start SQL Express service", ex); } } catch (Exception ex) { throw new EMMAException(ExceptionSeverity.Critical, "Problem accessing SQL Express service", ex); } return retVal; }
/// <summary> /// 停止Windows服务 /// </summary> /// <param name="serviceName">服务名称</param> public static void WindowsServiceStop(string serviceName) { System.ServiceProcess.ServiceController control = new System.ServiceProcess.ServiceController(serviceName); control.Stop(); control.Dispose(); }
internal static bool EnsureSqlExpressServiceIsRunning() { System.ServiceProcess.ServiceController cc = new System.ServiceProcess.ServiceController("MSSQL$SQLEXPRESS"); bool result = true; if (cc == null) { throw new Exception("SQLExpress Windows Service not found. Please install SQL Server Express."); } if (cc.Status != System.ServiceProcess.ServiceControllerStatus.Running) { if (MessageBox.Show("SQLExpress is not running. Start?", "SQL Express", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { cc.Start(); cc.Refresh(); if (cc.Status != System.ServiceProcess.ServiceControllerStatus.Running) { MessageBox.Show(@"There was a problem starting the SQLExpress Windows Service. Please start it using 'Control Panel\Administration Tools\Services' .", "SQL Express", MessageBoxButtons.OK, MessageBoxIcon.Error); result = false; } } else { result = false; } } return result; }
private void button2_Click(object sender, EventArgs e) { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(); sc.ServiceName = "MSSQLSERVER"; if (!sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Stopped)) { sc.Stop(); MessageBox.Show("SQL数据库服务已经关闭!", "提示信息"); } }
private string GetSystemServiceStatus(string service) { try { //foreach (System.ServiceProcess.ServiceController sc in System.ServiceProcess.ServiceController.GetServices()) //{ // if (sc.ServiceName.ToUpper().CompareTo(service.ToUpper()) == 0) // { // return sc.Status.ToString(); // } //} System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(); //sc.MachineName = "localhost"; sc.ServiceName = service; sc.Refresh(); switch (sc.Status) { case System.ServiceProcess.ServiceControllerStatus.StartPending: return "服务正在启动!"; case System.ServiceProcess.ServiceControllerStatus.ContinuePending: return "服务即将继续!"; case System.ServiceProcess.ServiceControllerStatus.Paused: return "服务已暂停!"; case System.ServiceProcess.ServiceControllerStatus.PausePending: return "服务即将暂停!"; case System.ServiceProcess.ServiceControllerStatus.Running: return "服务正在运行!"; case System.ServiceProcess.ServiceControllerStatus.Stopped: return "服务未运行!"; case System.ServiceProcess.ServiceControllerStatus.StopPending: return "服务正在停止!"; default : return "服务状态未知!"; } } catch (Exception e) { //ShowError(e.StackTrace.ToString()); return "Error:" + e.Message; } }
/// <summary> /// Stop the service that depends on the process and its child services /// </summary> /// <param name="process"></param> private void StopDependentService(Process process) { string queryString = "Select * From Win32_Service Where ProcessId=" + SafeGetProcessId(process) + " And State !='Stopped'"; try { using (CimSession cimSession = CimSession.Create(null)) { IEnumerable<CimInstance> serviceList = cimSession.QueryInstances("root/cimv2", "WQL", queryString); foreach (CimInstance oService in serviceList) { string serviceName = oService.CimInstanceProperties["Name"].Value.ToString(); using (var service = new System.ServiceProcess.ServiceController(serviceName)) { //try stopping the service, if cant we are not writing exception try { service.Stop(); // Wait 2 sec for the status to become 'Stopped' service.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 2)); } catch (Win32Exception) { } catch (InvalidOperationException) { } catch (System.ServiceProcess.TimeoutException) { } } } } } catch (CimException ex) { var errorRecord = new ErrorRecord(ex, "GetCimException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } }
void ServiceInstaller_Committed(object sender, InstallEventArgs e) { // Auto Start the Service Once Installation is Finished. var controller = new System.ServiceProcess.ServiceController(this.serviceInstaller1.ServiceName); controller.Start(); }