Launch JavaScript from Website / Exit Application - c#

Long story short, it's about a Windows Form Application with a WebBrowser control. The application opens a website, fills in username and password, logs in, launches a vpn client (exe) by executing a javascript. Once the vpn client is successfully started, the application should exit. The first half is working fine.
I'd like to check if the vpn client is running, if so, it should close the my application, otherwise wait for the exe to start.
private void LaunchJS()
{
HtmlDocument doc = webBrowser1.Document;
Object js = doc.InvokeScript("launchJS");
label1.Text = "complete";
}
.
if (label1.Text == ("complete"))
{
bool prc = false;
while (!prc)
{
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains("JS_plugin"))
{
prc = true;
Application.Exit();
}
}
}
}
The Problem I'm experiencing is that the javascript launch is unsuccessful, when I enable the second part (check process) of the code. The java script isn't executed, the program will never launch and the check process goes into an infinite loop.
Any help would be much appreciated!

doing the process check in a separate thread has resolved my issue.
private void GetPRo()
{
if (label1.Text == ("complete"))
{
bool prc = false;
while (!prc)
{
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains("JS_plugin"))
{
prc = true;
Application.Exit();
}
}
}
}
}
.
Thread CloseApp = new Thread(new ThreadStart(GetPro));
CloseApp.Start();

Related

Kill other instances if program is running?

I am trying to make it so that if another instance of my program is running, it should close down the instance that's already running and start the new instance. I currently tried this:
[STAThread]
static void Main()
{
Mutex mutex = new System.Threading.Mutex(false, "supercooluniquemutex");
try
{
if (mutex.WaitOne(0, false))
{
// Run the application
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new fMain());
}
else
{
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.Equals(Process.GetCurrentProcess().ProcessName) && proc.Id != Process.GetCurrentProcess().Id)
{
proc.Kill();
break;
}
}
// Run the application
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new fMain());
}
}
finally
{
if (mutex != null)
{
mutex.Close();
mutex = null;
}
}
}
But for some reason it doesn't kill the already running instance, it just kills itself most of the time and sometimes it doesn't do anything at all.
What do I do to get this to work?
EDIT: I know the usual way of doing it is showing a message that the application is already running, but in this application it is vital that it kills the old process instead of showing a message.
First of all you need to wait for mutex again after killing the previous process. When you that you will get AbandonedMutexException. For details of that please check this link I am assuming it is OK to continue after that exception.
You can try .
Mutex mutex = new System.Threading.Mutex(false, "supercooluniquemutex");
try
{
bool tryAgain = true;
while (tryAgain)
{
bool result = false;
try
{
result = mutex.WaitOne(0, false);
}
catch (AbandonedMutexException ex)
{
// No action required
result = true;
}
if (result)
{
// Run the application
tryAgain = false;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new fMain());
}
else
{
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.Equals(Process.GetCurrentProcess().ProcessName) && proc.Id != Process.GetCurrentProcess().Id)
{
proc.Kill();
break;
}
}
// Wait for process to close
Thread.Sleep(2000);
}
}
}
finally
{
if (mutex != null)
{
mutex.Close();
mutex = null;
}
}
In that example if I get AbandonedMutexException, I get ownership of the mutext and it is ok to continue.
Also, you use local Mutex, another user can run same application under another Terminal server session. MSDN says
On a server that is running Terminal Services, a named system mutex can have two levels of visibility. If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, and both are visible to all processes in the terminal server session. That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.

c# wait until dialog of started process closes

