Windows Service will not start as Local User - vb.net

EDIT 2: I now believe this is an issue with the machine I'm attempting to run the service on. I tried moving the service to a different machine that is setup similarly and the service was able to start successfully even as a Local User. Now I just need to figure out what's different between the two machines...
I have a Windows Service project (written in VB.net) that is installed and configured with a Startup Type of Automatic and the Log On As set to a Local User account. This service will start when the computer first starts up. However, if I stop the service and try to start it again, I get "Error 1053: The service did not respond to the start or control request in a timely fashion." immediately. However, if I change the Log On As to "Local System account" then the service will start.
Summary:
Service will run as Local User when computer first starts
Service will not run as Local User if started manually
Service will run as Local System when computer first starts
Service will run as Local System if started manually
I have read that Error 1053 is caused by the OnStart method not returning quickly enough. The fact that the service has started previously, and that I get the error message immediately, leads me to believe a timeout is not what's going on. To verify this, I created a completely new Windows Service Project and without changing anything I built and installed it. I get the same behavior.
I am at a loss as to what's happening. As far as I can tell, the Local User has all of the correct privileges to run a service (as is evident by the fact that it will start with those credentials when it the computer is first starting up), and the OnStart method isn't actually timing out (as is evident by the completely blank dumb service exhibiting the same behavior).
Any ideas as to what's preventing the service from starting, or where I can look for better error messages (I have looked in the Application Event Log, but nothing shows up there)?
EDIT:
Here is the code from the dumb service I created (using the EventLogger from here as a module).
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
EventLogger.WriteToEventLog("On Start")
End Sub
Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
EventLogger.WriteToEventLog("On Stop")
End Sub
And the Main method of the same project.
' The main entry point for the process
<MTAThread()> _
<System.Diagnostics.DebuggerNonUserCode()> _
Shared Sub Main()
EventLogger.WriteToEventLog("Starting Main Method")
Dim ServicesToRun() As System.ServiceProcess.ServiceBase
ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
EventLogger.WriteToEventLog("Leaving Main Method")
End Sub
When I try to run the Service as the Local User, none of the messages show in the Event Log and I get Error 1053. When I run the Service as the Local System, the messages show in the Event Log.
The reason I need to run the actual service as the Local User is so that it can access a network share. I am currently looking into using Windows User Impersonation, but I still think I should be able to start a simple service as a Local User.

Use this resource to create an event logger. Then wrap your code in each sub in a try/catch b/c most likely something is happening in your OnStart sub that is preventing the service from starting. Post some sample code of your onstart, onstop, and/or your service main subs and clarify why you need to use the local user vs the local system.

Related

Topshelf Windows Service times out Error 7000 7009

