C# Service calls Console Application that doesn't close - c#

What I have is a windows Service calling a console application that i'm running. However, when the service run it again, the console app doesn't close. is it best to have the app close itself when it's done running or have the service close it? In either cause can you give an example on how to close it?
while (true)
{
try
{
string ectory = #"C:\Program Files\Checker.exe";
EventLog.WriteEntry("PriceGrab", "Calling executeable");
var p = Process.Start(ectory);
if (!p.WaitForExit(30000))
{
p.Kill();
}
System.Threading.Thread.Sleep(600000); // wait 10 minutes
}
catch (Exception ex)
{
EventLog.WriteEntry("PriceGrabCall", ex.Message, EventLogEntryType.Warning);
}
This is what I have inside of my Service executable. This will not close the app. The app is designed to run once every 10 minutes. N/M works now...

It depends on the nature of the console app. If it's like a server app and it won't quit (has an infinite loop...), then you just start it once and only kill it when you don't need it anymore (or just leave it running...). If it's supposed to exit, you can give it some time to close itself, and then kill it if it didn't finish:
var p = Process.Start( ... );
// ...
if (!p.WaitForExit(5000)) { // wait 5 seconds
p.Kill();
}
But be careful when killing processes like this. You might lose the work that they were doing.

Just a suggestion that may be more robust: I've done something similar in the past and have used a solution where the console app is scheduled via Windows Task Scheduler every 5 mins or so and the service checks for new files created by the console app using a file system watcher.

Related

Restart c# console app after executing succesfull

How to automatically restart c# console application after a succesfull run? My program should be running continuously. And i should be like a loop but not in the code cuz that doesn't work.
What i've tried:
Application.Restart();
Environment.Exit(0);
And
System.Environment.Restart();
None of these seems to work for my project. So i'm looking for other ways?
There's a similar issue here for restating a console application here How restart the Console app?
Essentially you ask to start the application again.
If it's just that you want to run the same functionality you could use a loop or similar.
var shouldExit = false;
while(!shouldExit)
{
// do work.
var result = MethodToDoWork();
// Get whether user wants to restart
if(!result.Success)
{
shouldExit = true;
}
}

c# Open IE From Scheduled Task

I have a c# console application that I want to run from task scheduler that has 2 main functions: 1) Closes all Internet Explorer processes; and 2) Restarts Internet Explorer and loads the appropriate website.
The console app does exactly what it is supposed to do if run from the command line, but fails if executed from Task Scheduler.
The app is designed to run on the client computer the only function of which is to load a single website and broadcast the website to our internal TV Channel 195. We have connection issues with our ISP and while the connection issue is usually temporary, Internet explorer needs to be restarted to re-show the website.
I want to set it up to run multiple times each day to eliminate any possible connection issues between the web server and the client.
private static void StartExplorer()
{
Process _process;
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = "iexplore.exe",
Arguments = "-noframemerging -private -k \"http://tv.TheelmAtClark.Com\""
};
try{
_process = Process.Start(psi);
}
catch(Exception Ex)
{
Console.WriteLine(Ex.ToString());
}
}
Is it possible to run the app using task scheduler?
I would recommend that you look at alternative approaches, if possible.
A Firefox plugin like Reload Every is designed to do just this. I use this in our to project to a big screen TV.
However, if you are keen on doing this via Internet explorer, again there are two approaches
1) Something similar to the Firefox plugin I mentioned above - Autorefresher for IE
2) If you insist on having a task scheduler, as you mentioned above, here is how I think you can do it-
To kill all Internet Explorer instances, use PSKill. Invoke it via Process.Start with arguments to kill Internet Explorer.
To launch a new instance, try invoking Process.Start with UseShellExecute=true.

Keep application running all the time

