How to start windows service from application - winapi

I have a Windows Service and i want to start it using ServiceController.The service runs as LocalSystem.When i am trying to Start it i get:
System.InvalidOperationException: 'Cannot open [service] service on
computer '.'.' Inner Exception Win32Exception:Access is denied
Main
static void Main(string[] args) {
using (ServiceController controller = new ServiceController("someService")) {
controller.Start();
}
}
Can i somehow elevate the rights programatically in order to start the service (even if i need to use P/Invoke for Winapi ? ) .

You do indeed need to elevate. That requires creating a new process to start the service, either explicitly with the runas shell verb, or using the COM elevation moniker.

Related

Worker Service on Docker returns 1053 Error on startup

First, Docker novice.
Attempting to run a .Net5 Worker Service on a mcr.microsoft.com/windows/servercore:1909 docker image with the .Net5 and 3.1 sdks installed onto the system.
The Service is being installed by a C# program (its part of a larger package) that is using a wrapper for the advapi32.dll to create and otherwise work with the Windows Services and SCM. On other computers, including the host system, the service is installed correctly and will continue running. After installation on the docker image, the service (startup as AutomaticDelayed) is created but will return "The service did not respond to the start or control request in a timely fashion" as the only error.
Both from viewing the logs and running the service manually (from powershell) on the docker container, the service will continue running until the SCM kills it from timeout. I have extended ServicesPipeTimeout registry item to 10 minutes and the SCM will still timeout the application after it fails to respond.
Any thoughts?
EDIT: Had question about using .UseWindowsService() but we were already using that. This is the program main that all our services are using.
public class Program
{
public static void Main(string[] args)
{
if (!IsDebug())
System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddSingleton<SingletonHandler>();
services.AddHostedService<Worker>();
services.AddHostedService<Listener>();
})
.ConfigureLogging((hostingContext, logging) => {
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddFile(hostingContext.Configuration.GetSection("Logging"));
})
.UseWindowsService();
}
EDIT EDIT: I am attempting to run this on a Windows Server Core image if possible. I don't know if that messes with the capabilities of Worker Services.
you should call .UseWindowsService() when configuring your host builder. The method is contained in the package Microsoft.Extensions.Hosting.WindowsServices

How could a Windows service get its handle?

A service, which I'm developing, needs to call ChangeServiceConfig2 to change its configuration parameters. The function requires a service handle. So, to get its handle, the service calls OpenSCManager, which succeeded, and later OpenService. In the parameter lpServiceName of OpenService function I specify the name of the service but I got "Access denied". I changed the access rights in the manifest file to "requireAdministrator" but still got the error.
In general, how could a Windows service get its handle?
When creating the service, the lpServiceStartName argument determines the security context that the service will run in.
From the documentation for CreateService:
If this parameter is NULL, CreateService uses the LocalSystem account.
So in order for your service to run with administrator privilege, you need to specify NULL instead of an account name. According to the comments, you are currently running as Local Service; this does not grant administrator privileges.

make a windows service from executable

I'm looking for a way to create a Windows service from an executable that is not a service itself. Do I need a wrapper service to response Windows service calls that calls non-service process?
Note: I'm familiar with SC.EXE and how to make a service. unfortunately when starting services made from non-service executable, I'm getting 1053 timout error.
Try to look on how to use srvany.exe, it should be a tool allowing to launch an app as a service.

Trouble with running myprogram.exe as service on windows 2008

The MyProgram.exe is made to listen the request from pipe and using command prompt its working perfect but I tried to work it by using windows service but not success I have tried following steps on windows server 2008 enterprise:
> sc create MyService binPath= "C:\test\MyProgram.exe" DisplayName= "MyProgramService"
>[SC] CreateService SUCCESS
>sc start MyService
[SC] StartService FAILED 1053:
The service did not respond to the start or control request in a timely fashion.
reference
So I read on one blog that we need to create registry entry for the same then I tried the following steps
I found my newly created service under: HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\MyService
Click the key named MyService (it looks like a folder) from the menu in regedit. Select “edit” and “new” and then select “key.” This will create a new key which you should name “Parameters.” Next, right- click on the key that you just named “Parameters” and select “new” and then “string value.” Name the value “Application.” Double-click the string value and a box will pop up. In the box under “value data”, you need to put the full path to the Dropbox. In my case, the path was: C:\test\MyProgram.exe\MyProgram.exe
Start your new service. Navigate to the services list in the control panel‘s administrative tools or simply type services.msc in the run box. Find DropBox in the list and start it. New services should be set to start automatically, but feel free to check it to be sure.
But the service start for a few seconds and get terminated. When I start manually service from services.msc it give error
StartService FAILED 1053:
The service did not respond to the start or control request in a timely fashion.
Not sure why any one have work on it, please guidance to make it as service.
You can't run just any EXE as a Windows service. You must have an exe which understands what it means to be a service and which communicates appropriately with the Windows Service Control Manager.
Refer to the Microsoft documentation, starting with http://msdn.microsoft.com/en-us/library/windows/desktop/ms686953(v=vs.85).aspx.

WCF hosted in windows service errors

I have a WCF in VB which is to be hosted in a Windows Service. I managed the install program so the service actually installs. But, when I try to start the service, I get the following error:
The service on Local Computer started
and then stopped. Some services stop
automatically if they have no work to
do, for example, the Performance Logs
and Alerts service.
Cheking the Event Viewer gives me the following:
Service cannot be started.
System.ArgumentException: ServiceHost
only supports class service types.
at
System.ServiceModel.Description.ServiceDescription.GetService(Type
serviceType)
at
System.ServiceModel.ServiceHost.CreateDescription(IDictionary`2&
implementedContracts).........
Anybody have any ideas what's going on? Thanks!
The ServiceHost constructor must be concrete implementation of service contract.
It sounds like you are passing in the Interface rather than the service implementation.
svh = new ServiceHost(typeof(MCWCFService.MCManagementService));
svh.AddServiceEndpoint(
typeof(MCWCFService.IMCManagementService),
new NetTcpBinding(),
"net.tcp://192.168.0.2:8011");
svh.Open();
When creating the ServiceHost use the Class name - in the above it is MCManagementService. In the endpoint, use the interface - in the above it is IMCManagementService.

Resources