I have a windows service programmed in vb.NET, using Topshelf as Service Host.
Once in a while the service doesn't start. On the event log, the SCM writes errors 7000 and 7009 (service did not respond in a timely fashion). I know this is a common issue, but I (think) I have tried everything with no result.
The service only relies in WMI, and has no time-consuming operations.
I read this question (Error 1053: the service did not respond to the start or control request in a timely fashion), but none of the answers worked for me.
I Tried:
Set topshelf's start timeout.
Request additional time in the first line of "OnStart" method.
Set a periodic timer wich request additional time to the SCM.
Remove TopShelf and make the service with the Visual Studio Service Template.
Move the initialization code and "OnStart" code to a new thread to return inmediately.
Build in RELEASE mode.
Set GeneratePublisherEvidence = false in the app.config file (per application).
Unchecked "Check for publisher’s certificate revocation" in the internet settings (per machine).
Deleted all Alternate Streams (in case some dll was marked as web and blocked).
Removed any "Debug code"
Increased Window's general service timeout to 120000ms.
Also:
The service doesn't try to communicate with the user's desktop in any way.
The UAC is disabled.
The Service Runs on LOCAL SYSTEM ACCOUNT.
I believe that the code of the service itself is not the problem because:
It has been on production for over two years.
Usually the service starts fine.
There is no exception logged in the Event Log.
The "On Error" options for the service dosn't get called (since the service doesn't actually fails, just doesn't respond to the SCM)
I've commented out almost everything on it, pursuing this error! ;-)
Any help is welcome since i'm completely out of ideas, and i've been strugling with this for over 15 days...
For me the 7009 error was produced by my NET core app because I was using this construct:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
and appsettings.json file obviously couldn't be found in C:\WINDOWS\system32.. anyway, changing it to Path.Combine(AppContext.BaseDirectory, "appsettings.json") solved the issue.
More general help - for Topshelf you can add custom exception handling where I finally found some meaningfull error info, unlike event viewer:
HostFactory.Run(x => {
...
x.OnException(e =>
{
using (var fs = new StreamWriter(#"C:\log.txt"))
{
fs.WriteLine(e.ToString());
}
});
});
I've hit the 7000 and 7009 issue, which fails straight away (even though the error message says A timeout was reached (30000 milliseconds)) because of misconfiguration between TopShelf and what the service gets installed as.
The bottom line - what you pass in HostConfigurator.SetServiceName(name) needs to match exactly the SERVICE_NAME of the Windows service which gets installed.
If they don't match it'll fail straight away and you get the two event log messages.
I had this start happening to a service after Windows Creator's Edition update installed. Basically it made the whole computer slower, which is what I think triggered the problem. Even one of the Windows services had a timeout issue.
What I learned online is that the constructor for the service needs to be fast, but OnStart has more leeway with the SCM. My service had a C# wrapper and it included an InitializeComponent() that was called in the constructor. I moved that call to OnStart and the problem went away.

Required methods for a VB.NET service?

I’m taking over a project in VB.NET. The project is a windows service that is responsible for processing certain information from several databases and creates a text files with information required by the business. I'm having problems when starting the service once compiled. Every time I try to start the service the following error appears.
Error 1053: The service did not respond to the Start or Control
Request in a Timely Fashion.
My impression is that for some reason when I compile the project, the executable that is created does not have the characteristics that distinguish it as a Windows service. When I double click the .exe file no error appears anywhere. But through the Service Manager never works.
I saw in the code base that the Public Sub Main () method is commented. My question is, it is a requirement that in order to compile the project to be recognized as a service a Public Sub Main () method should be defined at least once in the code base?

vb.net console / service app

I'd like to enable my console app. to be installed also as a service using command prompt arguments, handling the following commands
d\:>myapp -console
d\:>myapp -install
d\:>myapp -uninstall
My vb.net service template is as follows,
Public Class MyService
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
End Sub
End Class
How I should proceed to run it as console and/or console.
Thanks in advance,
m0dest0
Ps. using vb.net and Vs 2008
Ps2. The kind of taks to be performed is suitable to be implemented either in console or service. Basically it will monitor files in a specific folder and the process the info.
This is doable, I have a service that does this very thing.
The main business logic should be encapsulated such that it can be run (launched as a thread) from within the Service or from a shared sub Main.
You will need to add a service installer if there is not one already, but the VS template adds that for you so you should be all set.
In your Main, you have to parse the command line (obviously) and execute the appropriate action. I would recommend, for one-stop-shopping, adding a -start and -stop command line option as well to stop and start the service.

Ensure a windows service is started from Visual Basic .Net

I have a WCF service being hosted in a Windows Service (using techniques discussed here) and it works great. I'm now writing a (VB.Net) frontend app that needs to call that service, but I don't want my users having to fiddle around with the services snap-in and starting the service manually.
Can I write some code to ensure the Windows Service is started, or start it if it isn't?
Edit: OF course, I can ensure the Service startup is set to automatic, but it doesn't need to be running all the time, and even then the frontend app still needs to be sure the service is running and start it if it isn't.
You can use the ServiceController class to manipulate a service as needed.
Example from MSDN using the Status property to check if a service needs to be started:
' Toggle the Telnet service -
' If it is started (running, paused, etc), stop the service.
' If it is stopped, start the service.
Dim sc As New ServiceController("Telnet")
Console.WriteLine("The Telnet service status is currently set to {0}", sc.Status)
If sc.Status.Equals(ServiceControllerStatus.Stopped) Or sc.Status.Equals(ServiceControllerStatus.StopPending) Then
' 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()
End If
' Refresh and display the current service status.
sc.Refresh()
Console.WriteLine("The Telnet service status is now set to {0}.", sc.Status)
You can do something like
Dim controller As New ServiceController("ServiceNameHere")
If controller.Status = ServiceControllerStatus.Stopped Then
controller.Start()
End If
Remember to add reference to and import System.ServiceProcess

How can I write to a custom event log from my ASMX web service running as network service?

I have a ASMX web services running as 'network service'. I want to be able to write to a custom event log every time a web service is called (and when errors happen).
I have created a new event log (MyLog) using the following code running as admin on a Windows server 2008 machine:
if (!EventLog.SourceExists(APPLICATIONNAME))
{
EventLog.CreateEventSource(APPLICATIONNAME, EVENTLOGNAME);
}
EventLog.WriteEntry(APPLICATIONNAME, "Service started", EventLogEntryType.Information);
where APPLICATIONAME is "MyApp" and EVENTLOGNAME is "MyLog" (names changed to protect the innocents).
Firstly, it creates a new "MyLog" event log (verified with eventvwr), but its contents are the same as the Application event log. I was expecting to get an empty, non-connected event log.
Secondly, when I try to write to the newly created event log from within the Application_Start method using the following code:
EventLog.WriteEntry(APPLICATIONNAME, "Service started", EventLogEntryType.Information);
I get a SecurityException of type System.Diagnostics.EventLogPermission.
I have tried to change the ACLs of the "MyLog" hive in the registry (as suggested on MSDN) but to no avail.
I'd rather not change the identity of the web service nor change the ACLs on the Application event log which is used by other applications on the system.
Since my web service is running in the context of SharePoint, I simply wrapped the call to EventLog.WriteEntry with SPSecurity.RunWithElevatedPrivileges.