How do I wait (block) my program until a specific dialog of my previous started process closes?
I'm starting pageant.exe to load a ssh key. Pageant is started with the class "Process". This works fine.
My ssh key has a passphrase. So my main program/process (this one started the process) has to wait until the user entered the ssh key passphrase.
I got an idea how to wait, but don't know how to do this in c#:
If pageant ask for the passphrase a dialog appears. So my main program/process can wait until the passphrase dialog is closed. Is it possible to do this in c#?
I got the idea from here.
EDIT: found a solution
// wait till passphrase dialog closes
if(WaitForProcessWindow(cPageantWindowName))
{ // if dialog / process existed check if passphrase was correct
do
{ // if passphrase is wrong, the passphrase dialog is reopened
Thread.Sleep(1000); // wait till correct passphrase is entered
} while (WaitForProcessWindow(cPageantWindowName));
}
}
private static bool WaitForProcessWindow(string pProcessWindowName)
{
Process ProcessWindow = null;
Process[] ProcessList;
bool ProcessExists = false; // false is returned if process is never found
do
{
ProcessList = Process.GetProcesses();
ProcessWindow = null;
foreach (Process Process in ProcessList)
{ // check all running processes with a main window title
if (!String.IsNullOrEmpty(Process.MainWindowTitle))
{
if (Process.MainWindowTitle.Contains(pProcessWindowName))
{
ProcessWindow = Process;
ProcessExists = true;
}
}
}
Thread.Sleep(100); // save cpu
} while (ProcessWindow != null); // loop as long as this window is found
return ProcessExists;
}
This might help you out, but doesn't give you entire control. I am not familiar with pageant, so I am not sure if it keeps running in the background or not. But in case the program automatically closes you could do this in your application.
So you could check in a loop if the Pageant application is open or not, once it is open you execute some code and once it is closed you enable the program again.
Execute this code in some background worker.
//Lets look from here if pageant is open or not.
while(true)
{
if (Process.GetProcessesByName("pageant").Length >= 1)
{
//block your controls or whatsoever.
break;
}
}
//pageant is open
while(true)
{
if (!Process.GetProcessesByName("pageant").Length >= 1)
{
//enable controls again
break;
}
}
//close thread

Monitoring process to be always running

Anybody knows how I could make a Monitor program in C# to control that an application will always be running? That I need it's a double monitor application, I will explain: I have a application Ap1 that have to control that Ap2 process it's always started, and Ap2 have to control that Ap1 process it's always started. In resume, if I kill Ap1 process the Ap2 application should start Ap1 immediatelly (and vice versa if Ap2 die).
This the code that I'm developing but didn't work, I don't know but when I kill the program monitored no started again.
public void Monitor()
{
Console.WriteLine("Monitoring {0} process...", processname);
while (IsProcessRunning() == true)
{
Process[] runningNow = Process.GetProcesses();
foreach (Process process in runningNow)
{
if (process.ProcessName == processname)
{
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Process:{0} is running actually", process.ProcessName);
}
else { /* Provide a messagebox. */ }
}
// Sleep till the next loop
Thread.Sleep(intInterval);
}
while (IsProcessRunning() != true)
{
ProcessMonitor proc = new ProcessMonitor("ConsoleApplication1", 1000);//Check if is running each 1 second
Console.WriteLine("Process:{0} is NOT running actually", processname);
//Application folder of exe
String applicationFolder = "C:\\App";
//Get the executable file
String procPath = applicationFolder + #"\Ap1.exe";
Console.WriteLine("Running {0} process...", proc.Name);
//Lauch process
Process p = Process.Start(procPath);
Console.WriteLine("Process running {0} OK", proc.Name);
//p.WaitForExit(10000);
}
}
And the main program:
static void Main(string[] args)
{
ProcessMonitor proc = new ProcessMonitor("ConsoleApplication1", 1000);//Check if is running each 1 second
if (proc.IsProcessRunning() != true)
{
Console.WriteLine("{0} is not running.", proc.Name);
//Application folder of exe
String applicationFolder = "C:\\App";
//Get the executable file
String procPath = applicationFolder + #"\Ap1.exe";
Console.WriteLine("Running {0} process...", proc.Name);
//Lauch process
Process p = Process.Start(procPath);
Console.WriteLine("Process running {0} OK", proc.Name);
//p.WaitForExit(10000);
}
else
{
proc.Monitor();
}
proc.FreezeOnScreen();
}
You could set up a task in the task scheduler that launches your program at a set interval (say every half hour). I believe you can set it to not start the task if there is already an instance running. (Correct me if I am wrong)
We needed this once and simply monitored the process list periodically, checking for the name of the process. If the process wasn't present for a given amount of time, we restarted it. You can use Process.GetProcessesByName.

