how to start the MYSQL service before my Windows service - c#

I have the windows service program which runs and sometime throw exception about system null reference. After my investigation, this is due to MySQL connection cannot establish due to MySql instance not up yet when startup computer. How to solve this problems???
thanks in advance

You can set in Windows the dependencies of each service.
You can go into Control Panel -> Administrative Tools -> Services (or run 'services.msc' from the command line). By double clicking any of the services and going to the Dependencies tab you can see what each service relies on.
Your service relies on the MySql service, so MySql should be in the dependencies list for it.
You can add items to the dependencies, here is a description of how to do this:
https://serverfault.com/questions/24821/how-to-add-dependency-on-a-windows-service-after-the-service-is-installed

This article can give you a hint on how code service dependencies:
http://bloggingabout.net/blogs/jschreuder/archive/2006/12/07/How-to_3A00_-Code-Service-Dependencies.aspx

Try the following code if you want to do it by yourself without dependencies
//Check if service is running
ServiceController mysqlServiceController = new ServiceController();
mysqlServiceController.ServiceName = "MySql";
var timeout = 3000;
//Check if the service is started
if (mysqlServiceController.Status == System.ServiceProcess.ServiceControllerStatus.Stopped
|| mysqlServiceController.Status == System.ServiceProcess.ServiceControllerStatus.Paused)
{
mysqlServiceController.Start();
try
{
//Wait till the service runs mysql
ServiceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, new TimeSpan(0, timeout, 0));
}
catch (System.ServiceProcess.TimeoutException)
{
//MessageBox.Show(string.Format("Starting the service \"{0}\" has reached to a timeout of ({1}) minutes, please check the service.", mysqlServiceController.ServiceName, timeout));
}
}

Related

How to solve "Error 1064: An exception occurred in the service when handling the control request."?

I'm a beginner, trying to develop a windows service that sends emails before the expiration date of an insurance policy. I set the service for auto start, yet it doesn't appear to start automatically (seen on Services console). And when I start it manually, it does send the alerts but stops with error 1064, which after checking the event viewer is caused by other instance of the service, already running. Yet, if I don't attempt to start the service manually no alerts are sent.
I tried to uninstall the service using installutil and reinstall it, to assure there's only a single instance running.
//According to event viewer this is the block of code where the issue occurs.
ServiceController[] services = ServiceController.GetServices();
// Iterating each service to check that if a service named
// EmailExpiracaoSeguroAuto is found then check that its status whether
// it is running or stopped. If found running then it will
// stop that service; else it starts that service
foreach (ServiceController x in services)
{
if (x.DisplayName == "EmailExpiracaoSeguroAuto")
{
if (x.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
x.Stop();
}
else
{
//More precisely HERE
x.Start();
}
}
}
}
My expectation is being able to overcome this error, having the service starting automatically and keep it running.

Could not start Windows Service, Error 1064

