How to keep Windows Service running after computer is restarted? - c#

I have this Windows Service (using SqlDependency) that sends me an e-mail everytime it is started and everytime a new row is inserted on my Sales table (the database has Service Broker enabled).
I also write a log file to register when the service is started, the data is inserted to the table, if the e-mail was successfully sent and when the service is stoped.
When I started the service manually, it worked just fine.
Then I turned my PC off and on again and inserted data on my table
in the database, but nothing happened (no e-mail sent and no
register in my log file).
I restarted the service manually and it worked fine again.
Turned the PC off and on again and nothing heppened again.
I made some research and changed the initialization type to Automatic
and tried again. And nothing happened again.
I changed the initialization type to Automatic Delayed and tried
again. But it didn't work too, even 1 hour after I turned the PC on.
Now I manually restarted the service and the log file registered that
the service stoped and started, I received the email that the service
started and, after I inserted data in my database table, both log
register and email message worked just fine.
Everytime it didn't work, I checked the services manager in Windows and it was marked as "Running".
I don't know if I need to configure something different in my code or in my service properties.
Has anybody ever had this issue?
EDIT
I modified my service and included a timer, so every minute passed it writes the time in my log text file. After I restarted my PC, the log file continued to register the time every minute, but did not register the insert I made in my database table.
My guess is that the service might be losing the database connection when the PC is restarted, so the SqlDependency cannot detect the changes. Does it make any sense?

Your service depends on SQL Server, but your service is probably starting before SQL Server has been started, or finished starting. This may be causing your SqlDependency to fail.
You can mark your service as being dependent on SQL Server, which means:
Windows won't attempt to start your service until SQL Server has started and is ready, and
Starting your service will cause Windows to start SQL Server before it starts your service
This can be achieved on the command-line with the sc command (which will need to be run at an administrative command prompt). If your SQL Server instance is named MSSQLSERVER and your service is named MyService the command would look like this:
sc config MyService depend= MSSQLSERVER
Note: The space after = and before MSSQLSERVER matters. The detailed syntax can be found on learn.microsoft.com.
Once this command has run successfully, this is what you'll see when looking at the properties of your service in Control Panel > Administrative Tools > Services:

Related

log4net and event logging suddenly stopped working on Windows service