Basically I need my application to run from system start until system shutdown. I figured out the following approach:
create MyApp.exe and MyService.exe
MyApp should install MyService as a service
MyService is supposed to run at startup and periodically check if MyApp is running. If it's not than start it.
That's the code I wrote for my service:
protected override void OnStart(string[] args)
{
while(true)
{
int processesCount =
Process.GetProcessesByName(Settings.Default.MyAppName).Count() +
Process.GetProcessesByName(Settings.Default.MyAppName + ".vshost").Count() +
Process.GetProcessesByName(Settings.Default.MyAppUpdaterName).Count();
if(processesCount==0)
{
//restore
var p = new Process { StartInfo = { FileName = Settings.Default.MyAppName, Arguments = "" } };
p.Start();
}
else
{
}
System.Threading.Thread.Sleep(3000);
}
}
How can I install this process so that it starts on windows start?
I'm not sure if this infinite loop in OnStart method is a good idea. Is it?
Is the general idea ok?
What I've done is have a windows service that runs the logic and main application code. Then if you need a GUI for it, have the windows service expose a web service via WCF and create a windows app that calls to the web service. On install, put you windows app in the windows startup.
This model will have the main application code running all the time, but the GUI is only up when a user is logged in.
Is the general idea ok?
As Hans points out in comments this is hostile to the user and fortunately won't work on Vista or later because services run in their own windows station. Put whatever logic you need to run all the time in the service and use an IPC mechanism such as WCF to communicate with an (optionally) running UI. If the user disables the service or exits the GUI respect their wishes...
How can I install this process so that it starts on windows start?
Add an entry to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run or HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Runthat points to your GUI application.
I'm not sure if this infinite loop in OnStart method is a good idea.
Is it?
No. You need to return from OnStart if you need to do work after OnStart returns create a Thread to do that work.

Closing process start from windows application on application close or exit

I am working on windows application. i have to run some window exe from my app, i am able to do the same but when i close my application these exe remains on running condition, i am not getting how can i close those exe. Please suggest some tips.
To run the Process
private void StartChildProcess(string fileName)
{
Process newProcess = new Process();
newProcess.StartInfo = new ProcessStartInfo(fileName); ;
newProcess.Start();
localProcess.Push(newProcess);
}
To close the process
private void CloseStartedProcesses()
{
while (localProcess.Count > 0)
{
Process process = localProcess.Pop();
if (process != null && !process.HasExited)
{
process.CloseMainWindow();
process.Close();
}
}
}
Some options:
Setup some communication system so the Main application can alert the other application to shutdown (read up on some WCF information or remoting)
Create a do.shutdown file and let the second application check if that file exists, simple but efficient.
Use the process.Kill options
Use Sendkey or equivalent to send a 'quit' key combination
Use Windows API - P/Invoke. FindWindow() or EnumWindows() to get the window handle. Then you can send WM_CLOSE or WM_QUIT to end the application via the SendMessage() function.
Note that if the application checks for user input on exiting (like a MessageBox asking weather the user really wants to quit) the only option might be to send WM_DESTROY which would be equivalent to Process.Kill (at least in respects to causing data loss - I am not certain it is the absolute equivalent).
Try this:
Process[] p = Process.GetProcessesByName("osk");
foreach (var item in p)
{
item.Kill();
}
The reason that the EXE you've ran from your application doesn't terminate once you close your application is probably because the 2nd application runs as a DIFFERENT, SEPARATE process.
If you run another process with System.Diagnostics.Process, it will remain in background until terminated manually or until it finishes it's job.
try this Process proc = Process.GetProcessesByName("processname");
proc.Kill();

how to block a user from opening new process like internet explorer or firefox?

I am looking for a way to block a user from opening new IE or firefox windows. Is there a way to do this using c#. I am looking at system.diagnostics
You could use a windows service since it runs on background and use this code to terminate a process (the code terminates a detected running internet explorer process)
while (true)
{
StartLoop:
try
{
foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcesses())
{
if (process.ProcessName.ToUpperInvariant().Equals("IEXPLORE"))
process.Kill();
}
}
catch
{
goto StartLoop;
}
}
How about making a group policy for the "testing account" that excludes most of the start menu and the desktop. Make your program the only one that can run.
It won't guarantee that another process won't be started, but it will certainly make it more difficult.

Categories