I wrote a Windows Service to run on Win10, and it worked perfectly fine until I decided to change it a bit. I rewrote some logic, tested it in both Debug and Release configurations, and everything was fine. Then I uninstalled the current version of the service using installutil.exe /u %servicename.exe% and reinstalled it again using installutil.exe %servicename.exe%.
For some reason, this new version cannot start, and it crashes with Error 1064. This is the full error text:
Windows could not start %servicename% service on Local Computer. Error 1064: An exception occurred in the service when handling the control request.
The last time I installed this service, I ran into some difficulties, but quickly fixed them by changing the Log On properties. This time, it is not working. Please help with this issue.
Thanks.
Update 1
Here are my Main() and OnStart() service methods:
Main()
static void Main()
{
#if DEBUG
var service = new SalesforceToJiraService();
service.OnDebug();
Thread.Sleep(Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new SalesforceToJiraService()
};
ServiceBase.Run(ServicesToRun);
#endif
}
OnStart()
protected override void OnStart(string[] args)
{
this.ConfigureServices();
this.timer.Start();
this.logger.Information("SalesforceToJira service started.");
}
Update 2
More code:
ConfigureServices()
protected void ConfigureServices()
{
this.configuration = ConfigurationHelper.LoadConfiguration(ConfigurationPath);
this.logger = ConfigurationHelper.ConfigureLogger(this.configuration.Logs.LogsPath);
this.timer = ConfigurationHelper.ConfigureTimer(this.configuration.ProcessInterval.TotalMilliseconds,
(sender, eventArgs) => this.ProcessCasesAsync(sender, eventArgs).GetAwaiter().GetResult());
this.salesforceClient = new SalesforceCliClient(this.configuration.Salesforce.CliPath);
this.jiraClient = Jira.CreateRestClient(
this.configuration.Jira.Url,
this.configuration.Jira.Username,
this.configuration.Jira.Password);
}
I'm using Newtonsoft.JSON for deserializing a JSON configuration file, Serilog for logging, System.Timers.Timer for periodic events, AtlassianSDK for the Jira API and some wrappers over Salesforce CLI for Salesforce.
Thanks to #Siderite Zackwehdex's comment, I was able to find the full stack trace of the underlying exception in EventViewer, under:
Windows Logs\Application
In my case, my service is named "HttpDispatcher", which appears in the "Source" column in the top pane.
I could see immediately it was due to a dependency issue where my .NET 4.7.2 project was not pulling across my .NET Standard references. (That ol' chestnut).
I faced the same issue. The reason was I forgot to set the Database connection properly in configurations.
I had this exact same error 1064 starting my service. For me the user I had the service registered as was not a valid user in the database. Once added, it worked great.
I also had the same error in my Windows Service.
The reason was it can't read a configuration parameter, so it crash.
Adding some validation (bugfixing), the Windows Services can start it correctly.
In my case the error was due to issues with Event log name
It got fixed after I went to RegEdit and deleted old service name from HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
I have also faced this issue. In my case it is due to connection fail with the data base. I think it is due to code throw the exception.
My error :
Windows could not start the service1 service on local computer.
Error 1064: An exception occured in the service when handling the control request
I corrected my issue by updating the third party DLL.
I faced the same issue, here is how I resolved it after troubleshooting.
If you are running service on the Server with multiple users, make
sure to run the service as admin user. Click on the service
properties and then on Log on tab click on this account and provide
the admin user name and password.
And If your service is accessing some shared drive, then make sure
you have a general user on all servers for accessing the shared
drives and add the user as local admin as well.
For me it happened when I tried to restart a process. Turned out the process was hanging in 'Stopping' so I had to kill it manually via command line and the PID.

Can't access ServiceController (InvalidOperationException) when trying to read on remote/another computer

I have a local service running on my computer and trying to get other computers to be able to read the status of my service (whether it's running, stopped, etc.) However, I am unable to as I get an InvalidOperationException error, saying that I am unable to open Service Control Manager. Locally, I am able to, but on another remote computer I am unable to. The ServiceController (cs) object just returns an object with properties that all have the InvalidOperationException error.
I've tried closing down all the firewalls on the other computers, tried running Visual Studio on Administrator privileges, but nothing seems to be working. I've noticed that others suggested hard coding your admin credentials and using WindowsIdentity and Impersonation but that wouldn't work for my project (as it wouldn't be a viable solution at my workplace - wouldn't make sense with the business logic as don't want to give clients any in-house credentials).
Here's my snippet of code:
public bool CheckServiceStatus()
{
try
{
string machineName = pubSubConfig.MachineName;
string serviceName = pubSubConfig.ServiceName;
System.ServiceProcess.ServiceController cs = new System.ServiceProcess.ServiceController(serviceName, machineName);
if (cs != null && cs.ServiceName == serviceName && cs.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
return true;
}
}
catch(Exception ex)
{
Trace.TraceError("Unable to check service status: /r/n {0}", ex.Message);
}
return false;
}
The error is this:
System.InvalidOperationException: Cannot open Service Control Manager on computer '___'.
This operation might require other privileges. ---> System.ComponentModel.Win32Exception: Access is denied
Does anyone know any workarounds as to how I can get other computers running my C# program to be able to read the ServiceController object?
Thanks!
So as I said in the comments, I was not able to get around the SCM (Service Control Manager) due to admin privileges when accessing another remote computer (makes sense if you think about security). However, I did find another solution that was more or less a workaround. I'll post the solution here in case anyone finds it helpful.
So to check the status of the Windows Service (like if it's running or not), I added an additional WCF service that is hosted in the Windows Service. So now the service can expose a method that literally just returns true.
Essentially the thought-process around it was that if the WCF service is accessible then that means the Window Service is running, and thus will always return true. If the Windows service is down, the WCF service will also be down and thus making that method not available. You wouldn't get anything to return, so you would know that the service is down and not running.
Hope that helps someone! I know it's not really a direct solution to the problem I had originally asked, but it was a workaround, indirect solution.

How to Programatically Start IIS 6.0 SMTP Virtual Server?

I would like to know how to programatically restart IIS 6.0 SMTP server.
The SMTP server I have setup crashes every now and then. I don't notice it for a couple days, but that is by far way too late to do anything about it.
I want to set up a scheduled task every 30 minutes or so to test if the SMTP server is running, and if its not, the Scheduled task with automatically start it back up.
I have found a way to check if the SMTP server is up and running, but I have not figured out how to restart the process if it crashes.
That way is posted here: Testing SMTP server is running via C#
Any help would be brilliant!
Thank you.
Im developing the Console application in C# to check if its running or not, so any code examples would be great too.
A ServiceController can help you, as it has start and stop methods. Look at the sample in the msdn page.
Another sample is taken from the ServiceControllerStatus Enumeration is nearly what you need (just replace the service name).
ServiceController sc = new ServiceController("Telnet");
Console.WriteLine("The Telnet service status is currently set to {0}",
sc.Status.ToString());
if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) ||
(sc.Status.Equals(ServiceControllerStatus.StopPending)))
{
// Start the service if the current status is stopped.
Console.WriteLine("Starting the Telnet service...");
sc.Start();
}
else
{
// Stop the service if its status is not set to "Stopped".
Console.WriteLine("Stopping the Telnet service...");
sc.Stop();
}
// Refresh and display the current service status.
sc.Refresh();
Console.WriteLine("The Telnet service status is now set to {0}.",
sc.Status.ToString());
Maybe I'm missing something, or something changed, but when you install SMTP service on Windows 2012R2, there is no dedicated service for it. So, for recent version of Windows the advice above won't work.
Luckily there's a way to do it much easier. Powershell:
([ADSI]'IIS://LOCALHOST/SMTPSVC/1').Start() #to start
([ADSI]'IIS://LOCALHOST/SMTPSVC/1').Stop() #to ... you guess
The weirdest thing is that you control smtp service through AD, but it works.
And of course this should be run elevated.
If you have several virtual SMTP servers, you may need to identify your server by index or by some property (e.g. .ConnectionTimeout) first.
in c# you can write:
enum StatusVirtualServerSMTP
{
Started = 2,
Stopped = 4
}
DirectoryEntry dir = new DirectoryEntry("IIS://localhost/SMTPSVC/1");
if (Convert.ToInt32(dir.Properties["SERVERSTATE"].Value) == (int)StatusVirtualServerSMTP.Stopped)
{
dir.Properties["SERVERSTATE"].Value = (int)StatusVirtualServerSMTP.Started;
dir.CommitChanges();
}