I have a Windows service (c#, .net v4.5.2) that runs daily and is supposed to log errors to the Windows Event log (via System.Diagnostics) and errors plus progress information to the database (via log4net). Log4net is set to write "INFO" level.
Both logging mechanisms were working fine last time I looked, but last night the Windows service failed. I went to the d/b and event log and found that it hasn't written to either since 20th June, until it logged the automatic restart (to both logs) after it crashed last night.
Platform is a Windows 2012R2 VM in Azure. The service takes change-tracked SQL updates from a slave database, applies them to the master database, backs up the master and restores it over the slave, the log4net log is on the master. It's all been running fine, it just gave up logging.
Can anyone explain why it might have stopped logging to both log4net and the Windows event log?
The application server, domain controller and database server were all rebooted at the same time on the day log4net stopped logging. The likely cause therefore is that when the application server started up and the Windows service started, log4net was unable to connect to the database and shut down.
(Absence of Windows events probably a red herring - since the service was otherwise running happily without any errors, there just wasn't anything for it to write to Windows events.)

Windows Service is running but not working

I have wrote two multi-threaded windows service.
Both connects to the same database.
Both are having a WCF service reference.
Say Service "A" is for getting the data from WCF service and writes it down to the connected database.
Say Service "B" is for getting the data from connected database and send it to WCF service.
Both starts perfectly and keeps running perfectly for days (though, i have not noted the frequency) But then something occurs and Service "A" status stays on "Running" but it isnt actually running. (I can say this because I am writing log file whenever the service perform something). However Service "B" has never got any problem.
For the resolution, I need to force kill the service using Command Prompt and then restart it. I have checked the event logs but nothing found. RAM is also available so memory is also not an issue.

There are no active servers. Background tasks will not be processed

I have a problem which I already looking at it for a few days and still have no solution.
I found this exception in my C# web app log.
[2015-12-03 13:56:06] [ERROR] [] [Error occurred during execution of
'Server Bootstrapper' component. Execution will be retried (attempt
120 of 2147483647) in 00:05:00 seconds.]
[System.Data.SqlClient.SqlException (0x80131904): Login failed for
user "A Network account".
It appears to me that it is using the network account to access the SQL database and because that network account is not granted access to the database, hence login failed and server cannot startup.
However, when I go to the Hangfire dashboard, I can see the recurring jobs, which seems to me that hangfire can access the database with the right account for retrieving the recurring jobs.
Also, in the IIS server, we already set the Identity to "ApplicationPoolIdentity" for the application pools. Hence, we should use the virtual account instead of the network account.
May I know anyone has the similar problem and have the solution. Really appreciate for your help!!
I ran into the same issue using Hangfire with SQL Server and EntityFramework Code First where EntityFramework was responsible for creating the database, so this suggestion is based purely off of that scenario.
If you are using EF Code First, your database isn't created until the context is created and accessed for the first time.
This means that at App Start your database might not exist. Hangfire won't create the database, it only creates the tables in an already existing database.
So what you might be seeing is:
No database exists.
Your app start's up and Hangfire tries to get itself running, the server process throws an error because EF hasn't created the DB.
The web application start finishes since the hangfire service crashing isn't fatal to the application.
Something in your web app calls into EntityFramework.
EF runs and creates the database (likely no hangfire tables at this point)
you access the hangfire dashboard, hangfire is now able to connect, and see the tables don't exist, so it creates them. (now you will see the tables in your db)
The dashboard can now see the database and show you the stats (likely 0 servers running) so it seems like everything is working.
The way I solved it was to make sure that even if the database is empty (not tables), it is at least created. This was hangfire can access it to install it's tables and start, and EF can access it, and create it's schema.
Also, (and this probably isn't it), GlobalConfiguration.Configuration.UseSqlServerStorage() should run first before other Hangfire startup configuration.
Hope that helps!
Steve
You should create background job server instance, see document here
In my case, the server name was too long and there was a SQL error saying it would be truncated. I was only able to see this error after starting it with Just My Code turned off in Visual Studio.
Moral of the story: Use a shorter name for the server and don't append your own unique-per-instance identifiers to it so it can't run into a truncate error. The column is an nvarchar(100).

Starting Windows service automatically at Windows startup that is dependent on Oracle

I have developed a Windows Service, that must start automatically during Windows startup. This service connects to an Oracle db, so I made my service dependent on Oracle Services by sc command line utility:
sc config MyService depend= OracleServiceXE/OracleXETNSListener
So far so good, dependency was set succesfully. But when Windows starting, my service could not start, I get the following (Oracle) error message: "ORA-12528: TNS:listener: all appropriate instances are blocking new connections".
As I think, the Oracle services are started when my service starts, but they are not 'fully initialized'. After some seconds I can start my service from service consol without any problem.
So, how can I start automatically my service at Windows Startup which is dependent on an Oracle DB connection?
My service was developed in C# on .Net 4 platform, in VS 2010 environment.
Pls. help me, it is a really important task form me!
Remember, the code for your service's startup should do as little as possible. In other words, don't have your service startup check for availability of the Oracle server, or indeed do anything. Have your service do the following:
Log the fact that it's started
Load any applicable configuration from config files/registry/etc
Spin-up a thread that will try and "startup" the service properly every N seconds, and will repeat M times until it gives up. Have N and M configurable from your config file/registry
Have the thread "try" to connect to the applicable Oracle server and if it fails, go to sleep for N seconds, and do this M times. If it succeeds it can then start doing the "meat" of what it's supposed to.
Ironically, it's probably the fact that the Oracle service does something similar to what I've proposed you do that's causing you the problem. By returning "Yes, I've started" quickly back to Windows when it's started, it allows your service to then be loaded, even though Oracle is still busy spinning stuff up. Ideally in this scenario rather than rejecting your requests, Oracle should enqueue them for processing when it is ready.

How to Synchronize Windows Service Access to SQL Server Database on Startup?

I have a WCF service that is running as a windows service. As soon as the WCF service starts it will try to connect to the DB and do some initialization processing.
I'm having an issue when I restart my machine (the wcf service is set to start automatically), the service would get an exception as too sql is busy. So it seems like the sql is trying to start and at the same time my service is trying to communicate with it.
For now, I did something like try/catch and I sleep for like 10 sec in my catch and I retry again until my initialization is successful.
This works pretty well. But I'm looking for a more elegant solution.
I don't want to set a dependency on sql on my windows service as the service can be installed on a different machine that the DB.
You might try configuring the "Recovery" options of your service when you deploy it to have it restart itself when it fails to load. You can do this via the SC.EXE command-line tool, WMI, or manually through the service properties (services.msc MMC).
Trying [n] times, with some timespan between retries, before ultimately failing if still unable to connect is not a bad solution if you consider monitoring and alerting.
The service actually failing to start will write warning/error events to the Windows event log, potentially triggering monitoring and alerting behavior that you might not want if its just waiting on a dependency to be available, and it will eventually recover.
HTH,
Z

Categories

Resources