OutputDataReceived event is never triggered in Windows Server 2008 (fine in Win7)

I have an odd problem I can't seem to diagnose.
I'm calling am external binary, waiting for it to complete and then passing back a result based on standard out. I also want to log error out.
I wrote this and it works a treat in Windows 7
namespace MyApp
{
class MyClass
{
public static int TIMEOUT = 600000;
private StringBuilder netOutput = null;
private StringBuilder netError = null;
public ResultClass runProcess()
{
using (Process process = new Process())
{
process.StartInfo.FileName = ConfigurationManager.AppSettings["ExeLocation"];
process.StartInfo.WorkingDirectory = Path.GetDirectoryName(ConfigurationManager.AppSettings["ExeLocation"]);
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += new DataReceivedEventHandler(NetOutputDataHandler);
netOutput = new StringBuilder();
process.StartInfo.RedirectStandardError = true;
process.ErrorDataReceived += new DataReceivedEventHandler(NetErrorDataHandler);
netError = new StringBuilder();
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
if (process.WaitForExit(TIMEOUT))
{
// Process completed handle result
//return my ResultClass object
}
else
{
//timed out throw exception
}
}
}
private void NetOutputDataHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
//this is being called in Windows 7 but never in Windows Server 2008
if (!String.IsNullOrEmpty(outLine.Data))
{
netOutput.Append(outLine.Data);
}
}
private void NetErrorDataHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
//this is being called in Windows 7 but never in Windows Server 2008
if (!String.IsNullOrEmpty(outLine.Data))
{
netError.Append(outLine.Data);
}
}
}
}
So I install it on a Windows Server 2008 box and the NetOutputDataHandler and NetErrorDataHandler handlers are never called.
The app is compiled for .NET v4.
Any ideas what I'm doing wrong?
You might want to inspect the code access security policy.
You may start by runing the caspol.exe with the -l parameter(s) of the caspol.exe for the -u[ser] running the app.
Don't forget to check if you still encounter the same issue when running the app as Administrator

Process.Start is blocking

