I'm trying to write a Windows service that opens a program when it starts/restarts. I doubt it makes a difference but it's a spreadsheet program like Excel just in case it's important to this task. It's located at the root of my D: drive. Process.Start works just fine in this console program (so I know I'm using it right):
namespace Example
{
public class Program
{
public static void Main()
{
System.Diagnostics.Process.Start(#"D:\program.exe");
}
}
}
I followed this guide: https://learn.microsoft.com/en-us/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer to write my own service. I have that exact same line in the OnStart method of my service project as seen here:
protected override void OnStart()
{
System.Diagnostics.Process.Start(#"D:\program.exe");
}
I opened the install utility as administrator and successfully built and installed as described in the guide. Nothing was happening when I started the service, so I looked up how to debug a service. I changed my OnStart method to:
protected override void OnStart()
{
System.Diagnostics.Debugger.Launch();
System.Diagnostics.Process.Start(#"D:\program.exe");
}
While stepping through my code, I could see Process.Start threw an InvalidOperationException error. I read up on it (https://learn.microsoft.com/en-us/dotnet/api/system.invalidoperationexception?view=netframework-4.7.2) but I'm stuck as to how to resolve it. I tried the local user, local service, and system service accounts when building and installing, but none helped. Has anyone launched executables in a service?
Related
I have a Window Service , that is running on my machine . I have separate console application in the same solution that is performing some functionality. In order to access the functions of the console application , I have add the *.exe file of the console application as a reference to the Window Service project.
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
{
// TODO: Insert monitoring activities here.
EventLog.WriteEntry("Monitoring the System", EventLogEntryType.Information);
string[] arr = new string[] { };
ConsoleApplication.Program.Main(null);
}
The Console application works perfectly file if I directly run through Visual Studio. However , If I call the Main() method from the Window Service I am getting a null pointer exception.
public static void Main(string[] args)
{
try
{
//CODE BREAKS HERE ON READING FROM CONFIG FILE
string genesis_sel= ConfigurationSettings.AppSettings["genesis_sel"].ToString();
}
catch (Exception ex)
{
//Exception code
}
}
Below is a snapshot of the Console application Project running in Visual Studio.
I am not sure what's causing the code to break while accessing the main method from a Window service.
Any suggestions?
Update: Added snapshot of the config file. I don't believe it's a rad access issue from the configuration file as it is reading correctly when I run the console application alone. There is an initialization issue when I access it through the window Service.
UPDATE Replaced the main method with a single event log , but still getting the same exception.
When you call the method it is running as part of your service, so it uses Environment and settings from your service. That means that you should have correct data in AppSettings of your service project. To bring more clarity: In this case function Main is part of your service and not a separate application root.
Otherwise you can run your console as separate process, but in that case you are loosing part of Control functions.
I would suggest, to separate common logic in a separate project/dll and call functions from it, it will be more clean and not so confusing
I am not able to detect this Logon event in Windows.
Here is my code:
namespace ConsoleApplication2
{
public class MyService: ServiceBase
{
public MyService()
{
CanPauseAndContinue = true;
CanHandleSessionChangeEvent = true;
}
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
base.OnSessionChange(changeDescription);
}
}
class Program
{
static void Main(string[] args)
{
MyService tpl = new MyService();
Thread t = new Thread(delegate()
{
while (true) { }
});
t.Start();
}
}
}
How do I test run this app and then remote desktop into my laptop? I can see the event generated in Windows EventViewer, but my OnSessionChange is never called (I added a breakpoint inside).
Is my code wrong or is the way I am testing wrong?
Normally multiple concurrent remote desktop sessions are not allowed on any of Windows desktop systems. So to use RDP to login as a different user then I assume that you have hacked this, or are using windows server (which rules out XP!).
Regardless, each user logged into the system will therefore have their own applications running and each set of applications are unique to that user. So App1 could be run independently by each user.
That means that your console application cannot detect the other user that is logged on.
To do this you must use a Windows Service. This runs in the background and can detect and work for multiple users and also detect login and logout. See this SO link
This is the purpose of inheriting MyService from ServiceBase. If you are not running the application as a service, then you are not running it correctly!
You need to first install your application as a service and then run it like a service.
You say that you don't think your application can run as a service. I'm not sure why, but if this is the case then you would have to instead look at creating some kind of script to run your application upon start-up/login.
This way, every time somebody logs in then your application would run. This might anyway be simpler for you.
Presently, I am attempting to profile a Windows service that I am working on using the new "Performance and Diagnostics" feature in Visual Studio 2013 (see http://blogs.msdn.com/b/visualstudioalm/archive/2013/07/12/performance-and-diagnostics-hub-in-visual-studio-2013.aspx). When I attempt to profile the service, I get this error message:
Cannot start service from the command line or a debugger. A Windows Service must first be intalled (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative Tool or the NET START command.
Normally when debugging the service, it works fine because I have the following code in Program.cs:
private static MySvc _serviceInstance;
private static readonly List<ServiceBase> _servicesToRun =
new List<ServiceBase>();
static void Main(string[] args)
{
_servicesToRun.Add(_serviceInstance);
if (Environment.UserInteractive)
{
_servicesToRun.ToArray().LoadServices();
}
else
{
ServiceBase.Run(_servicesToRun.ToArray());
}
}
static Program()
{
_serviceInstance = new MySvc();
}
Also, if I attempt to attach to a running app, in the dialog that appears it doesn't display any executing processes, and when I put the name of the service in there, it does not find it. Does anyone have any suggestions? TIA.
UPDATE: This is what I get when I attempt to attach to a process. Why doesn't the "Performance and Diagnostics" see any processes running on my computer? Why would it only connect to Windows Store apps instead of all exes? Please see this image:
The way I resolved the problem was the copy all the source code and make minor modifications to get everything to run in a Console application, then chose Debug->Performance and Diagnostics and ran the Console application using "Change Target" -> "Launch and executable file (.exe)"
I am having an issue launching a process from the system account. I just want to make it clear that I am not trying to run it under an interactive session, nor trying to impersonate any account. All I am trying to do is launch a process from the system account into the same session. The session in which the NTAUTHORITY\SYSTEM resides is 0 I believe.
I created a simple Windows Service that basically just uses Process.start to launch the executable. The Service is a system service.
I installed the service using SC as such:
sc create "MYSERVICE" binpath= "C:\Projects\MyService\MyService.exe" displayname= "My Awesome Service"
When I try to manually start the service I get a prompt that says "The ServiceName service on local computers started and then stopped. Some services stop Automatically if they are not in use by other services or programs."
Along with this the executable is never actually started. When monitoring it in processhacker I can see that the service does start, but the executable it attempts doesn't. Can anyone help me figure out why?
As I stated earlier my service is very basic, all it does is try and launch the executable when started:
protected override void OnStart(string[] args)
{
Process.Start("svrexec.exe");
}
protected override void OnStop()
{
}
Did you specify full path to your executable? The working folder for the system user is %windir%\System32.
Try Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "svrexec.exe"), or set Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory
Are you 100% sure it's not running?
I tried and mine is running under the SYSTEM User Name
check Show processes from all users in Task Manager
I have a windows service application. When I press the button, I want to start the service. But I'm receiving the following the error.
Window Service Start Failure:
Cannot start service from the command line or debugger. A Windows
Service must first be installed (using installutil.exe) and then started
with the ServerExplorer, Windows Service Administrative tool or the NET
START command.
C# Code:
namespace WindowsFormsApplication1
{
partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
RegistryKey KEY = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\baslat", true);
KEY.DeleteValue("timer",true);
}
protected override void OnShutdown()
{
RegistryKey KEY = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\baslat", true);
KEY.SetValue("timer","");
}
}
}
It's telling you what to do. You need to install the service inside windows. Then you can stop and start it using the windows service control manager.
You can't start it like an exe as services have different entry points. However there is nothing stopping you from having an exe that runs under the SCM and as a normal program.
You need to install the service, as the error message suggest :
installutil.exe yourservice.exe
Then you can start it with :
net start yourservice