Why does my .NET service start really slow on a XP boot

I have a .NET windows service which acts as a host for some wcf. In the OnStart method the service hosts are created and started. The service is configured to startup automatically. This works well on Windows 7 (32bit and 64bit) and it can be startet with "net start" on Windows XP Pro SP3. The service startup with "net start" command takes about 20 seconds.
But when Windows XP Pro SP3 is booting there's a timeout message in the event log. The service itself does not fail to startup, though do its dependencies. The problem can be reproduced on various XP machines. Core count and memory does not have an influence. The updates are up to date.
Now it's getting curious: I analyzed the trace and found out that the service is taking about 60 seconds for startup. Thus I've added a call to ReqestAdditionalTime(480000). But now the service takes slightly more than 480 seconds. The relation is obvious. The time is consumed in the following code section:
var asyncResults = new List<IAsyncResult>();
foreach (var host in myHosts)
asyncResults.Add(host.BeginOpen(null, host));
// wait until finished
while (asyncResults.Count != 0)
{
IAsyncResult ar = asyncResults[0];
if (!ar.IsCompleted) ar.AsyncWaitHandle.WaitOne(1000);
if (ar.IsCompleted)
{
asyncResults.Remove(ar);
var co = (ICommunicationObject)ar.AsyncState;
try
{
co.EndOpen(ar);
}
catch (Exception ex)
{
...
}
}
}
Do you have any idea what's happening here?
Hey, I found the resolution myself by doing some intensive Log-Research.
In the event log there were some services, which started AFTER the timeout of my service has been reached. As my service is running as a sepecial user, I could detect two services, which where acutally triggered by my own service. Thus I added those to the services dependencies and it works.
I wonder if there's a documentation, where the dependencies of wcf are listed.
As reference here are the services, my service is dependen on:
http
RPCSS
CryptSvc
HTTPFilter
RasMan
Latter two where those causing the deadlock.

Categories