I'm calling Process.Start, but it blocks the current thread.
pInfo = new ProcessStartInfo("C:\\Windows\\notepad.exe");
// Start process
mProcess = new Process();
mProcess.StartInfo = pInfo;
if (mProcess.Start() == false) {
Trace.TraceError("Unable to run process {0}.");
}
Even when the process is closed, the code doesn't respond anymore.
But Process.Start is really supposed to block? What's going on?
(The process start correctly)
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace Test
{
class Test
{
[STAThread]
public static void Main()
{
Thread ServerThread = new Thread(AccepterThread);
ServerThread.Start();
Console.WriteLine (" --- Press ENTER to stop service ---");
while (Console.Read() < 0) { Application.DoEvents(); }
Console.WriteLine("Done.");
}
public static void AccepterThread(object data)
{
bool accepted = false;
while (true) {
if (accepted == false) {
Thread hThread = new Thread(HandlerThread);
accepted = true;
hThread.Start();
} else
Thread.Sleep(100);
}
}
public static void HandlerThread(object data)
{
ProcessStartInfo pInfo = new ProcessStartInfo("C:\\Windows\\notepad.exe");
Console.WriteLine("Starting process.");
// Start process
Process mProcess = new Process();
mProcess.StartInfo = pInfo;
if (mProcess.Start() == false) {
Console.WriteLine("Unable to run process.");
}
Console.WriteLine("Still living...");
}
}
}
Console output is:
--- Press ENTER to stop service ---
Starting process.
Found it:
[STAThread]
Makes the Process.Start blocking. I read STAThread and Multithreading, but I cannot link the concepts with Process.Start behavior.
AFAIK, STAThread is required by Windows.Form. How to workaround this problem when using Windows.Form?
News for the hell:
If I rebuild my application, the first time I run application work correctly, but if I stop debugging and restart iy again, the problem araise.
The problem is not raised when application is executed without the debugger.
No, Process.Start doesn't wait for the child process to complete... otherwise you wouldn't be able to use features like redirected I/O.
Sample console app:
using System;
using System.Diagnostics;
public class Test
{
static void Main()
{
Process p = new Process {
StartInfo = new ProcessStartInfo("C:\\Windows\\notepad.exe")
};
p.Start();
Console.WriteLine("See, I'm still running");
}
}
This prints "See, I'm still running" with no problems on my box - what's it doing on your box?
Create a ProcessStartInfo and set UseShellExecute to false (default value is true). Your code should read:
pInfo = new ProcessStartInfo("C:\\Windows\\notepad.exe");
pInfo.UseShellExecute = false;
// Start process
mProcess = new Process();
mProcess.StartInfo = pInfo;
if (mProcess.Start() == false) {
Trace.TraceError("Unable to run process {0}.");
}
I had the same issue and starting the executable creating the process directly from the executable file solved the issue.
I was experiencing the same blocking behavior as the original poster in a WinForms app, so I created the console app below to simplify testing this behavior.
Jon Skeet's example uses Notepad, which only takes a few milliseconds to load normally, so a thread block may go unnoticed. I was trying to launch Excel which usually takes a lot longer.
using System;
using System.Diagnostics;
using static System.Console;
using System.Threading;
class Program {
static void Main(string[] args) {
WriteLine("About to start process...");
//Toggle which method is commented out:
//StartWithPath(); //Blocking
//StartWithInfo(); //Blocking
StartInNewThread(); //Not blocking
WriteLine("Process started!");
Read();
}
static void StartWithPath() {
Process.Start(TestPath);
}
static void StartWithInfo() {
var p = new Process { StartInfo = new ProcessStartInfo(TestPath) };
p.Start();
}
static void StartInNewThread() {
var t = new Thread(() => StartWithPath());
t.Start();
}
static string TestPath =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop) +
"\\test.xlsx";
}
Calls to both StartWithPath and StartWithInfo block my thread in a console app. My console does not display "Process Started" until after the Excel splash screen closes and the main window is open.
StartInNewThread will display both messages on the console immediately, while the splash screen for Excel is still open.
We had this problem when launching a .bat script that was on a network drive on a different domain (we have dual trusted domains). I ran a remote C# debugger and sure enough Process.Start() was blocking indefinitely.
When repeating this task interactively in power shell, a security dialog was popping up:
As far as a solution, this was the direction we went. The person that did the work modified domain GPO to accomplish the trust.
Start server via command prompt:
"C:\Program Files (x86)\IIS Express\iisexpress" /path:\Publish /port:8080
This take access to sub-threads of the tree process of OS.
If you want to launch process and then make the process independent on the "launcher" / the originating call:
//Calling process
using (System.Diagnostics.Process ps = new System.Diagnostics.Process())
{
try
{
ps.StartInfo.WorkingDirectory = #"C:\Apps";
ps.StartInfo.FileName = #"C:\Program Files\Microsoft Office\Office14\MSACCESS.EXE"; //command
ps.StartInfo.Arguments = #"C:\Apps\xyz.accdb"; //argument
ps.StartInfo.UseShellExecute = false;
ps.StartInfo.RedirectStandardOutput = false;
ps.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
ps.StartInfo.CreateNoWindow = false; //display a windows
ps.Start();
}
catch (Exception ex)
{
MessageBox.Show(string.Format("==> Process error <=={0}" + ex.ToString(), Environment.NewLine));
}
}

Categories

Resources